dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def make_system(): def system_linear(x,t,params): k,gamma = params["k"], params["gamma"] dx1dt = x[0][1] dx2dt = -k*x[0][0]-gamma*x[0][1] return torch.cat([dx1dt.view(-1,1), dx2dt.view(-1,1)], dim = 1) k = torch.tensor([1]) gamma = torch.nn.Parameter( torch.tensor([0....
This function generates an animated plot comparing forward and backward passes of a system's dynamics. It visualizes predicted states (forward pass) against data points and ground-truth trajectories, while depicting adjoint states (backward pass) with gradient arrows. The figure includes interactive playback, dual subp...
def make_figure_fwd_bwd(x0,T,data, indices_data): indices_data = indices_data xdata =data[indices_data] xdata = torch.tensor(xdata) system, params = make_system() out = forward_pass(x0,T,system) xpred = torch.cat([out[i] for i in indices_data], dim = 0) loss = backward_pass(...
def _load_save_file(self): if self.file.file is not None: appts = self.file.read_appts() self.allow_weekends = self.file.read_setting('allow_weekends') == 'True' ## reads key and converts json string to boolean self.allow_duplicates = self.file.read_setting('allow_dupli...
This code initializes an appointment scheduler with configurable start/end times, owner, and settings. It sets default work hours (9-17), checks for valid time ranges, loads/saves appointment data to a JSON file if an owner is specified, and calls info/help methods. The class manages appointment storage, duplication ru...
def __init__(self, **kwargs): self.appointments = [] self.start = Time(9) #TODO: check that end time is bigger than start self.end = Time(17) self.owner = None self.allow_duplicates = False self.allow_weekends = False self.allow_work_hours = True ...
def generate_batches(self, X, Y, batch_size): ''' param X: the input data param Y: the input labels param batch_size: The size of the batch for each iteration return: a list of randomly sampled batches (without replacement) ''' batches = [] s = np.arange(len(X)) np.random.shuffle(s) for i in ra...
The function trains a model using mini-batch gradient descent over multiple epochs. It computes training and test costs/accuracies per epoch, updates model parameters via forward/backward passes, and stores weights/biases as class variables. It returns lists tracking training/test costs and accuracies across epochs.
def train_model(self, X_train, Y_train, X_test, Y_test, lr=0.01, batch_size=1000, epochs=100): ''' param X_train: the input training data param Y_train: the input training labels param X_test: the test data param Y_test: the test labels param lr: the learning rate to control the step size param batc...
def randomly_place_all_ships(): """ Randomly initialises all ships with their positions and type and adds them to a fleet. :return: the newly compiled fleet with all 10 ships included """ fleet = [] # ship_lengths is determined by the fixed number of ships for each ship type in a game. ship_...
The main task of the code is to run a Battleships game where the user inputs coordinates to shoot at a board. It validates inputs, tracks hits/misses, prevents repeated shots, and ends when all ships are sunk or the user quits. It also counts total shots taken and provides appropriate feedback throughout the game.
def main(): """ Initialises the board. Takes valid user input to determine where to shoot on the board, prints response for invalid shots and tracks total number of shots taken. Allows user to quit when correct input is entered. """ current_fleet = randomly_place_all_ships() print("Let's play ba...
def collect_data(self): # = = = = = = = = = = = = = = = = # Data Recovery # = = = = = = = = = = = = = = = = if self.folder_zipped: subprocess.run(["tar", "-xf", self.path_zip, '-C',self.result_folder]) files = os.listdir(self.path) for f in files: path = self.path + '/' + f list_cs...
This code initializes an object to recover, process, and visualize data from compressed files. It sets up directories, initializes data dictionaries, collects data using `collect_data()`, extracts specific message formats (e.g., GPS, PHINS), and saves generated plots. The main task involves data retrieval, structure or...
def __init__(self, path_zip, date_d, date_f, Zip = True): self.path_zip = path_zip # data compressed directory self.folder_zipped = Zip self.result_folder = '../res' # decompress the folder in this directory self.path = self.result_folder + '/Store_data' # where to find the data self.ihm_path = '../IHM' ...
def noisy_msg(dff, msg, path, n = 10, compression = True, N_round = 3): # data filtering with the mean each n values # - - - Data Recovery - - - list_msg = dff[msg] Ly = [np.round(np.mean(list_msg[k:k + n]),N_round) for k in range(0,len(list_msg) - n,n)] d0 = pd.DataFrame(compressed_time(dff['Tim...
The code processes raw DRIX status data by extracting specific parameters like thruster RPM, rudder angle, fuel level, and emergency modes. It applies functions to filter, reduce, or analyze data, then compiles results into a list for further processing or debugging.
def extract_drix_status_data(Data): path = Data.result_path + "/drix_status" df = Data.drix_status_raw L = [] L.append(noisy_msg(df, 'thruster_RPM', path, 100, N_round = 0)) L.append(centered_sawtooth_curve(df,'rudderAngle_deg', path, 200, N_round = 0)) L.append(noisy_msg(df,'gasolineLevel...
def data_reduced(dff, msg, path, compression = True): # ~ ~ ~ Data Recovery ~ ~ ~ list_t, Ly = data_reduction(dff[msg], dff['Time']) list_t = reduce_time_value(list_t) df = pd.DataFrame(list(zip(list_t, Ly)), columns =['t', 'y']) if compression: compress_data(path, msg, df) ret...
This function extracts and processes specific Iridium status metrics from raw data, saving them to a designated path. It aggregates key parameters like link status, signal strength, message codes, and queue statistics into a list for further analysis. The processed data includes reduced representations of columns such ...
def extract_iridium_status_data(Data): path = Data.result_path + "/iridium" df = Data.iridium_status_raw L = [] L.append(data_reduced(df, 'is_iridium_link_ok', path)) L.append(data_reduced(df, 'signal_strength', path)) L.append(extract_registration_status_data(df, path)) L.append(data_redu...
def data_source(url): # Define the remote file to retrieve remote_url = url # Define the local filename to save data local_dir = './data_store/data/American Sign Language Letters.v1-v1.tensorflow' # Make http request for remote file data file = wget.download(remote_url) # Create a ZipFile Ob...
The main task of the code is to process dataset splits by loading annotations and images, converting them into a structured dictionary format, and writing them into TFRecord files for machine learning. It retrieves data from a specified URL, iterates through dataset splits, loads and processes data, and generates outpu...
def main(): url ='https://public.roboflow.com/ds/NCbDlihA4z?key=pcdffiYbus' data_source(url) for splits in args.datasplit: FILE_PATH = args.datapath + splits annotations_test, images = file_loader(FILE_PATH) dataset_test = convert_to_dict(FILE_PATH, annotations_test) prin...
def parse_matrix_from_str_lines(lines): """ Parses and returns matrix from passed string lines. """ mat = [row.split() for row in lines] return mat def is_valid_position(position, xy_mat, yz_mat, zx_mat): """ Returns True if there is no obstacle in position, False otherwise. """ x, y...
The code reads command-line arguments for start/end coordinates and a file, parses 3D matrices from the file, validates the start/end positions, and finds a path through the matrices. If a path exists, it prints the start, end, and path commands; otherwise, it reports no path. The main task involves matrix parsing, pos...
def main(): NUM_ARGS = 7 args = sys.argv assert ( len(args) == NUM_ARGS + 1 ), "Passed wrong number of arguments, expected {NUM_ARGS=}" # First argument is the name of the code file. sx_str, sy_str, sz_str, dx_str, dy_str, dz_str, filename = sys.argv[1:] sx = int(sx_str) sy = in...
def _process_verticals(self, img, edges, height): vertical = np.copy(edges) prnt("\n\nProcessing vertical lines...") structuring_element = cv2.getStructuringElement(cv2.MORPH_RECT, (1, height // 30)) vertical = cv2.erode(vertical, structuring_element) if self.visualize: ...
This code recognizes a Tetris board from a BGR image by detecting grid lines using edge detection and Hough transforms, calculating intersections to map the board's block grid, and returning the resulting grid structure with optional visualization and color mapping.
def recognize(self, img) -> np.ndarray[(int, int), Color]: """ recognize the tetris board from image array For Hough lines first processing : https://stackoverflow.com/a/48963987 :param img: BGR colored array :return: block grid """ height = img.shape[0] ...
def preprocess_graph(self, modified_adj): adj = modified_adj + sp.eye(modified_adj.shape[0]) row_sum = adj.sum(1).A1 degree_mat_inv_sqrt = sp.diags(np.power(row_sum, -0.5)) adj_normalized = adj.dot(degree_mat_inv_sqrt).T.dot(degree_mat_inv_sqrt).tocsr() return adj_normalized def ...
The code performs a targeted graph attack to misclassify a specific node by strategically perturbing edges in the graph. It iteratively selects and flips edges based on structural scores and power-law likelihood ratios, minimizing the impact on the graph's statistical properties while maximizing the target node's miscl...
def attack(self, ori_features: sp.csr_matrix, ori_adj: sp.csr_matrix, labels: np.ndarray, idx_train: np.ndarray, target_node: int, n_perturbations: int, W1, W2, **kwargs): """ Parameters ---------- ori_features : scipy.sparse.csr_matrix Original (unperturbed) n...
def get_args() -> Namespace: ap = ArgumentParser(description="Create parser and scanner components") ap.add_argument("--spec", required=True, help="The file to read") ap.add_argument("--ebnf", help="The ebnf file to write") ap.add_argument("--insns", help="The insns file to write") return ap.parse_a...
The main task of the code is to parse command-line arguments, load a JSON specification file, convert it into a structured format, and generate EBNF grammar and instruction files based on the specification. It reads input from `args.spec`, processes it into a list of operations, then invokes `gen_ebnf` and `gen_insns` ...
def main(): args = get_args() # read args.spec as json file with open(args.spec) as f: spec: List[Operation] = convert_spec(json.load(f)) gen_ebnf(args, spec) gen_insns(args, spec)
def ecdh_handshake(client_ip, client_port): """ Function that manages the handshake performed with the ECDH algorithm. Returns the derived key (shared secret) """ print("\nInitializing handshake...") time.sleep(1) server_private_key = ec.generate_private_key(ec.SECP384R1, default_backend())...
The code starts a server to listen for client 'Hello' messages, perform an ECDH handshake to derive a shared key, authenticate the client, receive encrypted data, decrypt it using AES with the derived key, and print the decrypted message if authentication succeeds.
def start_server(): """ Starts the server and the session. The server listens for a 'Hello' from the client. The session consist of the handshake and receiving a message (if authenticated). """ print("\nStarting server...") time.sleep(1) print("Server is up and running!") hello_message...
def LoadLmpsFile(trj_file, verbose=1): ''' Extract the coordinate list from a lammpstrj file. ''' if verbose: print('[INFO] Loading data from {}.'.format(trj_file)) coor_lis = [] if not trj_file.split('.')[-1] == 'lammpstrj': raise TypeError('Wrong file type') with open(trj_f...
The function `GenAngDihFile` processes a LAMMPS trajectory file (`lammpstrj`) to compute and save **angles** and **dihedrals** for each frame. It loads atomic coordinates, calculates per-frame angles and dihedrals using helper functions (`CalAngle`, `CalDihedral`), and writes them into a structured output file (`.angdi...
def GenAngDihFile(filepath, folderpath=None, verbose=1): ''' Load a lammpstrj file, then generate a file contain angles and dihedrals. ''' coor_lis = LoadLmpsFile(filepath) # print(coor_lis) frame = len(coor_lis) # print(frame) # print(len(coor_lis[0])) atom = int(len(coor_lis[0]) / ...
def count_fanatasy_score_for_player_for_event(self, event = None, player = None): player.score_array.append((event, self.fantasy_score_map[event])) player.total_score += self.fantasy_score_map[event] def initialise_game_score(self): self.player1_score = 0 self.player2_score = 0 def check...
This method determines the set winner by comparing player scores, increments the winner's set score, resets game scores, updates fantasy points for the set win, and checks if the set or overall game has concluded.
def count_set_point(self): if self.player1_score > self.player2_score: self.count_fanatasy_score_for_player_for_event(player=self.player1, event='SET_WIN') self.set_score[1] += 1 self.initialise_game_score() else: self.count_fanatasy_score_for_player_for_e...
def count_fanatasy_score_for_player_for_event(self, event = None, player = None): player.score_array.append((event, self.fantasy_score_map[event])) player.total_score += self.fantasy_score_map[event] def ace_serve_randomness(self): random_num = random.randint(0, 11) random_chance = True ...
This method updates player1's score and fantasy points when they win a point. It increments the player's score, logs if the match has ended, and optionally adds an ACE_SERVE fantasy point based on a randomized chance. The 'randomise_ace' parameter controls whether the ACE_SERVE event is randomly triggered.
def player1_scores(self, randomise_ace = True): if self.match_ended: log.info("Game ended Return") self.count_fanatasy_score_for_player_for_event(player= self.player1, event='POINT_WIN') if randomise_ace: random_chance = self.ace_serve_randomness() if random_ch...
def count_fanatasy_score_for_player_for_event(self, event = None, player = None): player.score_array.append((event, self.fantasy_score_map[event])) player.total_score += self.fantasy_score_map[event] def ace_serve_randomness(self): random_num = random.randint(0, 11) random_chance = True ...
This function updates Player 2's score and fantasy points in a game. It checks if the match has ended, increments Player 2's fantasy score for a point win, optionally adds an ACE_SERVE fantasy point based on a randomized chance, increases Player 2's actual score by 1, and retrieves the updated score. The 'randomise_ace...
def player2_scores(self, randomise_ace = True): if self.match_ended: log.info("Game ended Return") self.count_fanatasy_score_for_player_for_event(player=self.player2, event='POINT_WIN') if randomise_ace: random_chance = self.ace_serve_randomness() if random_cha...
def get_products(): request = json.dumps({ "requestType": "getAllProducts", "userKey": CONFIG.mend_user_key, "orgToken": CONFIG.mend_api_token, "agentInfo": AGENT_INFO }) response_obj = json.loads(call_api(data=request)) if check_response_error(response_obj): exit...
The function identifies projects to be removed by filtering projects associated with each product based on a configuration. It retrieves products, checks their projects, applies the filter, and compiles a dictionary of product tokens mapped to their filtered projects. The result is a structured list of projects requiri...
def get_projects_to_remove(): projects_to_remove = {} products = get_products() for product in products: print(f"Getting projects to remove for product: {product['productName']}") projects = get_projects(product['productToken']) projects_length = len(projects) if projects_len...
def parse_config_file(filepath): if os.path.exists(filepath): config = ConfigParser() config.optionxform = str config.read(filepath) return argparse.Namespace( mend_user_key=get_config_file_value(config['DEFAULT'].get("MendUserKey", config['DEFAULT'].get("WsUserKe...
The code parses configuration settings from a file or command-line arguments, identifies projects to delete, and either generates reports and deletes them (based on flags) or performs a dry run simulation. It handles config parsing, project cleanup logic, and conditional execution of report generation and deletion task...
def main(): global CONFIG if len(sys.argv) == 1: CONFIG = parse_config_file("params.config") elif not sys.argv[1].startswith('-'): CONFIG = parse_config_file(sys.argv[1]) else: CONFIG = parse_args() setup_config() if CONFIG.dry_run: print("Dry Run enable...
def do_replace_attn(key: str): # return key.startswith('up_blocks.2') or key.startswith('up_blocks.3') return key.startswith('up') def cal_latent(self, num_inference_steps, guidance_scale, unconditioning, img_noise_0, img_noise_1, text_embeddings_0, text_embeddings_1, lora_0, lora_1, alpha, use_lora, fix_lora=N...
This code generates a sequence of images by morphing between two states using varying alpha values. It loads LoRA weights into a UNet, configures attention processors for cross-attention storage/loading, computes latent representations for each alpha, converts them to images, and saves them if specified. The process in...
def morph(alpha_list, save=False): images = [] if attn_beta is not None: self.unet = load_lora(self.unet, lora_0, lora_1, 0 if fix_lora is None else fix_lora) attn_processor_dict = {} for k in self.unet.attn_processors.keys(): ...
def px_given_c(x, c): #evaluate true distribution p(x|c) at a given exposure x and covariate c px_gc = np.zeros((np.size(x),1)) for i in range(np.size(x)): if x[i]==1: #probability of treatment assignment px_gc[i] = 1-sigmoid(c[i]) else: #probability of no...
The main task of the code is to compute the weight (wt) and true density (true_den) for given inputs x and c. It calculates px_c as the conditional probability of x given c, multiplies it by the covariate distribution of c to get true_den, then divides the evaluated number of weights (eval_numOfwt) by true_den to deriv...
def wt_true(x,c): px_c = px_given_c(x,c) true_den = px_c*covariate_dist(c) wt = eval_numOfwt(x,c)/true_den return wt, true_den
def Tan(value): '''value is in degrees''' value = angle2degrees(value) return np.tan( np.deg2rad( value )) def Cos(value): '''value is in degrees''' value = angle2degrees(value) return np.cos( np.deg2rad( value )) def Fgeodesic(ad, theta, phi): ''' ad = (RA, Dec) inputs are in degrees, or radians, or ...
The code generates a polygon on a spherical surface by calculating points using geodesic distances and angular coordinates. It converts these points to degrees and returns their coordinates as a flattened list.
def IFUSpherePts(shotcentAD, ifucent, msize, pangle): '''final Polygon in units of degrees''' tanL = Tan( ifucent[0] ) tanM = Tan( ifucent[1] ) phi = np.arctan2( tanL, tanM ) theta = np.arctan( tanM / Cos(phi) ) adcent = Fgeodesic( shotcentAD, theta, phi + pangle) poly_table = [ Fgeodesic( adcent, msize/...
def get_init_walker_values(nwalkers=100, fit_powerlaw_index=False, nf50=1): ''' Before running emcee, this function generates starting points for each walker in the MCMC process. Starting points are randomly drawn from the uniform prior Parameters ---------- nwalkers : int number ...
The function `fit_model` performs Bayesian inference to fit a flux distribution model to observed data using Markov Chain Monte Carlo (MCMC) sampling. It estimates parameters (beta, f50, alpha) governing the completeness curve and flux distribution, accounting for multiple fields if provided. The MCMC process (via `emc...
def fit_model(f, fcmin=0.1, fcut=None, nwalkers=100, nsteps=1000, fill_vary_f50=True, plt_title='', fnames=None): ''' Fit the flux distribution Parameters ---------- f : 1d array linear fluxes --OR-- if fitting multiple fields, it is a list of 1d arrays f...
def set_base_dir(base_in=None): if base_in: base_dir = base_in else: base_dir = '/home/will/research/3dhst/3dhst_grism_data/' return base_dir def set_objlist(obj_list): if isinstance(obj_list,int): return [obj_list] else: return obj_list def create_phot_catalog(field, obj_list, filter_list='',...
The function filters an object list based on signal-to-noise ratio (SNR) thresholds. It returns objects with SNR ≥ min_snr (or < min_snr if badlist=True), using F160W data when F140W measurements are missing. Optional return of SNR values is supported.
def snr_cut(field, obj_list, min_snr=10, base_dir='', badlist=False,return_snr=False): '''return object list including only objects with SNR>min_snr unless badlist=True --> then, return objects with SNR<min_snr''' base_dir = set_base_dir(base_dir) obj_list=set_objlist(obj_list) field_loc = {'AEGIS':215., 'C...
def get_inputs(self, prompt_text): encodings_dict = self.tokenizer.batch_encode_plus([prompt_text], padding=True) input_ids = torch.tensor(encodings_dict['input_ids'], dtype=torch.int64, device=self.device) attention_mask = torch.tensor(encodings_dict['attention_mask'], dtype=torch.float32, devi...
The function generates text sequences using language models via decoding strategies (greedy, beam search, sampling). It processes input text, validates parameters, and uses model configurations for defaults. It handles attention masks, padding, and expands inputs for multiple sequences/beam search. The output is decode...
def generate(self, input_text, max_length: Optional[int] = None, min_length: Optional[int] = None, do_sample: Optional[bool] = None, early_stopping: Optional[bool] = None, num_beams: Optional[int] = None, temperature: Optional[float] = None, top_k: Optional[int] = None, top_p: Optional[float] = None, re...
def _create_read_queue( self, conn: Connection, condition: BooleanClauseList, order: List[UnaryExpression], group_name: str, block_size: int, ) -> Tuple[int, int]: Groups = self._meta.tables["read_queue_groups"] Queue = self._meta.tables["read_queue"]...
The main task of this code is to fetch alerts from a database based on specified conditions, handling them in batches using shared queues for concurrency control. It locks alerts to prevent duplicate processing, supports options for distinct results, historical data, and cutouts, and iteratively retrieves chunks until ...
def _fetch_alerts_with_condition( self, conn, condition, order: List[UnaryExpression] = [], *, distinct: bool = False, with_history=False, with_cutouts=False, group_name=None, block_size=None, max_blocks=None, ): """ """...
def _GetAllProjectsCommitIds(self): """Get commit ids for all projects from superproject and save them in _project_commit_ids. Returns: CommitIdsResult """ sync_result = self.Sync() if not sync_result.success: return CommitIdsResult(None, sync_result.fatal) data = self._LsTree() ...
The code updates the `revisionId` of each project in the provided list using commit IDs retrieved from a manifest. It first fetches all project commit IDs; if none are found, it returns an error. For each project, it skips updates if specified, checks for missing commit IDs, and logs errors if any. If all commit IDs ar...
def UpdateProjectsRevisionId(self, projects): """Update revisionId of every project in projects with the commit id. Args: projects: List of projects whose revisionId needs to be updated. Returns: UpdateProjectsResult """ commit_ids_result = self._GetAllProjectsCommitIds() commit_id...
def milestone_by_name(self, project_id, milestone_name): milestones = self.get("/projects/:project_id/milestones",project_id=project_id) for milestone in milestones: if milestone['title'] == milestone_name: return milestone def put(self, url_postfix, data, **keywords): ...
The main task of the code is to create or update a milestone in a project by formatting its due date, checking for an existing milestone with the same name, and using PUT/POST requests to either update an existing milestone or create a new one, ensuring proper ID handling and project-specific operations.
def create_milestone(self, dest_project_id, new_milestone): if hasattr(new_milestone, 'due_date'): new_milestone.due_date = new_milestone.due_date.isoformat() existing = Milestones.create(self.milestone_by_name(dest_project_id, new_milestone.title)) if existing: new_miles...
def parse_legacy_files(filelist, write_inputs): dataset = list() for filename in filelist: with open(filename) as fin: data = parse_PacBio_log(fin) dataset.append(data) if write_inputs: with open(filename+'.json', 'wt') as fout: pri...
The code processes input reports by parsing either legacy files or JSON data, merges the parsed datasets, and writes the merged results to a JSON file or a PacBio report based on command-line arguments.
def main(args): if args.legacy: dataset = parse_legacy_files(args.reports, args.write_input_json) # Merge the dictionaries merged = merge_legacy_count_dict(dataset) else: dataset = parse_report_json(args.reports) # Merge the dictionaries merged = merge_json_report...
def _read_reqs(self) -> Requirements: """Reads the packages.json file.""" if not self.packages_json.exists(): return Requirements([]) out = self.packages_json.read_text() data = Requirements.from_json(out) return data def _pip_install( env_path: Path, package: str...
This method installs a package or list of packages into a virtual environment using pip, validates the environment's existence, updates the requirements file with the installed package(s), and handles both string and list inputs while enforcing full isolation if specified.
def pip_install( self, package: str | list[str], build_options: str | None, full_isolation: bool, ) -> None: """Installs a package in the virtual environment.""" assert ( self.env_path.exists() ), f"The environment {self.env_path} doesn't exist, in...
def lock(self) -> Iterator[None]: """Locks the environment to prevent it from being used.""" self.file_lock.acquire() try: yield finally: self.file_lock.release() def installed(self) -> bool: """Returns True if the environment is installed.""" if n...
The function ensures all required packages are installed by comparing current and previous requirements. If not installed, it sets up the environment, installs missing packages using pip, updates the requirements file, and returns the environment state. It uses a lock for thread safety and handles package installation ...
def ensure_installed(self, reqs: Requirements) -> dict[str, Any]: """Ensures that the packages are installed.""" with self.lock(): if not self.installed(): self.install_environment() prev_reqs = self._read_reqs() if reqs == prev_reqs: r...
def init_datafolder(self): import os.path if os.path.isdir(self.root_dir+self.dataset_meta): pass else: os.mkdir(self.root_dir+self.dataset_meta) def init_shalist(self): self.shalist=[] if self.exists_namespace('shalist'): pass else: ...
The main task of the code is to initialize a dataset object by setting up the root directory, loading metadata, initializing data structures (shalist, filelist), ensuring mandatory namespaces exist, and validating the consistency between shalist and filelist lengths. It also applies a provided transformation function f...
def __init__(self, root_dir, transform=None): self.root_dir = root_dir self.dataset_meta='dataset_meta/' self.init_datafolder() self.transform = transform # Ensure existance of mandatory namespaces self.namespaces=[] self.init_shalist() self.init_filelist(...
def build_mem(transitions, net, tgt_state, pool, G, tgt_G): if similarity_method == 'embed_match': score = calc_embed_match(transitions, net, tgt_state, pool, G, tgt_G) mem_pool = MQLMem(memory_size=5000) add_to_mem_with_score(mem_pool, transitions, score) return mem_pool def train(args, net, o...
The main task of the code is to perform iterative querying and evaluation of a neural network on a target dataset using memory samples from source transitions. It trains the network with generated memory pools, evaluates performance metrics (accuracy, F1 scores) over multiple trials, and returns averaged results. The p...
def permql(args, env, net, old_net, G, tgt_G, src_transitions): be = time.time() env.reset(dataset='target') env.init_train(dataset='target') accs, macro_f1s, micro_f1s = [], [], [] pre_net = QNet(args, env.statedim).cuda() pre_net.load_state_dict(old_net.state_dict()) for i in range(ar...
def place_queens(board): count = 0 while count < board_size: row = random.randint(0, board_size - 1) col = count board[row][col] = 1 count += 1 def print_board(board): for i in range(board_size): for j in range(board_size): print(board[i][j], end=' ') ...
The code solves the N-Queens problem using Hill Climbing and Simulated Annealing algorithms. It initializes a chessboard, places queens, and applies both algorithms to find solutions. It prints the initial board, resulting configurations, number of attacking pairs, and moves required for each method.
def main(): global board_size board_size = int(input("Number of Queens: ")) board = [] for i in range(board_size): row = [] for j in range(board_size): row.append(0) board.append(row) print("Initial board:\n") place_queens(board) print_board(board) ...
def playRound(self): gamePiece = "R" if self.turn % 2 == 0 else "Y" inp = self.getInput() self.placePiece(inp,gamePiece) self.turn += 1 def checkGameState(self): for row in range(len(self.gameBoard)): for col in range(len(self.gameBoard[0])): if self.g...
The code's main task is to execute a game loop that repeatedly plays a round, checks the game state (e.g., for a win), and updates the board display until the game ends. Upon termination, it announces the winner.
def playGame(self): while self.playing: self.playRound() self.checkGameState() self.printBoard() print('\n' + self.winner + " has won this game of Connect4")
def generate_node(N_tl): x_dist = 250.0 y_dist = 200.0 with open("data/tandem.nod.xml", "w") as nodes: print("""<nodes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/nodes_file.xsd"> """, file=nodes) for i in range(1, N_t...
This code initializes a traffic signal control environment for reinforcement learning, setting up SUMO (Simulation of Urban Mobility) parameters, defining observation/action spaces, and initializing variables to track traffic metrics like queue lengths, wait times, and throughput. It prepares the simulation environment...
def __init__(self, gui, N_tl, N_time, slot, min_time, gamma, arrival_distributions): # self.__version__ = "0.1.0" # General variables defining the environment self.gamma = gamma self.N_tl = N_tl self.state_size = 9 self.gui = gui self.slot = slot s...
def filter_good_ROI_dic(ROI_dic,min_number): newdic={} for ROI in ROI_dic.keys(): if len(ROI_dic[ROI]['Mask IDs'])>=min_number: newdic[ROI]=ROI_dic[ROI] termination=False while not termination: termination=True keys=list(newdic.keys()) for ROI in keys: ...
The function processes lineage tree data by loading ROI and mask information, filtering valid regions, detecting division errors, visualizing lineage structures, and saving processed results while removing temporary files.
def run_whole_lineage_tree(direc,thres=final_thresh,min_number=min_len_ROI,thresmin=thres_min_division,show=True): dicname='Main_dictionnary.npz' listname='masks_list.npz' ROIdict='ROI_dict.npz' linmatname='non_trig_Link_matrix.npy' boolmatname="Bool_matrix.npy" linkmatname='Link_...
def detekt_roots(linkmat,dim): forwardlinks=[] backwardlinks=[] for i in range(dim): forwardlinks.append([]) backwardlinks.append([]) rootslist=[] for i in tqdm.trange(dim): if np.max(linkmat[i,:])>0: for j in range(i+1,dim): if link...
The function generates a boolean matrix highlighting the longest paths from root nodes to leaf nodes in a directed graph, using a given adjacency matrix and maximum time difference constraint. It detects roots, identifies leaf nodes, computes longest paths, and updates the boolean matrix accordingly.
def Bool_from_linkmatrix(linkmat,max_diff_time): dim=len(linkmat) newmat=np.zeros((dim,dim),dtype=bool) print('Roots and links detection') forwardlinks,backwardlinks,rootslist=detekt_roots(linkmat,dim) #detekts roots and transform the matrix into an adjacence list print('Leafs detection') endpoi...
def trans_vector_matrix(dic,max_diff_time): dic_list=list(dic.keys()) fichier=dic_list[-1] maxtime=dic[fichier]['time'] mat_vec=np.zeros((maxtime+1,2*max_diff_time+1,2),dtype=np.int32) mat_ang=np.zeros((maxtime+1,2*max_diff_time+1)) for number in tqdm.trange(len(dic_list)): fichier1...
The code processes a dictionary of data to compute and save lineage, link, and boolean matrices for constructing a lineage tree. It loads masks and dictionaries, calculates translation/rotation vectors, generates lineage relationships, cleans the matrix, converts to a boolean matrix, and saves results as NumPy files fo...
def Final_lineage_tree(dic,max_diff_time=depth_search,surfthresh=surface_thresh,finthres=final_thresh): path= os.path.join('results', dic) dicname = os.path.join(path,'Main_dictionnary.npz') listname = os.path.join(path,'masks_list.npz') linmatname = os.path.join(path,'non_trig_Link_matr...
def preprocessing(self): image_gray_ = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) clh = cv2.createCLAHE(clipLimit=5.0) clh_img = clh.apply(image_gray_) blurred = cv2.GaussianBlur(clh_img, (5, 5), 0) return clh_img, blurred def sobel_filter(self): ima_gray = cv2.cvtColor(s...
The main task of the code is to generate binary regions from an image by combining thresholding, Sobel filtering, and HSV space analysis. It selects the optimal binary image based on threshold parameters and conditions, applying different processing methods (e.g., opera_sobel, opera_sobel_hsv, opera_gray) to produce th...
def binary_regions(self, x_, y_, radius_): _, original_gray = self.preprocessing() thresh_gray = threshold_otsu(original_gray) norm_img = cv2.normalize(self.img, None, alpha=-0.1, beta=1.1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) self.img_ = (255 * norm_img).astype(np.uint8) ...
def well_region(self): ima_gray, final_ima = self.preprocessing() gabor_img = self.apply_gabor(final_ima) thresh = threshold_otsu(gabor_img) thresh = cv2.threshold(gabor_img, thresh, 255, cv2.THRESH_TOZERO_INV)[1] total = thresh.shape[0] * thresh.shape[1] total_n = np.sum...
The main task of the code is to initialize well region coordinates in an image. It checks if the initial counter (cont_ini) is below 6 to directly append new well coordinates using well_region(), or evaluates existing coordinates with eval_cords() before appending. If cont_ini ≥ 6, it uses seq_circular() for sequential...
def ini_well(self, img, cont_ini, cords_well): self.img = img if cont_ini < 6: ima_res, x, y, radius = self.well_region() cords_well.append([x, y, radius]) else: _, x, y, radius = self.well_region() ctr_range = self.eval_cords(cords_well, x, y, rad...
def result_weather(self): self.ui.cityLabel.setText(f"{self.city}") self.ui.currentTempLabel.setText(f"{self.temperature}°") self.ui.humidityLabel.setText(f"Humidity: {self.humidity}%") self.ui.pressureLabel.setText(f"Pressure: {self.pressure} hPa") self.ui.speedLabel.setText(f"W...
The code fetches weather data for a specified city using the OpenWeatherMap API, processes the JSON response to extract key metrics like temperature, humidity, and wind speed, stores the data in instance variables, and triggers methods to update the UI and handle time zones or themes.
def request_weather(self): city = self.ui.citySearch.text() if city: city = city.capitalize() api_key = "79d1ca96933b0328e1c7e3e7a26cb347" url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric" response = requests.g...
def count_like(): print("count_like") ep_df = get_episode() behavior_df = get_behavior() print("-----------") ep_behavior_df = ep_df.join(behavior_df.set_index('episode_id'), on='id') count_like_df = ep_behavior_df.groupby( ["book_id"]).size().reset_index(name='count') print(count_li...
The main task of the code is to insert data from a DataFrame into a PostgreSQL database table named 'like_count'. It retrieves the DataFrame using count_like(), establishes a database connection with specified credentials, and executes an insertion operation using execute_insert_count_like_to_db(). The function prints ...
def insert_count_like_to_db(): print('insert_count_like_to_db') df = count_like() print(df.columns) param_like_count = { "host": Config.POSTGRESQL_TEST_HOST, "port": Config.POSTGRESQL_TEST_PORT, "database": Config.POSTGRESQL_TEST_DB, "user": Config.POSTGRESQL_TEST_USER, ...
def convert_is_payment_success(): column_payment_names = ["order_id", "status", "timestamp", "episode_id", "amount"] payment_df = get_payment() sort_payment_df = payment_df.sort_values(by=['order_id']) sort_payment_df = sort_payment_df.reset_index(drop=True) print('sort_p...
The main task of the code is to insert payment success data into a PostgreSQL database. It retrieves data via `convert_is_payment_success()`, connects to a test database using configuration parameters, and executes an insertion operation into the 'payment_success' table. The process includes logging intermediate steps ...
def insert_payment_success_to_db(): print('insert_payment_success_to_db') df = convert_is_payment_success() print(df.columns) print(df.head()) param_test = { "host": Config.POSTGRESQL_TEST_HOST, "port": Config.POSTGRESQL_TEST_PORT, "database": Config.POSTGRESQL_TEST_DB, ...
def is_attacker_win(state) -> bool: # There are pieces at the highest level return state.tensor[0, -1] > 0 def is_defender_win(state) -> bool: # There are no more pieces return n_pieces(state.tensor) == 0 def is_done(state): # Did someone win? return is_defender_win(state) or is_attacker_win(sta...
The code defines a `step` method in a reinforcement learning environment, which processes an action, updates the state, calculates rewards for attacker and defender based on win conditions, checks if the episode is done, and returns the new state, done status, and reward.
def step(self, state, action) -> (int, torch.Tensor, float): reward = {0: int(is_attacker_win(state)), 1: int(is_defender_win(state))} state = state.apply_action(action) done = is_done(state) new_states = build_state(self.N, self.K) return state, done, reward
def checkConfig(): global repo_local_path global hal_dest_path global cmsis_dest_path global system_dest_path global md_HAL_path global md_CMSIS_path global stm32_def config_file_path = script_path / path_config_filename if config_file_path.is_file(): try: config...
The main task of the code is to manage STM32 device updates by checking configuration, generating a device list, handling user-specified additions, updating repositories, and either printing version info or executing core updates based on command-line arguments. It ensures valid STM32 additions, avoids duplicates, and ...
def main(): global stm32_list # check config have to be done first checkConfig() updateCoreRepo() stm32_list = genSTM32List(hal_dest_path, upargs.serie) if upargs.add: if upargs.add.upper() not in stm32_list: stm32_list = [upargs.add.upper()] else: print(u...
def predict(self,v): summation = 0 d = 0 while(d<D): if v[d] == 0 : continue summation += self.A[d]*(v[d]**self.B[d]).real print(summation) d += 1 return summation + self.bias def total_loss(self,P): summa...
The code trains a model using gradient descent to minimize a loss function. It iteratively updates parameters A, B, and bias by adjusting them with learning rate-multiplied gradients. For each epoch, predictions P are recalculated after each parameter update, and the total loss E is evaluated. The process repeats until...
def train(self,epochs,threshold,learning_rate): epoch = 0 P = [self.predict(v) for v in self.V] E = self.total_loss(P) while (epoch < epochs and E >= threshold): d = 0 while (d<D): A[d]-= learning_rate*self.d_total_loss_Ad(P,d) P = ...
def _prescreen(self, data): # fetch information from crowdsourced data n_task = len(np.unique(data[:, 0])) # number of tasks n_worker = len(np.unique(data[:, 1])) # number of workers n_task_group = len(np.unique(data[:, 2])) # number of task categories n_record =...
This method fits a model to the input data for classification tasks. It first prescreens the data, then applies binary fitting/inference if there are 2 task groups or multiclass fitting/inference for more than 2 groups, returning predicted labels. The process uses iterative optimization with specified maximum iteration...
def fit(self, data, maxiter=100, epsilon=1e-3, verbose=0): self._prescreen(data) if self.n_task_group == 2: self._binary_fit(data, maxiter=maxiter, epsilon=epsilon, verbose=verbose) label = self._binary_infer(data) return label elif self.n_task_group > ...
def torque_level(self): return self.get_state_value(self.TORQUE_LEVEL) def is_turning(self): return self.direction() in [self.steering.LEFT, self.steering.RIGHT] def direction_level(self): return self.get_state_value(self.DIRECTION_LEVEL) def direction(self): return self.get_state_value(...
This method adjusts the torque applied to the left and right wheels based on the vehicle's direction and turning state. It calculates a turning-side torque level when turning, then assigns this value to the appropriate wheel (left or right) depending on the direction. The wheels' torque levels are then updated to ensur...
def update_wheels_torque(self): left_torque = right_torque = self.torque_level() if self.is_turning(): torque_level_turning_side = self.steering.calculate_torque_level_turning_side(self.torque_level(), self.direction_level(), self.turning_apex) if self.direction() == self.steering....
def update_vehicle_state_values(self, data): status_bits = StatusBits(data[self.STATUS_INDEX]) self.vehicle_state[self.TORQUE_LEVEL] = data[self.TORQUE_LEVEL_INDEX] self.vehicle_state[self.REVERSE] = status_bits.reversed() self.vehicle_state[self.DIRECTION_LEVEL] = data[self.DIRECTION_L...
This code updates a vehicle's state using input data, checks if torque and direction levels are zero to decide stopping, and otherwise adjusts wheel torque, rotation, and steering for movement control.
def update(self, data): self.update_vehicle_state_values(data) if self.torque_level() == 0 and self.direction_level() == 0: self.stop_vehicle() else: self.update_wheels_torque() self.update_wheels_rotation() self.update_steering()
def read_dictionary(): with open(FILE, 'r') as f: for line in f: dictionary.append(line.replace('\n', '')) def initial_digit(d): """ TODO: # to reduce the search range, transform the dictionary into a three letters index # ['a','aa','aah','aal','aar'...] # use set...
The main task of the code is to generate anagrams for a given word using a dictionary. It reads the dictionary, processes user input, searches for valid anagrams, displays the results, and tracks the time taken. The loop continues until the user inputs "-1" to quit, resetting global variables after each search to ensur...
def main(): global possible, anagrams read_dictionary() initial_digit(dictionary) print('Welcome to stanCode "Anagram Generator" (or -1 to quit)') while True: search_word = str(input('Find anagrams for: ')).lower() start = time.time() if search_word == EXIT: break...
def parse_message(self, message: dict): """ Closed method for parsing message :param message: message dict from event object :type message: dict """ msg = message["text"].lower() cmd = msg.split("\n")[0].strip() id = message.get("peer_id") attachm...
This code initiates a polling loop to receive user messages via VK's longpoll. It executes an optional startup callback, processes new messages by parsing events, and restarts polling after handling timeouts or API errors. The core task is continuous message monitoring and processing with error resilience.
def start_polling(self, callback: Callable = None): """ Starting polling messages from users :param callback: [OPTIONAL] Function, which would be executed, when bot is started :type callback: Callable """ try: if callback is not None: callback...
def reset_mongo(): client = pymongo.MongoClient("mongodb://localhost") client.finalproject.users.drop() client.finalproject.listings.drop() client.finalproject.likes.drop() for user in load_data("user.json"): insert_user(user["name"], user["email"], user["dob"], "usernam...
The main task of the code is to connect to Neo4j and MongoDB, transfer data between them, and generate recommendations. It loads data from MongoDB to Neo4j, recommends listings/users for "Rachlin" using graph algorithms, and exports results back to MongoDB. Key steps include database reset, data migration, and personal...
def main(): uri = "neo4j://localhost:7687" user = "neo4j" password = "neo4jj" g = NeoApp(uri, user, password) client = pymongo.MongoClient() reset_mongo() # g.clear_database() # g.create_data() load_mongo_to_neo(client, g) # load data from mongo to neo4j # res = g.show_full_...
def _compounds(self, path): """Function to parse the compounds.txt file Extract the smile and the structure of each compounds of RP2Path output. Method to parse all the RP output compounds. :param path: Path to the compounds file :type path: str :rtype: dict ...
The main task of the code is to convert RetroPath2.0 (RP2) output files into SBML format by parsing compounds, pathways, and transformations from input files. It processes RP2's compounds.txt, out_paths.csv, and scope.csv to generate SBML models, applying flux bounds, compartment settings, and species grouping. The fun...
def rp2ToSBML(self, rp2_pathways, rp2paths_pathways, rp2paths_compounds, tmpOutputFolder=None, upper_flux_bound=999999, lower_flux_bound=0, maxRuleIds=10, pathway_id='rp_pathwa...
def get_geo(): """ Read in shapefile as Pandas DataFrame """ shape = './shapes/ELECTION_PRECINCTS.shp' return gpd.read_file(shape) def fake_data(): """ DEVELOPMENTAL FUNCTION """ import warnings warnings.filterwarnings('ignore') real_data = get...
The function aggregates geographical data with outreach data (either fake or real) by merging them on the 'PRECINCT' column, standardizing column names to uppercase, and returning the combined dataset for analysis.
def aggregate_data(dev=True, key=None): geo = get_geo() if dev: outreach_data = fake_data() else: outreach_data = get_all_precincts() outreach_data.columns = [x.upper() for x in outreach_data.columns] return geo.merge(outreach_data, on='PRECINCT')
def get_all_precincts(): """ Aggregates precinct geography and counts from outreach.db """ import warnings warnings.filterwarnings('ignore') # --- GeoData # Read shapefile as GeoPandas DataFrame geo_data = get_geo() # Add ID column geo_data['id'] = [0] * le...
The code generates an interactive choropleth map visualizing voter outreach data by precinct, using either real database data or fake data in development mode. It aggregates data for tooltips, applies styling, and saves the map as an HTML file in the templates folder for display.
def map_function_all_outreach(dev=True): """ Automated updating function ... this groups the outreach data by type, and pushes it to a Choropleth map of the city """ print('\n** Data incoming from database **\n') if not dev: # Isolate data from SQLite database ...
def empl_add_item_populate(emplEditScreen, uname): resetToDefaultElements(emplEditScreen, defaultWidgets) addFrame = Frame(emplEditScreen) addFrame.pack(padx=10, pady=10, expand=True, fill="both") empNm = StringVar() empSal = StringVar() Label(addFrame, text="Employee Name").pack() Label(add...
This code opens an employee management interface by creating a new window with buttons to add, modify, remove, or list employees, using the provided username. It hides the main screen, displays a welcome message, and initializes error handling and default UI elements for employee data operations.
def employee_editor_open(homeScreen, username1): homeScreen.withdraw() emplEditScreen = Toplevel(homeScreen) emplEditScreen.title("Menu Editor") emplEditScreen.geometry("640x480+200+200") Label(emplEditScreen, text="Welcome " + username1).pack() Label(emplEditScreen, text="").pack() top = Fr...
def showMenuAddUI(menuEditScreen, username): resetToDefaultElements(menuEditScreen, defaultWidgets) addMenuItemFrame = Frame(menuEditScreen) addMenuItemFrame.pack(padx=10, pady=10, expand=True, fill="both") itemName = StringVar() itemPrice = StringVar() Label(addMenuItemFrame, text="Item Name")....
This function creates a menu editor UI window to manage items, displaying the username. It hides the home screen, provides buttons to add/modify, remove, or list items, and includes an error label. The UI is initialized with default widgets and links to other functions for specific actions.
def showMenuEditorUI(homeScreen, username): homeScreen.withdraw() menuEditScreen = Toplevel(homeScreen) menuEditScreen.title("Menu Editor") menuEditScreen.geometry("640x480+200+200") Label(menuEditScreen, text="Welcome " + username).pack() Label(menuEditScreen, text="").pack() top = Frame(me...
def asses_pop(self, pop, is_children): for i in range(0, self._pop_size): if self._solution_found: return self.assess(pop[i]) pop = np.sort(pop) if not is_children: for i in range(0, self._pop_size): self._pop_scores[i] = pop[i...
The code implements a genetic algorithm's main loop to iteratively evolve a population toward a solution. It runs up to 10,000 iterations, performing selection, crossover, mutation, and population assessment at each step. Progress is logged every 500 iterations, and the loop terminates if a solution is found or the ite...
def run(self): logger.info("Genetic algorithm has started solving the problem") i = 0 MAX_ITERATIONS = 10000 while not self._solution_found: if i == MAX_ITERATIONS: logger.warning(f"Reached max iterations limit ({MAX_ITERATIONS}). Solving aborted.") ...
def calc_rows_loss_func(self): for row in range(self.get_size()): self.row_params[row].loss_func = self.calc_row_loss_func(row) def iterate_neighbours_in_row(self, row): max_diff = -math.inf self.row_params[row].fields_to_swap = np.array([]) for col in range(self.get_size()):...
The code implements the Tabu search algorithm to solve a problem by iteratively improving a board configuration. It initializes the board randomly, then repeatedly evaluates row loss functions, explores neighbor swaps, selects the best swap, and updates the Tabu list to avoid revisiting suboptimal solutions. The proces...
def run(self): logger.info("Tabu algorithm has started solving the problem") loops = 0 self.rand_init(self._board) MAX_ITERATIONS = 10000 while not self.is_solution(self._board): if loops == MAX_ITERATIONS: logger.warning(f"Reached max itertions limit ...
def table_change(): handle=input('Enter a name of the file:\n') rh=open(handle,'a') rh.close() rh=open(handle) str=rh.read() rh.close() if len(str)==0: create_file(handle,str) change=input("Want any change in the time table ?(Y/N)\n") if change.lower()=='y': while(cha...
This function checks if any scheduled tasks for the current day have passed. It reads a file containing day-time entries, compares the current time with these entries, and returns the earliest matching task's details if found. If no match is found, it returns a default response indicating no active task.
def day_check(): handle=table_change() fh=open(handle) current_time,day=ctime() f=0 c_time=current_time.split(':') for i in fh: sp=i.split('->') if sp[0]==day: each=sp[1].strip().split(',') for j in each: t=j.strip().split('=') ...
def scopus_parse_eid(full_metadata): return full_metadata.get('coredata', {}).get('eid') def scopus_parse_doi(full_metadata): try: return full_metadata['coredata']['prism:doi'] except KeyError: try: return full_metadata['item']['bibrecord']['item-info']['itemidlist']['ce:doi'] ...
This function parses Scopus API full metadata into a structured dictionary, extracting core publication details (title, authors, keywords, etc.), citation counts, abstracts, and related data using helper functions. It organizes fields like publication type, dates, affiliations, and references into a standardized format...
def scopus_parse_full_metadata(full_metadata): if full_metadata is None: return None coredata = full_metadata['coredata'] publication = { 'name': coredata.get('prism:publicationName', None), 'cover_date': coredata.get('prism:coverDate', None), 'type': coredata.get('prism:agg...
def scopus_search_by_title(title): title = title.strip(string.punctuation) params = { 'query': 'TITLE-ABS-KEY ( "{}" ) '.format(title) } res = requests_get(SEARCH_URL, params=params) if 'service-error' in res: if DEBUG >= 2: print(title) print(res) ret...
The code retrieves full metadata for a scholarly paper from Scopus by first searching via its title, extracting the Scopus Identifier (SID) from the top result, then fetching and parsing the complete metadata using that SID.
def get_metadata_by_title(title): results = scopus_search_by_title(title) if results is not None: sid = scopus_entry_get_sid(scopus_results_get_first_entry(results)) full_metadata = scopus_find_by_sid(sid) return scopus_parse_full_metadata(full_metadata)
def scopus_find_by_sid(sid): res = requests_get(ABSTRACT_SID_URL.format(sid)) return res.get('abstracts-retrieval-response') def scopus_parse_full_metadata(full_metadata): if full_metadata is None: return None coredata = full_metadata['coredata'] publication = { 'name': coredata.get...
This function retrieves metadata for each reference in the input metadata. It first attempts to fetch full metadata using a Scopus SID, then falls back to title-based retrieval if the SID method fails. The collected metadata for all references is returned as a list.
def get_references_metadata(metadata): if metadata['references'] is None: return None references = [] for ref in metadata['references']: full_metadata = scopus_find_by_sid(ref['sid']) ref_md = None if full_metadata is not None: ref_md = scopus_parse_full_metadata...
def hour_validation(): hour = '' minute = '' hour_selection = input("At what time? Enter your selection in 24h format (Ex. 13:00) or EOD: ") if hour_selection.lower() == 'eod': return 23, 0 try: hour_split = hour_selection.split(':') hour = hour_split[0] minute = hour...
The code provides a user interface to check package statuses. Users can view all packages or filter by attributes (ID, address, etc.) after inputting a time. It validates time inputs, processes packages, and displays results. If the hour is 23, it also shows driver positions. The loop continues until the user enters "Q...
def user_interface(): user_option = '' print('****************************************************************************') print("Hi! I can give you the packages status, you can finish by entering \"Q\"") print("Please select an option: ") print("1 - Status of all packages") print("2 - Status ...
def StackFrames(doppz, labels, frame_stack=10): max_index = doppz.shape[0] - frame_stack stacked_doppz = np.array([doppz[i:i + frame_stack] for i in range(max_index)]).transpose(0, 2, 3, 1) new_labels = np.array([labels[i + frame_stack - 1] for i in range(max_index)]) return stacked_doppz, new_labels de...
This code initializes a dataset processor for Doppler (doppz) data, loading and preprocessing a pickled DataFrame. It filters invalid activity labels, scales doppz values between dop_min and dop_max, stacks frames for temporal context, and prepares augmented data using a pipeline. Class attributes include activity coun...
def __init__(self, loc="merged_df2.pkl", class_count=3080, frame_stack=10, dop_min=9343, dop_max=36240): # Temp vals print(f"loading dataset from {loc}") df = pd.read_pickle(loc) df = df[df.Activity != ' '].reset_index() doppz = np.array(df['doppz'].values.tolis...
def StackFrames(doppz, labels, frame_stack=10): max_index = doppz.shape[0] - frame_stack stacked_doppz = np.array([doppz[i:i + frame_stack] for i in range(max_index)]).transpose(0, 2, 3, 1) new_labels = np.array([labels[i + frame_stack - 1] for i in range(max_index)]) return stacked_doppz, new_labels de...
The main task of the code is to initialize a dataset for machine learning by loading and preprocessing Doppler radar data. It scales the 'doppz' values, stacks frames for temporal context, and configures augmentation parameters based on class distribution. The code prepares data for training by setting up a transformat...
def __init__(self, loc="merged_df.pkl", frame_stack=10, augment=True): print(f"loading dataset from {loc}") df = pd.read_pickle(loc) df = df[df.Activity != ' '].reset_index() doppz = np.array(df['doppz'].values.tolist()) label = df['Activity'].values dop_max, dop_min = d...
def _createVariables(self): # Compute number of variables num_variables = 0 for rec_id in self.graph.nodes: if self.graph._checkIfMachine(rec_id): rec = self.graph.recipes[rec_id] # one for each input/output ingredient num_variables += ...
The code's main task is to set up and solve a system of equations representing resource constraints and machine interactions. It initializes variables, constructs equations from user-defined parameters and machine rules, builds a lookup index, connects machines, solves the system, and writes results to a graph.
def run(self): self._createVariables() # initialize v1, v2, v3 ... (first pass) # Construct system of equations self._addUserLocking() # add known equations from user "number" and "target" args self._addMachineInternalLocking() # add relations inside machines - eg 1000 wood tar -> 350 b...
def modifyTurbine(self, recipe, fuel_type): require( recipe, [ ['material', str, 'calculating power output (eg "infinity").'], ['size', str, 'calculating power output (eg "large").'], ] ) fuel = recipe.I._ings[0].name m...
The function `overclockRecipe` modifies a recipe's parameters based on predefined overclocking rules for specific machines. It uses a dictionary (`machine_overrides`) mapping machine names to corresponding modification functions (e.g., `modifyPyrolyse`, `modifyPerfect`). If the recipe's machine is in the dictionary, it...
def overclockRecipe(self, recipe, ignore_underclock=False): ### Modifies recipe according to overclocks # By the time that the recipe arrives here, it should have a "user_voltage" argument which indicates # what the user is actually providing. self.ignore_underclock = ignore_underclock ...
def create_left_frame(self): self.left_frame = tk.Frame(self, bg="pink") self.left_frame.grid(row=0, column=0, sticky="nsew") self.create_left_header() self.create_left_content() def create_right_frame(self): self.right_frame = tk.Frame(self, bg="white", width=2*self.settings.wi...
This code initializes a GUI component by setting up layout parameters, configuring grid expansion for the parent container, and creating left/right frames for interface elements. It establishes initial settings, tracks current items, and prepares the widget's structure within a container.
def __init__(self, parent, App): self.app = App self.settings = App.settings self.current_item = self.settings.item[0] self.last_current_item_index = 0 self.update_mode = False self.items_index = [] super().__init__(parent) #parent = window.container self...
def buildArtistXML(jsonArtist): """ Builds the XML tree for an artist given a Genius API-downloaded artist file """ artistRoot = ET.Element(util.ARTIST_HEAD) for song in jsonArtist['songs']: artistName = song['artist'] artistName = cleanArtistName(artistName) buildSongXML(son...
The main task of the code is to build an XML corpus from JSON artist and album data by loading artist files, generating XML structures for each artist, handling errors during processing, and performing post-processing tasks like adding supplemental albums, removing duplicates, normalizing names, and replacing infrequen...
def buildCorpus(): """ Main function to build the corpus from scratch. Reads in .json artist files from the rapdata directory and .json album files from the rapdata/album directory """ print("Building ILLMATIC corpus...") print() print() print("Loading artist JSON...") artists = data...
def turnPC(state,newNumbers): newNumberAt = randomEmptyField(state) h = newNumberAt[0] w = newNumberAt[1] newNumber = randomNumber(newNumbers) state[h][w] = newNumber def printStateStr(state): stateCopy = copy.deepcopy(state) valuesSet = set() for h in range(len(state)): valuesSe...
The code implements a game loop where the computer and player take turns modifying a game state. It starts by letting the computer play (turnPC), prints the state, then repeatedly prompts the player for input (turnPlayer) until the state changes. The inner loop ensures the player's move is processed only if the state h...
def play(state,newNumbers): while True: turnPC(state,newNumbers) printStateStr(state) stateCheck = copy.deepcopy(state) while stateCheck == state: turn = turnPlayer() turnResolve(state,turn)
def try_rotate(self): # check if we can rotate piece if self.current_piece is None: return if self.current_piece.locked: return prev_position = self.current_piece.position self.current_piece.move_next_pos() if not self.try_move(): self....
The main task of the code is to rotate the current game piece if possible. It checks if a piece exists, attempts rotation, clears the board, redraws the rotated piece, and locks it in place if successful, updating the game state accordingly.
def rotate_piece(self): if self.current_piece is None: return if self.try_rotate(): self.clear_board() self.draw_piece() self.try_lock_piece()
def game_over(self): if self.check_lock_conditions() and self.current_piece.y == 0: return True return False def try_remove_lines(self): for row_num, row in enumerate(self.board): if set([col.locked for col in row]) <= {1}: for col in row: ...
The main task of the code is to manage the core game loop: checking if the game is over, handling piece locking and line removal, advancing levels, updating current/next pieces, and drawing new pieces. It also triggers piece falling when active. The loop ensures game state transitions, score progression, and piece move...
def game_loop(self): # main game loop if self.game_over(): print("Game Over!") return if self.current_piece.locked: if self.try_remove_lines(): self.next_level() self.current_piece = self.ne...
def startCapture(self): ''' Starts buffering from the camera object using cv2 Video Capture Update time when frames are captured ''' try: logs.debug("Starting camera -> %s",self.id) self.capture = cv.VideoCapture(self.src) self.capture.set(cv.C...
This code continuously monitors a camera feed, captures and processes video frames, checks camera status, maintains counters, and restarts the camera if disconnected. It logs updates, validates frames, adds valid frames to a queue, and ensures the camera remains active within a timeout period.
def update(self): self.startCapture() self.lastUpdatePrint = int(time.time()) logs.debug(f"Starting Update Thread -> {self.id}") while True: curTime = int(time.time()) if curTime - self.lastUpdatePrint > 10: self.serverAli...
def formatTotalTime(seconds): seconds = seconds % (24 * 3600) hours = seconds // 3600 #floor division(rounds the number down) seconds %= 3600 minutes = seconds // 60 seconds %= 60 formattedTime="{:02d}:{:02d}:{:02d}".format(hours,minutes,seconds) return formattedTime def numArtist(artist...
The code calculates and prints statistics for a music catalog, including total playtime, number of songs, artists, albums, and identifies the shortest/longest songs. It processes a list of songs, extracts data, and formats results for display.
def printCatalogStats(songList): totalPlayTime=0 #catalog time numSongs=0 artistCounter=0 albumCounter=0 artistList=[] albumList=[] durationList=[] for song in songList: singleSong=song.split(',') numSongs+=1 playTime=int(singleSong[3]) totalPlayTime += pla...
def sampleGibbs(self, sample, sampleMap, T): V = sample.copy() for rnd in range(T): H = self.sampleH( V, sampleMap, True) V = self.sampleV(H, V, sampleMap) return V def updateDW(self, sample, sampleMap, VGibbs): pH0 = self...
The code trains a Restricted Boltzmann Machine (RBM) by performing Gibbs sampling on training data for T iterations per sample, accumulating gradient updates (dW) across batches, and applying weight updates (W) periodically. It shuffles samples per epoch, processes them in batches, and resets gradient accumulators afte...
def train(self, numEpochs, numBatches, batchSize, trainData, trainMap, T): # 1. get the number of samples in the training data numSamples = len(trainData) # 2. train the rbm numEpochs number of times for epoch in range(numEpochs): # 3. obtain a random ordering of the...
def _create_augmented_sequences(self, label:str, name:str): if not self.augment_data: return for s in self.augmented_seqs: s["sequence"] = PreprocessedSequence(output_folder=(self.output_folder + label), name=f"{name}_{s['name']}") def get_person_contour_points(yolo_resu...
This code processes a video clip to extract human contour features using a model, saving sequences of contiguous frames with detected features. It handles data augmentation by generating masks and bounding boxes, and stores both original and augmented sequences in labeled output folders.
def preprocess_clip(self, clip_name, clip_path, label): cap = cv2.VideoCapture(clip_path) frame_start = None frame_num = 0 self.current_seq = PreprocessedSequence(output_folder=(self.output_folder + label), name=clip_name) self._create_augmented_sequences(label, clip_name) ...
def _create_binned_image(self, image: np.ndarray): self.binned_image = np.zeros((image.shape[0], image.shape[1], 2), dtype=np.int8) self.binned_image[:, :, 0] = (image[:, :, 0] // self.features_bin_size[0]).astype(np.int8) self.binned_image[:, :, 1] = (image[:, :, 2] // self.features_bin_size[1]...
This code performs image segmentation using a level set method. It initializes the level set with a mask, iteratively updates the level set by calculating speed functions and switching edge points between internal/external regions, and returns the final segmented mask where the level set equals 1.
def apply (self, image: np.ndarray, mask: np.ndarray): self._create_binned_image(image) if not self.initialized: self._initialize(mask) for _ in range(self.max_iter): self._calculated_speed() self._switch_in_edge_points() self._switch_l_i...
def init_csv(self,name): #print("init_csv") filepath = self.save_path(name) with open(filepath,'w', newline="") as f: csvwriter = csv.writer(f,delimiter=",") csvwriter.writerow(['id','price','make','model','year','length','city','state','country','owner']) def make_reques...
The code scrapes data from multiple pages, extracts specific vehicle details (ID, price, specs, location, owner info), handles missing fields with defaults, and exports the collected data into a CSV file named 'output'.
def scrape(self,pages): #print("scrape") self.init_csv("output") for page in range(1,pages): print("Page: {} of {}".format(page,pages)) self.make_request() self.get_data() #print("") #print("\r\rGot data?\r\r") #print(self.d...
def _import_gate_def(gate_def: pyquil.quilbase.DefGate): pyquil_params = tuple(map(_import_expression, gate_def.parameters or [])) return _gates.CustomGateDefinition( gate_name=gate_def.name, matrix=_import_matrix(gate_def.matrix), params_ordering=pyquil_params, ) def _import_gate( ...
This function converts a PyQuil program into a quantum circuit by importing custom gate definitions, validating their uniqueness, processing gate instructions, and constructing a circuit with the appropriate number of qubits.
def import_from_pyquil(program: pyquil.Program): custom_names = [gate_def.name for gate_def in program.defined_gates] custom_defs = { gate_def.name: _import_gate_def(gate_def) for gate_def in program.defined_gates } if len(custom_names) != len(custom_defs): raise ValueError( ...
def _collect_unsupported_builtin_gate_defs(gates: Iterable[_gates.Gate]): unwrapped_gates = _unique_by(map(_unwrap_gate, gates), key=lambda gate: gate.name) return [ _gate_definition_from_matrix_factory_gate(gate) for gate in unwrapped_gates if _is_builtin_gate(gate) and not _is_supporte...
This function converts a quantum circuit into a PyQuil program by processing parameters, collecting custom gate definitions, translating operations, and assembling them into a valid PyQuil program structure.
def export_to_pyquil(circuit: _circuit.Circuit) -> pyquil.Program: var_declarations = map(_param_declaration, sorted(map(str, circuit.free_symbols))) custom_gate_definitions = [ *circuit.collect_custom_gate_definitions(), *_collect_unsupported_builtin_gate_defs([op.gate for op in circuit.operati...
def bind_gui(self): self.entDwnLink.bind( "<Button-3>", lambda x: ( self.entDwnLink.delete(0, END), self.entDwnLink.insert(0, self.entDwnLink.selection_get(selection="CLIPBOARD")), ) ) self.btnDownload.bind("<ButtonRelease>", la...
The code initializes a Tkinter GUI for a YouTube-dl application, setting up input fields for download links, configuration options (folder, title format, additional parameters), buttons for execution and downloading, a console for output, and link info controls. It loads settings, populates UI elements with stored valu...
def __init__(self): self.settings = load_settings() save_settings(self.settings) # tk gui root self.root = Tk() self.root.title("MinGui Youtube-dl") self.root.minsize(720, 360) # link block self.lbLink = Label(self.root, text="Download link: ", justify=L...
def decode_response(self, raw_data: str) -> dict: """ Cast raw data to array :param str raw_data: :return: dict :raise: ProcessException """ try: data = json.loads(raw_data) except ValueError: raise ProcessException('Error on resp...
The code initializes a callback object with provided data and a signature handler, decodes the data, validates the signature using the handler, and raises an exception if the signature is invalid.
def __init__(self, data: str, signature_handler: SignatureHandler): """ Callback constructor :param dict data: :param SignatureHandler signature_handler: """ self.__data = self.decode_response(data) self.__signatureHandler = signature_handler if self.chec...
def cv_metrics_table(res: DataFrame, metrics: dict = METRICS) -> DataFrame: preds_cols, targs_cols = get_preds_targs_cols(res) table = [] for i in res['fold'].unique(): df_fold = res[res.fold == i] preds, targs = df_fold[preds_cols], df_fold[targs_cols] metrics_fold = calc_metrics(pr...
The function `evaluate_cv` computes cross-validation metrics, confusion matrix, and classification report from input data, optionally saves them as CSV files in a specified directory, and returns the three results. It generates metric tables, confusion matrices, and classification reports, ensures the save directory ex...
def evaluate_cv(res: DataFrame, save_dir: str = None) -> Tuple[DataFrame, DataFrame, DataFrame]: filenames = ('metrics', 'confusion_matrix', 'report') metrics = cv_metrics_table(res) cm = conf_matrix(res) report = clf_report(res) if save_dir is not None: Path(save_dir).mkdir(exist_ok=True, p...
def load_fcs(self, df: pd.DataFrame, keep_cols: list, col_names: list) -> pd.DataFrame: return self.load_files(df.fcs, keep_cols=keep_cols, col_names=col_names) def load_pre_gate(self, df: pd.DataFrame, pre_gate: str): gate = self.load_files(df.gates, reset_index=False) gate = gate.reindex(self....
This code initializes a class to process and filter flow cytometry data (FCS) from a DataFrame. It loads FCS data, applies gating to filter events, categorizes labels, and manages event counts. Parameters like `pre_gate`, `vocab`, and `max_events` control data filtering and categorization. If `max_events` is set, it ad...
def __init__(self, df: pd.DataFrame, pre_gate: str = None, vocab: list = None, max_events: int = None, fcs_cols: list = None, fcs_col_names: list = None, multiclass_col: Union[str, int] = None, keep_events_labels: list = None): self.vocab = Categorize(vocab=vocab).vocab ...
def checkValidAssociation(x1, x2, SANINeuron1, SANINeuron2, layerIndex, layerBufferSANINodeList): result = False if(checkNonReplicateAssociation(x1, x2)): if(checkSkipLayerConnectivity(SANINeuron1, SANINeuron2, layerIndex)): if(checkNodeContiguity(SANINeuron1, SANINeuron2)): if(checkNonContiguousAssociationC...
This function updates a layered SANI (Self-Associative Neural Interface) network by establishing connections between neurons in the current layer, generating new concept nodes based on connection strengths, and propagating these nodes to the next layer. It processes neuron associations, adjusts weights using proximity ...
def updateLayeredSANIlayerStandard(HFconnectionGraphObject, networkConceptNodeDict, SANIlayerList, layerIndex, layer, generateSANINetwork=True): layerBufferSANINodeList = layer.sentenceSANINodeList #print("len(layerBufferSANINodeList) = ", len(layerBufferSANINodeList)) sentenceSANINodeList = [] networkSANINodeList ...
def flattenNestedListToSentences(articles): articlesFlattened = [] nestedList = articles for NLPsequentialInputTypeIndex in range(NLPsequentialInputTypeArticles, NLPsequentialInputTypeSentences, -1): #print("NLPsequentialInputTypeIndex = ", NLPsequentialInputTypeIndex) flattenedList = [] for content in nestedL...
The code converts nested article structures into sentence-level word vectors by flattening input, generating vector representations, padding/cropping sequences to a fixed length, and splitting data into training/test sets with uniform labels (all ones). It returns vector dimensions, padding indices, dataset statistics,...
def convertArticlesTreeToSentencesWordVectors(articles, limitSentenceLengthsSize, numberOfFeaturesPerWord=wordVectorLibraryNumDimensions): paddingTagIndex = paddingTagIndexVectorisedInput dataType = float #mandatory padExamples = True #mandatory cropExamples = True #mandatory minimumSentenceLength = 0 maximumSe...
def generateLayeredSANIFileName(sentenceOrNetwork, sentenceIndex=None, write=False): fileName = "useAlgorithmDendriticSANI" if(sentenceOrNetwork): fileName = fileName + "Sentence" fileName = fileName + "sentenceIndex" + convertIntToString(sentenceIndex) else: fileName = fileName + "Network" fileName = fileNa...
This function generates and displays layered SANI graphs for biological simulations. It checks if simulation drawing is enabled, then creates filenames, clears existing graphs, and renders either sentence-based or network-based SANI visualizations using provided layer data. The output is displayed and optionally saved ...
def drawLayeredSANIStatic(SANIlayerList, sentenceIndex): #print("drawLayeredSANIStatic") if(drawBiologicalSimulation): if(drawBiologicalSimulationSentence): fileName = generateLayeredSANIFileName(True, sentenceIndex, write=False) clearLayeredSANIGraph() drawLayeredSANIGraphSentence(SANIlayerList) print(...
def updateLayeredSANIlayerStandard(HFconnectionGraphObject, networkConceptNodeDict, SANIlayerList, layerIndex, layer, generateSANINetwork=True): layerBufferSANINodeList = layer.sentenceSANINodeList #print("len(layerBufferSANINodeList) = ", len(layerBufferSANINodeList)) sentenceSANINodeList = [] networkSANINodeList ...
This function updates a layered SANI graph by processing each layer with vectorized or standard methods, sorts nodes in the final layer, records causal predictions if enabled, draws the graph if specified, clears activations, and returns sorted nodes from the last layer.
def updateLayeredSANIgraph(HFconnectionGraphObject, networkConceptNodeDict, SANIlayerList, sentenceIndex): for layerIndex, layer in enumerate(SANIlayerList): if(layerIndex < SANInumberOfLayersMax): #ensure that higher layer SANI nodes can still be added #print("layerIndex = ", layerIndex) if(layerIndex < SANIn...
def findAllPaths(self, i, j): '''Find all possible paths from node i to node j.''' # Set all nodes as not visited visited = {n: False for n in self.nodes} # Create a list to store the path path = [] # Call recursive function to search for paths return self.searchP...
The function calculates the total probability of all possible paths from node i to node j by iterating through each path, multiplying the stopping probability at j with transfer probabilities along the path, and summing these products. It first retrieves or generates all paths between i and j, then computes the cumulat...
def _probability_path_ij(self, i, j): '''Calculate the probability of path i -> j. This is done following the general formulae on Tutzauer (2007).''' prob_ij = 0 if self.all_paths.get((i,j), None) == None: self.all_paths[(i,j)] = self.findAllPaths(i, j) for path in se...
def parse_puzzle(text): result = [] for c in text: if c != '0': result.append( int(c) ) return result return [int(c) for c in text if c != '0'] def print_puzzle(puzzle): for i in range(9): print(puzzle[i*9:(i+1)*9]) def solve(puzzle): for x in range(9): for y ...
The main task of the code is to read a file containing puzzles, parse each line into a puzzle object, print the first puzzle, and attempt to solve it using the `solve` function, with error handling for insufficient arguments.
def main(args): if len(args) < 2: print("not enough arguments") return with open(args[1]) as f: puzzles = [parse_puzzle(line) for line in f.read().splitlines()] print_puzzle(puzzles[0]) print() solve(puzzles[0])
def key_options(self) -> list[str]: # returns a list of keys that can be used for the move method key_options = [] for key in self.movement.keys(): tile = self.get_tile(key) if tile is not None: key_options.append(key) return key_options def get_t...
This method handles player movement and interactions with game tiles. It processes actions like moving to tiles, activating levers, collecting items, pushing boxes, attacking enemies, and updating game state (e.g., exits, buttons). It checks tile types and triggers corresponding behaviors, such as moving the player, mo...
def action(self, direction: str) -> None: if direction == "stay": # if the direction is stay, do nothing (this is not neccesary) return if direction in self.key_options(): tile = self.get_tile(direction) if isinstance(til...
def border(title, length=78): return '<' + center_text("< " + title + " >", '=', length) + '>' def center_text(text, space, length): delta = length - len(text) delta = delta / 2 delta -= 1 # Adjusting for rounding errors buff = "" for x in range(round(delta)): buff += space line = b...
This code renders a screen layout by displaying formatted sections including "Stats", "Messages", and "Commands" from the provided screen_state. It clears the screen, centers text, wraps long messages, and uses borders to structure each pane, ensuring proper alignment and formatting for a user interface display.
def paint(screen_state): common.clear_screen() print(border("Stats")) # Stats print(v_border + center_text(screen_state.stats, ' ', 78) + v_border) print(h_border) lines = create_center_pane(screen_state.left_pane, screen_state.right_pane) for line in lines: print(line) print(bor...
def finish_attack(our_hero, monster, view): if monster.is_alive(): screen_state.messages += '\n ' + monster.attack(our_hero) if not our_hero.is_alive(): hero_is_slain(our_hero, monster, screen_state, view) return False else: # Monster has been killed if monste...
This code handles a turn-based combat sequence between a hero and a monster. It updates the game screen with visuals, messages, and commands, processes player input (attack, use item, run), executes corresponding actions, and manages battle outcomes. The loop continues until the battle concludes, then displays the resu...
def fight_a_monster(our_hero, monster, view): is_attack_finished = False screen_state.left_pane = view.generate_perspective() screen_state.right_pane = monster.image screen_state.messages = "A %s stands before you, blocking your path!" % monster.name screen_state.commands = fight_commands while ...
def draw_healing_list(our_hero): border = "<================<o>================>\n" full_percent = round(our_hero.max_hit_points - our_hero.hit_points) response = border response += " Description | % Healed | Cost" + '\n' response += border response += " Full Healing | " + common.front_p...
This function provides a temple healing interface where a hero can choose to fully or partially heal by spending gold, with dynamic UI updates and exit options. It loops until the hero leaves, adjusting hit points, gold, and messages based on input commands.
def enter_the_temple(our_hero): is_leaving_temple = False message = "Welcome to Wudang Five Immortals Temple, weary traveler. How can we help you?" left_pane = images.tall_temple while not is_leaving_temple: right_pane = draw_healing_list(our_hero) screen.paint(screen.State( ...
def get_profile_from_id(instance_session, instance_url, instance_key, instance_profile, instance_name=''): instance_profiles = get_quality_profiles(instance_session=instance_session, instance_url=instance_url, instance_key=instance_key) profile = next((item for item in instance_profiles if item["name"].lower()...
The main task of the code is to synchronize content between two instances (A and B) by retrieving and aligning media profiles, filters, languages, and tags. It establishes sessions, resolves IDs from names, fetches content data, and uses `sync_servers` to propagate content bidirectionally if enabled. The function handl...
def sync_content(): global instanceA_profile_id, instanceA_profile, instanceB_profile_id, instanceB_profile, instanceA_profile_filter, instanceA_profile_filter_id, instanceB_profile_filter, instanceB_profile_filter_id, tested_api_version, instanceA_language_id, instanceA_language, instanceB_language_id, instanceB_l...
def failed_tests(): return tests_for_status('f') def blocked_tests(): return tests_for_status('b') def build_testers(): scores = executed_per_person() paths = path_per_person() for person in scores: person['last_path'] = paths[person['name']] return scores def test_statuses(): quer...
The main task of the code is to aggregate test-related metrics, including failed tests, blocked tests, tester information, and overall test statistics, while ensuring data consistency via a database transaction. It compiles these into a structured dictionary containing build version and test status summaries for dashbo...
def dashboard(): with db.transaction(): failed = failed_tests() blocked = blocked_tests() testers = build_testers() stats = test_statuses() stats['total'] = total_manual_tests() return { 'version': build.version, 'stats': stats, 'failed': failed,...
def login_screen(connection, cursor): while 1: if_registered = input("Have you already have an account (Y/N)?: ") # registered users if if_registered == 'Y' or if_registered == 'y': global email email = input("Please enter your email: ") password = getpa...
The main task of the code is to provide a user interface for interacting with an SQLite database. It connects to a specified database, enables foreign key constraints, and offers options to list products, search sales, post sales, search users, or log out. The program handles user input, executes database operations vi...
def main(): # Read the name of database if len(sys.argv) != 2: print("Invalid argument! One command line argument is required") sys.exit(0) # Connect to the database database = str(sys.argv[1]) connection = sqlite3.connect(database) cursor = connection.cursor() cursor.execut...
def gen_discovery_response(): response = discovery_response response["event"]["header"]["messageId"] = get_uuid() return response def gen_acceptgrant_response(): response = accept_grant_response response["event"]["header"]["messageId"] = get_uuid() return response def set_power_level(power_level...
The code defines an AWS Lambda handler for an Alexa smart home skill, processing incoming directives by identifying their namespace and name. It generates appropriate responses for actions like device discovery, authorization, power level adjustments, and state reporting. The handler logs requests/responses, handles sp...
def lambda_handler(request, context): """Lambda handler for the smart home skill """ try: logger.info("Directive:") logger.info(json.dumps(request, indent=4, sort_keys=True)) request_namespace = request["directive"]["header"]["namespace"] request_name = request["directive"]...