dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def F_beta(predicted_data,actual_data,beta,data_possibilities): #p: precision, r: recall. Predicted data and actual data must be the same size. At the moment will not work for multi-class true_pos, true_neg, false_pos, false_neg = get_confusion_matrix_data(predicted_data,actual_data,data_possibilities) p = ...
This function calculates a specified evaluation metric for a model's performance on a test dataset. Depending on the 'metric' input, it computes F-beta, Precision, Recall, Accuracy, or AUC. It uses provided results, test scores, and parameters like beta and data possibilities to calculate the score. For AUC, it plots a...
def get_metric(results, test_set_dice_score, test_set_dice_score_numerical_value, beta, data_possibilities, plot, metric, k, folder_temp): # plot = 1 (plot) or = 0 (no plot) if metric == 'F-beta': score = F_beta(results, test_set_dice_score, beta, data_possibilities) if metric == 'Precision': ...
def __is_valid_state(self, state): return state not in self.maze.holes def __build_P(self): for row in range(self.maze.num_rows): for col in range(self.maze.num_cols): current_state = self.maze.compute_index(col, row) if current_state in self.maze.holes: ...
This code initializes a reinforcement learning environment for a maze navigation task, setting up action/observation spaces, generating a maze with start/finish points, defining reward structures, obstacle placements, and rendering parameters. It constructs state-transition probabilities, prepares rendering components,...
def __init__(self, render_mode=None): super().__init__() self.render_mode = render_mode self.action_space = gym.spaces.Discrete(settings.NUM_ACTIONS) self.observation_space = gym.spaces.Discrete(settings.NUM_TILES) self.maze = KruskalMazeGenerator(settings.ROWS, settings.COLS) ...
def check_chest_exists(self, index): return index in self.maze.chests def __build_P(self): for row in range(self.maze.num_rows): for col in range(self.maze.num_cols): current_state = self.maze.compute_index(col, row) if current_state in self.maze.holes: ...
This method processes an action in a maze environment by updating the state, handling chest collection (removing chests and updating probabilities), checking termination conditions (winning or reaching a goal), and rendering visual/audio feedback. It returns the next state, reward, termination status, and other metadat...
def step(self, action): probability, next_state, reward, terminated = self.P[self.current_state][action][0] state_aux = self.current_state self.current_state, self.current_action = next_state, action if (self.check_chest_exists(next_state)): terminated = False se...
def _init_walls(self) -> None: for i in range(self.num_rows): for j in range(self.num_cols): current_index = self.compute_index(j, i) for offset_i, offset_j in self.neighborhood: n_i, n_j = i + offset_i, j + offset_j if not ((0 ...
This code generates a maze by initializing walls, using Union-Find to connect cells, removing redundant walls, finding a path from entrance to exit, generating holes, and returning the final wall configuration.
def generate(self) -> Set[Tuple[int, int]]: self._init_walls() parent = [i for i in range(self.num_rows * self.num_cols)] rank = [0 for i in range(self.num_rows * self.num_cols)] walls = list(self.walls) random.shuffle(walls) for i, j in walls: if self.__fin...
def get_create_team(search_term, messages, err): print("get_create") # Use fast cache if it exists data = cache.get('standings') if not data: standings_url = "http://api.sportradar.us/nba-t3/seasontd/2015/REG/standings.json" params = {'api_key': 'wfejyy6af8z84n9u8rdhrcgj'} try: ...
The function `api_query_sched` queries a team's schedule by either creating a new team entry and fetching its games or checking an existing team's schedule, appending status messages and returning the game count.
def api_query_sched(search_term, messages, err): print("api_query") messages.append("No games found in our database, querying API") newTeam, created = get_create_team(search_term, messages, err) if created: messages.append("New entry for " + newTeam.name + " successful, getting schedule") ...
def get_create_team(search_term, messages, err): print("get_create") # Use fast cache if it exists data = cache.get('standings') if not data: standings_url = "http://api.sportradar.us/nba-t3/seasontd/2015/PST/standings.json" params = {'api_key': 'pa8j2hgacuvgkavsz5zfna7n'} try: ...
The function queries an API to either create a new team or retrieve existing team data, then fetches or checks the team's schedule and returns the number of games. It appends status messages for tracking and handles both new and existing team scenarios.
def api_query_sched(search_term, messages, err): print("api_query") messages.append("No games found in our database, querying API for Team data") newTeam, created = get_create_team(search_term, messages, err) if newTeam: if created: messages.append("New entry for " + newTeam.name + ...
def generate_key_pair(): p = generate_prime(100, 300) q = generate_prime(100, 300) n = p * q phi = (p - 1) * (q - 1) e = random.randint(2, phi - 1) while gcd(e, phi) != 1: e = random.randint(2, phi - 1) d = mod_inverse(e, phi) return ((e, n), (d, n)) def encrypt(message, public...
The code generates an RSA key pair, encrypts user-input text with the public key, and decrypts it using the private key, demonstrating asymmetric encryption.
def main(): public_key, private_key = generate_key_pair() print("Public Key:", public_key) print("Private Key:", private_key) message = input("Enter the message to be encrypted: ") encrypted_message = encrypt(message, public_key) print("Encrypted message:", encrypted_message) decrypted_mes...
def log_config(logfile, mode): # ----------------------------------------------------------------------------------------------------------- FileFormatter = logging.Formatter( "%(asctime)s [%(funcName)-12.12s] [%(levelname)-8.8s] %(message)s") ConsoleFormatter = logging.Formatter( "[%(asct...
The code processes input events containing DMS task or replication instance ARNs, retrieves table validation metrics from these resources, and publishes them as custom CloudWatch metrics. It handles input validation, logs execution details, and gracefully exits on errors. The core task is to aggregate DMS validation da...
def lambda_handler(event, context): # ----------------------------------------------------------------------------------------------------------- try: global debug_mode debug_mode = 'DEBUG' if event.get('debug', False) else 'INFO' EXECUTION_LOG = 'dummy.txt' logger = log_config...
def create_board(): global board global board_size global num_of_ships global ship_positions random.seed(time.time()) # Set length of rows and cols to the board size (10) rows, cols = (board_size, board_size) board = [] # Vertical Rows for r in range(rows): ...
The main task of the code is to run a turn-based game where the player attempts to sink 6 ships using 50 ammo rounds. It initializes the game, displays the board, tracks remaining ships/ammo, handles player shots, and checks win/loss conditions in a loop until all ships are sunk or ammo is exhausted.
def main(): global game_over global num_of_ships global num_ships_sunk global ammo print(""" Welcome to... _ |_) _. _|_ _|_ | _ _ |_ o ._ _ |_) (_| |_ |_ | (/_ _> | | | |_) _> ...
def replace_noise(token, random_index): c = token[random_index] c_adjacents = find_adjacents(c) new_char = random.choice(c_adjacents) return token[:random_index] + new_char + token[random_index + 1:] def extra_noise(token, random_index): new_char = random.choice(string.ascii_letters) return toke...
The code applies random noise to a token by selecting one of four noise types (replace, extra, eliminate, transposition) with weighted probabilities (50%, 15%, 15%, 20%). It randomly chooses an index in the token and modifies it using the selected noise method, returning the altered token.
def change_token(token): choices = ['replace', 'extra', 'eliminate', 'transposition'] choices_possibilities = [50, 15, 15, 20] noise_type = random.choices(choices, weights=choices_possibilities)[0] random_index = random.randint(0, len(token) - 1) if noise_type == 'replace': return replace_...
def init_attributes(self): self.controllers_list = [] self.robot_name_space = "" self.publishers_array = [] def init_ROS_attributes(self): if not rospy.has_param('/odom_topic') or not rospy.has_param('/velocity_topic'): rospy.logerr("Required parameters not set! Please ensur...
This code initializes the DesistekSagaEnv environment by setting up attributes, ROS components, and invoking the parent class constructor with specific parameters. It waits for simulation readiness and logs initialization completion.
def __init__(self): rospy.logdebug("DesistekSagaEnv: Starting environment") self.init_attributes() self.init_ROS_attributes() super(DesistekSagaEnv, self).__init__(controllers_list=self.controllers_list, robot_name_space=self.robot_na...
def check_health(self): for dino in self.herd.dinosaurs: if dino.health <= 0: print(f'{dino.name} was defeated!') print() self.herd.dinosaurs.remove(dino) else: continue for robot in self.fleet.robots: ...
This code simulates a turn-based battle between robots and dinosaurs. It alternates actions between a randomly selected robot and dinosaur, checking health status after each turn. The loop continues until a termination flag is set, then concludes with a message indicating the battle's end.
def battle(self): while self.flag == False: self.check_health() random_robot = random.choice(self.fleet.robots) self.robot_turn(random_robot) self.check_health() if self.flag == True: break random_dino = random.choice(self.h...
def display_welcome(self): print('Welcome to Robots vs Dinosaurs! Get ready for one epic battle!') print() print(f'In the Robot Fleet we have {self.fleet.robots[0].name}, {self.fleet.robots[1].name}, and {self.fleet.robots[2].name}!') print() print(f'In the Dinosaur Herd we have...
The main task of the code is to initialize a game by creating a fleet and herd, display a welcome message, execute a battle sequence, and finally show the winners. It orchestrates the game flow from setup to conclusion.
def run_game(self): self.fleet.create_fleet() self.herd.create_herd() self.display_welcome() self.battle() self.display_winners()
def parse_arguments(): """Parse and validate command line arguments using argparse.""" parser = argparse.ArgumentParser( description="Convert an image file into an NES CHR (graphics) data file.", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( "-p"...
The main task of the code is to read an input image file, prepare it using a specified color palette, encode the image data, and write the encoded result to an output file. The function handles file operations, including opening, processing, and saving the image in binary format, while catching errors related to file a...
def main(): """The main function.""" args = parse_arguments() try: with open(args.input_file, "rb") as source: # open and prepare image source.seek(0) img = Image.open(source) img = prepare_image(img, args.palette) # encode image ...
def load_model_weights(self): _dir = self.base_model_dir + "/checkpoints/" latest = tf.train.latest_checkpoint(_dir) if latest == None: print("Model not found!") return 0 else: print("Loading model..") self.actor.load_weights(latest.replace("...
This code trains a reinforcement learning model by iteratively updating an actor and critic network using buffered data. It resumes training from a saved checkpoint if enabled, processes observations, actions, rewards, and advantages from the buffer, and performs gradient updates via the actor's policy and critic's val...
def train(self) -> None: if RESUME == True: start_pt = self.load_model_weights() step = 1 if (start_pt == 0) else start_pt + 1 try: while step <= MAX_STEPS: buffer = self.get_buffer() observations = buffer["observations"] ...
def solver(self): self.sudoku_solver(0, 0) def solver2(self): if self.sudoku_solver2(0, 0) == 1: return True else: return False def sudoku_printer(self): text = open("txt", "a") # print("\n-------------------------") text.write("\n-----------------...
This code generates a Sudoku puzzle by starting with a solved grid, randomly removing numbers based on the specified difficulty, and ensuring the puzzle remains solvable. It initializes a 9x9 matrix, fills it with a solver, then iteratively removes values while checking solvability, adjusting the grid to match the chos...
def sudoku_generator(self, difficulty): self.matrix = np.array([[0 for i in range(9)] for j in range(9)]) self.solver() self.solved_sudoku = np.copy(self.matrix) difficulties = [range(30, 40), range(40, 49), range(49, 58)] blank_spaces = random.choice(difficulties[difficulty]) ...
def get_rank(self): if torch.distributed.is_initialized(): return torch.distributed.get_rank() else: return 0 def is_master_process(self): if not torch.distributed.is_initialized(): return True else: return not self.get_rank() def setup_dat...
The function `setup_experiment` initializes an experiment by configuring datasets, models, and optimizers for training or inference. It handles checkpoint resuming, pretraining, and directory setup. When training, it loads states from a checkpoint if provided, otherwise initializes new models. For inference, it loads a...
def setup_experiment(self, is_training, exp_tag, resume_from=None, checkpoint=None, demo_input=None): map_location = {'cuda:0' : 'cuda:%d' % self.get_rank()} if self.is_master_process(): print('Setting up base directory...') dt = str(datetime.now()).replace('.', '-').replace(':', '-'...
def setup_experiment(self, is_training, exp_tag, resume_from=None, checkpoint=None, demo_input=None): map_location = {'cuda:0' : 'cuda:%d' % self.get_rank()} if self.is_master_process(): print('Setting up base directory...') dt = str(datetime.now()).replace('.', '-').replace(':', '-'...
The main task of the code is to train a machine learning model using a specified configuration. It initializes experiment settings, logs training progress, iterates through epochs, processes batches for model updates, manages distributed training, saves checkpoints periodically, validates the model, adjusts learning ra...
def train(self, cfg, exp_tag, resume_from): self.base_path, epoch, global_step = self.setup_experiment(True, exp_tag, resume_from=resume_from) if self.is_master_process(): print('Setting up logger and summary writer...') self.setup_logger(self.base_path, exp_tag) sel...
def is_master_process(self): if not torch.distributed.is_initialized(): return True else: return not self.get_rank() def setup_experiment(self, is_training, exp_tag, resume_from=None, checkpoint=None, demo_input=None): map_location = {'cuda:0' : 'cuda:%d' % self.get_rank(...
This code performs a testing evaluation of a model using the provided configuration (cfg), experiment tag (exp_tag), and checkpoint. It initializes logging, processes test data, computes batch losses/results, aggregates metrics across the epoch, evaluates final performance, and logs results with timing information. The...
def test(self, cfg, exp_tag, checkpoint): if self.is_master_process(): print('Setting up logger and summary writer...') self.base_path = self.setup_experiment(False, exp_tag, checkpoint=checkpoint) if self.is_master_process(): self.setup_logger(self.base_path, exp_tag) ...
def is_master_process(self): if not torch.distributed.is_initialized(): return True else: return not self.get_rank() def setup_experiment(self, is_training, exp_tag, resume_from=None, checkpoint=None, demo_input=None): map_location = {'cuda:0' : 'cuda:%d' % self.get_rank(...
This code runs a demo using a pre-trained model, processing test data to generate outputs. It sets up logging, initializes a video writer, and evaluates the model in inference mode. The demo processes batches, optionally repeating each batch multiple times, and logs timing and results. The main task is to execute a dem...
def demo(self, cfg, exp_tag, checkpoint, demo_input): if self.is_master_process(): print('Setting up logger and summary writer...') self.base_path = self.setup_experiment(False, exp_tag, checkpoint=checkpoint, demo_input=demo_input) if self.is_master_process(): self.setu...
def createproject(id): projectname = namevalidation() projectdescription = descvalidation() target = targetnumvalidation() projectstartDate = datevalidation()[0] projectendDate = datevalidation()[1] print("creating project") print( f" project name : {projectname} \n project de...
The main task of the code is to provide a menu-driven project management system, allowing users to create, edit, delete, or view projects via input choices. It interacts with external functions (createproject, editproject, deleteproject, viewproject) and persists changes to a file ("projects.txt") while handling basic ...
def projects(id): while True: choice = int(input( "for create projects enter 1 or for edit projects enter 2 or for delete projects enter 3 or for view projects enter 4 or for exit 5 : ")) try: choice == 1 or choice == 2 or choi...
def back_prop(X, Y, weightsAndBiases, NUM_HIDDEN, hidden_layers): loss, Zs, Hs, yhat = forward_prop(X, Y, weightsAndBiases, NUM_HIDDEN, hidden_layers) dJdWs = [] # Gradients w.r.t. weights dJdbs = [] # Gradients w.r.t. biases Ws, bs = unpack(weightsAndBiases, NUM_HIDDEN, hidden_layers) g = yhat -...
The code performs a single training iteration using backpropagation. It computes gradients, updates weights and biases via gradient descent with momentum (epsilon, alpha), and records the parameter trajectory. The function returns updated weights/biases and the trajectory of weight states during training.
def train(X_train, Y_train, weightsAndBiases, hidden_num, hidden_layers, epsilon,alpha): trajectory = [] bp = back_prop(X_train, Y_train, weightsAndBiases, hidden_num, hidden_layers) grad_w, grad_b = unpack(bp, hidden_num, hidden_layers) W, B = unpack(weightsAndBiases, hidden_num, hidden_layers) W,...
def train(X_train, Y_train, weightsAndBiases, hidden_num, hidden_layers, epsilon,alpha): trajectory = [] bp = back_prop(X_train, Y_train, weightsAndBiases, hidden_num, hidden_layers) grad_w, grad_b = unpack(bp, hidden_num, hidden_layers) W, B = unpack(weightsAndBiases, hidden_num, hidden_layers) W,...
This function performs mini-batch stochastic gradient descent (SGD) training for a neural network with multiple hidden layers. It iterates over epochs, processes data in batches, updates weights/biases using gradient descent with momentum (via 'alpha'), and tracks weight trajectories. After each epoch, it evaluates mod...
def SGD_flow(X_train, Y_train, epochs, batch_size, weightsAndBiases, hidden_num, hidden_layers, learning_rate, alpha, X_valid, Y_valid): print("epochs",epochs) TRAJECT = [] for epoch in range(epochs): print("epoch",epoch) N_batches=int((len(X_train.T)/batch_size))...
def initWeightsAndBiases(hidden_num, hidden_layers) : Ws = [] bs = [] np.random.seed(0) W = 2 * (np.random.random(size=(hidden_num, NUM_INPUT)) / NUM_INPUT ** 0.5) - 1. / NUM_INPUT ** 0.5 Ws.append(W) b = 0.01 * np.ones(hidden_num) bs.append(b) for i in range(hidden_layers- 1): ...
The function `findBestHyperparameters` performs a grid search over predefined hyperparameters (e.g., layers, units, batch size, learning rate) to train and validate a neural network. It splits the training data into training and validation subsets, iterates through all hyperparameter combinations, trains models using S...
def findBestHyperparameters(trainX, trainY, testX, testY): #hidden_layers_list=[3,4,5] #hidden_numbers_list = [30,40,50] #mini_batch_size_list=[16,32,64] #epsilon_list=[0.001,0.05,0.01,0.1] #epochs_list=[40,60,80] #alpha_list=[0.00001,0.0001,0.00002] hidden_layers_list=[3] hidden_numb...
def _build(self): self._create_variables() if FLAGS.gnn=='gcn': self._create_generator() elif FLAGS.gnn=='igcn': self._create_generator_igcn() def _classifier(self, input_tensor, act=tf.nn.relu): """classification""" hiddens = input_tensor for i in...
This code implements a domain adaptation model using a Wasserstein GAN with gradient penalty (WGAN-GP). It constructs generator, classifier, and discriminator networks, computes domain adaptation loss (Wasserstein distance with gradient penalty), L2 regularization, and supervised classification loss. Optimizers are def...
def build(self): """ Wrapper for _build() """ with tf.variable_scope(self.name): self._build() theta_C = [v for v in tf.global_variables() if 'clf' in v.name] theta_D = [v for v in tf.global_variables() if 'dis' in v.name] theta_G = [v for v in tf.global_variables() ...
def checkIfValidMoves(htmlStoragedmoves): moves = [] previousDataPly = 0 missingDataPly, lastDataPly = None, None for item in htmlStoragedmoves: divs = item.split('<div') for div in divs[1:]: if "timestamp" in div or "data-tooltip" in div: # skip divs with timestamp ...
The code automates chess game analysis by scraping move data from chess.com using Selenium, validates moves, converts positions to FEN notation, retrieves evaluations (centipawn/mate scores), and logs game data to 'games.txt'. It handles browser automation, real-time move tracking, and evaluation parsing for chess game...
def main(): currentPos = [] lastFen, lastPgn = "", "" moveNumber = 0 options = webdriver.ChromeOptions() options.add_argument("start-maximized") options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) opti...
def __optimize_step(self): '''a single optimization step based on the loss''' with tf.GradientTape() as tape: current_loss = self.total_loss() grad = tape.gradient(current_loss, self.optimized_frame) constants.OPTIMIZER.apply_gradients([(grad, self.optimized_frame)]) self.optimized_fram...
The code optimizes an image through multiple epochs (30 for the first frame, otherwise a predefined number) by repeatedly applying optimization steps. It updates internal state variables and returns the optimized result as either an image or a numpy array, depending on the 'as_image' parameter.
def optimize(self, as_image=True): '''optimize the image many times and then return the result as an array or image''' print("Epoch: ", "") for j in range(30 if self.first_frame else constants.EPOCHS): for _ in range(constants.STEPS_PER_EPOCH): self.__optimize_step() print(j, end=" ") ...
def init(): global ADT_DIR, SOLCMC, DOCKER_SOLCMC, ADT_DIR, TIMEOUT, SANDBOX_DIR, SOLVER_TYPE, TG_PATH, TG_TIMEOUT, FORGE_PATH # Dockerfile-solcmc SANDBOX_DIR = "../sandbox" tmp = os.path.dirname((os.path.dirname(os.path.realpath(__file__)))) SANDBOX_DIR = tmp + "/sandbox" if platform == "darwin...
The main task of the code is to generate Solidity test cases from a given source file or directory. It processes input arguments, parses contract signatures, runs test generation for each contract, removes duplicate tests, generates Solidity test files, executes tests, and logs results with timing and visualization. Th...
def main(filename): start_time = time.time() init() global ADT_DIR, SOLCMC, DOCKER_SOLCMC, ADT_DIR, TIMEOUT, SOLVER_TYPE, SANDBOX_DIR, TG_PATH, TG_TIMEOUT, FORGE_PATH if not filename: parser = argparse.ArgumentParser(description='python script for Solidity Test Generation') insourse = ['...
def set_nominal(va=None,vb=None,vc=None,vd=None) : # sets outs to nominal voltage, optional arguments set the nominal voltage # note that vdd will be set to 0 until a nominal value is defined if va is not None : global vnom_a vnom_a = va if vb is not None : global vnom_b vnom...
This code tests the retention capability of memory devices by writing data to hardware pins, reading it back, and counting bit flips over multiple cycles. It handles voltage checks, data operations, and tracks retention errors across active memory slots, returning flip results for evaluation.
def test_retention(v,show=True,n=1,size=1,alt=False): size = 1 # size in kB if v > 1.8 : print('about to test v > 1.8V ~~ this could damage low power chips.') input('enter "C" to continue') pins = [board.D5,board.D6,board.D13,board.D19,board.D26,board.D24, board.D25,boa...
def set_nominal(va=None,vb=None,vc=None,vd=None) : # sets outs to nominal voltage, optional arguments set the nominal voltage # note that vdd will be set to 0 until a nominal value is defined if va is not None : global vnom_a vnom_a = va if vb is not None : global vnom_b vnom...
This code tests memory retention under varying voltage conditions by cycling through voltage levels, writing data to memory, reading it back, and counting bit flips to assess data integrity. It warns against high voltages, iterates n times, and returns flip counts for each memory slot.
def test_retention(v,show=True,n=1,size=1): size = 1 # size in kB if v > 1.8 : print('about to test v > 1.8V ~~ this could damage low power chips.') cmd = input('enter "C" to continue') if cmd != 'C' : return 0 pins = [1,2,3,4,5,6,7,8,9,10,11,12] slots =...
def rollcall(status=0x41,show=True) : set_nominal() slots = ['A1','A2','A3','B1','B2','B3','C1','C2','C3','D1','D2','D3'] awake = [False] * len(slots) addr_bytes = [0] * len(slots) for i in range(len(slots)) : cs[i].value = True time.sleep(0.01) mosi = [0x01,status] # format ...
The code automates testing SRAM single-event upset (SEU) rates under varying voltage conditions. It sweeps voltage ranges, writes a test pattern to active SRAM slots, applies stress, measures bit-flip counts, and logs results (SEUs, timestamps, configs) to CSV files for analysis.
def auto_sweep(v_sweep=[3.3,0.6,0.3],seu_min=1000,inc=60,pattern=85,folder='data/sram/seu/test/') : size = 32 # size in kB active,awake = rollcall() pins = [board.D5,board.D6,board.D13,board.D19,board.D26,board.D24, board.D25,board.D7,board.D12,board.D16,board.D20,board.D21] pins = [x for (x...
def rollcall(status=0x41,show=True) : set_nominal() pins = [board.D5,board.D6,board.D13,board.D19,board.D26,board.D24, board.D25,board.D7,board.D12,board.D16,board.D20,board.D21] slots = ['A1','A2','A3','B1','B2','B3','C1','C2','C3','D1','D2','D3'] global active, awake, addr_bytes with b...
This function scans hardware pins for Single Event Upsets (SEUs) by comparing read data against a known pattern. It filters active pins/slots, reads bit data, checks for mismatches, logs results in a CSV, and returns the total error count.
def seu_scan(v='auto',t='auto',size=32,pattern=85,threshold=1000) : if trial is None: print('please use memex.create_trial() to specify a trial csv') return 0 print(trial) active,awake,addr_bytes = rollcall(show=False) pins = [board.D5,board.D6,board.D13,board.D19,board.D26,boar...
def read_input(filename): with open(filename, 'r') as f: blocks = [[int(x) for x in s.split()] for s in f.read().splitlines()] return blocks def gold(coords): # write your code here return [] def rounding(matrix): # Compute the individual row and column sum # If any sum is not divisible ...
The code processes command-line arguments to perform graph-related tasks: "gold" calculates coordinates, "rounding" adjusts a matrix, and "maxflow" computes maximum flow in a graph. It reads input files, executes the specified task, and outputs results.
def main(args = []): # Expects 2 command-line arguments: # 1) name of a file describing the graph if len(args) < 2: print("Too few arguments! There should be at least 4.") print("flows.py <cmd> <file>") return task = args[0] if task == "gold": coords = read_input(arg...
def _get_sets(self, num_labels, num_samples, noise, loc, w, full_x=[], full_y=[], count = 0): """ Helper function to generate datasets for each party, that ideally should fulfill the label distribution indicated by user. NOTE: the function will be in a infinite loop until the desired label distr...
The main task of the code is to generate a federated learning dataset for a specific party, including creating a local model by perturbing a global model. It calculates label distributions based on weights, adjusts for sample leftovers, adds noise, and trims data to match desired label counts. The function returns the ...
def _generate_task(self, num_samples, noise, loc, label_weights, perturb): """ Get datasets for each party Args: num_samples (int): Number of data samples for this current party noise (float): Scale of the noise for this party l...
def get_all_days_of_year(serie: pd.Series)->set: collection = set() for date in serie.index: collection.add(date.dayofyear) return collection def daily_prediction(model: Sequential, TS_norm_full: pd.Series, temperature_norm: pd.Series, lag_value: int, daily_time_stamps: pd.DatetimeIndex): if len...
The function `test_set_prediction` generates predictions for a time series test set using a trained model. It processes each day in the test set, handles stateful model initialization via seeding, and aggregates daily predictions. It also denormalizes results if required, returning predicted and actual values for evalu...
def test_set_prediction(model: Sequential, setting: forecast_setting, serie: time_serie, test_set:pd.Series, X_train, X_val, real_values: bool = True, seeding: bool = False): # assumption that the test set has no gaps in the dates is not valid model.reset_states() if seeding: # seeding only usefull when hav...
def create_sqlitedb(output_path, mft_csv_path, usnjrnl_csv_path): '''Create db and return path if successful, else return empty string''' start_time = time.time() sqlite_path = os.path.join(output_path, 'NTFS.sqlite') if os.path.exists(sqlite_path): rand = ''.join(random.choice(ascii_uppercase) ...
The function processes USNJRNL journal data by combining MFT and USNJRNL CSV files into an SQLite database, generates full file paths from the journal entries, and stores these paths back into the database. It creates a CSV of full paths, adds them to the SQLite database, and tracks execution time. Error handling is in...
def rewind(output_path, mft_csv_path, usnjrnl_csv_path): start_time = time.time() sqlite_path = create_sqlitedb(output_path, mft_csv_path, usnjrnl_csv_path) if not sqlite_path: return out_csv_path = os.path.join(output_path, 'USNJRNL.fullPaths.csv') print('[.] ..Rewinding journal and computi...
def sequence_algorithm(self, seq): for action in seq: self.rotate(action) def rotate(self, action): copy = self.clone_state() self._actions.append(action) # action: an action in ACTIONS if action == 'U+': self._state['F'][0] = [copy['R'][0][j] for j in range(3)] self._state['L'][0] = [copy['F'][0]...
This function positions a white edge piece on a Rubik's cube by applying specific rotation sequences based on its initial face (U, F, L, B, R) and coordinates (i,j). It moves the edge to the bottom face (D), adjusts its orientation via face rotations, and ensures correct alignment using predefined algorithms. If the ed...
def solve_single_white_edge(self, face, i, j): # adjust the white edge to downside if face == 'U': if (i, j) == (2, 1): self.sequence_algorithm(['F+', 'F+']) elif (i, j) == (1, 0): self.sequence_algorithm(['L+', 'L+']) elif (i, j) == (0, 1): self.sequence_algorithm(['B+', 'B+']) else: ...
def sequence_algorithm(self, seq): for action in seq: self.rotate(action) def find_improper_white_corner_u(self): for i in [0, 2]: for j in [0, 2]: if self._state['U'][i][j] != 'w': return (i, j) if ((i, j) == (2, 0) and (self._state['F'][0][0] != 'r' or self._state['L'][0][2] != 'g')) or \ ...
This function solves a single white corner on a Rubik's Cube by applying predefined rotation sequences based on the corner's position (face, i, j). It handles cases for front, left, back, right, up, and down faces, adjusting the cube's state through specific algorithms. The code rotates the D face when needed, maps cor...
def solve_single_white_corner(self, face, i, j): # print(face, i, j) if face in ['F', 'L', 'B', 'R'] and i == 0: if face == 'F': if j == 0: self.sequence_algorithm(['L+', 'D-', 'L-']) else: # j = 2 self.sequence_algorithm(['R-', 'D+', 'R+']) elif face == 'L': if j == 0: self....
def sequence_algorithm(self, seq): for action in seq: self.rotate(action) def find_improper_middle_layer(self): pos_map = { 'F': (0, 1), 'L': (1, 0), 'B': (2, 1), 'R': (1, 2) } for face in ['F', 'L', 'B', 'R']: if self._state[face][2][1] != 'y' and self._state['D'][pos_map[face][0]][pos_map...
This function solves a single improper middle layer of a Rubik's cube by applying predefined rotation sequences based on the detected position (j) of the misplaced edge. It uses face mappings and rotations to align the middle layer edges, checking and adjusting the cube state iteratively until the middle layer matches ...
def solve_single_middle_layer(self, face_1, face_2, j): # if the improper middle layer is on the side if j != None: if j == 0: self.sequence_algorithm(['D+', face_2 + '+', 'D-', face_2 + '-', 'D-', face_1 + '-', 'D+', face_1 + '+']) else: # j = 2 self.sequence_algorithm(['D-', face_2 + '-', 'D+',...
def find_yellow_corner_with_correct_position(self): fac_map = { (0, 0): [('D', 0, 0), ('F', 2, 0), ('L', 2, 2)], (0, 2): [('D', 0, 2), ('F', 2, 2), ('R', 2, 0)], (2, 0): [('D', 2, 0), ('L', 2, 0), ('B', 2, 2)], (2, 2): [('D', 2, 2), ('R', 2, 2), ('B', 2, 0)] } for pos in fac_map: correct = True ...
This code solves the positioning of yellow corners on a Rubik's cube by first identifying if any yellow corner is already in the correct position. If not, it applies a predefined algorithm to rotate corners. It then maps correct positions to face pairs and uses a sequence of moves involving D rotations and face-specifi...
def solve_position_yellow_corners(self): correct_pos = self.find_yellow_corner_with_correct_position() while not correct_pos: self.sequence_algorithm(['D+', 'L+', 'D-', 'R-', 'D+', 'L-', 'D-', 'R+']) correct_pos = self.find_yellow_corner_with_correct_position() fac_map = { (0, 0): ['L', 'R'], (0, 2)...
def find_yellow_corner_with_incorrect_orientation(self, initial = False): fac_map = { (0, 0): [('D', 0, 0), ('F', 2, 0), ('L', 2, 2)], (0, 2): [('D', 0, 2), ('F', 2, 2), ('R', 2, 0)], (2, 0): [('D', 2, 0), ('L', 2, 0), ('B', 2, 2)], (2, 2): [('D', 2, 2), ('R', 2, 2), ('B', 2, 0)] } for pos in fac_ma...
The function solves the orientation of yellow corners on a Rubik's Cube by identifying misoriented corners, rotating the cube to align them, and applying predefined move sequences to correct their orientation. It repeatedly detects incorrect corners, adjusts their positions via rotations, and executes algorithms to fix...
def solve_orient_yellow_corners(self): fac_map = { (0, 0): 'L', (0, 2): 'F', (2, 2): 'R', (2, 0): 'B' } initial = True pos = self.find_yellow_corner_with_incorrect_orientation(initial) init_pos = pos while pos != None: if initial: initial = False else: # turn the critial pos t...
def find_adjacent_solved_yellow_edges(self): fac_map = { 'F': 'L', 'L': 'B', 'B': 'R', 'R': 'F' } for i in range(4): for face in ['F', 'L', 'B', 'R']: if self._state[face][2][1] == FACE2COR[face] and self._state[fac_map[face]][2][1] == FACE2COR[fac_map[face]]: # face, fac_map[face] are t...
The main task of the code is to solve the yellow edges of a Rubik's cube by repeatedly applying a specific algorithm until adjacent yellow edges are aligned. It first searches for an adjacent solved yellow edge; if none exists, it loops through a predefined move sequence to create one. Once a solved edge is found, it a...
def solve_yellow_edges(self): face_1 = self.find_adjacent_solved_yellow_edges() while face_1 == None: self.sequence_algorithm(['L+', 'D+', 'L-', 'D+', 'L+', 'D+', 'D+', 'L-']) face_1 = self.find_adjacent_solved_yellow_edges() # self.print_cube() # print(face_1) # raw_input('press ENTER') if not ...
def _extract_rules(self, hitlist): rules = {} for hit in hitlist: if not hit.ruleid in rules: rules[hit.ruleid] = self._to_sarif_rule(hit) return list(rules.values()) def _extract_results(self, hitlist): results = [] for hit in hitlist: res...
The code generates a SARIF-formatted report by structuring tool metadata, rules, and analysis results from a hitlist. It constructs a JSON object with tool driver details, supported taxonomies (e.g., CWE), and result data, then serializes it to JSON for output.
def output_sarif(self): tool = { "driver": { "name": self.TOOL_NAME, "version": self.TOOL_VERSION, "informationUri": self.TOOL_URL, "rules": self._extract_rules(self._hitlist), "supportedTaxonomies": [{ ...
def show_csv(self): csv_writer.writerow([ self.filename, self.line, self.column, self.defaultlevel, self.level, self.category, self.name, self.warning + ".", self.suggestion + "." if self.suggestion else "", self.note, self.cwes(), self.context_text, self.fingerprint(), ...
The code formats and displays code issue details (filename, line/column, risk level, category, warning message, suggestions, and context) in either plain text or HTML, depending on output_format. It conditionally outputs CSV/SARIF formats, escapes HTML, links CWE IDs, and handles multi-line text rendering.
def show(self): if csv_output: self.show_csv() return if sarif_output: return if output_format: print("<li>", end='') sys.stdout.write(h(self.filename)) if show_columns: print(":%(line)s:%(column)s:" % self, end='') ...
def h(s): # htmlize s if we're generating html, otherwise just return s. return htmlize(s) if output_format else s def process_directive(): "Given a directive, process it." global ignoreline, num_ignored_hits # TODO: Currently this is just a stub routine that simply removes # hits from the curre...
The function `process_c_file` analyzes C/C++ source files to identify specific code patterns (e.g., security flaws) using a rule set. It reads the file, skips unpatched files, handles encoding errors, and parses code while ignoring comments/strings. It tracks source lines of code (SLOC), processes `#include` directives...
def process_c_file(f, patch_infos): global filename, linenumber, ignoreline, sumlines, num_links_skipped global sloc filename = f linenumber = 1 ignoreline = -1 cpplanguage = (f.endswith(".cpp") or f.endswith(".cxx") or f.endswith(".cc") or f.endswith(".hpp")) incomment =...
def print_warning(message): sys.stderr.write("Warning: ") sys.stderr.write(message) sys.stderr.write("\n") sys.stderr.flush() def h(s): # htmlize s if we're generating html, otherwise just return s. return htmlize(s) if output_format else s def process_c_file(f, patch_infos): global filename...
The function `maybe_process_file` recursively processes files and directories, handling only C/C++ source files. It skips symbolic links (if restricted), directories starting with a dot, and non-regular files. For valid C/C++ files, it checks if they are in `patch_infos` before calling `process_c_file` for further hand...
def maybe_process_file(f, patch_infos): # process f, but only if (1) it's a directory (so we recurse), or # (2) it's source code in a language we can handle. # Currently, for files that means only C/C++, and we check if the filename # has a known C/C++ filename extension. If it doesn't, we ignore the f...
def print_warning(message): sys.stderr.write("Warning: ") sys.stderr.write(message) sys.stderr.write("\n") sys.stderr.flush() def h(s): # htmlize s if we're generating html, otherwise just return s. return htmlize(s) if output_format else s def process_c_file(f, patch_infos): global filename...
The function `process_file_args` processes command-line-specified files and directories, handling symbolic links, normal files, and directories. It prioritizes C/C++ files, skips non-existent files with specific warnings (e.g., incorrect dashes), and avoids processing symbolic links if restricted. Directories are recur...
def process_file_args(files, patch_infos): # Process the list of "files", some of which may be directories, # which were given on the command line. # This is handled differently than anything not found on the command line # (i.e. through recursing into a directory) because flawfinder # ALWAYS proces...
def ESB(self, pState, pPID): lLegalOptions = pState.getLegalPacmanActions() counter = 0 for lOption in lLegalOptions: counter = counter + 1 #expansion lChildState = pState.generatePacmanSuccessor(lOption) if lChildState is None: s...
This function performs a Monte Carlo Tree Search (MCTS) to determine the optimal action in a game state. It initializes node tracking variables, iteratively expands nodes via selection until no further expansion is possible, and returns the best child direction based on explored paths. The core tasks include state eval...
def getAction(self, state): self.mNodeList = [] self.mTotalNodesVisited = 0 self.lSuccessorNotEmpty = True currentNodeId = 0 currentState = state while self.lSuccessorNotEmpty: if currentState.isWin() + currentState.isLose() == 0: self.ESB(...
def preprocess(self, data): norm_data = np.clip((data - self.range[0]) / (self.range[1] - self.range[0]), 0, 1) categorical_data = np.floor(self.bin_size*norm_data).astype(int) return categorical_data def calculateInfo(self, pT, pF): if pT == 0 or pF == 0: return 0 val = ((-pT/(pT+pF)) * math.log2(pT/(pT+p...
The code trains a decision tree classifier by preprocessing input data, counting class instances (0s and 1s) in the target labels, calculating information metrics (InfoD) based on class distribution, and constructing the root node of the tree using the processed data and labels.
def train(self, X, y): categorical_data = self.preprocess(X) self.datalen = len(categorical_data) cy=0 cn=0 for out in y: if out == 0: cy = cy + 1 elif out == 1: cn = cn + 1 self.InfoD = self.calculateInfo(cy,cn) self.rootNode = self.getNextNode(categorical_data,y)
def print_header(s): print(s + "\n" + len(s)*"=") def run(cmd, cwd=TOP_DIR, check=True): # Runs 'cmd' with subprocess, returning the decoded stdout output. 'cwd' is # the working directory. It defaults to the top-level Zephyr directory. # Exits with an error if the command exits with a non-zero return c...
This function identifies symbol references in code that may lack the CONFIG_ prefix in preprocessor directives (e.g., #ifdef, defined()). It scans module paths, excludes symbols already defined as macros to avoid false positives, and uses git grep in batches to check for unprefixes symbols in conditional compilation co...
def check_missing_config_prefix(): print_header("Symbol references that might be missing a CONFIG_ prefix") # Paths to modules modpaths = run(("west", "list", "-f{abspath}")).splitlines() # Gather #define'd macros that might overlap with symbol names, so that # they don't trigger false positives ...
def print_header(s): print(s + "\n" + len(s)*"=") def referenced_sym_names(): # Returns the names of all symbols referenced inside and outside the # Kconfig files (that we can detect), without any "CONFIG_" prefix return referenced_in_kconfig() | referenced_outside_kconfig() def is_selecting_or_implyin...
The main task of the code is to identify and report symbols in a configuration system that appear unused. It checks each defined symbol to see if it is not selecting/implying other symbols, not part of a choice, and not referenced elsewhere. If so, it prints the symbol's name and locations, helping detect potentially r...
def check_unused(): print_header("Symbols that look unused") referenced = referenced_sym_names() for sym in kconf.unique_defined_syms: if not is_selecting_or_implying(sym) and not sym.choice and \ sym.name not in referenced: print(name_and_locs(sym))
def file_conversion(top_dir, chunk_dir_index, dada1, dada2): """ Converts telescope data to filterbank file """ tstart = time.time() # make directory organized by chunk index chunk_dir_name = '%s/chunk%d' % (top_dir, chunk_dir_index) os.mkdir(chunk_dir_name) print('Creating new dire...
The code processes radio astronomy data by converting files, parallelizing data processing, post-processing results, and generating candidate plots, while measuring and reporting time taken for each step.
def pipeline(chunk_dir_index, dada1, dada2): """ Runs pipeline """ tstart = time.time() top_dir = '/data' #file_bases = ["%s/m81_lcp" %top_dir, #"%s/m81_rcp" %top_dir] #file_bases = glob.glob('/data/*.X-LCP.fil', recursive=True) + glob.glob('/data/*.X-RCP.fil', recurs...
def densenet121(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> DenseNet: r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_. The required minimum input size of the model is 29x29. Args: pretrained (bool): If True, ...
This code initializes a Densenet-based encoder with configurable versions (121, 169, 161, 201), loads pre-trained weights if specified, calculates pyramid-level channel configurations based on Densenet layers, and constructs convolutional units for feature pyramids with specific input/output channels. It prepares the e...
def __init__(self, densnet_version=121, pretrained_weights=True): super(DensenetPyramidEncoderTest, self).__init__() if 121 == densnet_version: self.densenet = densenet121(pretrained=pretrained_weights) layers = [6, 12, 24, 16] num_init_channels = 64 chann...
def is_out_of_bounds(x, y): return x < 0 or x > size or y < 0 or y > size def is_box_empty(x, y): return board[x][y] == None def create_piece(index_x, index_y, color): x = index_x * box_size + offset_x y = index_y * box_size + offset_y board[index_x][index_y] = color if color == "B": pe...
This code handles a player's move in a turn-based game by validating click coordinates, placing a piece of the current color, checking for a win, and switching turns. It ensures the move is within bounds, the target box is empty, and the player's color matches the current turn. If a win is detected, the game ends; othe...
def on_click(x, y): global current_color if (is_player_black and current_color == "W") or ( (not is_player_black) and current_color == "B" ): return index_x = round((x - offset_x) / box_size) index_y = round((y - offset_y) / box_size) logger.info( f"click event: on ({x} ...
def iterate_num_at_start_of_string(s): i = 0 generated_pws = list() subs = char_substitution(s[1:]) while i < 10: if s[0] != i: # finds number temp = str(i) + s[1:] # adds i to the start of the string generated_pws.append(temp) for s...
The function generates new passwords by appending the most common numbers (from "number_occurences.csv") to the start and end of a given password. It first modifies the input password by removing numbers from its start/end, then combines these numbers with the cleaned password. If `is_char_sub` is False, it also checks...
def add_most_popular_numbers(pw,top=0,is_char_sub=False): generated_pws = list() if not is_char_sub: if re.search(r'^\d[a-zA-Z]+',pw) != None:# if password starts with just 1 number generated_pws+=iterate_num_at_start_of_string(pw) if re.search(r'[a-zA-Z]+\d$',pw) != None:# if passw...
def split(rows): bestQuestion = None currentUncertainty = gini(rows) nFeatures = len(rows[0]) - 1 bestGain = 0 # iterate over every value to find the best question for col in range(nFeatures): # for each feature values = set([row[col] for row in rows]) # unique values in th...
The main task of the code is to recursively build a decision tree by partitioning data based on the question with the highest information gain. If no further splits are possible (gain=0), it returns a leaf node. Otherwise, it recursively constructs true and untrue branches using the partitioned data and returns a tree ...
def buildtree(rows): # partition the dataset on each of the unique attribute, # calculate the information gain, # return the question that produces the highest gain. gain, question = split(rows) #print(gain) #print(question) #if no more questions, then return leaf if gain == 0: return Leaf(row...
def read_schedule(self): posts = [] for attempt in range(5): try: page = self.get_wiki_page(self.config.wiki) if page and len(page.content_md) > 0: for section in yaml.safe_load_all(page.content_md): post = self.pro...
The code's main task is to update scheduled posts by reading a schedule, processing posts with the current time, submitting them, removing inactive timers, and pausing for a configured delay. It extends posts with the schedule, filters them using `consider_posts`, submits valid ones, cleans up dead timers, logs the del...
def update(self): posts = [] schedule = self.read_schedule() if schedule: posts.extend(schedule) now = datetime.now(timezone.utc) queue = self.consider_posts(posts, now) self.submit_queue(queue, now) for timer in reversed(self.timers): i...
def display_main_menu(): display_portal_name("Menu") print("Enter 'a' to add a new object to the store") print("Enter 'r' to remove item from the store") print("Enter 's' to shop at the store") print("Enter 'v' to view inventory of the store") def gather_obj_data(): desc = input("Enter object's ...
The main task of the code is to manage a shop inventory system with persistent data storage. It loads/saves shop items using pickle, allows adding/removing items, displaying inventory, and accessing a shop portal for transactions. The program maintains a CashRegister object across sessions and provides a menu-driven in...
def main_menu(): # creating the main loop first try: infile = open(FILE, 'rb') ret = pickle.load(infile) print(f"Objects found on {FILE} proceeding to use them!") myShop = Shop(ret) infile.close() except EOFError: print(f"No objects were found on: {FILE}\nC...
def from_seq_to_atoms(seq, atoms): return [atoms[s-1] for s in seq] def filter_atoms(atoms): return [a.serial for a in atoms if any_within_distance(a, atoms)] def any_legal(candidates, atoms): out = [] for i in candidates: for j in candidates: if i != j: print("i.seri...
The code processes input lines to parse atomic coordinates, creates Atom objects, filters them, checks legality, identifies order, and plots results. It converts sequence data to atoms, filters valid ones, verifies legality, determines order, and visualizes the output.
def process_input(lines): atoms = [] for line in lines: data = line.strip().split("\t") seq = int(data[0]) coords = data[1].split(" ") atom = Atom(seq, float(coords[0]), float(coords[1]), float(coords[2])) atoms.append(atom) alpha_carbon = from_seq_to_atoms(filter_ato...
def compute_R(state): """ Compute the rewards array which signifies the rewards for the given board state and player's turn. "Immediate gratification." Input: state: (True, (None,None,None,1,1,0,1,0,None)) Output: an array of integers, the largest integer being the best...
This function performs a single training turn in Tic-Tac-Toe using Q-learning. It updates the Q-value table by selecting an action via epsilon-greedy exploration/exploitation, computing immediate rewards, and applying the Bellman equation to update Q-values based on the new state and future rewards. It returns the upda...
def play_tictactoe_turn_training(Q, state): """ Play a single turn of tic tac toe while training. * * * UPDATES THE Q MODEL. * * * Returns the new board state and the next person's turn. """ # the immediate rewards based on the given board_state R = compute_R(state) if ra...
def suggest_move(Q, state): """ Given a trained brain, Q, and a state: (True, (0, 1, 0, 1, None, None, None, None, 0)) recieve an index into the board state for the suggested next move. """ board_state = state[1] winner = check_winner(board_state) # there is already a win...
The function `unit_test` simulates multiple Tic-Tac-Toe games using a Q-learning model, testing different configurations of who starts first, whether AI plays, and tracking outcomes. It records game results in a dictionary, incrementally updates progress display based on `starting_percent`, and uses AI or random moves ...
def unit_test(first, AI, starting_percent=0): """ Tests the Q model with the given parameters for the number_of_games Record it in the record dictionary. INPUT: (True, True, 0) who goes first: True/False who has ai: ...
def reset_game(): """ 'zero's' everything out. """ board = [None,None,None,None,None,None,None,None,None] board_state = tuple(board) turn = bool(random.getrandbits(1)) winner = None player_symbol = None return board, board_state, turn, winner, player_symbol def play_tictactoe_turn_tr...
The code trains a Q-learning agent for Tic-Tac-Toe over multiple epochs. Each epoch simulates a game, updating the Q-table during turns until a winner is determined. Progress is tracked by printing completion percentages at 1% intervals.
def train(EPOCHS, Q): for epoch in range(EPOCHS): # ignore 'player_symbol' variable. board, board_state, turn, winner, player_symbol = reset_game() while winner == None: board_state, turn = play_tictactoe_turn_training(Q, boar...
def reset_game(): """ 'Zero's' everything out. """ board = [None,None,None,None,None,None,None,None,None] board_state = tuple(board) turn = bool(random.getrandbits(1)) state = (turn, board_state) winner = None player_symbol = None return state, winner, player_symbol def play_t...
The code trains a Q-learning model (Q) for tic-tac-toe by simulating multiple game episodes. Over a specified number of epochs, it plays the game, updates state-action values based on rewards, and records outcomes. The loop resets the game, progresses turns, and checks for a winner, adjusting Q-values iteratively. Prog...
def train(EPOCHS, Q): """ Given an integer # of epochs and an initialized Q, train the Q, by slowly building up the state-actions by playing tic-tac-toe and recording the rewards. """ for epoch in range(EPOCHS): # ignore 'player_symbol' variable. state, winner, player_symbol = r...
def get_valid_tickets(string: str) -> Sequence[Sequence[int]]: notes, _, nby_tickets = string.split("\n\n") ranges = parse_notes(notes) valid_tickets = [] for tick in nby_tickets.split("\n")[1:]: ticket = parse_ticket(tick) if is_valid_ticket(ranges, ticket): valid_tickets.a...
The main task of the code is to process input text by splitting it into notes, identify valid tickets, determine possible indices for each note, and return a list of indices corresponding to values specified in the 'vals' parameter.
def get_indeces(txt: str, vals=[0, 1, 2, 3, 4, 5]) -> Sequence[int]: notes = txt.split("\n\n")[0].split("\n") valid_tickets = get_valid_tickets(txt) posible = [get_possible_index(note, valid_tickets) for note in notes] dic = get_dic(posible) return [key for key, val in dic.items() if val in vals]
def get_num_preds( image, predictions, cached_features, class_names, paths, max_size=1920 ): _, _, h, w = image.shape x = y = 0 scale = max_size / max(h, w) if scale < 1: h = math.ceil(scale * h) w = math.ceil(scale * w) if isinstance(predictions, torch.Tensor): predic...
The code performs model validation/inference for object detection, calculating metrics like mAP and IoU. It loads a model (e.g., YOLO), processes input data, runs predictions with NMS, evaluates against ground truth labels, and saves results. The task includes ResNet feature extraction, confusion matrices, and COCO JSO...
def run( data, weights=None, # model.pt path(s) batch_size=32, # batch size imgsz=640, # inference size (pixels) conf_thres=0.001, # confidence threshold iou_thres=0.6, # NMS IoU threshold task="val", # train, val, test, speed or study device="", # cuda device, i.e. 0 or 0,1,2,3 o...
def process_ingredients(res, items, items_carbon_values): res_list = [] for row in res: ingredients_list = [] for ing in row["recipe"]["ingredientLines"]: ingredients_list.append(ing) serving_size = row["recipe"]["yield"] value = get_carbon_value( ingredie...
The code processes user inputs to search recipes via the Edamam API, combining meal type, ingredients, and dietary preferences. It constructs API queries, filters inaccessible recipes, and prepares results with carbon footprint and cost data for display in a template.
def process(): app_id = secret.edamam_app_id app_key = secret.edamam_api_key meal_type = request.form.getlist("mealcheck") meal_type = ",".join(meal_type) ingredients = request.form["ingredients"] health = request.form.getlist("dietcheck") health = ",".join(health) selectedIng = request....
def display_settings_menu(self): title_color = "\033[1;33m" option_color = "\033[36m" reset_color = "\033[0m" separator = "\033[1;34m─" * 30 + "\033[0m" space = " " * 4 title = f"{title_color}--- Settings Menu ---{reset_color}" options = [ "1: Change D...
The code presents a settings menu, allowing users to select options (1-5) to modify settings. It processes each choice, updates the interface, and repeatedly displays the menu until the user selects option 5 to exit.
def change_settings(self): self.display_settings_menu() while True: choice = input("Choose an option (1 -5): ").strip() if choice == "5": break self.process_setting_choice(choice) self.draw_interface() self.display_settings_menu...
def get_human_input(self): prompt = "\033[1;34mEnter your move or command\n>>> \033[0m" return input(prompt).strip().lower() def provide_help(self): suggestion = self.human.suggest_move(self.board) help_message_color = "\033[1;33m" no_move_color = "\033[1;31m" reset_color...
The function handles a human player's turn by capturing input, processing commands like "help" or "settings", validating moves, and updating the game state. It returns `True` if a valid move is made, `False` otherwise to signal turn completion or invalid input.
def human_turn(self): move = self.get_human_input() if move == "help": self.provide_help() return False elif move == "settings": self.change_settings() return False elif self.validate_move(move): self.make_human_move(move) ...
def reset_board(self): self.board.reset() if random.choice([True, False]): random_move = random.choice(self.board.get_free_fields()) self.board.set_cell(*random_move, self.computer.symbol) def draw_interface(self): self.clear_screen() self.display_title_bar() ...
The code implements a game loop where the human and computer alternate turns on a board. It resets the board, draws the interface, handles player moves, checks for a winner, updates statistics, and prompts the user to continue. The loop ends when the board is full or the player chooses to stop.
def play(self): while True: self.reset_board() is_human_turn = True while self.board.get_free_fields(): self.draw_interface() if is_human_turn: if not self.human_turn(): continue els...
def init_wassa(self): for key in self.wassa: for dataset_version in self.wassa[key]: local_dataset = self.get_wassa_dataset(self.wassa[key][dataset_version]) self.global_dataset = np.concatenate((self.global_dataset, np.array(local_dataset))) def init_archive(self): ...
The code initializes a class by loading configuration data from 'config.json', setting up dataset parameters (WASSA, archive, corporate), initializing empty data structures, and training a classifier through methods like `init_wassa()`, `init_archive()`, `init_corporate()`, and `train_model()`. The main task is to conf...
def __init__(self): self.classifier = None self.df = None with open('config.json') as config_file: data = json.load(config_file) self.wassa = data["WASSA"] self.archive = data["archive"] self.corporate = data["corporate"] self.global_dataset...
def build_dataset(ifg_list, version, product_prefix, aoi, track, orbit): '''Generates the ds dict''' starttime = get_times(ifg_list, minimum = True) endtime = get_times(ifg_list, minimum = False) date_pair = '{}_{}'.format(starttime[:10].replace('-', ''), endtime[:10].replace('-','')) if starttime =...
The code builds and submits an AOI-track product by creating a dataset and metadata, then generating a product directory. It uses input parameters to construct the product, prints key details like version, start/end times, and location, and prepares the product structure for submission.
def build(ifg_list, version, product_prefix, aoi, track, orbit): '''Builds and submits a aoi-track product.''' ds = build_dataset(ifg_list, version, product_prefix, aoi, track, orbit) met = build_met(ifg_list, version, product_prefix, aoi, track, orbit) print('Publishing Product: {0}'.format(ds['label']...
def sort_by_hash(es_results_list): ''' Goes through the objects in the result list, and places them in an dict where key is full_id_hash (or generated version of hash) ''' sorted_dict = {} for result in es_results_list: idhash = get_hash(result) if idhash in list(sorted_dict.keys()):...
This function identifies acquisition lists matching audit trail products within a specified area of interest (AOI) by filtering based on time, location, and hash values. It excludes greylisted hashes and returns matching acquisition lists.
def get_matching_acq_lists(self, aoi, audit_trail_list, greylist_hashes): '''returns all acquisition lists matching the audit trail products under the given aoi''' aoi_met = aoi.get('_source', {}).get('metadata', {}) start = aoi_met.get('starttime', False) end = aoi_met.get('endtime', Fa...
def aoi_track_is_published(self, gunws, aoi_id): '''determines if the aoi_track product is published already. Returns True/False''' gunw = gunws[-1] gunw_type = gunw.get('_type') prod_type = 'S1-GUNW-AOI_TRACK' if gunw_type == 'S1-GUNW-MERGED': prod_type = 'S1-GUNW-ME...
The function `tag_and_publish` tags objects in the input list with an AOI ID, checks if an AOI-track product already exists, and if not, builds a validated product using a determined prefix (based on object type) and metadata. It skips processing if the product is already published or if the input list is empty.
def tag_and_publish(self, gunws, aoi): '''tags each object in the input list, then publishes an appropriate aoi-track product''' if len(gunws) < 1: return if self.aoi_track_is_published(gunws, aoi.get('_source').get('id')): print('AOI_TRACK product is already p...
def sort_duplicates_by_hash(es_results_list): ''' iterates through the list of products and removes products with duplicate full_id_hash (using creation time) and returns a dict sorted by full_id_hash. ''' sorted_dict = {} for result in es_results_list: idhash = get_hash(result) ...
The main task of the code is to determine if GUNW (or merged) products are complete for specific tracks and orbits by comparing hashes of acquisitions and GUNWs. It tags acq-lists with "gunw_generated" or "gunw_missing" based on completeness, and publishes TRACK_AOI products if all required GUNWs are present. The proce...
def gen_completed(self, gunws, acq_lists, aoi): '''determines which gunws (or gunw-merged) products are complete along track & orbit, tags and publishes TRACK_AOI products for those that are complete''' complete = [] hashed_acq_dct = sort_duplicates_by_hash(acq_lists) hashed_gunw...
def get_objects(prod_type, location=False, starttime=False, endtime=False, full_id_hash=False, track_number=False, orbit_numbers=False, version=False, uid=False, aoi=False): '''returns all objects of the object type that intersect both temporally and spatially with the aoi''' idx = INDEX_MAPPING.get(prod_ty...
The main task of the code is to evaluate and publish Area of Interest (AOI) products by filtering Sentinel-1 GUNW (Ground Motion Velocity) data using audit trails and greylists. It retrieves relevant products, checks AOI uniqueness, identifies matching acquisitions, and tags/publishes complete GUNW datasets.
def run_aoi_evaluation(self): '''runs the evaluation & publishing for an aoi''' # get all audit_trail products over the aoi audit_trail_list = get_objects('S1-GUNW-acqlist-audit_trail', aoi=self.uid) # determine all full_id_hashes from all audit_trail products full_id_hashes = li...
def gen_hash(es_obj): '''copy of hash used in the enumerator''' met = es_obj.get('_source', {}).get('metadata', {}) master_slcs = met.get('master_scenes', met.get('reference_scenes', False)) slave_slcs = met.get('slave_scenes', met.get('secondary_scenes', False)) master_ids_str = "" slave_ids_st...
The main task of the code is to evaluate S1-GUNW and S1-GUNW-MERGED products against greylists and acquisition lists to identify complete products, then tag and publish them. It handles hash generation, AOI matching, orbit filtering, and error checking for data consistency across acquisition trails and areas of interes...
def run_greylist_evaluation(self): '''runs the evaluation and publishing for a greylist''' # fill the hash if it doesn't exist if self.full_id_hash is False: print('attempting to fill hash for submitted product...') self.full_id_hash = gen_hash(get_objects(self.prod_type,...
def gen_hash(es_obj): '''copy of hash used in the enumerator''' met = es_obj.get('_source', {}).get('metadata', {}) master_slcs = met.get('master_scenes', met.get('reference_scenes', False)) slave_slcs = met.get('slave_scenes', met.get('secondary_scenes', False)) master_ids_str = "" slave_ids_st...
The function evaluates GUNW or GUNW-merged products by checking their completeness against audit trails and AOIs. It generates hashes, filters by orbit and AOI, matches acq-lists, and tags/publishes completed products. The process ensures data integrity and proper categorization for downstream use.
def run_gunw_evaluation(self): '''runs the evaluation and publishing for a gunw or gunw-merged''' # fill the hash if it doesn't exist if self.full_id_hash is False: print('attempting to fill hash for submitted product...') self.full_id_hash = gen_hash(get_objects(self.pro...
def load_context(): '''loads the context file into a dict''' try: context_file = '_context.json' with open(context_file, 'r') as fin: context = json.load(fin) return context except: raise Exception('unable to parse _context.json from work directory') def run_aoi_e...
The code initializes an object by loading context data, validating input parameters (e.g., product type), and triggering evaluation workflows. It checks for valid product types, raises errors for invalid inputs, and executes specific evaluation methods like `run_aoi_evaluation`, `run_greylist_evaluation`, or `run_gunw_...
def __init__(self): '''fill values from context, error if invalid inputs, then kickoff evaluation''' self.ctx = load_context() self.prod_type = self.ctx.get('prod_type', False) self.track_number = self.ctx.get('track_number', False) self.full_id_hash = self.ctx.get('full_id_hash'...
def connectionErrorPopup(self): # declare the below popup window msg = QMessageBox() msg.setWindowTitle('Connection Error') msg.setText('No device connected. Please connect a device and try again.') msg.setIcon(QMessageBox.Critical) msg.setStandardButtons(QMessageBox.Ok) ...
The main task of the code is to interface with a hardware board via UART to retrieve its current mode and parameters. It establishes a serial connection, sends a predefined command packet, reads the response, extracts the device ID and mode from the data, updates UI elements (mode labels, connection status), and handle...
def board_interface(self): # interface with board to get current state and which mode is enabled # make UART connection with board # send command to board to get current mode # send command to board to get current values of parameters # for now, pretend board is connected and we start in...
def setUsername(self): # set username label, called when landing window is created conn = connect('users.db') c = conn.cursor() c.execute('SELECT username FROM all_users WHERE id=?', (self.id,)) username = c.fetchone()[0] self.user_Value.setText(username) c.close() def ch...
This code initializes a landing page UI, sets up user-specific data (ID, username), checks database parameters, configures device status variables, and connects UI buttons to handler functions for navigation, connection, mode changes, and parameter updates. It prepares the interface for device interaction and state man...
def __init__(self, stacked_window, id): super(LandingWindow, self).__init__() loadUi('./windows/landingpage/landingpage.ui', self) self.stacked_window = stacked_window self.stacked_window.setWindowTitle("Landing Page") # set default values & initialize variables self.cur...
def searchInGoogleEngine(self, query:str): query = query + Sage.__searchPhraseBase for first_http_adress in search(query, tld="co.in", num=1, stop=1, pause=3): return first_http_adress def getHttp(self,adress:str, subadress:str): y = requests.get(adress + subadress) return ...
The method searches Google for the given question, retrieves the result, and processes it with the search phrase to generate a refined response.
def askSearchQuestion(self, question:str, searchPhrase:str): adress = self.searchInGoogleEngine(question) response = self.getHttp(adress,"") return self.deepQuestionProcess(response, searchPhrase)
def calculateOptimalCellSize(self, cells, headers): col_lengths = [0] * len(cells[0]) sum_len = 0 for i in range(0, len(cells)): for j in range(0,len(cells[i])): col_lengths[j] += len(cells[i][j]) sum_len += len(cells[i][j]) if len(ce...
This function processes HTML table content by converting it into a structured Unicode table. It reads the HTML table, renames columns, converts all values to strings, replaces 'nan' with '-', calculates optimal cell sizes, constructs table headers based on column structure, and assembles the final table by iterating th...
def createUnicodeTable(self, content:str): data = pd.read_html(content)[0] data4Cells = data.values data.rename(columns=lambda x: re.sub('Unnamed:[\w\s\d_]+','--',x),inplace = True) #convets every value to string for c in range(0, len(data4Cells)): for i in range(0, ...
def encode(self, x, conditioning=None, mask=None): """Encode an image x.""" # Encode if using encoder-decoder; otherwise just return data sample if self.use_encdec: if conditioning is not None: cond = self.embed(conditioning) else: cond = ...
The main task of the code is to compute and return three loss components—reconstruction loss, latent KL divergence loss, and diffusion loss—for a diffusion model with conditioning. It encodes inputs, calculates reconstruction error, applies a prior-based latent loss, samples time steps for diffusion, and computes the d...
def __call__(self, x, conditioning=None, mask=None): d_batch = x.shape[0] # 1. Reconstruction loss # Add noise and reconstruct f = self.encode(x, conditioning) loss_recon = self.recon_loss(x, f, conditioning) # 2. Latent loss # KL z1 with N(0,1) prior l...
def add_missing_money_to_state_mappings(state_mappings_df, meta_data_totals): # Group together calculated state totals to get the total calculated receipts from the database # Compare this to the true receipts from the meta data file grouped_totals = state_mappings_df.groupby(['fec_id']).sum()[['total_recei...
The main task of the code is to generate visual data blocks representing political fundraising by party/state, handling rounding issues and untracked funds. It loads and filters 2020 campaign data, creates synthetic rows for unaccounted donations, categorizes contribution sources, and assigns blocks to candidates. The ...
def main(): # ==== Load data files ===== # # Candidate totals by state state_mappings_df = pd.read_csv('db_outputs/candidate_states.csv') # Total large individual donor money by candidate (to differentiate between large/small indiv. donations) big_money_totals = pd.read_csv('db_outputs/total_big_...
def WriteLog(Message, FuncName, ErrorType: LogLevel = "Info"): options = get_args(LogLevel) assert ErrorType in options, f"'{ErrorType}' is not in {options}" TimeStamp: str = DateTimeLog() logger = logging.getLogger(FuncName) if ErrorType == 'Info': logging.basicConfig(filename='events.log'...
The code defines a function 'Lucy' that initializes and trains a ChatterBot AI to respond to user queries via speech recognition. It configures the bot with custom responses, trains it using predefined conversation examples and a CSV dataset, and integrates text-to-speech for interaction. The bot handles specific tasks...
def Lucy(): WriteLog(Message='Starting Lucy Functions', FuncName='Lucy', ErrorType='Info') from chatterbot import ChatBot from chatterbot.trainers import ListTrainer from chatterbot.trainers import ChatterBotCorpusTrainer chatbot = ChatBot( "Lucy", storage_adapter="chatterbot.storag...
def WriteLog(Message, FuncName, ErrorType: LogLevel = "Info"): options = get_args(LogLevel) assert ErrorType in options, f"'{ErrorType}' is not in {options}" TimeStamp: str = DateTimeLog() logger = logging.getLogger(FuncName) if ErrorType == 'Info': logging.basicConfig(filename='events.log'...
The main task of the code is to convert spoken input into text. It records audio using `record_audio()`, processes it with `recognize_speech()` to extract a query, and returns the recognized text. The function also logs informational messages to track its execution.
def GetSpeech(): WriteLog(Message='Starting GetSpeech Functions', FuncName='GetSpeech', ErrorType='Info') # Getting speech instead of having to type to Lucy audio = record_audio() query = recognize_speech(audio) WriteLog(Message='Closing GetSpeech Functions', FuncName='GetSpeech', ErrorType='Info') ...
def WriteLog(Message, FuncName, ErrorType: LogLevel = "Info"): options = get_args(LogLevel) assert ErrorType in options, f"'{ErrorType}' is not in {options}" TimeStamp: str = DateTimeLog() logger = logging.getLogger(FuncName) if ErrorType == 'Info': logging.basicConfig(filename='events.log'...
The main task of the code is to handle user queries via a GUI, using a chatbot for general responses and specific functions for weather checks, web searches, and reminders. It initializes a ChatterBot, processes exit commands, retrieves weather data, performs searches, sets reminders, and uses text-to-speech for respon...
def LucyGUI(query): WriteLog(Message='Starting Lucy Functions', FuncName='Lucy', ErrorType='Info') from chatterbot import ChatBot chatbot = ChatBot( "Lucy", storage_adapter="chatterbot.storage.SQLStorageAdapter", database_uri='sqlite:///site////lucy.sqlite3', logic_adapters=[...
def build_max_heap(A): global heap_size heap_size = len(A) - 1 n = len(A) for i in range((n // 2), -1, -1): max_heapify(A, i) return A def max(A): # build_max_heap(A) return A[0] def extract_max(A): global heap_size reset_heap_size(A) maximum = A[0] A[0], A[len(A) -...
The code demonstrates max heap operations: building a max heap from an array, extracting the maximum element, deleting a specified key, and inserting a new key, while displaying the array state at each step to illustrate heap functionality.
def driver(): A = [16, 14, 0, 18, 9, 1] print("Array before building max heap: ") print(A) print("**** built_max_heap ****") built_max_heap = build_max_heap(A.copy()) print(built_max_heap) print() print("Max of built_max_heap: ") print(max(built_max_heap)) print() print(...
def read_file(filename): try: file = open(filename, 'r') return file.readlines() except IOError: print("Error opening the given file name: " + filename) sys.exit() def get_words_from_line_list(linelist): word_list = [] for line in linelist: words_in_line = get_wor...
The main task of the code is to process a text file by reading its contents, extracting individual words, counting the frequency of each word, and returning an alphabetically sorted list of [word, frequency] pairs. This involves reading the file, splitting text into words, tallying occurrences, and organizing results i...
def word_frequency_for_file(filename): # Returns alphabetical sorted list of [word,frequency] pairs for a given file line_list = read_file(filename) word_list = get_words_from_line_list(line_list) # print(word_list) frequency_mapping = count_frequency(word_list) return frequency_mapping
def check_height(self, sandbox): self.list_of_heights = [0] * sandbox.width for x in range(sandbox.width): for y in range(sandbox.height): if (x, y) in sandbox.cells: self.list_of_heights[x] = sandbox.height - y break return s...
This function calculates a composite score for a game board based on multiple factors like height, cleared lines, holes, bumps, and blockades. It uses different weighted coefficients depending on the sandbox height, combining these factors multiplicatively to determine an overall score for evaluating game states.
def score_board(self, sandbox, board, shape): # a = -0.510066 # b = 0.760666 # c = -0.35663 # d = -0.184483 if self.check_height(sandbox) > 130: a = -0.710066 b = 0.760666 c = -0.35663 d = -0.184483 e = -0.495432 ...
def rotation_range(self, board): if str(board.falling.shape) == "Shape.I": return 2 elif str(board.falling.shape) == "Shape.O": return 1 else: return 4 def move_to_target(self, board, t_rot, t_pos): try: current_position = board.falling.lef...
The code evaluates potential moves in a game by simulating two-step actions (rotations and positions) on cloned game boards, calculating scores for each scenario, and selecting the move sequence with the highest combined score. It prioritizes discarding if optimal, returning the best move or a discard action based on h...
def choose_best_move(self, board): best_score = -10000000 best_moves = [] score = 0 for rotation1 in range(self.rotation_range(board)): for position1 in range(10): sandbox = board.clone() shape1 = str(sandbox.falling.shape) mov...
def rotation_range(self, board): if str(board.falling.shape) == "Shape.I": return 2 elif str(board.falling.shape) == "Shape.O": return 1 else: return 4 def move_to_target(self, board, t_rot, t_pos): try: current_position = board.falling.lef...
The main task of the code is to determine the optimal move sequence for a Tetris-like game by evaluating all possible rotations and positions for two consecutive moves. It calculates scores for each combination, tracks the highest-scoring moves, and prioritizes discarding the current piece if beneficial. The function r...
def choose_best_move(self, board): best_score = -10000000 best_moves = [] score = 0 for rotation1 in range(self.rotation_range(board)): for position1 in range(10): sandbox = board.clone() shape1 = str(sandbox.falling.shape) mov...
def game_winner_check(self) -> bool: """ Checks if anyone won the whole game by comparing players score against the set score limit. Adds another round if the scores of players are equal and score limit is reached. """ if self._players[0] == self._players[1] and self._players[0]....
This method manages the game loop by alternating player turns, checking for round and game-winning conditions, handling draws, and repeating the game if desired. It runs while the game is active, processes moves, determines outcomes, and concludes with a farewell message when the game ends.
def game_loop(self): """Main method responsible for the game""" while self._game_on: while not self.game_winner_check(): while not self.round_winner_check(): if self.board_has_empty_cells_check(): self.change_player() ...
def run_cmd(command: str) -> int: return subprocess.run(command, shell=True).returncode def get_cmd_result(cmd: str) -> str: ret = subprocess.run(cmd, shell=True, capture_output=True) return ret.stdout.decode().strip() def set_alias_for_git(home: Path) -> None: config = home / ".gitconfig" if not co...
The main task of the code is to automate the setup of a user's development environment by copying utility files, configuring shell aliases, setting up pip sources, installing Python packages, and modifying shell configuration files like .bashrc or .zshrc. It ensures aliases and paths are correctly set, handles pip conf...
def main(): home = Path.home() aliases_path = home / ALIAS_FILE if aliases_path.exists(): a = input(f"`{aliases_path}` exists. Continue and replace it?[y/(n)] ") if not a.lower().strip().startswith("y"): return try: repo = Path(__file__).parent.resolve() except Na...
def do_request(self): headers = self.get_headers() resp = requests.request(self.method, self.full_url, data=self.body, headers=headers) return resp def save_into_file(self, data): with open(self.get_full_filepath(), 'wb') as fwrite: fwrite.write(data) def is_file_untracked(s...
The code fetches data from a URL, saves it to a file, checks if the file is new or modified, commits changes to version control, sends notifications on modifications, and updates the last fetched timestamp. It ensures data tracking and change detection with optional automatic saving.
def fetch(self, do_save=True): resp = self.do_request() self.save_into_file(resp.content) fetch_date = timezone.now() if self.is_file_untracked(): commit_msg = 'New URL ({}) is now being tracked'.format(self.url_name) self.commit(commit_msg) elif self.is_...
def read_query(nome_tab,lista_conn,cur,j): sc = -1 while sc<1 or sc>2: lista_conn[j][0].send("Cosa vuoi visualizzare? (1: visualizza tutta la tabella ; 2: applica condizioni)".encode()) sc = int(lista_conn[j][0].recv(1024).decode()) if sc==1: leggi_tabella(cur,lista_conn...
The code connects to a MySQL database, prompts a user to select a table (zone_di_lavoro or dipendenti_filippo_sacchetti), and allows CRUD operations (create, read, update, delete) on the chosen table via client-server interaction. It loops until the user exits, sending options and executing queries based on user input.
def db_get(lista_conn,lock,j): cn = mysql.connector.connect( host="127.0.0.1", user="root", password="", database="azienda", port=3306, ) cur = cn.cursor() tab=-1 while tab<1 or tab>2: lista_conn[j][0].send("su quale tabella vuoi agire? ...
def parseArgs(): parser = argparse.ArgumentParser(description="Yummarize is a script that summarizes youtube videos into recipe pdfs") parser.add_argument("url", help="The url of the youtube video you want to summarize") parser.add_argument("path", help="The path to the directory you want to save the recipe...
The main task of the code is to extract a recipe from video captions, retrieve video metadata, and save the results. It parses input arguments, fetches captions from a given URL, generates a recipe from the captions, extracts video title and channel information, then stores the recipe, video details, and original URL t...
def main(): settings = parseArgs() user_input = settings.url caption = getCaptions(user_input) recipe = getRecipe(caption) videoTitle, channel = (getVideoMetaData(get_video_id(user_input))) save(recipe, videoTitle, channel, user_input, settings.path)
def get_resource(id: int) -> Resource | None: try: resource = database.session.query(Resource).filter_by(id=id).one() except NoResultFound: return None return resource def append_resource_history(resource: Resource, msg: str) -> list[tuple[datetime, str]]: history = resource.history ...
This function allows a user to claim a resource by its ID. It checks if the resource exists and is available, marks it as taken by the current user, records the action in the resource's history, updates the database, and adds the resource to the user's latest resources list. If the resource is unavailable or not found,...
def take_by_id(id): resource = get_resource(id) if resource is None: return make_response({"error": f"No resource found with id {id}"}, 400) if resource.taken: return make_response({"error": f"Resource {id} already taken"}, 400) resource.taken = True resource.taken_by = current_user....
def get_resource(id: int) -> Resource | None: try: resource = database.session.query(Resource).filter_by(id=id).one() except NoResultFound: return None return resource def append_resource_history(resource: Resource, msg: str) -> list[tuple[datetime, str]]: history = resource.history ...
The main task of the code is to release a resource by updating its status (marking it as not taken), clearing ownership details, recording a release history entry with the current user's name, and saving these changes to the database. It returns an error if the resource isn't found or a success response upon successful...
def release_by_id(id): resource = get_resource(id) if resource is None: return make_response({"error": f"No resource found with id {id}"}, 400) resource.taken = False resource.taken_by = None resource.taken_on = None resource.history = append_resource_history(resource, f"Released by {cur...
def get_resource(id: int) -> Resource | None: try: resource = database.session.query(Resource).filter_by(id=id).one() except NoResultFound: return None return resource def append_resource_history(resource: Resource, msg: str) -> list[tuple[datetime, str]]: history = resource.history ...
This function updates a resource's details in a database using form data. It retrieves the resource by ID, validates the update form, updates the resource's attributes (name, type, notes, group, history), and saves changes. If the form is invalid, it renders the resource edit template. If valid, it redirects to the hom...
def update_by_id(id): resource = get_resource(id) if resource is None: abort(404) form = get_resource_update_form() if form.validate_on_submit(): # TODO add name validation to prevent update to exising name resource.name = form.name.data resource.resource_type = form.reso...