dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def qExtractRotationZ(self, quat): q = copy.deepcopy(quat) q[1], q[2] = 0, 0 mag = math.sqrt(q[0]*q[0] + q[3]*q[3]) q[0] /= mag q[3] /= mag return q def qmult(self, q1, q2): q1 = np.array(q1).reshape(4, 1) q2 = np.array(q2).reshape(4, 1) q...
The code calculates a calibrated quaternion by offsetting an input quaternion with a predefined nPose rotation, applying inverse rotations to align axes, and adjusting for sensor-specific exceptions (e.g., removing Y-axis influence for shoulders, zeroing Z-axis for calibration, and swapping X/Y for feet). It returns th...
def getOffsetQuaternion(self): qInput = self.quaternion.getQuaternionAsList() qNpose = self.quaternionOffset.getQuaternionAsList() qCalibration = self.calibrationOffset.getQuaternionAsList() ## NPOSE OFFSETING # Extract rotation Z of qOffset qNposeRotationZ = self.qExtr...
def get_mode(self): a = { ALL_TOGETHER: AggregatorDecision.GLOBAL, BY_DESTINATIONS: AggregatorDecision.GLOBAL, } return a[self.method] def get_group_of_schedules(self): return [Schedule.objects.filter(date__date=self.date)] def generate_schedule(self, schedules, a...
The main task of the code is to generate and manage an AggregatorDecision for a specific date. It deletes existing decisions with the same date, creates a new decision with the current date and mode, processes a group of schedules by generating individual schedules, and returns the newly created AggregatorDecision obje...
def generate_decision(self) -> AggregatorDecision: aggregate_decision = AggregatorDecision.objects.filter(decision_date=self.date) if aggregate_decision.exists(): aggregate_decision.delete() aggregate_decision = AggregatorDecision.objects.create(decision_date=self.date, ...
def process_book(book, *args, **kwargs) -> Dict: try: return _process_book(book, *args, **kwargs) except Exception as e: log("Error while processing: {}: {}".format(book, e)) def better(new: Dict, current: Dict) -> bool: """ Decide if the `new` version is better than the `current` one ...
The code traverses a directory tree to find ZIP files, processes them into book objects, selects the best valid book using a comparison function, adds it to the instance, and recursively processes subdirectories. It handles multilingual content and specific encodings, logging warnings if no valid book is found.
def iter_booksdir(self, orig: Path): subd = [] books = [] for elem in orig.iterdir(): if elem.is_dir(): subd.append(elem) elif elem.suffix == ".zip": books.append(elem) # Parse all books in the folder if books: ...
def three_of_a_kind(self) -> tuple[Card]: return next(iter(self._combinations(3)), None) def one_pair(self, pairs=None) -> tuple[Card]: inner_pairs = pairs if pairs is not None else self.pairs() if inner_pairs: return max(inner_pairs, key=lambda p: p[0].value) def pairs(self) -> set...
The function checks if the hand contains a full house (three of a kind plus a pair of different value). It first identifies three of a kind, then searches for a pair with a distinct value. If both exist, it returns them as a tuple.
def full_house(self) -> Optional[tuple[Card]]: triple = self.three_of_a_kind() if triple: pair = self.one_pair(pairs=[ p for p in self.pairs() if p[0].value != triple[0].value ]) if pair: return triple, pair
def processInput(self): if self.is_main_menu or self.is_game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False break elif (event.type == pygame_gui.UI_BUTTON_PRESSED and ...
(Main task: The code runs a game loop that continuously processes input, updates game state, renders frames, and maintains a 60 FPS target by calculating delta_time for consistent timing. It operates while `self.running` is True.)
def run(self): while self.running: self.processInput() self.update() self.render() self.delta_time = self.clock.tick(60) / 1000.0
def boot(self): self.com = client('slave', 'localhost', 8888) sys.stdout.write = self.write self.processor = message_processor() def main(self) -> None: """main function that runs the code""" message_list = [] multi = False to_execute = False while True: ...
The code defines a method `crash_preventer` that attempts to execute `boot()` and `main()` methods. If a `ConnectionAbortedError` or `ConnectionResetError` occurs, it recursively calls itself to retry execution, aiming to handle network-related interruptions and prevent program termination by restarting the process.
def crash_preventer(self): try: self.boot() self.main() except ConnectionAbortedError: self.crash_preventer() except ConnectionResetError: self.crash_preventer()
def speak(audio): engine.say(audio) engine.runAndWait() print(audio) def takeCommand(self): #It takes microphone input from the user and returns string output r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 ...
The code listens for voice commands like "wake up" or "hello," and upon detection, triggers the `taskExecution()` method to perform predefined tasks. It continuously waits for user input, responding only when specific keywords are recognized, indicating a voice-activated system designed to execute tasks based on verbal...
def run(self): # self.taskExecution() speak("please say wake up to continue") while True: self.query = self.takeCommand() if "wake up" in self.query or "hello" in self.query: self.taskExecution()
def getStarted(): # make sure the bot doesn't simply roll continuous for the first couple plays time.sleep(5) while not locateOnScreen("Bob.png", confidence = .9): turnTime = time.time() print("Getting Started... ", end = '\r') # status time.sleep(20) click(XY.ENEM...
This code automates a game process by waiting for specific screen elements (e.g., "Play" button, "initializer_BG"), clicking randomized positions to interact with the game, handling initialization and confirmation steps, and performing automated actions like buying/moving/playing cards during battle phases. It loops th...
def autoBG(): while not locateOnScreen('Play.png', confidence = .8) and not locateOnScreen('Alt_Play.png', confidence = .8): # wait for play to be available print("Waiting for Play button",end = '\r') # time.sleep(30) click(1400 + randint(-13,13), 880 + randint(-13,13)) # click Play! ...
def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text an...
The code generates the "Constructors" section in a class's docstring by processing constructor nodes. It adds section headers, iterates through nodes to format constructor signatures with indentation, and calls subnode parsing to handle nested elements, ensuring proper documentation structure for classes where SWIG doe...
def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', ...
def add_text(self, value): """Adds text corresponding to `value` into `self.pieces`.""" if isinstance(value, (list, tuple)): self.pieces.extend(value) else: self.pieces.append(value) def add_line_with_subsequent_indent(self, line, indent=4): """Add line of text an...
This function generates standard documentation for member definitions (memberdef_nodes) by adding docstring features, function signatures (if enabled), and parsing nodes to produce formatted output with proper indentation and syntax. It processes each node to create SWIG-compatible documentation without handling functi...
def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: ...
def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: ...
This method generates docstring entries for overloaded functions when enabled, creating a section listing each overload's documentation. If not overloaded or disabled, it uses standard handling. It adds function signatures, indented details, and parses subnodes for each overload, formatting them under "Overloaded funct...
def handle_typical_memberdefs(self, signature, memberdef_nodes): """Produces docstring entries containing an "Overloaded function" section with the documentation for each overload, if the function is overloaded and self.with_overloaded_functions is set. Else, produce normal documentation...
def _combine_sections(self, sections, segment_flags): """ _combine_sections iterates over sections and writes their content to file (satisfying alignment requirements). Finally, creates new segment and adds its information to segment header table. Additionally, updates PHDR segment and E...
The main task of the code is to merge REL file sections with specific permissions (R, RW, RWX, RX) into existing segments using `_combine_sections`, then update relocations via `_set_relocations` and adjust the entry address with `_update_entry_address` to integrate the REL data properly into the target executable.
def generate_new_segments(self): """ generate_new_segments combines rel_reader.fetch_rel_sections and _combine_sections functions in order to merge REL file sections with permissions R, RW, RWX, RX. In the end it calls _set_relocations in order to update relocations related to REL file. ...
def create_vis(self, canvas=None): """ Creates a visualisation. By default, uses a vpython canvas, so imports vpython. Subclass class and change this to change the way visualisations are made. Parameters ---------- canvas: vpython canvas display into which the...
The code runs a simulation for a specified duration (`time`), using time steps (`dt`). It initializes visualization and force display if enabled, imports `vpython` if needed, and iteratively calls `simulate(dt)` until the target time is reached or a cycle completes. It also manages real-time visualization rates and hal...
def run_for(self, time, dt=0.01): """ Run simulation for a certain amount of time(as measured in the system's time). Recommended to use this instead of simulate(dt) for most situations. Parameters ---------- time: float Time for which the simulation will go on...
def commandlineargs(): # Allowing command line arguments to change key parameters in analysis # Initial values # Step size h = 0.01 # Number of steps N = 20000 # Number of steps taken before recording a data point rec_n = 100 # Central galaxy free to move stationaryB = False # Intial Step is a RK4 step RK4...
This code simulates gravitational interactions between a stationary central galaxy, a moving galaxy, and test particles using the Verlet integration method. It initializes galaxy and particle positions, updates their trajectories over N time steps, records position data at intervals, and plots results. Key tasks includ...
def main(): # Ability to set h, N and rec_n via command line arguments as well as fixing the position of the central galaxy h, N, rec_n, e, f, iangle, fixed, RK4step, co = commandlineargs() # Records the intial wall time i.e. that measured by a stopwatch external to computer t0 = time.time() # Central stationary ...
def coq_file(args, f): rewrites = args.rewrites N = num_digits(rewrites) coq_B(f) print("Context", file=f) print(f"(* N = {N} *)", file=f) count_sig(N, f) for n in range(1, N + 1): count_lemma(N, n, f) print(".", file=f) print(file=f) hint_rewrite(N, f) print(file=f) ...
This script processes command-line arguments to generate or time proof files for Coq or Lean. It accepts rewrite counts, proof methods (autorewrite/congruence for Coq, simp for Lean), and output handling. It validates inputs, selects the appropriate theorem prover, prepares output files with correct extensions, and eit...
def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument("rewrites", type=int) parser.add_argument("-o", "--output") parser.add_argument( "-t", "--time", action="store_true", help="time running theorem prover" ) parser.add_argument( "--proof", ...
def prepare(simCtx, lines, port_id, involved_dexes): simCtx = deepcopy(simCtx) bootstrap_line = lines[0].strip() approved_tokens = bootstrap_line.split(',')[1:] bootstrap_block = int(bootstrap_line.split(',')[0]) - 1 fork_url = 'http://localhost:{}'.format(FIRST_PORT+port_id) hard_reset(fork_u...
This code simulates blockchain transaction execution on a forked network, calculates Maximum Extractable Value (MEV) through CEX/DEX settlements, and logs optimal results. It processes transaction lines, manages blockchain state, handles token balances, and returns MEV metrics while supporting best-case scenario loggin...
def simulate(simCtx, lines, port_id, involved_dexes, best=False, logfile=None, settlement='max'): simCtx = deepcopy(simCtx) # Note that nonces need to sync up with the snapshot! fork_url = 'http://localhost:{}'.format(FIRST_PORT+port_id) w3 = Web3(Web3.HTTPProvider(fork_url)) bootstrap_line =...
def getTestBits(self, repetitions): return np.tile(np.array([1,1,1,1,1,0,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,0,0,1,0,1,0,1,0,1,0]), repetitions) def receiveHammingEncoded(self, duration, repetitions=3, bits=False, from_file=False, file_path=None, save_file=False, recording_name=Non...
This code tests the accuracy of encoded data by comparing expected bits with received bits. It uses Hamming or repetition encoding to receive data, calculates differences, and computes error metrics like sum, weight, and percentage to evaluate transmission reliability.
def test(self, rec_duration, testBitRepetitions, encodeRepetitions, hamming): expected = self.getTestBits(testBitRepetitions) if hamming: actual = self.receiveHammingEncoded(rec_duration, repetitions=encodeRepetitions, bits=True, save_file=Tru...
def split_sentence_to_words_and_tags(line: str): """ Split the sentence with words and tags into 2 lists :param line: input line from text file. e.g. "'The_DT Treasury_NNP is_VBZ still_RB ._.\n" :return: [list of words in order], [list of tags in order] """ splited_words = re.split(' |[\n]', lin...
This function computes the objective function and its gradient for optimization, using features and tags from a given file. It calculates the left and right sigma components, applies softmax for gradient computation, and incorporates L2 regularization. The output is the negative of the objective (with regularization) a...
def function_l_and_gradient_l(v: np.array, *args): file_path = args[0] lam = args[1] feature_statistics = args[2] features_indices = args[3] # first part - saving all the needed 'f' values in the first iteration only (one time per train file) global active_indices_sentences_i global flatten...
def process_commandline() -> argparse.Namespace: """Process commandline, enhanced with environment variables. The ArgumentParser is split into two parsing moments; 1. First handle list and delete (and log while we are at it) 2. Handle the remaining arguments The second step may be adjusted by the ...
The main task of the code is to manage TransIP DNS records by processing command-line arguments, establishing a connection, and performing actions like listing, deleting, updating, or creating DNS records, while handling required parameters such as TTL to avoid errors.
def transip_dns_main(): """Functional process of the script. This function call out to: - process the commandline - processses the parameters to create a connection with TransIP, list the domain and provide the requested dns record - Act on the commandline by - List the domain - D...
def get_split_feature(self, data): features = list(data.columns) # if no featrues left (only target column left) if len(features) == 1: return None # removing target column from list of features features.remove("target_col") # calculating gain ratios for all features ...
The main task of the code is to recursively build a decision tree by selecting the optimal attribute to split data, handling both categorical and continuous features, and creating subtrees for each partition until base conditions (empty data, pure target, or max depth) are met.
def build_tree(self, node, data, depth, max_depth): # checking for base conditions (if depth == max_depth, or data is pure) if len(data) == 0 or data["target_col"].nunique() == 1 or (max_depth is not None and depth == max_depth): return node # getting best attribute to split the data...
def run_creation_task(self, task_number:int, previous_result:str): # NOTE, the -1 previous_task = self.task_list[task_number-1] summary_of_prevous_tasks = self.get_info_on_previous_tasks(previous_task) print("Running task creation chain") inputs:Dict = ...
This code manages a sequence of tasks by initializing a "start" task, executing each task in a loop, storing results in a vector store, dynamically adding new tasks based on previous results, and reprioritizing the task list. It iterates up to `max_runs`, updating task numbers and tracking progress, ensuring efficient ...
def run(self): # add a starting task to the task list mytask = Task(name="start", description="start") self.task_list.append(mytask) # inputs are teh objective, results, task_description, incomplete_tasks self.run_creation_task(task_number=0, previous_result="") ...
def checkConvertEmptyInputs(): # No files selected for conversion if data.convertNames == []: displayInfo(NO_CONVERT_SELECTION_TITLE, NO_CONVERT_SELECTION_PROMPT, root) return True # No save path selected elif data.convertDest == "": displayInfo(NO_DEST_TITLE,...
The main task of the code is to convert images to JPG format with specified quality settings, handling potential errors like invalid inputs, file access issues, and unsupported formats. It preprocesses images, writes the converted output to a destination file, displays success or error messages accordingly, and cleans ...
def convert(): if not checkConvertEmptyInputs(): try: q = parseQuality() preprocessImages(q) with open(data.convertDest, "wb") as f: f.write(jpgConvert(data.convertNames, dpi=72)) data.lastOutputAddress = data.convertDest di...
def ShowToDos(): # global ListOfToDos with open("todos.txt", "r") as file: ListOfToDos = file.read().split("\n") ListOfToDos = ListOfToDos[:-1] if ListOfToDos == [""]: ListOfToDos = [] with open("todos.txt", "w+") as f: f.write("\n"...
This function presents a menu for managing a to-do list, allowing users to show, add, remove, update, clear tasks, or exit. It processes user input to call corresponding functions, with error handling for invalid commands.
def Command(): print("\n(1)Show ToDos\n(2)Add ToDos\n(3)Remove ToDos\n(4)Update ToDos\n(5)Clear List\n(6)Exit App\n") command = input(">>> ") if command == "1": ShowToDos() elif command == "2": AddToDos() elif command == "3": RemoveToDos() ...
def theta(var): return np.arccos(-var) def L(var): return np.sin(np.pi-2*thetat(var))/(np.sin(thetat(var))) def thetat(var): return np.arcsin((ni/nt)*np.sin(thetai(var)))
The function `l2xcoord2` computes an x-coordinate using trigonometric expressions involving angles `theta(var)` and `thetat(var)`, combined with a length parameter `L(var)`. It calculates `-sin(theta(var)) + L(var) * cos(π/2 - theta(var) - thetat(var))`, likely modeling a kinematic or geometric transformation for a sys...
def l2xcoord2(var): # Coordinate for l2x[1] and l3x[0] return -np.sin(theta(var))+L(var)*np.cos(np.pi/2-theta(var)-thetat(var))
def L(var): return np.sin(np.pi-2*thetat(var))/(np.sin(thetat(var))) def theta(var): return np.arccos(-var) def thetat(var): return np.arcsin((ni/nt)*np.sin(thetai(var)))
The function computes a y-coordinate by adding the input variable `var` to a term involving the product of `L(var)` and the sine of an angle derived from `theta(var)` and `thetat(var)`, adjusted by π/2. This likely calculates a geometric or mechanical coordinate adjustment based on rotational angles and lengths.
def l2ycoord2(var): # Coordinate for l2y[1] and l3y[0] return var+L(var)*np.sin(np.pi/2-theta(var)-thetat(var))
def l2ycoord2(var): # Coordinate for l2y[1] and l3y[0] return var+L(var)*np.sin(np.pi/2-theta(var)-thetat(var)) def l2xcoord2(var): # Coordinate for l2x[1] and l3x[0] return -np.sin(theta(var))+L(var)*np.cos(np.pi/2-theta(var)-thetat(var)) def l1ycoord(var): # Coordinate for l2y[0] and l1y[1] return var def...
The function computes an angle theta by combining inverse trigonometric functions (arcsin, arctan) with coordinate values and constants, likely for geometric or physical modeling, using a complex formula involving ratios of y/x coordinates and parameters nt/ni.
def thetaf(var): return (-np.arcsin((nt/ni)*np.sin(np.arctan(l2ycoord2(var)/l2xcoord2(var))+np.arctan((-(l2ycoord2(var)-l1ycoord(var)))/(l2xcoord2(var)-l1xcoord2(var)))))+np.arctan(l2ycoord2(var)/l2xcoord2(var)))
def check_valid_move(self, action, ret_grid=True, bad_reward=0): ''' Returns: done: Boolean - whether the action ends the game or not grid (optional): ndarray - returns the grid with piece added color_grid (optional): ndarray - returns the color grid with piece added...
This function processes a game action by validating the move, updating the grid and score when rows/columns are cleared, resetting pieces if necessary, and determining if the game is done based on remaining moves. It returns whether the game is completed and the accumulated reward.
def execute_action(self, action): done, grid_manip, color_grid_manip, reward = self.check_valid_move(action) if done: return True, reward # Reward for any rows/columns completed rows = [] cols = [] for y in range(self.grid_shape[0]): ...
def check_valid_move(self, action, ret_grid=True, bad_reward=-50000): ''' Returns: done: Boolean - whether the action ends the game or not grid (optional): ndarray - returns the grid with piece added color_grid (optional): ndarray - returns the color grid with piece ...
This code processes a game action by validating moves, clearing completed rows/columns, updating rewards, and determining game completion. It checks for valid moves, updates the grid state, calculates rewards for cleared lines, resets pieces if needed, and returns whether the game is done along with the reward.
def execute_action(self, action): done, grid_manip, color_grid_manip, reward = self.check_valid_move(action) if done: return True, reward # Reward for any rows/columns completed rows = [] cols = [] for y in range(self.grid_shape[0]): ...
def usage(): print() print("Commands:") print(" init\t\t\t Initialize the config") print(" build\t\t\t Build the project") print(" run\t\t\t Build and run the project") print(" clean\t\t\t Remove the build directory") print(" config\t\t View the config") print(" help\t\t\t Show thi...
The main task of the code is to handle command-line arguments for a build/config tool, executing actions like initialization, building, running, cleaning, or displaying configuration based on the provided subcommand (e.g., "init", "build", "run", "clean", "config"). It delegates tasks to corresponding functions and ens...
def main(): if len(sys.argv) <= 1: usage() elif sys.argv[1] == "init": init_config(config=CONFIG, config_loaded=config_loaded) elif sys.argv[1] == "build": build(CONFIG) elif sys.argv[1] == "run": if build(CONFIG): run(os.path.join(CONFIG.build_dir, CONFIG.bin...
def get_commands(self) -> list: files = listdir(self.__directory) cmds = [] for f in files: name, ext = path.splitext(f) if ext in [".sh", ".bash", ".zsh"]: cmds.append(name) return cmds def parse_args(self) -> None: self.arg_parser = Argum...
This code initializes a command-line application by setting its name, description, and command directory. It retrieves available commands, parses command-line arguments, and executes the application.
def __init__(self, name: str, description: str, commands_dir: str) -> None: self.app = name self.desc = description self.__directory = path.abspath(commands_dir) self.commands = self.get_commands() self.parse_args() self.run()
def next_move(x, y, board): min_degree_index = -1 min_degree = N + 1 next_x = 0 next_y = 0 start = randint(0, 1000) % N for cnt in range(0, N): i = (start + cnt) % N next_x = x + dx[i] next_y = y + dy[i] degree = get_degree(next_x, next_y, board) if can...
The code attempts to solve the Knight's Tour problem on an N×N chessboard, starting at (0,0). It iteratively finds valid moves using `next_move`, marks the board, and checks if the final position connects back to the start (if `closed=True`). If successful, it prints the board and returns `True`; otherwise, returns `Fa...
def knights_tour(closed=True): board = [[-1 for _ in range(N)] for _ in range(N)] start_x = 0 start_y = 0 board[start_y][start_x] = 1 x = start_x y = start_y for _ in range(N * N - 1): x, y = next_move(x, y, board) if x == -1 and y == -1: break if closed an...
def describe_collection( self, collection_name: str, extra: bool = True, timeout: int = None ) -> dict: """Describe the named collection. Args: collection_name (str): Name of the collection. extra (bool, optional): Whether to include extra easier to read data. Defaul...
The main task of the code is to search a vector database collection for vectors similar to input data, applying filters and returning top-k results with optional fields and vectors. It handles parameters, checks collection existence, constructs queries, processes results, and optionally retrieves vector data for each h...
def search( self, collection_name: str, data: Union[List[list], list], search_params: dict = None, top_k: int = 10, filter_expression: str = None, output_fields: List[str] = None, include_vectors=False, partition_keys: List[Union[str, int]] = None,...
def build_huffman_tree(data): frequency = defaultdict(int) for char in data: frequency[char] += 1 heap = [HuffmanNode(char, freq) for char, freq in frequency.items()] heapq.heapify(heap) while len(heap) > 1: left = heapq.heappop(heap) right = heapq.heappop(heap) mer...
The main task of the code is to compress client-received data using Huffman coding. It decodes incoming data, constructs a Huffman tree, generates binary codes, prints ASCII and Huffman representations, creates a frequency table, compresses the data, and sends the compressed result back to the client via the socket con...
def handle_client(client_socket): try: data = client_socket.recv(1024).decode('utf-8') print(f"Received data from client: {data}") # Build Huffman tree and get codes root = build_huffman_tree(data) huffman_codes, huffman_tree_codes = build_huffman_codes(root) # Prin...
def _get_absolute_path(self, concat=''): return f'{self._base_path}/{concat}' def _ignore_file(self, file): move_file(self._get_absolute_path(file), f'{self.not_processed_path}/{file}') def sheets_copy(self, wb): output, created = self.get_output_file() if created: output.rem...
This code processes an Excel file by validating its existence and format, loading it into a workbook object, copying its sheets, and handling errors by ignoring invalid files while logging issues.
def process(self, file): if not self._base_path: raise 'base path is required' if not is_file(self._get_absolute_path(file)): self._ignore_file(file) print('not is a file:', file) return try: wb = load_workbook(self._get_absolute_path(...
def clean_up(path): """Remove all entries in the config DB and delete directories""" CONFIG_DB_CLIENT.backend.delete("/pb", must_exist=False, recursive=True) CONFIG_DB_CLIENT.backend.delete("/eb", must_exist=False, recursive=True) CONFIG_DB_CLIENT.backend.delete( "/script", must_exist=False, rec...
The main task of the code is to test metadata generation for a processing block, including creating metadata, adding files, and updating their statuses. It verifies that generated metadata matches expected outputs, checks metadata updates after file additions, and confirms status changes are correctly reflected in the ...
def test_metadata_generation(): """ Test generating a metadata, adding files and updating status """ # Wipe config db and directories clean_up(f"{MOUNT_PATH}/product") # Create eb and pb create_eb_pb() # Get processing block iD for txn in CONFIG_DB_CLIENT.txn(): pb_list = ...
def clean_up(path): """Remove all entries in the config DB and delete directories""" CONFIG_DB_CLIENT.backend.delete("/pb", must_exist=False, recursive=True) CONFIG_DB_CLIENT.backend.delete("/eb", must_exist=False, recursive=True) CONFIG_DB_CLIENT.backend.delete( "/script", must_exist=False, rec...
This test verifies that attempting to add a file with an existing path to metadata raises a ValueError, ensuring duplicate file paths are prevented. It cleans test data, retrieves processing block details, compares metadata, and triggers an exception when duplicating a file path "vis.ms" to validate proper error handli...
def test_with_duplicate_file_path(): """ Check if the file with same path has already been added to the list." """ # Wipe config db and directories clean_up(f"{MOUNT_PATH}/product") # Create eb and pb create_eb_pb() # Get processing block iD for txn in CONFIG_DB_CLIENT.txn(): ...
def get_data() -> NoReturn: '''Reads an input file. Extracts MD parameters and trajectory data.''' if mode == 0: file_name = r"\ideal\ideal.xyz" elif mode == 1 or mode == 2: file_name = r"\water\water.xyz" elif mode == 3: file_name = r"\set1\set1.xyz" elif mode == 4: ...
The main task of the code is to compute and visualize the Radial Distribution Function (RDF) by retrieving data, initializing RDF parameters, calculating RDF values, normalizing them, outputting the results, and generating visualizations.
def main() -> NoReturn: get_data() init_RDF() calc_RDF() normalise_RDF() output_RDF() viz_RDF()
def generate_data() -> np.array: "Produce training set coords data" pos = generate_pos(n_atoms) cell = 0 while cell == 0: cell = generate_cell() data = np.concatenate((pos, cell), axis = 0) return data def output_GMIN(data: np.array, file_pos: int) -> NoReturn: # Note: Output functions ...
The main task of the code is to generate a training dataset by repeatedly creating feature data samples, flattening them into rows, and storing them in a NumPy array. It then passes this dataset to two functions: `output_GMIN` for individual sample processing and `output_BayesOpt` for Bayesian optimization using the fu...
def main(): training = np.empty([n_training, n_features]) for i in range(n_training): data = generate_data() data_as_row = data.flatten() training[i] = data_as_row output_GMIN(data, i + 1) output_BayesOpt(training)
def _make_normal(self): """Make sure we use the normal settings.""" self.hard_mode = False self.settings.bar_speed = 3 self.settings.ball_speed = 1 self.settings.brick_hp = 1 self.settings.brick_points = 10 self.settings.brick_hp_scale = 1.4 def _start_game(self):...
This function handles keypress events in a game, controlling a bar's movement (left/right), activating normal/hard game modes (via 'P'/'H' keys) when inactive, and quitting the game (via 'Q'/'ESC'). It sets flags for movement and triggers mode/start/quit methods based on key inputs.
def _check_keydown_events(self, event): """Respond to keypresses.""" if event.key == pygame.K_RIGHT: # Make the bar move right. self.bar.moving_right = True elif event.key == pygame.K_LEFT: # Make the bar move left. self.bar.moving_left = True ...
def _make_normal(self): """Make sure we use the normal settings.""" self.hard_mode = False self.settings.bar_speed = 3 self.settings.ball_speed = 1 self.settings.brick_hp = 1 self.settings.brick_points = 10 self.settings.brick_hp_scale = 1.4 def _start_game(self):...
The code handles mouse clicks on buttons to control game states. It checks if the play button is clicked to start the game, toggles the help menu visibility when the help button is clicked, and switches to hard mode when the hard mode button is clicked, initiating game actions like starting or resetting the game.
def _check_buttons(self, mouse_pos): """Respond when the player clicks the play button.""" if ( self.play_button.rect.collidepoint(mouse_pos) and not self.stats.game_active and not self.menu.drawn ): # The player clicked the play button. ...
def _quit_game(self): """Quit the game and check the high score.""" # Check the high score. self.sb.check_high_score() # Quit the program. pygame.quit() sys.exit() def _check_keydown_events(self, event): """Respond to keypresses.""" if event.key == pygame...
This method handles Pygame events by checking for quit signals, keyboard inputs (keydown/up), and mouse clicks. It triggers corresponding callbacks for key and mouse actions, then checks for collisions between the ball and bricks to update game interactions.
def _check_events(self): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: # Quit the game. self._quit_game() elif event.type == pygame.KEYDOWN: # Pass the event to the keyd...
def handle_keys(event, running, screen, cells, size): if event.type == pygame.QUIT: pygame.quit() return running, False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: running = not running update_screen(screen, cells, size) if event.key...
This function manages a game loop for a cellular automaton, handling user input, updating cell states, rendering the grid, displaying rules and statistics, and controlling the game's runtime with pauses. It processes events, updates the screen, and maintains the game state based on user interactions and predefined rule...
def game_loop(running, screen, cells, max_alive): while True: for event in pygame.event.get(): running, flag = handle_keys( event, running, screen, cells, c.CELLS_SIZE ) if not flag: return if pygame.mouse.get_pressed()[0]: ...
def display_rules(screen): default_font = pygame.font.Font(None, 21) rules_text = ['HOTKEYS', 'Press "Spacebar" to pause', 'Press "c" to reset field', 'Press "q" to quit game',] text_offset = 30 for rule in rules_text: text = default_font.ren...
The code initializes a Pygame game by setting up the display window, creating a grid of cells, rendering the game grid and rules, calculating initial statistics, updating the screen, and launching the game loop with initial parameters. It prepares the game environment for further interaction and simulation.
def game_init(): pygame.init() screen = pygame.display.set_mode(c.SCREEN_SIZE) cells = np.zeros( (c.SCREEN_HEIGHT // c.CELLS_SIZE, c.ACTIVE_WIDTH // c.CELLS_SIZE) ) screen.fill(c.COLOR_GRID) display_rules(screen) max_alive = 0 calculate_and_display_stats(screen, cells, max_alive)...
def HandleProxy(request): url = request.GET.get("url", None) if (not url): url = request.POST.get("url", None) if (not url): return HttpResponse("url not specified") try: response = proxy_view(request, url) except Exception as e: return HttpResponse(f"ERROR: whil...
The function `Common` processes HTTP requests by routing them based on the URL path. It checks for proxy requests, handles authorization, serves registered API endpoints, and falls back to rendering templates or static files. It also manages secured routes and Python module execution, returning appropriate responses or...
def Common(request): path = request.path[:-1] if request.path.endswith("/") else request.path if ( path.endswith("favicon.ico")): return HttpResponse(f"{path}!!"); rpaths = [c for c in request.path.split("/") if (c) ]; if len(rpaths) and rpaths[0] == "proxy": return HandleProxy(requ...
def scale_down_counts(counts,times=1): ''' scales down the whole matrix "counts" by a factor of 2^times ''' if times==0: return counts assert counts.shape[0] > 8, 'No further scaling down allowed' cts = np.zeros(tuple((np.array(counts.shape[:2])/2).astype('int'))+(3,)) #...
This function scales the counts data by a specified factor, adjusts the number of bins in the model based on the scaled counts, and updates the model if the bin dimensions are inconsistent. It returns the scaled counts array.
def scale_counts(self,times=0): key_counts = 'counts' if self.params['correlation_model']=='shifted' else 'counts_unshifted' counts = scale_down_counts(self.model[key_counts],times) self.params['nbins'] = counts.shape[0] self.update_bins(self.params['nbins']) if self.model['p_s...
def update_bins(self,nbins): self.params['nbins'] = nbins self.params['arrays'] = self.build_arrays(nbins) def load_footprints(self,loadPath,s=None): ''' function to load results from neuron detection (CaImAn, OnACID) and store in according dictionaries TODO: ...
The code builds a 2D neuron matching probability model by analyzing spatial neuron distances and footprint correlations across sessions. It iterates through sessions, aligns data to a reference session, calculates kernel density, and updates histograms for nearest neighbors (NN) and non-nearest neighbors (nNN). The mod...
def build_model(self,save_results=False): ''' Iterate through all sessions in chronological order to build a model for neuron matching. The model assumes that the closest neuron to a neuron in the reference session ("nearest neighbor", NN) has a high probability of being the same neuron. Ne...
def scale_counts(self,times=0): key_counts = 'counts' if self.params['correlation_model']=='shifted' else 'counts_unshifted' counts = scale_down_counts(self.model[key_counts],times) self.params['nbins'] = counts.shape[0] self.update_bins(self.params['nbins']) if self.model['p_s...
The main task of the code is to visualize and compare the probability distribution of "same" particle pairs ($p_{same}$) and their counts in a joint model of correlation and distance. It generates 2D plots for single-model fits (correlation/distance) against data, and 3D surface plots for joint $p_{same}$ and counts ov...
def plot_p_same(self,times=0,animate=False): counts = self.scale_counts(times) nbins = counts.shape[0] self.update_bins(nbins) X, Y = np.meshgrid(self.params['arrays']['correlation'], self.params['arrays']['distance']) fig = plt.figure(figsize=(8,10)) ax_corr = [...
def get_rigs() -> list: global rigsDB # Get all the tables in the database rows = rigsDB.execute("SELECT name FROM sqlite_schema WHERE type='table';") rigs = [] for row in rows: rigs.append(row) # Make a list of each rig in the database return rigs def select_show(): # window with a...
The code initializes a GUI application for managing ArtNet connections and rig data. It sets up a Tkinter window with controls to add/delete heads, displays a head list, connects to a SQLite database, and starts an ArtNet connection. The interface includes a show selector, resizable panels, and event bindings for user ...
def main(): global artnetConnection atnetSetup = setup_window.setup_window() artnetConnection = StupidArtnet( atnetSetup[0], atnetSetup[3], atnetSetup[2], atnetSetup[1]) try: artnetConnection.start() except: # error message if not establishable pass # Initialal ...
def saveDataToObject(self, showPopup: bool = True): if self.objIndex >= len(self.allObj): return vox = VoxMLObject() # Entity if len(str(self.ui.entityType.text())) > 0: vox.Entity.Type = str(self.ui.entityType.text()) # Lex if len(str(s...
This function creates a new VoxML object based on a template, updates the UI to display relevant attributes and sections, and saves data. It appends a new object to the list, sets the UI selection, hides irrelevant elements, and conditionally shows specific UI components (entity, lex, type, etc.) depending on the templ...
def createNewVoxMLObject(self, template: str, create: bool = True): if self.objIndex >= 0: self.saveDataToObject() if create: self.allObj.append(VoxMLObject()) self.ui.chooseVoxMLObject.addItem(template) self.ui.chooseVoxMLObject.setCurrentIndex(len(self.a...
def saveDataToObject(self, showPopup: bool = True): if self.objIndex >= len(self.allObj): return vox = VoxMLObject() # Entity if len(str(self.ui.entityType.text())) > 0: vox.Entity.Type = str(self.ui.entityType.text()) # Lex if len(str(s...
This function updates the UI to reflect the selected VoxML object by saving current data, loading the new object's data, displaying its image or 3D mesh based on available resources, and showing a confirmation message. It handles both image and mesh visualization, toggling visibility of elements like the block frame an...
def changeSelectedVoxMLObject(self): self.saveDataToObject(False) self.objIndex = self.ui.chooseVoxMLObject.currentIndex() self.loadDataToEditing() self.createNewVoxMLObject(str(self.allObj[self.objIndex].Entity.Type), False) self.ui.blockFrame.show() objName = self.ui....
def saveDataToObject(self, showPopup: bool = True): if self.objIndex >= len(self.allObj): return vox = VoxMLObject() # Entity if len(str(self.ui.entityType.text())) > 0: vox.Entity.Type = str(self.ui.entityType.text()) # Lex if len(str(s...
This method loads 3D models/images from a file based on the specified type (vox/obj/img), saves existing data if needed, processes the file using appropriate loaders, stores results in dictionaries, adds objects to a list, and updates the UI with new entries and visual feedback.
def addObjectFromFile(self, inpath: str, type: str) -> None: if self.objIndex >= 0: self.saveDataToObject() if inpath != None and len(inpath) > 0: if type == "vox": objs = self.loader.loadFileToObject(inpath) elif type == "obj": objs = ...
def discover_url_params(self): # TODO: Docstrings guessed_params = {path: parse.urlparse('%s/%s' % (self.base_url, path)).query for path in self.valid_paths['guessed']} discovered_params = {path: parse.urlparse('%s/%s' % (self.base_url, path)).query ...
The code's main task is to identify and collect input sources from URLs, form fields, and browser cookies by calling respective discovery functions, then store the results in instance attributes for further processing or analysis.
def discover_inputs(self): """ Calls URL parameter, form input field, and browser cookie discovery functions. Assigns results to 'discovered_params', 'discovered_fields', and 'discovered_cookies' attributes, respectively :return: None """ self.discovered_params = self.di...
def stage_thrust(vessel, stage): stage_engines = [engine for engine in vessel.parts.engines if engine.part.stage >= stage > engine.part.decouple_stage] if len(stage_engines) == 0: return 0 return sum(e.available_thrust for e in stage_engines) def stage_delta_v(vessel, stage): other_mass = 0 ...
This function calculates the total burn time required for a rocket to achieve a specified delta-v by iterating through each stage. It uses the Tsiolkovsky equation to determine mass flow rates, subtracts achievable delta-v per stage, and accumulates burn time. If stages are exhausted before delta-v is met, it returns N...
def get_burn_time(vessel, delta_v): burn_time = 0 remaining_dv = delta_v stage = vessel.control.current_stage while remaining_dv > 0: if stage < 0: return None f = stage_thrust(vessel, stage) curr_dv = min(stage_delta_v(vessel, stage), remaining_dv) remaining_...
def install_tensorflow_extension( args, compat, download_tf_=False, download_tf_lite_=False, download_tf_deps_=False, download_tf_lite_deps_=False, download_tf_tools_=False, ): global CONST_release_pkg, CONST_lib_ext, CONST_lib_dir, CONST_env_path download_tf = download_tf_ down...
The code installs WasmEdge plugins by validating plugin names, versions, and system compatibility, downloading plugin archives from GitHub, extracting them, and copying them to specified directories. It handles TensorFlow-related plugins by installing dependencies and ensures proper placement based on the target path.
def install_plugins(args, compat): global CONST_lib_dir url_root = "https://github.com/WasmEdge/WasmEdge/releases/download/" url_root += "$VERSION$/WasmEdge-plugin-$PLUGIN_NAME$-$VERSION$-$DIST$_$ARCH$.tar.gz" if len(args.plugins) >= 1: for plugin_name in args.plugins: plugin_versio...
def ssidgen(self): # def ssidgen(): os.system("ls -1 /etc/NetworkManager/system-connections/ > /tmp/wifilist.txt") with open("/tmp/wifilist.txt", 'r') as file_handle: # read file content into list lines = file_handle.readlines() # print list content self.groupBox = QG...
This code initializes a GUI window for a Wi-Fi QR code generator, sets window properties, generates SSID and password data, creates a Wi-Fi QR code using the extracted parameters, saves it as '/tmp/key.png', and prepares to open the generated image. The main task is to generate and save a Wi-Fi QR code with specific au...
def __init__(self): super().__init__() self.title = "wifiqr-gui" self.top = 200 self.left = 400 self.width = 400 self.height = 100 self.iconName = "icon.png" self.ssidgen() self.xdgop = "xdg-open '/tmp/key.png'" ssidraw = self.button_pushed...
def ScanWithShowing(): current = datetime.now() oh,om = current.hour,current.minute #if oh > 5 or (oh==5 and om>30): # raise TimeoutError(f"{bcolors.FAIL} Wach la7bib 7ab ta3milna data? afta7 brk 9bal 7isa wla during {bcolors.BOLD}hada 9adar yakhrab system des absences aghla9 aghla9") presents = ...
This code reads student data from a CSV file, presents a menu for managing attendance and points, and executes tasks like scanning presence, adding points (with double points for leaders), resetting absences, and session data. It handles user input to perform specific operations on student records, ensuring proper data...
def main(): StudentClasses = [] with open(os.path.join("Data","coding.csv")) as f: f.readline() reader = csv.reader(f) for i,stud in enumerate(reader): StudentClasses.append(student(stud[0],stud[1],stud[2],stud[3],stud[4],stud[5],stud[6],i+1)) print("\n\n") print("\t\...
def transmit_model(self, only_parameter=True, featurizer=True, classifier=True): assert featurizer or classifier # _classifier.weight = # _classifier.bias = """ Description: Send the updated global model to selected/all clients. This method coul...
The code implements a three-stage federated learning process: 1) Training a shared featurizer via FedAvg across clients, 2) Training personalized local classifiers using ERM on clients, and 3) Training a center classifier with ERM+MinDiff to balance performance and fairness. It includes model transmission, client updat...
def fit(self): """ Description: Execute the whole process of the federated learning. Stage 1: FedAvg. Train a featurizer using FedAvg. Stage 2: Local classifier training. Train a local classifier using ERM. Stage 3: Center classifier training. Train a cent...
def main_help_text(self): """ Returns the script's main help text, as a string. Return different commands grouped by modules. """ usage = [ "", "Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name, "", "...
The main task of the code is to determine the subcommand from command-line arguments, generate an appropriate parser for that subcommand, and either display help information or execute the command. It handles cases where no arguments are provided by defaulting to help, checks for help subcommands to display relevant gu...
def execute(self): """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ try: subcommand = self.argv[1] except IndexError: subcommand = help_subcommands[...
def create_heatmap_representations(self, source_image, kp_driving_value, kp_source_value): """ Eq 6. in the paper H_k(z) """ spatial_size = source_image.shape[2:] gaussian_driving = kp2gaussian(kp_driving_value, spatial_size=spatial_size, kp_variance=self.kp_variance) gau...
This code processes input images and keypoints to generate a deformed source image, deformation map, occlusion mask, and heatmap representation. It uses sparse motion fields derived from keypoints, combines them with heatmaps, and applies a hourglass network for refinement. The output includes deformed imagery, motion-...
def forward(self, source_image, kp_driving_value, kp_driving_jacobian, kp_source_value, kp_source_jacobian): source_image = self.down(source_image) bs, _, h, w = source_image.shape heatmap_representation = self.create_heatmap_representations(source_image, kp_driving_value, kp_source_value) ...
def subSample(dataset, ratio): sample = [] nSample = round(len(dataset)*ratio) while (len(sample) < nSample): index = randrange(len(dataset)) sample.append(dataset[index]) return sample def buildTrees(train, maxDepth, minSize, nFeatures): root = getSplit(train, nFeatures) split(root, maxDepth, minSize, nFeatu...
The code implements a random forest algorithm by training multiple decision trees on subsampled datasets, each with a specified maximum depth and minimum size. It constructs 'nTrees' trees, using 'nFeatures' for splitting, then aggregates predictions via bagging (averaging) for the test set. The function returns the ag...
def random_forest(train, test, maxDepth, minSize, sampleSize, nTrees, nFeatures): trees = [] for i in range(nTrees): sample = subSample(train, sampleSize) tree = buildTrees(sample, maxDepth, minSize, nFeatures) trees.append(tree) predictions = [baggingPredict(trees, row) for row in test] return (predictions)
def parse_annotations( translation_unit: clang_index.TranslationUnit, filter_fn: Callable[[clang_index.Cursor], bool], ) -> Dict[str, List[AnnotationDescriptor]]: res: Dict[str, List[AnnotationDescriptor]] = defaultdict(list) for k, v in fetch_annotations(translation_unit.cursor, filter_fn): res...
The code parses a C/C++ translation unit into a structured SourceModel, extracting class and function types with optional filtering. It uses annotations parsed from the unit to build the model, applying a filter function to determine which cursors to process. If the translation unit is valid, it returns a SourceModel c...
def parse_source_model( translation_unit: clang_index.TranslationUnit, filter_fn: Callable[[clang_index.Cursor], bool] = lambda _: True, ) -> SourceModel: if translation_unit: annotation_map = parse_annotations(translation_unit, filter_fn) return SourceModel( class_types=parse_c...
def __get_local_ip(self): return MyIp().get_ip() def __generate_qrcode_bytes(self,data): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=1, border=1, ) qr.add_data(data) qr.make(fit=True) ...
The main task of the code is to handle commands related to retrieving local IP addresses and generating QR codes in different formats (base64 bytes or ASCII art) based on input arguments. It also processes connection-related tasks or exits with help if no valid command is provided, while catching exceptions to display ...
def __action(self, args): try: if args.ip_address: ip_type = args.ip_address if ip_type == 'qrcode_base64': ip = self.__get_local_ip() base = self.__generate_qrcode_bytes(ip) print(base) elif...
def pre_process_two_clause(self): """ Count and store the two_clause_dict """ two_clause_count = defaultdict(int) for clause in self.formula: if len(clause) == 2: for lit in clause: two_clause_count[abs(lit)] += 1 for lit, c...
The main task of the code is to solve a SAT problem using the CDCL algorithm, check the validity of the solution if satisfiable, generate an unsatisfiability proof if needed, and output results. It processes input clauses, runs CDCL, records runtime, validates solutions with SolutionChecker, writes solution and statist...
def solve(self, input_file, output_file): """ First, it will run the cdcl to see if there a satisfiable solution If satisfiable: it will run the SolutionChecker to check if the solution is valid Elseif unsatisfiable (and if proof activated): it will call the UnsatProver to generate an un...
def mean_x (x): mean_x = sum(x)/len(x) return round (mean_x,2) def median (x): list_2 = list.sort() if n%2 != 0: median = int (((n+1)/2)-1) return list[median] else: median1 = int((n/2)-1) median2 = int(n/2) return (list[median1] + list[median2])/2 def std_dev (x...
This function calculates the skewness of a dataset using the formula: 3 × (mean - median) / standard deviation. It first computes the mean, median, and standard deviation of the input data, then applies the formula to quantify the asymmetry of the distribution. A positive result indicates right-skewed data, while a neg...
def skewness (): skewness = 3*(mean_x(list - median(list))/std_dev(list)) return skewness
def login_success(): session() def password_not_recognized(): # print("working...") global screen4 screen4 = Toplevel(screen) screen4.title("Failed") screen4.geometry("150x100") screen4.configure(bg="#ffcccb") Label(screen4,text="",bg="#ffcccb").pack() Label(screen4, text="Incorrect ...
The code verifies user login by checking if the entered username exists as a file and if the password matches the content of that file. It retrieves input from GUI fields, clears them, checks for file existence, reads stored credentials, and triggers success or error functions based on validation.
def login_verify(): # print("working...") username1=username_verify.get() password1=password_verify.get() usernamee_entry1.delete(0,END) password_entry1.delete(0,END) list_of_files= os.listdir() if username1 in list_of_files: file1=open(username1,"r") verify=file1.read().spl...
def game_start(): global game_state,random_color display_surface.fill(grey) r = random.randrange(0, 255) g = random.randrange(0, 255) b = random.randrange(0, 255) rand_color = (r, g, b) print_sth("press 'ESC' to quit at anytime" , green , (90 , 10) , font_4) print_sth('SNAAKE BOII' , ran...
The code defines a game loop that continuously runs while `game_isActive` is True. It checks the current `game_state` and calls corresponding functions: `game_start()` for 'start', `game_in()` for 'in', and `game_over()` for 'over', printing the state each iteration. The loop manages game flow by responding to state ch...
def game_loop(): while game_isActive == True: print(game_state) if game_state == 'start': game_start() if game_state == 'in': game_in() if game_state =='over' : game_over()
def add_password(id): if password_exists(id): if get_user_consent('overwrite', id): force_delete_password(id) else: print('Adding new password aborted.') return keyring.set_password(keyring_system, id, password()) print_success_message('added', id) def delete_password(id): if not...
This script manages Ansible vault passwords stored in the GNOME keyring. It allows users to add, delete, or retrieve passwords based on the provided action (`add`, `del`, or default retrieval). The `--vault-id` parameter specifies the vault ID linked to the password. If no action is specified, it outputs the stored pas...
def main(): parser = argparse.ArgumentParser(description= ''' Provide ansible vault passwords from the gnome keyring. ''', ) parser.add_argument('action', nargs='?', default=None, help=''' `add`: Add a password to the keyring. `del`: Delete a password from the keyring. If acti...
def _is_zip(file_bytes: bytes) -> bool: try: return file_bytes.startswith(b"\x50\x4B\03\04") except TypeError: return False def _match_to_dict(match: Union[yara.Match, List[yara.Match]]) -> Union[List[Dict], ...
This function scans ZIP files (from bytes/BytesIO or file path) to extract and analyze contents, applying matching rules to detect patterns. It handles password attempts, recursively scans nested ZIPs (up to max depth), processes PDFs, and returns matches with locations and tags, logging warnings for inaccessible files...
def _scan_zip(self, payload: Union[bytes, BytesIO, str], filename: str = None, passwords: List[str] = None, _current_depth: int = 0): if isinstance(payload, str): if not path.exists(payload): raise FileNotFoundError(f"{payload} not found") ...
def _submit_prompt( self, prompt, context, engine=None, temperature=None, max_tokens=None, n=1, display=True, ): if engine is None: engine = self.engine if temperature is None: temperature = self.temperature ...
This method processes a user prompt within a conversation context, submits it to a model, counts tokens, and stores both the prompt and generated response in a database. It manages conversation history, updates token counts, and ensures the conversation title is set if undefined.
def talk_to_me(self, prompt, context=None): if context is None: context = self.database._get_context(self.conversation_id) if self.system is not None: context = [{"role": "system", "content": self.system}] + context new_message = self._submit_prompt(prompt, context) ...
def fetch(self, url: str): print('HTTP GET request to URL: %s' % url, end='') res = requests.get(url) print(' | Status code: %s' % res.status_code) return res def content_empty(content): obj = content.find("div", {'class': 'layout-standard'}) if obj: return "...
This code scrapes property listings from Zoopla.co.uk for a given postcode district, iterating through pages to collect data on for-sale/rent properties. It constructs URLs, fetches HTML content, checks for results, parses relevant data, and stores findings. The loop terminates when no more results are found or a max_p...
def run(self, post_code_district: str, listing_type: str = "for-sale", search_radius: int = 0, mode: str = 'w', max_page=None, sleep_between_pages=1): page: int = 1 last_page: bool = False try: while not last_page: ...
def create_and_stock_shop(): # Initialise an instance of the shop data class s = Shop() # Read in stock csv file and get shop cash from first row with open('../stock.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') # Set the shop's cash based on the first value in the ...
The code implements a shop management system with a menu-driven interface. It allows users to view the shop's current state, process batch orders from a customer file, or interactively take live orders. The system creates a shop, handles customer orders by updating stock, and loops until the user selects "0" to exit. K...
def main(): #Clear screen for readability #clear() #print("Setting up the shop for today ...\n") #time.sleep(1) # Add this line to pause for 1 seconds, these were used in debugging # Create the shop by calling this function s = create_and_stock_shop() # A forever loop while True: ...
def display_menu(self): self.clear_screen() print("\n") print("\t\tWelcome to my shop") print("\t\t----------------------------------") print("\t\tMain Menu") print("\t\tSelect 1 for Shop Overview") print("\t\tSelect 2 for Batch orders") print("\t\tSelect ...
The main task of the code is to manage a shop's operations via a menu-driven interface, allowing users to view the shop, process batch orders (using customer data), handle live orders interactively, and exit. It continuously displays the menu, processes user choices, and executes corresponding actions like displaying s...
def main(self): while True: self.display_menu() choice = input("\n Please select an option from the main menu: ") if choice == "1": print("1: SHOP OVERVIEW") self.shop.display_shop() self.return_to_menu() elif choi...
def get_file_names(dir_name): input_path = os.path.join(script_dir, dir_name) files = [] file_dir = None for (dir_path, _, filenames) in os.walk(input_path): file_dir = dir_path files = filenames break if file_dir is None or len(files) == 0: raise Exception("No files ...
The function `start_file_load` loads and processes `.tsoi` and `.ttoi` files from a specified directory, filtering by date ranges and parameters like `threshold` and `with_weights`. It creates `ApprovalProfile` objects from the files, aggregates all voters, and optionally removes incomplete profiles. It returns lists o...
def start_file_load(dir_name, threshold=None, from_date=None, to_date=None, only_complete=False, with_weights=False): """ Loads all tsoi and ttoi files directly within the given directory. All tsoi and ttoi files should conform to the naming convention of *_date.t...
def make_controls(self, root): controls = Frame(root, background=root.cget("background")) SearchBox(controls, command=self.__on_search_request, placeholder="Type and press enter", entry_highlightthickness=0).pack(side=LEFT, ipady=1, padx=1) Label(controls, text="Cnt:").pack(si...
This method initializes a UI component by creating a frame within the provided tabs, setting up controls and a message box, and displaying relevant output messages. It configures the frame's dimensions, prevents size adjustment, and integrates interactive elements for user interaction and message display.
def show(self, tabs): self.parent = tabs root = Frame(tabs, width=self.width, height=self.height-50) root.pack_propagate(0) self.make_controls(root) self.element = root self.make_messages_box(root) self.__output_messages(self.topicName)
def _acceleration(self): """ Calculate the acceleration value for 1st and 2nd stage """ a1 = (self.finalV**2 - self.initialV**2) / (2 * (self.stage1Length + self.accRatio * self.stage2Length)) a2 = a1 * self.accRatio return a1, a2 def _totalTime(self): ""...
This code initializes a system's dynamics and geometry parameters for a slower, setting up acceleration stages, velocity calculations, and trap properties. It configures initial/final velocities, acceleration ratios, and offsets, then derives stage accelerations, middle velocity, and total time. Trap-related properties...
def __init__(self, initialV, finalV, accRatio, geoOffset = 0, timeOffset = 0): """ Initialize slower geometry and dynamics settings; All geometry parameters are calculating from trap center; """ ## DYNAMICS OF SLOWER ##################### ### Con...
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument( 'filename', help="The CSV file to parse", type=Path ) parser.add_argument( '-A', '--adult', help="Set the value of adult tickets", default=9.0, type=flo...
The main task of the code is to process ticket booking data by parsing command-line arguments, reading bookings from a file, calculating totals based on ticket types and their assigned values, and printing the computed results. It handles adult, senior, and child ticket quantities, aggregates booking data, and outputs ...
def main() -> None: args = parse_args() ticket_values = { 'Adult': args.adult, 'Senior': args.senior, 'Child': args.child, } bookings = read_bookings(args.filename) totals = calculate_totals(bookings[1:], labels=bookings[0], ticket_values=ticket_values) print_totals(totals)
def load_parameters(self, config_file): with open(config_file, 'r') as f: config = json.load(f) for key, value in config.items(): if hasattr(FLAGS, key): setattr(FLAGS, key, value) def build_model(self): # With the functional API we need to de...
The main task of the code is to initialize a model by either loading an existing neural network from disk or creating a new one if it doesn't exist. It sets up model parameters, checks for saved weights, and manages checkpointing. The code handles environment interaction through action space configuration and ensures m...
def __init__(self, env, model_id): self.n_actions = env.action_space.n self.model_name = os.path.join(MODEL_PATH, model_id) if os.path.exists(self.model_name + '.h5'): # load model and parameters self.model = keras.models.load_model(self.model_name + '.h5') s...
def m_loss(self,episode_reward): def loss(y_true,y_pred): tmp_pred = keras.layers.Lambda(lambda x: keras.backend.clip(x,0.05,0.95))(y_pred) tmp_loss = keras.layers.Lambda(lambda x:-y_true*keras.backend.log(x)-(1-y_true)*(keras.backend.log(1-x)))(tmp_pred) policy_loss=keras.la...
The code initializes a model by either loading an existing one from disk or creating a new one if it doesn't exist. It sets up neural network structures, compiles the model with a custom loss function involving episode rewards, and handles model parameters. The task involves model loading/checkpointing, neural network ...
def __init__(self, env, model_id): self.n_actions = env.action_space.n self.model_name = os.path.join(MODEL_PATH, model_id) if os.path.exists(self.model_name + '.h5'): # load model and parameters self.model = keras.models.load_model(self.model_name + '.h5') se...
def generate_episode(env): states_list = [] # shape = (x,80,80) action_list=[] # 1 if we chose up. 0 if down rewards_list=[] network_output_list=[] observation = env.reset() observation, reward, done, info = env.step(1) lives = info['ale.lives'] done = False policy_output_list = [] ...
The code trains a DDPG agent by collecting multiple episodes of states, actions, rewards, and network outputs. It processes rewards, converts actions to one-hot encoding, and updates the DDPG model using the network outputs as targets. The function returns collected data for further analysis or training iterations.
def train_ddpg(ddpg, env, n_batches=10): batch_state_list=[] batch_action_list=[] batch_rewards_list=[] batch_network_output_list = [] for i in range(n_batches): states_list,action_list,rewards_list, network_output_list = generate_episode(ddpg, env) batch_state_list.extend(states_li...
def get_filters(order): if order not in principal_filters or order not in wavelet_filters: # Calculate principal filter. principal_filter = None if order == 0: principal_filter = np.array([1.0, 1.0]) principal_filter /= np.linalg.norm(principal_filter) else: ...
The code tests a 2D wavelet transform and its inverse using a specified order (k=10). It calculates norms of the original and transformed arrays, verifies reconstruction accuracy by comparing the inverse transform to the original, and includes loops to analyze wavelet filter properties through inner products and vector...
def main(): # k is the order to test. k = 10 filters = get_filters(k) print(filters) wavelet_filter = filters['wavelet'] vect = np.ones_like(wavelet_filter) for i in range(k+1): print(np.inner(vect, wavelet_filter)) for j in range(2*k+2): vect[j] *= (j-i) arra...
def mmm2csv(self, src): joint_names, mmm_dict = parse_motions(src.as_posix())[0] root_pos = np.array(mmm_dict['root_pos'], dtype=np.float) #* 0.001 / 0.056444 #root_pos = root_pos[:, [1,2,0]] root_rot = np.array(mmm_dict['root_rot'], dtype=np.float) #* 180/np.pi #root_rot = root_rot[:, [1,2,0]] ...
The code generates a skeleton structure with new joint hierarchies and offsets. It creates parent-child relationships, reads joint data, reorders joints via permutation, parses an XML skeleton file, computes joint offsets, and constructs a Skeleton object with updated parameters, returning it along with the permutation...
def get_skeletonNpermutation(self): ## make a parents_list parents = [-1, 3, 0, 2, 1, 8, 9, 0, 7, 1, 6, 12, 5, 16, 17, 0, 15, 1, 14, 20, 13] joints_left = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] joints_right = [13, 14, 15, 16, 17, 18, 19, 20] ## read a demo file to get the joints joints, _, ...
def update_income_bin_percentile(self): # Get column relative to the age column = 8 for inx, column_age in enumerate([25, 35, 45, 55, 65, 75]): if self.age < column_age: column = inx + 2 break random_walk_bin = np.random.normal(loc=0, scale=1, ...
The code simulates an agent's monthly actions in a model, including aging, income and equity updates, house buying/selling decisions based on strategy (naive/sophisticated), and policy-driven savings adjustments. Agents assess housing market opportunities, calculate affordability, and decide to list their house if util...
def step(self): """ Step of an agent represents the actions of the agent during one month """ self.monthly_ageing += 1 if self.monthly_ageing == 12: self.age += 1 self.monthly_ageing = 0 # Update the income of the agent self.income, self....
def getRelatedSnakeParts(self): self.relatedSnakeParts = [x for x in game.snakeParts if x.snakeIndex == self.snakeIndex] return self def get_key(val, dict): """ Gets the key of the given value in the dictionary. """ for key, value in dict.items(): if val == value: r...
This code initializes a game entity (likely a snake part) by setting its type, position, velocity, appearance, and state. It handles default values for position and velocity, generates random positions if unspecified, creates a PyGame rectangle for rendering, assigns color and rotation, and initializes alive status and...
def __init__(self,type:string,snakeIndex:int,color:tuple,pos:tuple=False,velocity:pg.Vector2=False): # General fields self.type, self.snakeIndex = type, snakeIndex self.getRelatedSnakeParts() # Physical fields randomPos = game.getRandomAvailablePos((1,playfield.rectDims[1])) ...
def plotQ(q_table, verbose=False, recolor=0.98, arrows=True): """ Plots the values of each state on the board using matPlotLib. The board is colored with a gradient to distinguish between high and low valued states, and arrows are plotted on each state that point to the highest valued neighbor. Followin...
The main task of the code is to implement the **value iteration algorithm** for updating a Q-table in reinforcement learning. It iteratively improves the Q-values of state-action pairs by applying the Bellman equation: Q(s,a) = reward(s,a) + discount_factor * expected future rewards. The process continues until the max...
def value_iteration(q_table, eps=0.01, max_iter=10000, plot=False, plotEvery=False, verbose=False, recolor=0.98, arrows=True): """This is the value iteration algorithm. It updates the q_table by updating a values of a state to be the reward of leaving that state by taking action a plus the expected future rewards t...
def scrape_summary(category): """ Scapes the summary of the lotto results based on the category Save it to the database then return it """ print("Scraping summary...") base_url = os.environ.get("WEB_URL") url = f"{base_url}/6-{category}-lotto-result-history-and-summary" user_agent = u...
The function checks if provided lottery combinations match a winning combination for a specific category and draw date. It retrieves historical data, validates inputs, compares user combinations with stored results, and returns match details, prize amounts, or "No Prize" if no match is found, handling errors gracefully...
def check_combinations(combinations, category, draw_date): """Check if the combination is a winning combination and return the details""" games = { "6/42 Lotto": "6/42 Lotto", "6/45 Mega Lotto": "6/45 Mega Lotto", "6/49 Super Lotto": "6/49 Super Lotto", "6/55 Grand Lotto": "6/55 ...
def symbols_to_binary(line): bin_str = "".join(["1" if ch == "#" else "0" for ch in line]) return bin_str def find_horizontal_reflections(pattern): if result := find_reflections(pattern): return result if result := find_reflections(pattern[::-1]): return len(pattern) - result def find_ve...
The code reads input patterns from a file, converts them into binary representations, and calculates their reflection symmetry values. It checks for horizontal and vertical reflections in each pattern, summing their contributions (horizontal reflections weighted by 100). The main task is to compute the total reflection...
def solve(): patterns = None with open("day13_input.txt") as f: patterns = f.read().split("\n\n") total = 0 bin_patterns = list( map(lambda p: [symbols_to_binary(i) for i in p.splitlines()], patterns) ) for i, pattern in enumerate(bin_patterns): if horizontal_result := ...
def find(self, query, namespaces=None, element=None): ''' :param query: Query string :type query: str :param namespaces: dictionary of namespaces in the XML document :type namespaces: dict :param element The element that should be searched :type element: xml.etre...
This function extracts and processes sensitive decision attributes from XML data by mapping them to their corresponding classes, then writes the results to CSV files for further analysis.
def get_decision_data_attributes(self): # get the xml element sensitiveDecisions # loop through the list of obtained attributes and try to find the class to which it belongs. # if a class is found, append the class_name. If no class is found return the attribute as it is try: ...
def _validateInput(self, mailboxesToBackup, day): if not mailboxesToBackup: self.writeLog('Non ci sono caselle di posta da allineare') raise Exception('Non ci sono caselle di posta da allineare') if not day: self.writeLog('Non hai passato un giorno valido da backuppar...
The code's main task is to validate inputs, convert the date string to a datetime object if necessary, log the start of a process, execute a backup operation for specified mailboxes on a given day, and log the completion. It handles input verification, date parsing, and triggers a backup workflow while maintaining logg...
def exec(self, mailboxes, rawDay): self._validateInput(mailboxes, rawDay) day = rawDay if not isinstance(rawDay, str) else datetime.datetime.strptime(rawDay, '%Y-%m-%d') self.writeLog(self._getTitle(day) + ' start') print(self._getTitle(day).capitalize() + ' ... ', end='') ...
def validateTargetDirectory(self,dirName): if (not os.path.exists(dirName)): raise Exception('La directory %s non esiste. Impossibile procedere con il ripristino del backup' % (dirName)) def writeLog(self, message, newLine = "\n"): logmessage = "%s - %s" % (datetime.datetime.now().strftime("...
The code restores data by uploading non-empty files from a specified directory. It constructs the target path using a backup root directory, validates the directory, logs the start of the restore, iterates through files, skips zero-byte files, uploads each valid file, and logs the completion of the restore process.
def exec(self, dirName): dirPath = os.path.join(self.config[zmbackup.constant.BACKUP_ROOTDIR_KEY], dirName) self.validateTargetDirectory(dirPath) print('Sto riprstinando la directory %s' % (dirName)) self.writeLog('Start restore directory %s' % (dirName)) files = listdir(dirPath...
def report(what, host="EBMS host name not specified"): """ Send an email report telling what happened during this run of the program. @param what string for the body of the email message @return nothing """ recips = get_dev_notification_recipients() if no...
(The main task of the code is to invoke a URL for marking unreviewed articles on an EBMS host, log the process and results, handle command-line arguments, and report success/failure with elapsed time. It checks for required input, constructs the URL, configures logging, fetches data from the endpoint, processes respons...
def main(): """ Invoke the URL for marking unreviewed articles and log results. """ start = datetime.datetime.now() if len(sys.argv) < 2: cmd = sys.argv[0] message = "command line argument for EBMS host name is required" print("usage %s EBMS-HOST-NAME" % cmd) report(...
def file_name(filepath): return os.popen('basename '+ filepath).read().split('\n')[0] def mdsum(filepath): relfilepath=os.path.relpath(filepath,os.getenv('HOME')) homefilepath=os.getenv('HOME')+'/'+relfilepath command='md5sum '+homefilepath return os.popen(command).read().split()[0] def get_token():...
This function synchronizes a local file with a server by comparing MD5 hashes. It checks the server for the file's existence and hash. If the file is missing (404) or the hashes differ, it deletes and re-uploads the local file. The process ensures server and client file versions match, using authentication and relative...
def sync_file_from_client(filepath): filename=file_name(filepath) md5sum=mdsum(filepath) relfilepath=os.path.relpath(filepath,os.getenv('HOME')) token=get_token() headers={ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36...
def create_login_csv(): file_exists=os.path.isfile(os.getenv('HOME')+'/loginData.csv') if not file_exists: with open (os.getenv('HOME')+'/loginData.csv', 'w') as csvfile: fieldnames=['username','password','savepassword','scheme','decryptionkey'] writer=csv.DictWriter(csvfile, del...
The code handles user login by checking if a user exists; if not, it guides them through registration, allowing selection of an encryption scheme (AES/DES), saves user data, and logs them in. It creates a login CSV, prompts for registration confirmation, and directs unregistered users to a registration URL.
def login(user): create_login_csv() defaultscheme='aes' print('Username: '+user) if check_user(user): login_user(user) else: response=input('Have you registered? [Y/N]') if (response == 'Y' or response == 'y'): print('Encryption schemes available: ') ...
def Scale_Value(self): self.ser.write(b"\x1bP\r\n") weight = self.ser.readline() self.ser.write(b"\x1bP\r\n") weight = self.ser.readline() weight=re.findall("\d+\.\d+",str(weight)) weight = float(weight[0]) return weight def Temp_Correction(self,temp,...
(Collects sensor data including weight, temperature, humidity, and calculates corrections/errors, then logs these values with timestamps and relative time into a CSV file using the provided writer. The function ensures valid weight readings before proceeding and applies temperature-based adjustments.)
def Collect(self,starttime,refD,rtdsensor,writer): timestamp = datetime.datetime.now().replace(microsecond=0) relativetime = (timestamp-starttime)/datetime.timedelta(hours=1) weight = self.Scale_Value() while weight<10: print('Scale Error = Value Too Small...
def RTD_init(self): #Initalize RTP100 sensor to GPIO5 spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) cs = digitalio.DigitalInOut(board.D5) rtdsensor = adafruit_max31865.MAX31865(spi,cs, wires = 4) return rtdsensor def Sartorius_init(self,COM): #Initialize Sa...
The code performs data acquisition by logging sensor readings (temperature, weight, humidity) into a CSV file. It checks for an existing file, appends data if confirmed, or initializes new data with user inputs for salinity and volume. Data is collected every 5 seconds for the first 10 minutes, then every minute therea...
def Aquire(self): count = 0 ecount = 0 plt.show(block=True) rtdsensor=self.RTD_init() #ksensor = self.K_type_init() self.Sartorius_init('/dev/ttyUSB0') if os.path.isfile(self.filename): answer = input('File already exists! Would you like to appen...
def getFreeMemoryLocations(self): memLocs = [] inMemBlock = False memStartPos = -1 #iterate over the memory store to find the beginning of each block of memory for i in range(len(self.memory)): if (self.memory[i] == '.'): if (not inMemBlock): ...
The function attempts to allocate memory for a process by checking free memory locations. If a suitable location is found, the process is added there. If not, it defragments memory and recursively retries allocation, using the `checkFirstRun` method to manage the defragmentation and recursion, ensuring the process is p...
def addProcessFirst(self,process, firstRun = True): freeLocs = self.getFreeMemoryLocations() #check all free memory locations for the first location big enough to contain the new process for loc in freeLocs: if (loc[1] >= process.memSize): #we found a location for the...
def getFreeMemoryLocations(self): memLocs = [] inMemBlock = False memStartPos = -1 #iterate over the memory store to find the beginning of each block of memory for i in range(len(self.memory)): if (self.memory[i] == '.'): if (not inMemBlock): ...
This code allocates a process to the smallest available memory block that can fit it. If no suitable block exists, it defragments memory and retries. The function prioritizes efficient memory usage by selecting the minimal required space, ensuring optimal allocation while handling fragmentation through recursive checks...
def addProcessBest(self,process, firstRun = True): freeLocs = self.getFreeMemoryLocations() #check all free memory locations for the smallest location big enough to contain the new process smallestValidLocSize = None smallestValidLoc = None for loc in freeLocs: if (lo...
def _check_exists(self) -> bool: return os.path.exists(self.training_file) and os.path.exists(self.test_file) def load_images(path): return read_ubyte(path).astype(np.float) / 255 def load_labels(path): return read_ubyte(path).astype(np.int)
The code downloads and processes the MNIST dataset: checks if files exist, creates a directory, downloads resources with MD5 verification, loads image/label data from compressed files, and saves processed training/test sets as pickled objects. It ensures data is stored locally for later use in machine learning tasks.
def download(self): if self._check_exists(): return os.makedirs(self.folder, exist_ok=True) for url, md5 in self.resources: filename = url.rpartition("/")[2] download_url(url, root=self.folder, filename=filename, md5=md5) print("Processing...") ...
def heuristic(state): value = 0 newState = state.copy() # check if goal state is reached if all(newState): return value # find where power pack is power = newState[POWER_INDEX] if power: # flip power pack and one robot to beginning newState[POWER_INDEX] = False ...
This code implements the A* search algorithm to find the optimal path from an initial state to a goal state. It uses a priority queue (heap) to explore nodes, expanding the lowest-cost node first. The algorithm checks for the goal state, generates successors, and avoids revisiting states by comparing costs. It returns ...
def AstarSearch(initialState, goalState): nodeCount = 0 node = Node(state=initialState, parent=None, cost=0, heuristic=heuristic(initialState), depth=0) explored = [] heap = [] heapq.heappush(heap, node) # while frontier is not empty, search for goal state solution = None ...
def playPrologue(self): self.displayWaiting() while True: if MODE == MODE_FLASK and self.flask.is_active_force_check(): break elif MODE == MODE_MQTT and self.mqtt.is_active(): break self.clock.tick(FPS) # Get a...
The code's main task is to execute a game sequence by calling playPrologue(), playMain(), and playEpilogue() methods, handle Quit/KeyboardInterrupt exceptions by printing "Goodbye", and publish a quit signal via Flask or MQTT based on the MODE, ensuring proper termination of the game session.
def play(self): try: if MODE in [MODE_FLASK, MODE_MQTT]: self.playPrologue() self.playMain() self.playEpilogue() except (Quit, KeyboardInterrupt): print("Goodbye") if MODE == MODE_FLASK: self.fl...
def generate_game_id(): # animal = rd.choice(ANIMALS) # beer = rd.choice(BEER_TYPES) # code = generate_3_digit_code() # combination = f"{animal}{beer}{code}" # change this to a 4 digit alphanumeric code combination = ''.join(rd.choice(string.ascii_uppercase + string.digits) for _ in range(4)) ...
This code implements a Streamlit-based trivia game management system. It allows users to create new games by uploading question data (CSV/XLSX), generate unique game IDs, and store questions in Firestore. It supports loading existing games via Game ID, toggling answer visibility, managing game settings (show answers/wa...
def main(): st.set_page_config(layout="wide", page_title="Trivia Game Management", page_icon="✍️") with st.sidebar: st.title('Advanced Settings') st.write('**Note:** These settings are for advanced users only. Please do not change these settings unl...