dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def timeout_set(self, duration: float): """Sets the estimated completion time for a just-issued task. Because there's no flow control between the printer and computer, special care must be taken to avoid overrunning the printer's buffer. Serial output is throttled based on seri...
The code initializes a printer by setting up serial communication parameters (port, baudrate), configuring firmware version, calculating byte transmission time, and applying print settings like heating parameters and print density. It ensures the printer is ready for data reception after power-up by setting a timeout, ...
def __init__(self, port: str, baudrate: int, *args, **kwargs): """Initialise the printer. :param port: the port of the printer :type port: str :param baudrate: the baudrate of the printer :type baudrate: int """ # Firmware is assumed version 2.68. Can override ...
def feed(self, lines: int = 1) -> None: """Feeds by the specified number of lines. :param lines: the number of lines to feed :type lines: int, optional """ if self.firmware_version >= 264: self.write_bytes(27, 100, lines) self.timeout_set(self.dot_feed_t...
The code prints a barcode using a thermal printer, selecting the appropriate barcode type and formatting based on the firmware version. It checks if the specified style is supported, raises an error if not, and sends printer commands to generate the barcode. The text is encoded differently depending on the firmware ver...
def print_barcode(self, text: str, style: Barcode) -> None: """Prints a barcode. :param text: the text to encode in the barcode :type text: str :param style: the style (or type) of the barcode to use :type style: Barcode :raises TypeError: if the barcode style isn't supp...
def set_print_mode(self, mask: PrintMode) -> None: """Set a print mode. :param mask: the print mode to set :type mask: PrintMode """ self.print_mode |= mask.value self.write_print_mode() # Stop if we're not changing the height or width if mask not in (Pr...
The main task of the code is to enable or disable bold text rendering by setting/unsetting a bold print mode, while preventing text size from reverting to a smaller default by adjusting font size ("L" or "M") under specific character height and column width conditions when bold mode is toggled.
def bold(self, mode: bool) -> None: """Enables or disables bold text. :param mode: True for on, False for off :type mode: bool :raises TypeError: if mode is not True or False """ # Switch it on if mode is True: self.set_print_mode(PrintMode.BOLD_MASK...
def draw(win, paddles, ball, left_score, right_score): win.fill(BLACK) left_score_text = SCORE_FONT.render(f"{left_score}", 1, WHITE) right_score_text = SCORE_FONT.render(f"{right_score}", 1, WHITE) win.blit(left_score_text, (WIDTH//4 - left_score_text.get_width()//2, 20...
The code implements a Pong-style game with two paddles and a ball, using Pygame. It handles player input, collision detection, scoring, and particle effects. The game loop updates the display, moves the ball, checks for wins, and resets the game when a player reaches the winning score.
def main(): run = True clock = pygame.time.Clock() left_paddle = Paddle(10, HEIGHT//2 - PADDLE_HEIGHT // 2 + 200, PADDLE_WIDTH, PADDLE_HEIGHT) right_paddle = Paddle(WIDTH - 10 - PADDLE_WIDTH, HEIGHT // 2 - P...
def get_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Download kernels from Kaggle.") subparsers = parser.add_subparsers(dest="command") # competition-refs command competition_refs_parser = subparsers.add_parser( "competition-refs", help="Fetch competition referenc...
The main task of the code is to process command-line arguments and export data based on the specified command. It calls different functions to generate output files: `export_competition_refs` for competition references, `export_kernel_refs` for kernel references with filters, and `export_kernels` for kernel data, all w...
def main() -> None: args = get_args() if args.command == "competition-refs": export_competition_refs(args.out) elif args.command == "kernel-refs": export_kernel_refs(args.competitions, args.exclude, args.out) elif args.command == "kernels": export_kernels(args.kernels, args.excl...
def print_arms_blocking_head(human): print("\tLeft Wrist: (" + str(human.body_parts[LWrist].x) + "," + str(human.body_parts[LWrist].y) + ")") print("\tRigt Wrist: (" + str(human.body_parts[RWrist].x) + "," + str(human.body_parts[RWrist].y) + ")") print("\tLeft Elbow: (" + str(human.body_parts[LElbow].x) + "...
The code determines a human's action based on arm positioning. It checks if the person is performing a "hook" (right or left), "blocking" (arms shielding head), or "nothing" (no specific action). It returns one of these strings, handling errors by printing "No human found" if invalid input occurs.
def move(human_arr): # human_count = len(human_arr); # #print("human number is " + str(human_count)); # human_nums = human_arr[0]; # #print(human_nums); # human = person(human_nums); # print_arms_blocking_head(human); try: human_count = len(human_arr) #print("human number...
def timingdelta(tf): if tf== '1m': tf=timedelta(minutes=1) elif tf == '5m': tf=timedelta(minutes=5) elif tf == '15m': tf=timedelta(minutes=15) elif tf == '30m': tf=timedelta(minutes=30) elif tf == '45m': tf=timedelta(minutes=45) elif tf == '1h': tf...
The main task of the code is to download historical cryptocurrency data for a given symbol and timeframe. It checks if the data exists in a database collection; if so, it retrieves the latest entry and calculates a time range based on the timeframe. If the collection doesn't exist, it computes a start time from the cur...
def historic(symbol,timeframe,limited): coin = '{}_{}'.format(symbol,timeframe).replace('/','') #print(coin)#if print(coin) if coin in db.list_collection_names(): if db[coin]: data=list(db[coin].find().sort("_id", pymongo.DESCENDING).limit(1))[0] date=data['date'] ...
def spawn_pellets(self, amount): for i in range(amount): if len(self.pellets) < 200: self.spawn_pellet() def update_agents(self): for agent in self.agents: self.update_agent(agent) def render(self): self.screen.fill((0, 0, 0)) self.draw_pellets() ...
This code manages a game loop that handles events (like quitting or spawning pellets), maintains a dynamic agent population (adding new agents if under 8, removing excess if over 16), updates agent behavior, and renders the game state. It ensures continuous simulation by balancing agent numbers and processing game even...
def run(self): while self.running: for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False if event.type == SPAWN_PELLET: self.spawn_pellets(1) # if len(self.pellets) < 20: # ...
def update_user_name(): res = tableOperate("update", dictionary_formatter("User", {"userID" : 1, "name": "James"})) secres = tableOperate("update", dictionary_formatter("User", {"userID" : 98754, "name": "4335432"})) print("res: ", type(res)) print("sec res: ", type(secres)) print(res.status) print(secres.statu...
The function `update_all_tables` executes multiple database update operations for user and schedule fields (e.g., names, emails, passwords, license numbers, dates). It sequentially calls specialized update functions, wrapping them in a try-except block to catch and print assertion errors during execution, ensuring erro...
def update_all_tables(): try: update_user_name() update_user_email() update_user_pwdHash() update_licence_licenceNumber() update_schedule_dateTime() update_schedule_repeatEvery() update_pool_licenceID() except AssertionError as e: print(e.args)
def __getField(data, field): if field in data: ret = data[field] del data[field] return ret return None def tableOperate(op, data): response = "invalid table","400" if "table" in data: table = __getField(data, "table") if op == "insert": response ...
This function processes API requests by interpreting JSON payloads. It checks for an "operation" field to determine actions like insert, update, select, delete, vehicle lookup, or matchmaking. Valid operations trigger corresponding functions (tableOperate, vehicleLookup, matchmake), while invalid operations return a 40...
def api(): data = request.get_json() if not data: return "no payload","204" # No response if no payload if "operation" in data: op = __getField(data, "operation") if op in ("insert","update","select","delete"): return tableOperate(op, data) ...
def check_checker_on_file(self, file: str): """ Given a file (a, b, c .., g), this function checks to see if there are any checkers in that particular column. If there is an empty circle, the function will return the circle name of that empty circle. """ column = [f"{file}{rank}"...
The main task of the code is to handle a mouse click event in a Connect 4 game, placing a checker in the selected column if possible, checking for a winning condition, updating the game state, and switching turns between players. It ensures the game ends when a player achieves four connected checkers and highlights the...
def on_click(self, event): """ In the event that the cursor is clicked, a checker will be placed in the last available row if any. """ # check first to see if the game is over if self.game_over: return # if the game is over do nothing # the game is not over ...
def draw_a_board_game(board): board_flat_list = [] # board flattening list of list for row in board: for element in row: board_flat_list.append(element) # board visualization for the user print("\n {} | {} | {} \n--- --- --- \n {} | {} | {} \n--- --- --- \n {} | {} | {} \n".for...
The code implements a two-player Tic Tac Toe game, allowing players to choose symbols (X/O), alternating turns, validating inputs, checking for a win after each move, and restarting the game if desired. It handles game flow, win detection, and user interaction for a complete playable experience.
def play(): print("Welcome to Tic Tac Toe game.") # empty board initialization board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] # call the board drawing function (shows empty board at the start) draw_a_board_game(board) # ask user which letter they want to ...
def vaccinate_city(starting_city, vaccine_effectiveness): ''' Vaccinate everyone in a city Inputs: starting_city (list): the state of all people in the simulation at the start of the simulation vaccine_effectiveness (float): the chance that a vaccination will be effective R...
The function `run_simulation` simulates the spread of a contagious disease in a city, starting from an initial population state. It vaccinates the population based on given effectiveness, then iteratively simulates each day of infection spread until no infected individuals remain. The simulation uses a random seed for ...
def run_simulation(starting_city, days_contagious, random_seed=None, vaccine_effectiveness=0.0): ''' Run the entire simulation Inputs: starting_city (list): the state of all people in the city at the start of the simulation days_contagious (int): the number of a days ...
def compute_internal_values(t): ''' Assign a value to the internal nodes. The value of the leaves should already be set. The value of an internal node is the sum of the value of its children. Inputs: t (Tree): a tree Returns: The input tree t should be modified so that every in...
The function computes rectangles for a treemap visualization of a given tree. It processes the tree's structure, sorts its children, and recursively divides the bounding rectangle space to generate a list of Rectangle objects representing the treemap layout.
def compute_rectangles(t, bounding_rec_width=1.0, bounding_rec_height=1.0): ''' Computes the rectangles for drawing a treemap of the provided tree. Inputs: t: (Tree) a tree bounding_rec_height, bounding_rec_width: (float) the size of the bounding rectangle. Returns: a list ...
def load_trees(filename): ''' Loads trees from a json file. The json file should consist of a dictionary mapping tree names to trees represented as lists. Input: filename: (string) name of the json file. Returns: dictionary mapping tree names (strings) to Tree instances. ''...
The main task of the code is to process a tree structure from a file, compute internal values and paths, generate rectangles representing the tree's layout, and either print these rectangles or visualize them using a drawing module. It loads tree data, selects a specific subtree, calculates geometric parameters, and ou...
def cmd(tree_file, key, output): import drawing data = load_trees(tree_file) data_tree = data[key] compute_internal_values(data_tree) compute_paths(data_tree) rectangles = compute_rectangles(data_tree) if output == "-": for rect in rectangles: print(rect) else: ...
def settings(): return html.Div([ heading_panel(), save_panel(), html.Br(), connect_panel()]) def stress_level(): return html.Div([ html.H5( 'Stress Level', id='text_stress_label'), html.H6( '', id='text_stress_value', style={'color': WHITE})]) def plots(): x, hr = synthetic.sinusoid() hr...
The code defines a `layout()` function that returns a Dash HTML Div containing three components: `settings()`, `stress_level()`, and `plots()`. Its main task is to structure a user interface by aggregating these elements into a cohesive web layout for visualization or interaction, likely part of a Dash-based web applic...
def layout(): return html.Div([settings(), stress_level(), plots()])
def play_lines(self, number): target_index = self.curr_index + number if target_index > self.curr_index: max_index = target_index if target_index < len(self.infile) else len(self.infile) - 1 while self.curr_index < max_index: if max_index - self.curr_index <= self...
The main task of the code is to handle key input events for controlling playback operations, including navigating between lines, specifying playback duration or target lines, and toggling tier aggregation. It processes different key presses to trigger actions like playing previous/next lines, setting playback time or l...
def process_key(self, character): if character == self.keys['PREVIOUS']: self.play_lines(-1) elif character == self.keys['NEXT']: self.play_lines(1) elif character == self.keys['PLAY_FOR_TIME']: value = self.get_int_value('Milliseconds: ') if value...
def draw_screen(self): self.screen.clear() self.screen.border(0) self.screen.refresh() self.draw_help() def read_file(self, filename): try: reader = open(sys.argv[1], 'r') for line in reader: self.infile.append(line) except IOError:...
This code initializes a curses-based interface to display and interact with a text file. It reads a file, displays lines with line numbers, and processes user inputs for navigation, playback control, and screen resizing. Key features include handling repeated commands, aggregating views, and dynamically updating the sc...
def main(self, stdscr): # Draw the shortcut key bar self.screen = stdscr self.draw_screen() # Read the file self.read_file(sys.argv[1]) self.play_lines(1) exit = False last_pressed = None while not exit: self.draw_book() ...
def perform_feature_engineering(self): ''' function that splits the data into training and test with dependent and independent variables. input: df: pandas dataframe response: four pandas dataframe split into train and test. output: ...
The main task of the code is to train and evaluate Random Forest and Logistic Regression models using grid search for hyperparameter tuning. It performs feature engineering, generates predictions on training/test data, creates feature importance and ROC plots, saves the best models, and returns predictions along with t...
def train_models(self): ''' train, store model results: images + scores, and store models input: X_train: X training data X_test: X testing data y_train: y training data y_test: y testing data output: None ...
def run_task(self, window: ProgressBar): self.task_thread = Thread(target=self.graph.change_state) self.task_thread.start() window.bar.start() self.after(10, lambda: self.check_task(window)) def have_grid(self, widget): return bool(widget.grid_info()) def forget(self, widget): ...
The main task of the code is to display a progress bar, execute a task, and dynamically manage UI elements by hiding or retrieving widgets based on their current grid state, ensuring proper user interface updates during task execution.
def progressbar(self): """Show progress bar and change state""" window = ProgressBar(self) window.grab_set() self.run_task(window) if self.have_grid(self.player2): self.forget(self.player2) self.forget(self.label4) else: self.retrieve1(...
def config_gui(): class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def writelines(self, datas): self.stream.writelines(datas) self.stream...
The main task of the code is to initialize a GUI, retrieve and process branch data from starting nodes, sort branches by length (longest first), draw them, and save the resulting image. It orchestrates data cleaning, branch extraction, visualization, and output storage in a structured workflow.
def main(): config_gui() # used to define the instance coral_gui's attributes coral_gui.start_get_and_clean() print('New Process Initiated') branches = [] print(f'Getting Branches...', end=' ') starting_nodes = define_starting_nodes() # fills the list "branches" with branches from eac...
def suggest_greeting_intent(intent_request): return { 'dialogAction': { "type": "ElicitIntent", 'message': { 'contentType': 'PlainText', 'content': 'Hello there, how may I help you?' } } } def suggest_thankyou_intent(intent_request...
The code's main task is to route incoming intent requests to specific handler functions based on the intent name. It logs the request, checks the intent name, and dispatches to corresponding functions like suggest_greeting_intent or suggest_dining_intent. If the intent is unsupported, it raises an exception.
def dispatch(intent_request): logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot's intent handlers if intent_name == 'GreetingIntent': retu...
def get_arg(key, default=None): # type: (str, Any) -> Any """Get the argument value or default""" if default is None: default = "" return plugin.args.get(key, [default])[0] def paginate(json, category, idx=None): """Adds pagination to results pages""" if not json: return next...
This function displays section menus and playable items in an XBMC plugin. It retrieves data based on parameters like 'idx' (for menus) or 'href' (for playable content), processes pagination/filters, adds menu items with counts, parses search results, sets content type, and finalizes directory output using XBMC plugin ...
def section(): # type: () -> None """Show section menus and playable items""" idx = get_arg("idx", False) href = get_arg("href", False) category = get_arg("category") offset = get_arg("offset", 0) if idx: # Section menu url = locs.get_search_url(idx, page=offset) data...
def get_arg(key, default=None): # type: (str, Any) -> Any """Get the argument value or default""" if default is None: default = "" return plugin.args.get(key, [default])[0] def add_menu_item(method, label, args=None, art=None, info=None, directory=True): # type: (Callable, Union[str, int], d...
The function handles search operations in a plugin, allowing users to perform, save, delete, or view searches. It processes query parameters, manages saved searches via a menu, prompts for new input, fetches search results from a URL, and displays them. Conditional logic directs actions like deletion, menu rendering, o...
def search(): # type: () -> Optional[bool] """Search the archive""" query = get_arg("q") category = get_arg("category", ku.localize(32007)) # Search # Remove saved search item if bool(get_arg("delete", False)): locs.searches.remove(query) xbmc.executebuiltin("Container.Refresh()...
def make_bold(node): text = place_mark(node, "<b>", "</b>") return text def make_monospace(node): text = place_mark(node, "<code>", "</code>") return text def make_italic(node): text = place_mark(node, "<i>", "</i>") return text def make_horizontal_rule(node): return "<hr />" def make_headin...
The function generates markup by dynamically calling a type-specific function (e.g., make_bold, make_italic) based on the node's type_node attribute. If no match is found, it returns the node's text at the specified print level.
def make_markup(node): return globals()['make_' + node.type_node](node) if node.type_node == "bold": return make_bold(node) elif node.type_node == "monopace": return make_monospace(node) elif node.type_node == "italic": return make_italic(node) elif node.type_node == "horiz...
def plot_time_vs_size_general(): for bn, xl, yl in BENCHNAMES: plot_time_vs_size_general_per_benchmark(bn, xl, yl) def plot_time_vs_size_error_bar(): for bn, xl, yl in BENCHNAMES: for psn, _ in PSNAMES: plot_time_vs_size_error_bar_single(bn, psn, xl, yl) def plot_time_vs_threads(): ...
The main task of the code is to generate three visualizations analyzing performance metrics: plotting time versus data size (general trend), time versus data size with error bars (variability), and time versus number of threads (parallelism impact). It executes these plots sequentially to compare computational efficien...
def main(): plot_time_vs_size_general() plot_time_vs_size_error_bar() plot_time_vs_threads()
def get_parked_user(): return get_user_model().objects.get_or_create(username=DEFAULT_USER)[0] def generate_association_code(): return uuid4().hex def publish_unassociated_msg(self): # send association MQTT message assoc_msg = { 'associated': False, 'code': self.associati...
The code's main task is to dissociate a user by retrieving a parked user, generating a new association code, saving the updated state, and publishing an unassociated message to notify the user of their disassociation.
def dissociate(self): self.user = get_parked_user() self.association_code = generate_association_code() self.save() self.publish_unassociated_msg()
def draw_hand(np_random): """Returns player and dealer card choices.""" return [draw_card(np_random), card_color(np_random)] def is_bust(hand): # Is this hand a bust ? return False if 1 <= sum_hand(hand) <= 21 else True def sum_hand(hand): # Return current hand total return sum([card * color for card,...
This code implements a step function for a Blackjack environment. It processes a player's action (hit or stick), updates the game state, checks for bust conditions, and determines rewards and termination. If the player hits, they draw a card and may bust (ending the game with a -1 reward). If the player sticks, the dea...
def step(self, action): assert self.action_space.contains(action) if action: # hit: draw another card from the deck self.player.append(draw_hand(self.np_random)) if is_bust(self.player): done = True reward = -1 else: d...
def get_xpath_list( self: "Mif25Parser", xml: ET.ElementTree, query: str ) -> ET.ElementTree: """Return the list of node satisfy query.""" return xml.xpath(query, namespaces=self.namespace) def process_name(self: "Mif25Parser", names: ET.ElementTree) -> Name: """Process names element...
This code parses a MIF25 XML file by extracting interactor data, including names, cross-references, types, and organism information, and stores the structured data in a dictionary for further processing or analysis.
def parse(self: "Mif25Parser", path: str) -> None: """Parse the mif25 file. Args: path: path of the mif25 file. """ xml_parser = ET.XMLParser(remove_blank_text=True) xml = ET.parse(path, xml_parser) # Currently, assuming there is only one entry node and inte...
def convert_to_coordinates(x_pos:float, y_pos:float) -> list: x_coord = (right_bound - left_bound) * x_pos + left_bound y_coord = (top_bound - bottom_bound) * y_pos + bottom_bound return [y_coord, x_coord] def in_area(coordinate:list) -> int: i = 1 for area in get_groups(group_file): bound =...
This code analyzes an image to calculate dark pixel occupancy in specific areas. It samples pixels at intervals defined by 'res', checks if pixels are dark (R<20), and counts occurrences per area using 'in_area()'. It then computes the percentage of dark pixels relative to each area's total pixels, updating a global re...
def get_area_occupancy(file): img = Image.open(file) img_width, img_height = img.size print('img size: ' + str(img_width) + ',' + str(img_height)) for x in range(0, img_width): if x % res != 1: continue for y in range(0, img_height): if y % res != 1: ...
def terraform_apply(ctx): """Execute terraform apply command.""" project = ctx.config.run.env.project env = ctx.config.run.env.name with ctx.cd(f"terraform/{env}"): ctx.run(f"TF_VAR_project={project} terraform apply") def pipeline_build(ctx): """Generate pipeline YAML for Vertex AI Pipeline...
The main task of the code is to execute a deployment workflow by applying Terraform configurations, building and pushing CI/CD pipelines, and constructing/pushing Docker images, all orchestrated through the `deploy` function to automate infrastructure and application deployment processes.
def deploy(ctx): """Execute all tasks for deployment""" terraform_apply(ctx) pipeline_build(ctx) pipeline_push(ctx) docker_build(ctx) docker_push(ctx)
def set_complex_link(self, bond): self.initial_complex.set_bond_to_link(bond) def set_fragment_link(self, bond): self.initial_fragment.set_bond_to_link(bond) def prepare_fragment(self): """ It prepares the input fragment for later fragment replacement techniques to generate new m...
This code initializes a Fragment object by preparing a fragment structure for replacement in a protein-ligand complex. It loads the complex and fragment structures, sets bonding points using specified atoms, and creates a deep copy of the fragment for preparation. The method links the fragment to the complex's topology...
def __init__(self, initial_complex, fragment, bond_atoms, resname, top_complex=None, top_fragment=None): """ It initialices a Fragment object and generates the prepared strcuture for the fragment according to the target complex. Parameters ---------- ini...
def _load_table_of_not_exists(self, model): logging.debug('does database exists with name=%s', model.__name__) my_cursor = self._get_cursor() sql = 'SHOW TABLES' logging.debug('executing sql=%s', sql) my_cursor.execute(sql) if not self._exists(my_cursor, model.__name__): ...
This code persists an instance to a database by generating and executing SQL INSERT/UPDATE statements based on whether the instance has an ID. It validates the model/schema, loads necessary tables, handles pre-persist operations, and returns the saved instance with its ID updated if newly inserted.
def save(self, instance, model=None): """ Save the instance provided. :param instance: instance of object to save :param model: Specify what model/table to save to. :return: persisted instances will be returned. Although implementation may modify the original instance itself ...
def evaluate(self): start = time() eval = Evaluate() val = eval.eval(self.board) self.evaluate_cnt += time() - start return val def move_order(self, move_list, depth, max_depth): move_list.sort(key=lambda move: self.evalmove(str(move)), reverse=True) if depth: ...
This function performs a quiescence search in a chess AI using alpha-beta pruning. It evaluates board positions, checks for endgame conditions (checkmate, stalemate, repetition), and prioritizes capture moves. It recursively explores legal moves, updating alpha/beta bounds to prune branches, ensuring efficient evaluati...
def Quies(self, alpha, beta): if self.board.is_checkmate(): return -100000 if self.board.is_stalemate(): return 0 if self.board.is_repetition(3): return 0 val = self.evaluate() if val >= beta: return beta if val > alph...
def Quies(self, alpha, beta): if self.board.is_checkmate(): return -100000 if self.board.is_stalemate(): return 0 if self.board.is_repetition(3): return 0 val = self.evaluate() if val >= beta: return beta if val > alph...
The code implements a Principal Variation Search (PVS) algorithm with alpha-beta pruning for a chess engine. It evaluates positions recursively, considering depth, time limits, and game-ending conditions (checkmate, stalemate, repetition). It uses move ordering, null move pruning, and tracks the principal variation (pv...
def pvSearch(self, depth, alpha, beta, maxDepth, pline): line = [] if time() - self.start > self.timeout and maxDepth >= 5: self.is_timeout = True return alpha pv_search = False if depth == 0: return self.Quies(alpha, beta) if self.board.i...
def calcTotalPayloads(jObj, counter): aux = jObj if isinstance(aux, list): for i in range(0, len(aux)): counter = calcTotalPayloads(jObj[i], counter) else: counter += 1 return counter def getJSONData(jsonObject, path): result = jsonObject for i in range(0, len(path)): result = result[path[i]] return re...
The code reads JSON network data, extracts payloads, converts them into a numerical array based on specified bit-length (1/4/8), and returns a pandas DataFrame containing processed payload data, limited by maxPayloads.
def importJSONData(filePath, payloadPath, bitLength = 1, maxPayloads = 100): if(bitLength != 1 and bitLength != 4 and bitLength != 8): print("Please enter a valid bitLength. Either 1, 4 or 8 bits.") exit() global totalIterations print("Storing JSON file data in a pandas DataFrame ... ") # Open JSON file cont...
def genius_GET(method, payload): # This is the root URL of the Genius API rootURL = "https://api.genius.com/" # This is the URL with the method appended on it methodURL = rootURL + method # Here, we'll define the headers for the GET request headers = {} headers["Authorization"] = "Bearer " + "pqcx0vgdr82coni...
The function `fieldSearch` retrieves song-related data from an API by searching for a song and artist, then extracts specific fields from the result. It constructs a GET request with the combined song title and artist, processes the JSON response into a DataFrame, identifies the top result's ID, and fetches detailed fi...
def fieldSearch(songTitle, artist): # Prepare the GET request method = "search" payload = {"q": (songTitle + " " + artist)} request = genius_GET(method, payload) # Try to convert the GET request into a DataFrame try: df = pd.DataFrame(request.json()["response"]["hits"]) df = pd.DataFrame(result for result i...
def genius_GET(method, payload): # This is the root URL of the Genius API rootURL = "https://api.genius.com/" # This is the URL with the method appended on it methodURL = rootURL + method # Here, we'll define the headers for the GET request headers = {} headers["Authorization"] = "Bearer " + "w252du0jshm3gu3...
The main task of the code is to search for a song by title and artist using a GET request, extract the first result's ID, and retrieve associated metadata via the FieldsFromSongID function, returning a DataFrame of fields or None if an error occurs.
def fieldSearch(songTitle, artist): # Prepare the GET request method = "search" payload = {"q": (songTitle + " " + artist)} request = genius_GET(method, payload) # Try to convert the GET request into a DataFrame try: df = pd.DataFrame(request.json()["response"]["hits"]) df = pd.DataFrame(result for result i...
def init_args(): args = get_args() args.address = get_address(args.address).address return args def get_property_data(address, client): property_id, listing_id = _get_property_ids(address, client) if not listing_id: print("Missing Listing ID") return client.below_the_fold(property_id) de...
The code retrieves property data from Redfin using a specified address, parses the JSON response, and prints the structured data in a human-readable format. The main task involves initializing arguments, fetching data via the Redfin API, parsing the result, and displaying it neatly.
def main(): global args args = init_args() client = Redfin() data_json = get_property_data(args.address, client) parsed_data = parse_data(data_json) pp = pprint.PrettyPrinter(indent=4) pp.pprint(parsed_data)
def parse_header(self): self.index += 12 self.request_id, self.flags, self.count_questions, self.count_answers, self.count_authorities, self.count_additional = unpack( '!HHHHHH', self.request[:self.index]) self._parse_flags() def parse_question(self): domain_name, self.index ...
This code initializes an object to parse and organize data from a request. It sets up attributes like `index`, parses the header, and extracts multiple sections (questions, answers, authorities, additions) by iterating based on their respective counts. Each section is parsed using dedicated methods, structuring the req...
def __init__(self, request): self.request = request self.index = 0 self.parse_header() self.questions = [self.parse_question() for _ in range(self.count_questions)] self.answers = [self.parse_answer() for _ in range(self.cou...
def get_sentence_length(self, low, high): return random.randint(low, high) def generate_word(self, text, k): ''' Returns a random word based on the specified text and n-grams learned by the model ''' weights = [] for v in self.vocab: prob = self.get_ne...
This function generates a continuation of the input text by appending 1-4 generated words, skipping or breaking on special "~" tokens, then capitalizing "I" and adding punctuation for a natural-sounding response.
def continue_to_say_something(self, input_text): ''' Returns a phrase that follows the user input ''' length = self.get_sentence_length(1,4) words_left = length answer = "" while words_left > 0: next_word = self.generate_word(input_text, 0.00004) ...
def get_ending_punctuation(self): # ending_punctuations = [ # '.', '...', '!', '?', '?!', '!!', ' ~ ~', # '♡', '☆', '★', ' ♫', ' ♩', ' ☽' # ] ending_punctuations = [' 😁', ' 😆', ' 🤣', ' 😉', ' 😊', ' 🥰', ' 🤩', ' 😚', ' 😋', ' 😜', ' 😝', ' 🤗', ' 🤔', ' ...
The function generates a natural-sounding sentence using a probabilistic model, prioritizing completion at sentence separators ("~") over fixed length limits. It attempts up to three retries, selects starting words based on frequency weights, builds the sentence iteratively, and ensures proper capitalization, punctuati...
def say_something(self): ''' Returns a complete sentence based on the learned model ''' # to achieve a natual ending sentence, the sentence should end when reaching a sentence separator ("~") # instead of being cut off by the word limit. so we retry building the sentence for max 3 times. ...
def generate_random_atom(): r = np.random.rand(3) * box_length return [r] def generate_random_molecule(bond_length): r1 = np.zeros(3) r2 = np.random.rand(3) scale = bond_length / np.linalg.norm(r2) r2 = r2 * scale #translate r = np.random.rand(3)* box_length r1 += r r2 += r ...
This function initializes a molecular system by randomly placing non-overlapping molecules (methane, ethane, propane, butane) within a box of specified length. It attempts up to 1000 iterations per molecule to avoid overlaps with existing positions, appending valid positions to a list. If all Npart molecules cannot be ...
def init_system(box_length, Npart): positions = [] for i in range(Npart): max_iter = 1000 it = 0 while it < max_iter: if molecule_type == 'methane': mol_pos = generate_random_atom() elif molecule_type == 'ethane': mol_pos = generat...
def rotated_area(a): an = geom.Area() for curve in a.GetCurves(): curve_new = geom.Curve() for v in curve.GetVertices(): curve_new.Append(rotated_vertex(v)) an.Append(curve_new) return an def make_zig(a, y0, y, zig_unidirectional): for curve in a.GetCurves(): ...
The code generates zigzag toolpaths within a given geometric area by dividing it into horizontal strips based on the 'stepover' parameter. Each strip is intersected with the original area to create horizontal segments, and zigzag patterns are constructed by alternating direction (if enabled) across these segments. The ...
def zigzag(a, stepover, zig_unidirectional): if a.NumCurves() == 0: return global rightward_for_zigs global curve_list_for_zigs global sin_angle_for_zigs global cos_angle_for_zigs global sin_minus_angle_for_zigs global cos_minus_angle_for_zigs global one_over_units one_over...
def zigzag(a, stepover, zig_unidirectional): if a.NumCurves() == 0: return global rightward_for_zigs global curve_list_for_zigs global sin_angle_for_zigs global cos_angle_for_zigs global sin_minus_angle_for_zigs global cos_minus_angle_for_zigs global one_over_units one_over...
This function generates toolpaths for pocketing operations in CNC machining. It creates offset contours based on tool radius, stepover, and zig-zag parameters, then processes these contours to produce cutting paths at specified depths. The function handles both conventional and climb cutting modes, with options for rec...
def pocket(a,tool_radius, extra_offset, stepover, depthparams, from_center, keep_tool_down_if_poss, use_zig_zag, zig_angle, zig_unidirectional = False,start_point=None, cut_mode = 'conventional'): global tool_radius_for_pocket global area_for_feed_possible tool_radius_for_pocket = tool_radius if keep_...
def fMod(f, m): return [rMod(f[0], m), rMod(f[1], m)] def fMult(f1, f2): return [rAdd(rMult(f1[0], f2[1]), rMult(f1[1], f2[0])), rAdd(rMult(f2[1], f1[1] ), rMult(rMult(f1[0], f2[0]), [5, 1] ))]
This function computes the modular exponentiation of a raised to the power p modulo m using a recursive approach. It employs exponentiation by squaring, splitting into even/odd cases to reduce the exponent recursively, ensuring efficient computation of a^p mod m by breaking the problem into smaller subproblems with mod...
def power_mod(a, p, m): if p == 1: return fMod(a, m) if p%2 == 1: return fMod(fMult(a, power_mod(fMod(fMult(a, a), m), p//2, m)), m) return fMod(power_mod(fMod(fMult(a, a), m), p//2, m), m)
def fScal(r, f): return [rMult(r, f[0]), rMult(r, f[1])] def rInv(r): return [r[1], r[0]] def fDet(f): return rSub(rMult(rMult([5, 1], f[0]), f[0]), rMult(f[1], f[1])) def rScal(s, r): return rRed([s*r[0], r[1]])
The main task of the code is to compute the inverse of a mathematical object `f` by applying reciprocal operations to its determinant and components. It returns a scaled version of the reciprocal determinant combined with a modified rational part, likely handling complex or structured numerical inverses.
def fInv(f): #print("scalar = ", rInv(fDet(f))) #print("irrational part = ", f[0]) #print("rational part = ", f[1]) return fScal(rInv(fDet(f)), [f[0], rScal(-1, f[1])])
def get_tokens(self, text): text = text.encode("ascii", "ignore").decode() # remove emoji tokens = re.split(r'[ |+|\n|\u2026|:|;|?|!|"|\]|\[|~|/|&|(|)|*]', text) return tokens def handle_entity(self, idx): term = self.text_tokens_list[idx] end_with = False if not term.en...
This function parses and processes text tokens by handling entities, numbers, hashtags, and hyphenated terms. It filters out stop words, processes numerical ranges, and extracts valid terms, appending them to a document-term list.
def parse_sentence(self, text: str): self.text_tokens_list = self.get_tokens(text) idx = 0 while idx < len(self.text_tokens_list): term = self.text_tokens_list[idx] next_term = None # handle entity if len(term) > 0 and term[0].isupper(): ...
def parse_sentence(self, text: str): self.text_tokens_list = self.get_tokens(text) idx = 0 while idx < len(self.text_tokens_list): term = self.text_tokens_list[idx] next_term = None # handle entity if len(term) > 0 and term[0].isupper(): ...
The code parses a document by extracting metadata (tweet ID, date, text, URLs) and processing the full text. It removes "t.co" links by modifying the text using indices, parses URLs into terms, and constructs a Document object with processed text, terms, and metadata for further analysis.
def parse_doc(self, doc_as_list): tweet_id = doc_as_list[0] tweet_date = doc_as_list[1] full_text = doc_as_list[2] url = doc_as_list[3] indices = doc_as_list[4] retweet_text = doc_as_list[5] retweet_url = doc_as_list[6] quote_text = doc_as_list[8] ...
def retrieve_docs(passages: str, passages_embeddings: str, retriever_path: str, dataset: str | List[DataQA], output_file: str, num_chunks: int = 1, chunk_idx: int = 0, n_docs: int = 3 ...
The code processes a dataset through rollout generation, document retrieval, perplexity-based reward computation, and SFT dataset preparation. It checks for pre-existing outputs, reusing them if available, otherwise generating data using specified models and parameters. The final output is a prepared dataset ready for ...
def main(args) -> List[DataQA]: dataset: str = os.path.join(args.dataset_folder, args.dataset_name, f"{args.split}.json") if not os.path.isfile(dataset): raise FileNotFoundError ### Rollout ### print("Rollout start!") output_file = os.path.join(args.output_folder, args.dataset_name, f"r...
def t1(clients_send,temp_,username): mes1='SEND ' + username + '\n \n' mes1=mes1.encode() clients_send[temp_[1]].send(mes1) def error_103(connectionSocket): msg4='ERROR 103 Header incomplete\n \n' connectionSocket=s_sd_cl(msg4, connectionSocket) def dlt(username,clt,clt1): del clt[username] ...
The function processes incoming messages to handle different scenarios: if the message starts with 'RECEIVED', it triggers `t1` for client updates; if the second part is '103', it sends an error response and removes the user from client lists; otherwise, it handles another error type. The main task is to manage message...
def not_all_recipients(message,clients_send,connectionSocket,username): temp=message.split() if temp[0] == 'RECEIVED': t1(clients_send, temp, username) elif temp[1] == '103': error_103(connectionSocket) dlt(username,clients_send,clients_recv) else: error_102(temp_, cl...
def check(username): i=0 while i<len(username): if not username[i].isdigit(): if not username[i].isalpha(): return False if username[i].isdigit() or username[i].isalpha(): i=i+1 return True def s_sd_cl(msg4,connectionSocket): connectionSocket=send...
The main task of the code is to handle client communication by registering users for sending/receiving messages, validating commands, and forwarding messages to specified recipients. It processes incoming data, checks username validity, manages client sockets in dictionaries, and handles errors like invalid recipients ...
def communicate(connectionSocket, addr,temp): username=temp[2] if len(temp)<1: connectionSocket.close() sys.exit() return if not check(username): msgg='ERROR 100 Malformed username\n \n' connectionSocket=s_sd_cl(msgg,connectionSocket) sys.exit() elif ch...
def hierarchical_type_prefix_str(self, hierarchical_type_prefix): return 'struct' if hierarchical_type_prefix == CppHierarchicalTypeDefinition.STRUCT else \ 'class' if hierarchical_type_prefix == CppHierarchicalTypeDefinition.CLASS else \ 'union' if hierarchical_type_prefix == C...
This function generates a C++ class/struct declaration string from a hierarchical type object, including its name, inheritance, and members categorized by access level (public, protected, private), with proper syntax formatting and indentation.
def hierarchical_type_str(self, hierarchical_type): prefix_str = self.hierarchical_type_prefix_str(hierarchical_type.hierarchical_type) name_str = hierarchical_type.name if hierarchical_type.base_types: inherits = [self.inheritance_str(i) for i in hierarchical_type.base_type...
def get_id(self) -> str: """Gets the spark-submit submission ID Returns: str: spark-submit submission ID (returns -1 if no code) """ return self.submit_response['submission_id'] def _get_status_response(self) -> str: if self.is_yarn: status_cmd = f'yarn a...
This function checks the submission status of a Spark job by retrieving its driver state from a status response. It parses the response using regex, logs a warning if "driverState" is missing, updates the job's driver state in submit_response, and marks the job as concluded afterward.
def _check_submit(self) -> None: if self.get_id() and not self.concluded: response = self._get_status_response() driver_state = re.findall(r'"driverState" : "(.+)"', response) if len(driver_state) < 1: logging.warning(f"driverState not found in output \"{resp...
def get_id(self) -> str: """Gets the spark-submit submission ID Returns: str: spark-submit submission ID (returns -1 if no code) """ return self.submit_response['submission_id'] def _get_kill_response(self) -> Tuple[str, int]: if self.is_yarn: kill_cmd = ...
The code's main task is to terminate a running Spark job in cluster mode by sending a kill request, updating the job's state to 'KILLED', and handling errors if the job has already concluded or lacks a submission ID. It logs warnings for concluded jobs, raises exceptions for invalid states, and ensures proper state tra...
def kill(self) -> None: """Kills the running Spark job (cluster mode only) Returns: None """ if self.concluded: logging.warning( f"Spark job \"{self.spark_args['name']}\" " f"has concluded with state \"{self.submit_response['driver...
def get_initial_opinions(cluster_number): initial_opinions = [] for i in range(num_agents): initial_opinions.append(opinion_timeline_agents[i][0]) peoria_initials = initial_opinions[0:max_node_array[0]] bloomington_initials = initial_opinions[cluster_range[1][0]:cluster_range[1][1]] quincy...
This function simulates the evolution of opinion dynamics within a specific cluster over 99 time units. It initializes cluster opinions, calculates driving forces, iteratively updates opinions using these forces, and tracks the percentage of non-zero opinions over time. The results are stored in a DataFrame and visuali...
def get_change_simulated(edge_props, cluster_index): simulated_percentage_overtime = [] # initial state # initial_state_all = [0,opinion_timeline_agents[:,0]] # initial_state_this_cluster = initial_state_all[cluster_range[i][0]:cluster_range[i][1]] # simulated_percentage_overtime.append(initial_st...
def calculate_carbon(e_buy): if e_buy > 0: c_co2 = e_buy # electricity bought from main grid; kwh P_CO2 = P_price # RMB/Kg carbon_cost = P_CO2 * c_G_buy * c_co2 + 0.56*e_buy else: carbon_cost = 0*e_buy return carbon_cost def calculate_degrade(power_FC,FC_pre_power,power_EL,EL...
The function calculates an overall reward for an energy system by combining carbon emission costs, battery degradation costs, and penalties/rewards for system states (e.g., battery and hydrogen storage levels). It uses sigmoid functions to normalize costs, applies weights (0.8 for carbon, 0.2 for degradation), and aggr...
def calculate_cost(time_step,pv_power,wt_power,p_fc,pre_p_fc,p_el,pre_p_el,p_bat,e_buy,soc_bat,soc_h2,delta_m,m_fcv): carbon_cost = calculate_carbon(e_buy) degrade_cost = calculate_degrade(p_fc,pre_p_fc,p_el,pre_p_el,p_bat) degrade_cost = 0 if degrade_cost < 0 else degrade_cost degrade_cost = sigmoid(d...
def draw_sunny_day(): # draw the house draw_house('yellow', 'light yellow', 'brown', 'red') # Draw the sun penup() setheading(30) forward(50) dot(20, 'orange') penup() def draw_starry_night(): # draw the house draw_house('navy', 'orange', 'yellow', 'black') # draw the moon ...
The main task of the code is to visualize a sequence of steps by drawing labeled scenes (sunny, starry, cloudy, gloomy days) and dynamically placing/moving images across the screen based on directional commands (East, West, North, South) within a turtle graphics environment. It handles initial scene setup, image placem...
def visualise(steps): penup() pencolor('black') goto(-(cell_size * 6), cell_size) draw_sunny_day() goto(-(cell_size * 6), (cell_size - 30)) write('A : A sunny day!', align='left', font=big_font) goto(-(cell_size * 6), -(cell_size * 2)) draw_starry_night() goto(-(cell_size * 6), -(cel...
def get_mode(self): return self.mode def find_cover_loop(self,X, first=None): """This method is executed in a loop executor. It finds the cover points""" logger.info(f'find_cover_loop={X}') if X.shape[0]>0: self.accum_data.append(X) cover=self.cover if...
The main task of the code is to determine the operational mode and execute corresponding processing on input data X. It checks the mode: if "find_cover", it runs a coverage search loop; if "split_loop", it splits X into subsets. Otherwise, it returns nothing. The function acts as a dispatcher, routing input to specific...
def master_loop(self,X): try: mode=self.get_mode() if mode=='find_cover': self.find_cover_loop(X) return None if mode=='split_loop': subsets=self.splits_loop(X) return subsets # ...
def create_cmd_line(args): cmd_line = LPB_CMD_LINE for arg, val in args.items(): arg_key = '{' + arg + '}' cmd_line = cmd_line.replace(arg_key, str(val)) return cmd_line def capture_process_data(arguments): res = defaultdict(lambda: []) proc = subprocess.Popen(arguments, stdout=subpr...
The code runs a benchmark by iterating over combinations of sessions, detection frequencies, and sample rates. For each combination, it executes a command, captures process data, extracts metrics like CPU/GPU usage, transcoding duration, and real-time ratios, then saves aggregated results to a CSV file.
def run_bench(args): try: sessions = list(range(1, int(args.sessions_list) + 1)) except: sessions = eval(args.sessions_list) freqs = eval(args.detection_freq_list) rates = eval(args.detection_sample_rate_list) args_grid = product(sessions, freqs, rates) res_list = [] for sess...
def get_determinant(matrix_, dimensions): """Calculates the determinant of a matrix given its dimensions and the matrix itself.""" # Base case, if the square matrix is of dimensions 1X1 if int(dimensions[0]) == int(dimensions[1]) == 1: return int(matrix_[0][0]) # Base case, if the square matrix...
The code computes the inverse of a square matrix using the adjugate method. It calculates the determinant, constructs the cofactor matrix, transposes it to form the adjoint, and scales by the reciprocal of the determinant. If the determinant is zero, it handles the error by printing that the matrix is non-invertible; o...
def get_inverse(matrix): det_matrix = get_determinant(matrix, [len(matrix), len(matrix[0])]) cof_matrix = get_cofactors_matrix(matrix) adjoint = transpose_through_main(cof_matrix, [len(cof_matrix), len(cof_matrix[0])]) try: inverse_matrix = multiply_constant(adjoint, 1 / det_matrix) except Z...
def get_pos(h, w): return [(w + i[0], h + i[1]) for i in space_ship()] def paint_blocks(stdscr, blocks, string): for s in blocks: stdscr.addstr(s[1], s[0], string) stdscr.refresh() def cycle(blocks): possible_blocks = get_possible(blocks) new_blocks = check_dead(possible_blocks, blocks) + ch...
The code creates an animated text-based interface using the curses library. It continuously cycles and redraws blocks (patterns) on the screen, creating a moving effect by alternating between displaying "x" and clearing with " " (space). The blocks are centered within the terminal window, updating their positions in a ...
def main(stdscr): stdscr.clear() curses.start_color() curses.curs_set(0) height, width = stdscr.getmaxyx() blocks = get_pos(height // 2, width // 2) while True: paint_blocks(stdscr, blocks, "x") time.sleep(0.01) paint_blocks(stdscr, blocks, " ") blocks = cycle(bl...
def do_consume(self, queue_ref: Queue[tuple], event_ref: Event): print(f'{__name__}: Worker {self.id} awaiting work.') # Wait for the producer to signal that work is available... event_ref.wait() print(f'{__name__}: Worker {self.id} woke up.') # Get the work item. clie...
This method determines the next state of a worker by evaluating its current state, transitioning to appropriate actions like consuming from a queue, receiving data, handling tasks, or resetting. It manages state transitions for processing workflows, error recovery, and task completion, returning the next state or termi...
def do_next(self, queue_ref: Queue[tuple], event_ref: Event): if self.state == WORKER_ST_IDLE: return WORKER_ST_CONSUME elif self.state == WORKER_ST_CONSUME: return self.do_consume(queue_ref, event_ref) elif self.state == WORKER_ST_RECV: return self.do_recieve...
def transform_coords_to_img(path, height, s, tx, ty): new_path_x = (path[:, 0] - tx) / s new_path_y = height - (path[:, 1] - ty) / s return np.vstack((new_path_x, new_path_y)).T.astype(np.int32) def show_result(imgs, title): if not imgs: return False height, width = i...
This function identifies and tracks an opponent vehicle by processing occupancy grid data. It transforms grid points into map coordinates, filters obstacles within track boundaries, clusters detected points, and publishes the largest cluster's centroid as the opponent's position. Debug visualization and message publish...
def get_opponent(self): if self.grid is None: return # self.visualize_occupancy_grid() # Calculate wall points map_v = self.map[:, :, 0].flatten() map_x = self.map[:, :, 1].flatten() map_y = self.map[:, :, 2].flatten() map_x = map_x[map_v > 0] ...
def get_opponent(self): if self.grid is None: return # self.visualize_occupancy_grid() # Calculate wall points map_v = self.map[:, :, 0].flatten() map_x = self.map[:, :, 1].flatten() map_y = self.map[:, :, 2].flatten() map_x = map_x[map_v > 0] ...
This callback processes the robot's inferred pose from a particle filter, updating its global position and orientation. It identifies the opponent, checks visualization parameters, and triggers rendering of grids, obstacles, opponent poses, and bounding boxes if enabled. The frame count is incremented for tracking.
def pose_callback(self, pose_msg): """ The pose callback when subscribed to particle filter"s inferred pose Args: pose_msg (PoseStamped or Odometry): incoming message from subscribed topic Returns: """ # Read current state if self.real_test: ...
def favicon(): icon_path, *_ = icon_data(negative=True) return SvgFragment( (0, 0, 64, 64), [Path(d=square(64, anticlockwise=True) + icon_path)]) def logo(): inner_r = 4 icon_path, (c1x, c1y), (c2x, c2y), (c3x, c3y) = icon_data( base_width=5, inner_r=inner_r) return SvgFragme...
The main task of the code is to generate SVG files from predefined SVG AST nodes and save them to a specified directory. It creates three SVG files—'favicon', 'logo', and 'logo_and_text'—by writing their respective AST nodes to individual `.svg` files within the provided destination directory.
def main( dest_dir: 'The directory to which to write output files'): svgs = { 'favicon': favicon().svg_ast_node, 'logo': logo().svg_ast_node, 'logo_and_text': logo_and_text().svg_ast_node } for name, svg in svgs.items(): with open(os.path.join(dest_dir, name + '.svg')...
def f1(n, l, m): prod = 1 while True: if n <= 0: break prod = prod * (1/n) * (l/m) n -= 1 return prod def f2(n, l, m): prod = l/m n -= 1 while True: if n <= 0: break prod = prod * (l / m) / n n -= 1 return prod def pi0(c...
The function `mmc` computes key performance metrics for an M/M/c queueing system. It calculates values like system utilization (`f1`, `f2`), steady-state probabilities (`pi0`), expected time and number in queue (`etq`, `enq`), system time (`et`), system count (`en`), Erlang formula (`erlang`), and blocking probability ...
def mmc(c, l, m, Pmax, display = False): _f1 = f1(c, l, m) _f2 = f2(c, l, m) _pi0 = pi0(c, l, m) _etq = etq(c, l, m, _pi0) _enq = enq(c, l, m, _pi0) _et = et(c, l, m, _etq) _en = en(c, l, m, _et) _erlang = erlang(c, l, m, _pi0) _fc = fc(l, m, Pmax) if display: print(f"f1 ...
def mkdir(path_to_dir): """ Make a new directory at "path_to_dir". Parameters ---------- path_to_dir : str Path to directory that will be created. Returns ------- None """ if not os.path.exists(path_to_dir): os.mkdir(path_to_dir) def write_precomputed(block, pa...
The function `write_to_local` saves segmentation labels and associated 3D meshes to a specified directory. It creates subdirectories for mesh data, writes labels using `write_precomputed`, saves meshes via `meshing.save_mesh`, and generates segment properties. The task involves organizing and persisting labeled segment...
def write_to_local(labels, meshes, root_dir): """ Writes labels and meshes as precomputed to subdirectory in "root_dir". Parameters ---------- labels : numpy.array Segmentation. meshes : dict Dictionary of meshes where the keys are object ids and values are meshes. r...
def move_through_path(blocks, snake, path): reference = path.pop() x1, y1 = snake[0].get_index() x2, y2 = reference.get_index() if y1-y2 == 1: # UP return move_snake(blocks, snake, 0) elif y1-y2 == -1: # DOWN return move_snake(blocks, snake, 1) elif x1-x2 == -1: # RIGHT r...
The function `move_random` randomly selects a valid direction for a snake to move within a grid, checking neighboring cells for 'blank' or 'path' tiles. If valid neighbors exist, it shuffles them and attempts movement, returning a game-over status. If no valid moves are available, it loops until a random valid directio...
def move_random(blocks, snake): neighs = snake[0].get_neighbours(blocks) neighs = [x for x in neighs if x.kind == 'blank' or x.kind == 'path'] if len(neighs) > 0: random.shuffle(neighs) game_over = move_through_path(blocks, snake, neighs) return game_over else: while True...
def load_data(data_directory): # create a list of all the sub directories in this folder (each one is a letter) directories = [d for d in sorted(listdir(data_directory)) if isdir(join(data_directory, d))] # numerical labels for each letter labels = [] # all the images in t...
This code trains a convolutional neural network (CNN) to classify hiragana characters using TensorFlow. It loads training images, builds a CNN with two convolutional layers, dropout, and a fully connected layer, then trains the model for 20 steps. After training, it evaluates the model on test data, preprocesses images...
def train_neural_network(): # where the data is on my computer ROOT_PATH = "/Users/jamienelson/Documents/CS 585" train_data_directory = join(ROOT_PATH, "hiragana_images") # load the data for training images, labels, one_hot_encoding, letter_lookup = load_data(train_data_directory) # ...
def create_dicts(): file_name = input("file name? ") open_file = open(file_name, "r") word_rating = {} # sentiments word_count = {} # counts updated_file = no_punc(open_file) for line in updated_file: line = line.strip() line = line.lower() for word in line.split(): ...
The main task of the code is to provide a menu-driven interface for querying word scores, calculating file averages, updating scores based on user feedback, and displaying statistical information like minimum/maximum values or categories. It interacts with dictionaries storing word counts and ratings, allowing users to...
def main(): (word_count, word_rating) = create_dicts() action = '0' while action != '5': action = print_prompt() if action == '1': word = input("which word? ") print("score = " + str(word_rating[word])) print(word, end = " ") file_avg(...
def collect_company_urls(ctx: BrowserContext, company_name: str) -> dict[str:str]: page = ctx.new_page() page.goto('https://apps.apple.com') # accept regional redirection continue_btn = page.wait_for_selector(selector="#ac-ls-continue", state="visible") continue_btn.click(delay=get_delay_ms()) ...
The code crawls app information from a company's website by first locating the company's URL, extracting app URLs, and then gathering details from each app page. It uses Playwright for browser automation, supports headless mode and logging, and returns a list of app data.
def crawl_company_apps(company_name: str, **kwargs) -> dict[str:Union[str, list]]: log = ... if kwargs.get('print'): log = print company_name = company_name.lower() data = [] with sync_playwright() as p: browser = p.chromium.launch( headless=kwargs.get('headless', False)...
def game_level1(self): self.run_logic() ## --- Changes I am Making for my Second Level --- ## if len(self.good_block_list) == 0 and len(self.bad_block_list) == 0: self.level += 1 for i in range(24): # Changin...
This function manages game states based on the current level. It triggers specific instructions or game levels (-1 to 3), updates the game state, and renders the display frame. When reaching level 4, it sets a win condition and displays the final frame.
def game_logic(self, screen): if (self.level == -1): instructions1.number_1(screen) elif (self.level == 0): instructions2.number_2(screen) elif (self.level == 1): self.game_level1() self.display_frame(screen) elif (self.level == 2): ...
def stop_servos(): serial_arduino.write(STOP) wait_for_char(ROGER_THAT) def dispense_victims(side, number): for i in range(0, number): if side == 0: left_packet() pass else: right_packet() pass def signaling_victim(): print("Signaling victi...
The code monitors two thermal sensors, checks if either temperature exceeds 28°C, stops servos if true, and dispenses victims based on which sensor triggered the threshold. It prioritizes dispensing victims with specific parameters depending on the sensor reading, ensuring safety by halting operations when temperatures...
def check_thermal_sensor(): temperature1 = thermal_sensor1.get_object_1() temperature2 = thermal_sensor2.get_object_1() if temperature1 > 28 or temperature2 > 28: stop_servos() if temperature1 > 28: dispense_victims(1, 0) else: dispense_victims(1, 1) s...
def login(self): for i in range(10): try: self.obj=SmartConnect(api_key=self.angel_api_keys) data = self.obj.generateSession(self.angel_client_id,self.angel_password,pyotp.TOTP(self.angel_token).now()) refreshToken= data['data']['refreshToken'] ...
The code's main task is to continuously monitor the market opening time (9:30 AM IST). When the market opens, it authenticates, fetches BANKNIFTY's LTP, places a market order, then processes Nifty options data and executes the main logic. If the main function returns "complete," it exits. Exceptions are logged, ensurin...
def websocket(self): while True: try: if time(9, 30) <= datetime.now(timezone("Asia/Kolkata")).time() and self.market=="undone": self.login() self.banknifty_price=self.obj.ltpData("NSE", 'BANKNIFTY', "26009")['data']['ltp'] ...
def value_function_second_to_last(wealth, worker, wage, interest_rate, beta, delta): """Value function in the second to last period. Args: wealth (float): wealth worker (bool): indicator for worker wage (float): wage interest_rate (float): interest rate beta (float): dis...
The code computes the value function, consumption, and work decisions for a two-period economic model. It evaluates optimal choices for workers and retirees across wealth grids, using parameters like interest rate and wage. The solution involves backward induction, calculating period-1 values first, then determining pe...
def create_solution(wealth_grid, simulation_grid, params): """Create solution of 2-period model. Args: wealth_grid (np.array): grid of wealth simulation_grid (np.array): grid of simulation params (dict): parameters Returns: np.array: value function np.array: consumpt...
def _fit(self, samples): self.w = np.nanstd(samples, axis=0) def prime_argmin_gt(func, thresh=0.05, x0=1, x_max=100, forbiddenmultiples=[12], args=()): """Find minimum integer with function evaluation greater than some threshold which is prime and not a factor of given set of numbe...
The function `fit_gof` optimizes the number of skips required to decorrelate time series data in `sample_a` and `sample_b`, then performs a goodness-of-fit (GOF) test. It calculates optimal skip counts (`n_skip_a`, `n_skip_b`) to meet a target p-value, computes statistics (`T`, p-value) for uncorrelated subsets, and ag...
def fit_gof(self, sample_a, sample_b, n_k, n_skip_0=1, max_skip=100, p_val=0.05, loop_skip_opt=True, periodics=[12], loop_test_meth='simple'): """ Optimise skips and run GOF test. Fit the number point time points that must be skipped to decorrelat...
def _calculate_mu(n_a, n_b): """Calculate the expected test statistic if samples were from same distribution.""" n = n_a+n_b return (n_a*(n_a-1) + n_b*(n_b-1)) / (n*(n-1)) def _calculate_sigma(n_a, n_b, n_k): """Calculate the expected standard deviation of the test stati...
This function performs a goodness-of-fit test between two samples by combining them, calculating statistical metrics (mu_T, sigma_T), and determining a test statistic (T) and p-value to assess distribution similarity. It optionally shuffles data, computes neighbor-based statistics, and returns results for hypothesis te...
def gof(self, sample_a, sample_b, n_k, shuffle=False, seed=None, log_matches=False): """ Carry out the test of goodness of fit between two samples """ # data processing mixed_samples = np.concatenate((sample_a, sample_b), axis=0) classes = np.con...
def rentalduration(self): return (self.end_date - self.start_date).days+1 def createaction(self,actor,price): who = actor action_type ="" if actor == "driver": action_type = "debit" else: action_type = "credit" action = { "who": who, ...
The main task of the code is to generate a list of financial actions (driver, insurance, assistance, drivy, owner) based on rental duration, price, and selected options. It calculates individual costs, applies commissions, and incorporates optional fees (GPS, baby seat, insurance). The function returns these structured...
def setactions(self): duration = self.rentalduration() actions = [] driver = self.createaction("driver",self.price) actions.append(driver) commission = self.calculatecommission() #options gps = 0 baby_seat = 0 additional_insurance = 0 if "...
def width(self): return terminal_width() - len(self.line_start) def terminal_lines(lines: str | List[str], width=terminal_width()) -> int: """Return the lines as they would be printed to the terminal.""" if isinstance(lines, list): lines = "".join(lines) lines = lines.splitlines(True) or [""...
The main task of this code is to update the terminal display by rendering lines from `term` (derived from input `lines` or `self._value`), comparing them with existing lines in `self._term_lines`, and efficiently updating mismatched lines. It handles cursor positioning, line clearing, and partial updates to minimize fl...
def draw(self, lines: str | List[str] = None): if lines is None: lines = self._value width = self.width() hidden = False term = terminal_lines(lines, width) logger.debug(f"Drawing {term} on {self._term_lines}") mismatch = self._mismatch_index(term) lim...
def draw(self, lines: str | List[str] = None): if lines is None: lines = self._value width = self.width() hidden = False term = terminal_lines(lines, width) logger.debug(f"Drawing {term} on {self._term_lines}") mismatch = self._mismatch_index(term) lim...
This code replaces a substring in a document by splitting the input string into lines, modifying the first and last lines with specified prefixes and suffixes, reconstructing the lines with proper newlines, and updating the document's value. It also adjusts the cursor position and redraws the display.
def replace(self, string: str, start: Cursor, end: Cursor): logger.debug(f"Replacing {string} {start} {end}") lines = string.split("\n") line_start = self._value[start.row][: start.column] line_end = self._value[end.row][end.column :] # TODO: Have terminal_lines() handle this? ...
def terminal_lines(lines: str | List[str], width=terminal_width()) -> int: """Return the lines as they would be printed to the terminal.""" if isinstance(lines, list): lines = "".join(lines) lines = lines.splitlines(True) or [""] new_lines = [] for line in lines: end = "" if ...
This method processes an input value (string or list of strings) by formatting it to fit the terminal's width, updates the UI display, moves the cursor to the end of the text, and ensures the cursor is visible. It handles text adjustment, rendering, and cursor positioning for terminal-based output.
def set(self, value: str | List[str]): self._value = terminal_lines(value, self.width()) self.draw() self.jump_to_end() show_cursor()
def draw(self, lines: str | List[str] = None): if lines is None: lines = self._value width = self.width() hidden = False term = terminal_lines(lines, width) logger.debug(f"Drawing {term} on {self._term_lines}") mismatch = self._mismatch_index(term) lim...
This method adjusts a cursor's position within a text area based on given motion, handling edge cases like negative rows, exceeding lines, and column constraints by adjusting rows and columns, then updates the target cursor and triggers movement with optional flushing.
def move(self, motion: CursorMotion, flush=True): row = self._target_cursor.row col = self._target_cursor.column row = row + motion.row if row < 0: self._value = (["\n"] * -row) + self._value self.draw() self.set_target(Cursor()) return ...
def regions(): """menu of regions for user to select""" location = inquirer.select( message="Where will you go?", choices=["Revelstoke", "Jasper", "Squamish", "Banff", Choice(value=None, name="Exit")], ).execute() return location def actions(): """options menu""" print("\n") ...
The code provides an interactive tool for checking avalanche reports, weather forecasts, gear recommendations, and slope evaluations in specific mountain regions (Jasper, Squamish, Revelstoke, Banff). It allows users to select a region and navigate through safety-related data, with options to switch regions or return t...
def main(): """main driver function""" location = None hello_text = pyfiglet.figlet_format("AVI-CHECK", font="colossal", width=110) bye_text = pyfiglet.figlet_format("See you later", font="colossal", width=110) print(hello_text) print(" Welcome to AVI-CHECK, your one stop for trip planning and m...
def _start_session(self): while True: try: password = "" while password == "": password = getpass.getpass(f"password for '{self.location}': ") sess = session.Session( hostname=self.hostname, p...
The code's main task is to execute a sequence of system configuration actions, including package installations/removals, file copies/deletions, and service restarts, as defined in a scenario. It tracks execution time, manages sessions, and conditionally runs a rehearsal phase. The operations are performed in a structur...
def run(self): self.session = self._start_session() start = time.perf_counter() # 0. rehearsal start if self.rehearsal: self._execute_rehearsal_start() # 1. package installs for pkg in self.scenario.packages: if pkg.action == "install": ...
def get_state(self, peer_socket): if peer_socket in self.peer_state: return self.peer_state[peer_socket] return None def send(self, peer_socket, message_name, message_data): msg = pickle.dumps((message_name, message_data)) print("sending message {} from {}".format(message_nam...
This function handles state-driven message sending for a peer socket in a distributed system. It checks the peer's state and sends corresponding messages ("ELECTION", "OK", "COORDINATE") while updating socket registration and state. If an unknown state is encountered, it logs an error and raises an exception. The task ...
def send_message(self, peer_socket): peer_state = self.get_state(peer_socket) if peer_state == state.SEND_ELECTION: self.send(peer_socket, "ELECTION", self.group_members) self.modify_socket_with_selector(peer_socket, selectors.EVENT_READ) elif peer_state == state.SEND_OK:...
def pr_sock(self,sock): """Printing helper for given socket.""" if sock is None or sock == self or sock == self.listener: return 'self' return self.cpr_sock(sock) def register_socket_with_selector(self, sock, event): try: self.selector.register(sock, event) ...
This code accepts a new peer connection, configures the socket for non-blocking I/O, registers it with a selector for read events, and initializes the client's state to either WAIT_FOR_OK (if the client sent an election) or WAIT_FOR_MESSAGE for further processing.
def accept_peer(self): client_sock, addr = self.listener.accept() print("accepting connection from {} with addr {}".format(self.pr_sock(client_sock), addr)) client_sock.setblocking(False) self.register_socket_with_selector(client_sock, selectors.EVENT_READ) client_state = self.ge...
def compare_process_id(self, process1, process2): if process1[0] > process2[0]: return True elif process1[0] < process2[0]: return False else: return process1[1] > process2[1] def create_and_register_peer_socket(self, member): try: peer_so...
This code initiates a leader election in a distributed system. It compares the current node's process ID with peers, sending election messages to nodes with lower IDs and marking them as QUIESCENT. If no higher ID is found, the current node declares itself the leader. The process involves checking all group members, es...
def start_election(self): print("-=-=-=-=-=-=-=- Starting Election -=-=-=-=-=-=-=-=-") self.elecion_in_progress = True highest_pid = True for member in self.group_members: if self.compare_process_id(member, self.process_id): peer_sock = self.create_and_registe...
def pr_sock(self,sock): """Printing helper for given socket.""" if sock is None or sock == self or sock == self.listener: return 'self' return self.cpr_sock(sock) def unregister_socket(self, client_sock): try: self.selector.unregister(client_sock) except K...
This function processes incoming messages from a client socket, handling "OK", "ELECTION", and "COORDINATE" commands. It updates client states, manages socket registration, triggers elections, and synchronizes group member lists. Upon "OK", it terminates the election; on "ELECTION", it updates members and initiates a n...
def parse_message(self, msg, client_state, client_sock): print("msg {} received from sock {}".format(msg, self.pr_sock(client_sock))) message_name = msg[0] data = msg[1] if len(msg) >= 2 else None if message_name == "OK": print("received OK from {} ".format(self.pr_sock(clien...
def start_game(): # Player global player player = Player(player_color, 10, 10) player.rect.x = 50 player.rect.y = 50 all_sprites_list.add(player) # Guards summon_guards() # Bushes bush3 = Bush(BUSH_COLOR, 30, 30) bush3.rect.x = player.rect.x - player.width bush3.rect....
The code defines a game loop for a Pygame-based game, handling player movement via keyboard inputs, collision detection with guards (reducing lives) and bushes (hiding the player), level progression upon reaching a win area, and game state updates. It manages game variables like level, lives, and player visibility, res...
def game(): global level global lives global player_color running = True start_game() while running: # Setting the framerate to 30fps just # to see the result properly clock.tick(30) screen.fill(SURFACE_COLOR) for event in pygame.event.get(): ...
def draw_text(text, font, color, surface, x, y): textobj = font.render(text, 1, color) textrect = textobj.get_rect() textrect.topleft = (x, y) surface.blit(textobj, textrect) def game(): global level global lives global player_color running = True start_game() while running: ...
The main task of the code is to display a main menu with two buttons ("PLAY" and "SETTINGS") using Pygame. It handles user input by detecting mouse clicks, checks if the mouse is over a button, and triggers the `game()` or `options()` functions when buttons are pressed. The loop continuously updates the screen, process...
def main_menu(): running = True while running: clock.tick(30) screen.fill(SURFACE_COLOR) draw_text('Main Menu', font, (0,0,0), screen, 200, 40) mx, my = pygame.mouse.get_pos() #creating buttons button_1 = pygame.Rect(150, 100, 200, 50) button_2 = pygam...
def unpack(self, jwt_object: str) -> Tuple[ValidationPath, dict]: """ We first need to get the unverified headers to get a hold of the certificate so we can use the certs public key to verify the jwt objects signature. The certificate chain needs to be validated first. """ header...
The main task of the code is to verify the integrity and authenticity of a Google Attestation JWS object by validating fields like nonce, APK package name, basic integrity, CTS profile, and certificate key IDs. It unpacks the attestation data, checks cryptographic signatures, and ensures compliance with Google's Safety...
def verify(self): """ Verify the given attestation based on the Google documentation. The attestation is formatted as JWS object. Raises a PyAttestException as soon as one of the verification steps fails. See also: Google Documentation https://developer.android.com/training/saf...
def pre_loop(self): pass def input(self, prompt): return input(prompt) def on_empty(self): return True def run_command(self, commands: list): cmd_args = commands if not cmd_args: self.print_error(f'No synamic command arg(s) provided to run.') return 1 ...
This code processes shell commands in a loop, handling user input, executing commands, and managing loop state. It strips input, checks for emptiness, runs commands via `run_command`, and returns the last exit code. The loop continues until input is empty and `on_empty()` returns false, or manually stopped. Pre/post-lo...
def on_shell(self, *cmd_args): self.pre_loop() self.__loop_running = True last_retcode = -1 while self.__loop_running: inres = self.input(self.prompt_text).strip() if not inres: empty_ret = self.on_empty() if empty_ret: ...
def insertSymbol(person_symbol,person_rowno,person_colno): board[person_rowno][person_colno] = person_symbol # At this place checkBoard() function is called to check the board. returned_value = checkBoard() if(returned_value=='X'): return 'X' elif(returned_value=='O'): return 'O' ...
The code simulates a two-player Tic-Tac-Toe game on a 3x3 grid. Players alternate turns entering row and column coordinates to place their symbols ('X' for Player 1, 'O' for Player 2). The game checks for a winner after each move using the playerShifting() function. If no winner is declared within 7 moves, the game end...
def main(): person1_symbol = 'X' person2_symbol = 'O' times = 7 print("Person1's turn..") person1_rowno = int(input('Enter row number(0-2):')) person1_colno = int(input('Enter column number(0-2):')) insertSymbol(person1_symbol,person1_rowno,person1_colno) printBoa...
def __initialize_dirichlet__(self): """ Initialization of the transformation database. Associate a key to each transformation. :return: updates the dictionary {transformation: key} """ dirichlet = pd.DataFrame(columns=['transformation'] + self.variables) dirichlet['trans...
The code executes an optimization algorithm to iteratively improve solutions, tracking the best Mean Absolute Error (MAE) and corresponding parameters. It runs for a set number of iterations, updating generations, selecting individuals, and adjusting probabilities. If convergence is detected (no improvement for `dead_i...
def run(self, output=True): """ Algorithm run execution. :param output: Boolean. If True then an output is printed in each iteration. Otherwise, not. :return: best_individual array, best MAE found double """ convergence = 0 self.__initialize_dirichlet__() ...
def create_line(cord1,cord2): return static_line(cord1,cord2,5) def level_failed(bypass=False): global level,targets_done,pending if bypass: pending=True targets_done=0 if not bypass: level-=1 print("Level failed! Retrying...") for bal in start_ball_moving: deacti...
This code handles user input and game logic for drawing lines with specific properties based on key presses and mouse clicks. It tracks progress (lines_done/lines_needed), creates lines with varying colors and velocities, manages game states (pending, level failure), and updates game elements like balls and platforms. ...
def observer(keys): global pending,cord1,cord2,lines_done,lines_needed,current_type,level if pending and mouse_clicked() and lines_done<lines_needed: if cord1==(-100,-100): cord1=mouse_point() elif cord2==(-100,-100): cord2=mouse_point() if current_type=='n': ...
def cost_fnct(FILENAME, v, t, size): with open(FILENAME, 'r') as file: c = csv.DictReader(file) somme = 0 for l in c: km = normalise_data(float(l['km']), v[0], v[1]) price = float(l['price']) somme += calcul0(t, km, price)**2 tmp = 1 / (2*size) *...
This code performs gradient descent to optimize parameters `t` by minimizing a cost function derived from a CSV dataset. It iteratively updates `t[0]` and `t[1]` using normalized data and calculated gradients, appending each iteration's cost to the `cost` list. The process adjusts the parameters based on the dataset's ...
def learn(FILENAME, v, size, cost): t = [0, 0] for i in range(ITER): cost.append(cost_fnct(FILENAME, v, t, size)) with open(FILENAME, 'r') as file: c = csv.DictReader(file) somme = [0, 0] for l in c: km = normalise_data(float(l['km']), v[0], v[...
def initialize_visits(bna, clinical): """Given two pathes to the bna (eeg mostly) and clinical data sets, returns a merged df (named 'visits') which contains all visits, merged to same date with both bna and clinical columns""" #Step 1: open csvs and create the 'final_date' column for each visit, to avoid ...
The main task of the code is to generate a feature matrix (X) for machine learning by merging clinical and BNA data, extracting predictive features per subject (baseline treatment start and BNA changes between visits), and returning a DataFrame of these features along with a dictionary mapping subjects to their data gr...
def generate_X(bna_path, clinical_path): #returns a tuple of df and dict """Main function of this module""" bna = pd.read_csv(bna_path) clinical = pd.read_csv(clinical_path) visits = initialize_visits(bna,clinical) # from raw data (bna and clinical dfs), creates a df named visits, a merged version of t...
def add_user(username: str, password: str) -> bool: """Adds a user to the database Args: username (str): the user's username password (str): the user's password Returns: bool: True if user was added, False if not """ user = User(username=username, hash=security.create_hash...
The code tests user and credential management functions by creating a user, generating hashes/salts, adding multiple credentials, retrieving them, updating one, deleting a credential, and removing the user. It validates operations like hash creation, credential storage, retrieval, updates, and deletion, ensuring system...
def run_tests() -> str: print(f"{security.create_hash('test')=}") add_user("test", "test") print(f"{get_user_hash('test')=}") print(f"{get_user_salt('test')=}") print(f"{add_credential('test', 'test', 'test', 'test')=}") print(f"{add_credential('test1', 'test', 'test', 'test')=}") print(f"{...
def _get_all_actions(self, data: Any) -> Generator[str, None, None]: """Recursively get all action names from workflow data""" if isinstance(data, dict): for key, value in data.items(): if key == self.workflow_action_key: yield value elif i...
This function updates a GitHub Actions workflow file by checking each action for newer versions, replacing outdated ones with the latest versions, and generating markdown notes detailing the updates. It reads the workflow YAML, ignores specified actions, fetches new versions, applies changes if available, and writes th...
def _update_workflow(self, workflow_path: str) -> set[str]: """Update the workflow file with the updated data""" updated_item_markdown_set: set[str] = set() try: with open(workflow_path, "r+") as file, gha_utils.group( f'Checking "{workflow_path}" for updates' ...