dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def loadPlayerList(self, serialized_player_list): player_list = [] for serialized_player in serialized_player_list: player_list.append(self.unserializePlayer(serialized_player)) print(player_list) return player_list def loadRoundsList(self, serialized_rounds_list): r...
This function deserializes a tournament from a dictionary by extracting fields like name, date, place, state, and rounds, then initializes a Tournament object with these values. It loads player lists, rounds, and scoreboards using helper methods, returning the reconstructed tournament instance.
def loadTournament(self, serialized_tournament): name = serialized_tournament['name'] place = serialized_tournament['place'] format = "%d-%m-%Y-%H-%M" date = datetime.datetime.strptime(serialized_tournament['date'], format) state = serialized_tournament['state'] curr_r...
def prepare_text_decryption(cipherText): i = 0 while i < len(cipherText): if i!= 0 and i != len(cipherText)-1 and cipherText[i] == 'X': if cipherText[i-1] == cipherText[i+1]: cipherText = delete_char(cipherText,i) if i ==len(cipherText)-1 and cipherTe...
The code implements a Playfair cipher for encryption/decryption using a user-provided key. It generates a 5x5 matrix, takes user input for plaintext or ciphertext, and processes it through separate functions for encryption or decryption. The loop allows repeated operations until exiting.
def main(): #Getting user inputs Key (to make the 5x5 char matrix) print(prepare_text_decryption("cipheXerTeXtZ")) key = input("Enter key: \n").replace(" ","").upper() while(1): choice=int(input("\n 1.Encryption \n 2.Decryption: \n 3.EXIT \n")) if choice==1: plainText = inpu...
def print_npc_instructions(self): # TODO: Print the instructions to the game print("Welcome to TicTacToe!") print("You are player X and the NPC is player O") print("Take turns placing your pieces - the first to 3 in a row wins!") return None def print_board(self): # TODO:...
The main task of the code is to run a turn-based game between a player (X) and an AI (O) on a board, alternating turns until a win or tie is detected. It prints instructions, updates the board after each move, checks for game-ending conditions, and displays results like "You win!", "AI wins", or "Tie" accordingly.
def play_npc_game(self): # TODO: Play game self.print_npc_instructions() self.print_board() while not (self.check_win("X") or self.check_win("O") or self.check_tie()): self.take_turn("X") self.print_board() if self.check_win("X"): prin...
def print_instructions(self): # TODO: Print the instructions to the game print("Welcome to TicTacToe!") print("Player 1 is X and Player 2 is O") print("Take turns placing your pieces - the first to 3 in a row wins!") return None def print_board(self): # TODO: Print the bo...
The main task of the code is to run a tic-tac-toe game by alternating turns between two players ("X" and "O"), checking for win or tie conditions after each move, and displaying the board and game outcome (win/tie) until the game concludes.
def play_game(self): # TODO: Play game self.print_instructions() self.print_board() while not (self.check_win("X") or self.check_win("O") or self.check_tie()): self.take_turn("X") self.print_board() if self.check_win("X"): print("Playe...
def _build_designmatrix(self, x): n_samples, n_features = x.shape designmatrix = self._vander(x[:, 0]) #loop over features and append Vandermonde matrix for each features without constant column for i in range(1, n_features): van = self._vander(x[:, i]) desi...
The code fits a polynomial model to data using convex optimization via CVXPY, supporting L2, L1, and Huber loss functions. It incorporates regularization (L1/L2) and feature-specific constraints (sign, monotonicity, curvature). The design matrix is normalized, and constraints are translated into linear inequalities. Th...
def fit(self, x, y, loss = 'l2', m = 1, constraints = None, \ verbose = False): ''' Fits the polynomial model to data ``x`` and ``y`` via cvxpy Parameters -------- x : ndarray (m, n) Predictor variables of ``m`` samples and ``n`` features y : nda...
def render(rules, mark_points=False): # Parse to construction euclidean_objects = [parse_rule(rule) for rule in rules] # Render all_shapely_obj, all_shapely_point = {}, {} all_viewable_objs = [] current_plot = initial_plot() for euc_obj in euclidean_objects: point_a_shapely = s...
The main task of the code is to generate and validate visual concepts based on input rules, rendering objects and checking their visibility. If valid, it saves intermediate steps and plots to specified paths, while handling errors and closing plots appropriately. The process repeats until a valid configuration is achie...
def generate_concept(rules, mark_points=False, steps_path=None, path=None, show_plots=False): i = 0 while i < 1: try: all_viewable_objs = render(rules, mark_points) if visibility_test(all_viewable_objs): if steps_path: save_steps_joint(all_view...
def get_directories(): items = os.listdir(PHOTO_PATH) return list(filter(lambda x: os.path.isdir(PHOTO_PATH + '/' + x), items)) def get_images(path): items = os.listdir(PHOTO_PATH + '/' + path) filtered_items = list(filter(is_original, items)) result = [] for img in filtered_items: widt...
The main task of the code is to collect all photo albums from the /photos directory by processing each directory's images, storing metadata in a configuration dictionary, and writing this data to a JSON file. It also provides user feedback during processing and includes a thank-you message with a GitHub link for sharin...
def run(): print('Starting to collect all albums within the /photos directory...') config = {} dirs = get_directories() print('Found {length} directories'.format(length=len(dirs))) for i, path in enumerate(dirs): print(str(i+1) + ': Processing photos for the album "{album}"'.format( ...
def fiducialNodeToPolyData(self, path): point = [0,0,0] polydataPoints = vtk.vtkPolyData() points = vtk.vtkPoints() [success,fiducialNode] = slicer.util.loadMarkupsFiducialList(path) if not success: print("Could not load landmarks: ", inputFilePath) return for i in range(fiducialNode...
This code aligns 3D meshes with corresponding landmarks using either dense correspondence or CPD (Coherent Point Drift) algorithms. It loads a base mesh and landmarks, imports additional models and landmarks from directories, computes dense correspondences, adds magnitude features, and saves the aligned result as a .vt...
def runDCAlign(self, baseMeshPath, baseLMPath, meshDirectory, landmarkDirectory, outputDirectory, optionCPD, optionErrorOutput): if optionErrorOutput: self.errorCheckPath = os.path.join(outputDirectory, "errorChecking") if not os.path.exists(self.errorCheckPath): os.mkdir(self.errorCheckPath) ...
def fiducialNodeToPolyData(self, path): point = [0,0,0] polydataPoints = vtk.vtkPolyData() points = vtk.vtkPoints() [success,fiducialNode] = slicer.util.loadMarkupsFiducialList(path) if not success: print("Could not load landmarks: ", inputFilePath) return for i in range(fiducialNode...
This function aligns symmetric 3D mesh models and their corresponding landmarks using either a base dense correspondence method or CPD (Coherent Point Drift) algorithm. It processes input meshes and landmarks from specified directories, computes symmetric correspondences, adds magnitude features for symmetry analysis, ...
def runDCAlignSymmetric(self, baseMeshPath, baseLMPath, meshDir, landmarkDir, mirrorMeshDir, mirrorLandmarkDir, outputDir, optionCPD, optionErrorOutput, optionPointOutput): if optionErrorOutput: self.errorCheckPath = os.path.join(outputDir, "errorChecking") if not os.path.exists(self.errorCheckPath): ...
def load_data(nrc_path, data_path): emolex_df = pd.read_csv(nrc_path, names=["word", "emotion", "association"], skiprows=1, sep='\t') emolex_words = emolex_df.pivot(index='word', columns='emotion', values='association').reset_index() data = pd.read_csv(data_path) return emolex_words, data def data_prep...
The main task of the code is to analyze emotional word distributions and intensity across different time points (Time 1 vs. Time 3) in PEERS data using a lexicon. It loads and prepares data, extracts emotion-related words, subsets transcripts for specific time intervals, and computes distributions of original and lexic...
def main(): warnings.filterwarnings("ignore") lexicon, data = load_data("NRC-Emotion-Intensity.txt", path_to_data) data = data_preparation(data) data_lex = get_emo_words(data, lexicon) # PEERS: Time 1 VS Time 3 peers_subset = data_lex[data_lex["transcript"]<13000] time1_peers = peers_subset...
def openDiscordAndLogin(userEmail, userPass, channelLink, chromeDriverLocation): ''' :param userEmail: The email you wish to use to login to discord :param userPass: The password associated with this email for discord login :param channelLink: Web link to the channel you wish to open :param chromeDr...
The main task of the code is to automate interactions with a Discord bot by repeatedly sending commands like "fish," "hunt," and "beg" to perform in-game actions, parse responses, post messages, and transfer collected items to a storage bot. It runs in a loop for 500 iterations, managing delays and parsing messages to ...
def main(): # Creating the browser instance browser = openDiscordAndLogin(USERNAME, PASS, CHANNEL_LINK, CHROME_DRIVER_LOCATION) # Wait for channel to load time.sleep(10) # Config settings numF = 0 delay = 17 time.sleep(10) numLoops = 500 for i in range(0, numLoops): # S...
def get_swf_info(args): result = subprocess.run(args, stdout=subprocess.PIPE) output = result.stdout.decode('utf-8') return output.splitlines() def get_swf_object(list, type): item = filter(lambda x: type in x , list) item = next(item, None) if item == None: return None else: ...
The main task of the code is to recursively extract JPEGs, PNGs, MP3s, and MovieClips from SWF files using a command-line tool, storing them in a specified directory while respecting a recursion limit to prevent infinite loops. The function processes each file, identifies embedded media, and calls specialized extractio...
def extract(dir, file, i): print(str(i) + " " + file) i += 1 if (i > config.recursion_limit): return #get SWF info swf_objects = get_swf_info([config.cmd, "-o", "-n output", file]) #extract JPEGs jpeg_ids = get_swf_object(swf_objects, "JPEGs") extract_jpegs(jpeg_ids, dir, file...
def get_fire_pokemons(): fire_id = find_id_of_fire_type_pokemons() if fire_id: fire_pokemons_api = POKEMON_TYPE_API + '/' + fire_id response = read_api(fire_pokemons_api) try: fire_pokemons = response.json().get('pokemon') except json.JSONDecodeError as e: ...
The function retrieves the five heaviest fire-type Pokémon by fetching their weights from an API, handling JSON decoding errors, and returning a dictionary of the top five heaviest fire Pokémon with their weights. If fewer than five fire Pokémon exist, it returns an error.
def get_five_heaviest_fire_pokemons(): pokemon_weights = {} fire_pokemons = get_fire_pokemons() for pokemon in fire_pokemons: pokemon_name = pokemon['pokemon']['name'] pokemon_url = pokemon['pokemon']['url'] pokemon_api_response = read_api(pokemon_url) try: pokemo...
def _set_verbose(verbose_flag=True): """Set global verbose flag. Args: verbose_flag: A boolean to enable/disable verbose messages. Default is True. Returns: None """ global verbose verbose = verbose_flag def _get_jwt_token(env, credentials): """Add description here. Args: ...
The function `run_deployment_process` deploys a bot to a specified environment using provided credentials. It constructs a deployment URL and file path, retrieves a JWT token for authentication, deploys the bot, waits 15 seconds, and checks the deployment status. The process includes verbose logging if enabled, utilizi...
def run_deployment_process(env, credentials, bot_name, mne, verbose_flag=True): """Run Main deployment process. Args: Returns: """ print("Starting deployment process") if verbose_flag: _set_verbose(verbose_flag) url = config['hosts'][env] path = config['file_path']+mne de...
def parse_args(): parser = argparse.ArgumentParser(description='instance check script') parser.add_argument('-i', '--input_file', help='input_file', type=str, required=False) parser.add_argument('-o', '--ouput_file', help='ouput_file', type=str, required=False) parser.add_argument('-d', '--days_back', h...
The main task of the code is to process EBS volume data by reading input CSV files, retrieving associated EC2 instance information, fetching CloudWatch metrics for the volumes, and outputting the aggregated data to a CSV file. The script parses command-line arguments, reads volume data, extracts EBS details, and collec...
def main(): args = parse_args() vol_df = pd.read_csv(args.input_file) # get volume and associated Ec2 instance information ebs_info_df = get_vol_info(args, vol_df) # pull Cloudwatch data for volumes and output to csv get_ebs_data(args, ebs_info_df)
def _read_file(skills_file: str) -> dict[str | int, dict | list]: with open(skills_file) as f: # Loads the config file configs = yaml.load(f, Loader=yaml.FullLoader) return configs def _add_legends(self) -> None: # legend nodes step: int = 50 x: ...
The code initializes a network visualization by loading configuration data from a file, setting graph parameters (max proficiency, edge style), constructing a tree structure, and rendering/saving the network. It reads input file, configures graph properties, builds the network topology, and generates the visual output ...
def __init__(self, skills_file: str): self.configs: dict[str | int, dict | list] = self._read_file(skills_file) self.max_proficiency: int = self.configs["network_config"]["max_proficiency"] self.edge_width: int = self.configs["network_config"]["edge_width"] self.edge_c...
def str2numArr(str): s = str.upper() arr = [] for c in s: arr.append(ord(c)-65) return arr def matInvbyMod(mat, n): det = npl.det(mat) detRound = round(det) % n matInv, exc = mat, "" if detRound == 0: exc += "Matriks bersifat singular\n" else: inv = modInv(det...
The function decodes a Hill cipher encrypted message using the modular inverse of a given key matrix. It converts the ciphertext to numerical form, computes the inverse key matrix modulo n, applies it to ciphertext blocks, converts results back to text, and trims padding 'X' characters.
def hillDecode(c, matKey, n): matKey = np.array(matKey) dim = len(matKey) cNumArr = str2numArr(c) invKey, exc = matInvbyMod(matKey, n) if exc != '': p = exc else: pArr = [] for i in range(0,len(cNumArr),dim): end = min(i+dim, len(cNumArr)) key = i...
def set_up_logging(debug: bool) -> None: logging.basicConfig( format="[%(levelname)s] %(message)s", level=logging.DEBUG if debug else logging.INFO, ) def get_environment_variables() -> PathsToBinaries: def load(env_var_name: str, error_message: str) -> Optional[Path]: env_var = os.en...
The main task of the code is to process C source files for end-to-end decompiler testing by validating their file paths, retrieving compilers, and adding tests using environment variables. It parses command-line arguments, checks file existence and structure, and executes test setup for each valid file while handling d...
def main() -> int: parser = argparse.ArgumentParser( description="Add or update end-to-end decompiler tests." ) parser.add_argument( "files", help=( "Files containing C code to compile (then decompile). " "Each one must have a path of the form " "`...
def build_pattern( *, to_replace: str, regex: bool, match_case: bool, match_entire: bool ) -> str: pattern = to_replace if not regex: pattern = re2.escape(pattern) if match_entire: pattern = "\\A" + pattern + "\\z" if not match_case: pattern = "(?i)" + pattern return patt...
The main task of the code is to replace substrings in specified columns of an Arrow table according to parameters like regex patterns, replacement strings, and case sensitivity. It validates regex and replacement formats, applies transformations to selected columns using `build_pattern` and `build_replacement`, and ret...
def render_arrow_v1(table, params, **kwargs): if params["regex"]: # Validate regex. # # Error 1: it's an invalid regex try: pa.compute.replace_substring_regex( pa.array([""]), pattern=params["to_replace"], replacement="" ) except pa.Arr...
def transform(self, parsed): d = {} for x in parsed: rel = x.dep_ parent = x.head.i + 1 dependent = x.i + 1 if parent == dependent and rel == 'ROOT': parent = 0 if parent not in d.keys(): d[parent] = {} ...
This function simplifies complex sentences by splitting them into simpler versions, primarily by identifying and separating appositive phrases and relative clauses. It processes each input sentence using NLP tools, analyzes dependency structures, and generates alternative sentence forms. If appositives or relative clau...
def getSplitSentences(self, sentences): ''' I simplifies the list of sentence received into simpler ones. eg: input: ["My father, who is a President, is an honest man."] output: ['my father , is an honest man .', 'my father is a president'] eg: input: ["My brothe...
def _play_button_pressed(self): if not self._track_has_played: # if first time opening, need to Play self._trivia.PlayNextTrack() self._track_has_played = True # enable all buttons once audio is finished playing time.sleep(self._trivia.get_interval_length()) self._btn_increase.configure(state=NORMAL...
This code initializes a GUI frame for a game/trivia application, setting up score tracking, navigation buttons (Home/Settings), audio controls (replay, interval adjustment), answer toggling, and success/failure actions. It creates interactive elements like labels, buttons, and variables to manage game state, audio play...
def __init__(self, parent, controller, sessionName=constants.SESSION): ctk.CTkFrame.__init__(self, parent) self.lbl_title = ctk.CTkLabel(self, text=sessionName, font=LARGE_FONT) self.lbl_title.place(relx=0.5, rely=0.1, anchor=ctk.CENTER) self._score = StringVar() self._score.set("Score: 0") lbl_score = ct...
def get_xyz(self): # wild_df = self.get_pdb_df(pdb_file=self.wild_pdb,chain_id=self.wild_chain) # mutant_df = self.get_pdb_df(pdb_file=self.mutant_pdb,chain_id=self.mutant_chain) wild_ppdb = self.get_ppdb(pdb_file=self.wild_pdb,chain_id=self.wild_chain) mutant_ppdb = self.get_ppdb(pdb_f...
The code computes the 20 nearest neighbors for each atom in a molecular structure using a KNN classifier, converts the resulting neighbor distances and indices into PyTorch tensors, and returns them as edge attributes and indices for graph-based representation.
def get_nearest_neighbors(self): # Read the PDB file using the pandaspdb library # pdb = PandasPdb().read_pdb(self.pdb_file) # Select the columns containing the XYZ coordinates X,y = self.get_xyz() # Initialize the KNN classifier knn = NearestNeighbors(n_neighbors=30) ...
def get_xyz(self): # wild_df = self.get_pdb_df(pdb_file=self.wild_pdb,chain_id=self.wild_chain) # mutant_df = self.get_pdb_df(pdb_file=self.mutant_pdb,chain_id=self.mutant_chain) wild_ppdb = self.get_ppdb(pdb_file=self.wild_pdb,chain_id=self.wild_chain) mutant_ppdb = self.get_ppdb(pdb_f...
The main task of the code is to convert PDB protein structure data into a graph representation for machine learning. It extracts atomic coordinates, one-hot encoded atom/residue sequences, and nearest-neighbor edge connections. The graph is constructed using PyTorch Geometric's Data class, combining node features (coor...
def pdb_to_graph(self): node_coords, label_coords = self.get_xyz() # if MIN_MAX_SCALE: # node_coords = self.min_max_scale(node_coords) # label_coords = self.min_max_scale(label_coords) node_one_hot_sequence_atoms, node_one_hot_sequence_residues, mutated_atoms_index_list ...
def prune_profile(self, profile, threshold): pruned_profile = [] for p in profile: pruned_p = [] for n in p: if n < threshold: n = 0 n = round(n, 2) pruned_p.append(n) pruned_profile.append(pruned_p) return prune...
The code initializes a class to process an input profile by swapping axes, pruning based on a threshold, and setting up data structures (chroma_sums, stencil) for analyzing chromatic features. It prepares parameters like theta_window and populates initial values for chroma maxima and stencil generation, enabling subseq...
def __init__(self, profile, threshold, theta_window): profile = util.swap_axes(profile) profile = self.prune_profile(profile, threshold) self.theta_window = theta_window self.chroma_sums = [] self.chroma_max = 0 self.set_chroma_sums(profile) self.stencil = [] ...
def Inext(I, U, le, R, Lk, hn, Rk, Ck): k1 = f(I, U, le, R, Lk, Rk) q1 = g(I, Ck) k2 = f(I + hn * k1 / 2, U + hn * q1 / 2, le, R, Lk, Rk) q2 = g(I + hn * k1 / 2, Ck) k3 = f(I + hn * k2 / 2, U + hn * q2 / 2, le, R, Lk, Rk) q3 = g(I + hn * k2 / 2, Ck) k4 = f(I + hn * k3, U + hn * q3, le, R, Lk...
The code simulates a dynamic system over 1200 time steps using numerical methods. It initializes parameters (resistance, inductance, capacitance, etc.) and iteratively calculates updated current (I) and voltage (Uc) values using `Inext` and `Unext` functions. Time (t) increments with each step, and results are stored i...
def main(): R = 0.35 le = 12 Lk = 0.000187 Ck = 0.000268 Rk = 0.25 Uc = 1400 I = 0 hn = 0.000001 t = 0 for i in range(1200): I = Inext(I, Uc, le, R, Lk, hn, Rk, Ck) Uc = Unext(I, Uc, le, R, Lk, hn, Rk, Ck) t += hn Igraph.append(I) Ugraph....
def run(command, env_vars=None): if env_vars: for key, value in env_vars.items(): os.putenv(key, value) print('*** Running: %s%s%s' % (COLOR_OK, command, COLOR_END)) if os.system(command): raise RuntimeError(' FAILED: %s' % (command)) def java_exe(): path = JAVA_HOME return 'export JAVA_HOME=...
This function performs a smoke test on an Elasticsearch release package by verifying file existence, unzipping the release, installing the x-pack plugin, configuring a dummy user, starting Elasticsearch, and checking for correct plugin loading, license type, and server startup. It raises errors on failures and cleans u...
def smoke_test_release(release, files, release_hash): for release_file in files: if not os.path.isfile(release_file): raise RuntimeError('Smoketest failed missing file %s' % (release_file)) tmp_dir = tempfile.mkdtemp() run('unzip %s -d %s' % (release_file, tmp_dir)) es_dir = os.path.join(tm...
def parse_args(): parser = argparse.ArgumentParser(description="TDVT runner of the Tableau connector for Elasticsearch.", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("-t", "--taco-dir", help="Directory containing the connector file.", default=TACO_SRC_DIR...
This code's main task is to execute a TDVT test run by setting up the environment, handling directory management, installing required files, configuring data sources and override settings, and then running the test while measuring execution time. It includes options for cleaning directories, initializing the workspace,...
def main(): started_at = time.time() args = parse_args() cwd = os.getcwd() if args.clean: import shutil # dependency! shutil.rmtree(args.run_dir) if not os.path.isdir(args.run_dir): os.makedirs(args.run_dir) os.chdir(args.run_dir) if not os.path.isdir(TDVT_SDK_REPO...
def get_soup_from_page (url): # Only use US websites headers = { "Accept-Language": "en-US, en;q=0.5" } # applies the backoff factor to the requesting of the url an unlimited number of times session = requests.Session() retry = Retry(connect=5, backoff_factor=3) a...
This function collects and processes data from multiple 4chan/pol URLs by scraping HTML content, extracting thread objects, removing duplicates compared to prior data, converting results to a NumPy array, and writing them to a dataset. It scans for new posts, manages thread listings, and ensures data integrity through ...
def data_collection_and_processing (): # tells users that it is running again print("\nScanning /pol for new posts...") urls = ["https://boards.4chan.org/pol/", "https://boards.4chan.org/pol/2", "https://boards.4chan.org/pol/3", "https://boards.4chan.org/pol/4", "https://boards.4chan.org/pol...
def action_to_click(self, action): x, y = self.action_to_board_index(action) return int(x - (self.board_width // 2)), int(y - (self.board_height // 2)) def is_valid_action(self, action): if self.action_space_type == LGEnv.AS_MULTI_DISCRETE: return self.action_mask[action[0], action[1...
The code processes a game action by simulating a click, updating the environment state, calculating rewards based on success, goal collection, and move limits, and logging results. It returns the observation, reward, completion status, and metadata like click validity and goals collected.
def step(self, action): x, y = self.action_to_click(action) reward = 0 self.total_clicks_performed += 1 click_successfull = False goals_collected_now = 0 if self.is_valid_action(action): try: result = self.simulator.session_click(self.game['...
def display_sunny(): global flip flip = flip + 1 % 10 update_sunny(0, flip) def display_cloud(): global flip flip = flip + 1 % 10 update_cloud(0, flip) def display_rain(): global flip flip = flip + 1 % 10 update_rain(0, flip) def display_thunderstorm(): glob...
The function `display_gif` maps a given `weather_id` to a specific weather condition using a predefined dictionary. Based on the retrieved condition (e.g., sunny, rainy), it calls the corresponding function to display an associated GIF. If the condition is unrecognized, it defaults to displaying fog. The task involves ...
def display_gif(weather_id: str): weather_type = Weather.data['weather_condition'][weather_id] if weather_type == 'sunny': display_sunny() elif weather_type == 'cloudy': display_cloud() elif weather_type == 'rainy': display_rain() elif weather_type == '...
def coinsOwned(self): # calculates coins owned using utxo totalCoins = 0 for txn in self.utxo: totalCoins += txn.coins return totalCoins def deleteCoins(self, coins): # deletes transactions from utxo whose outputs are used deletedYet = 0 toDelete = [] for i ...
This code simulates a node generating transactions with random receivers, deducting coins, creating transaction objects, and broadcasting them. It runs in a loop with exponential interarrival times, initializes mining processes if it's the first iteration, and manages a transaction queue for the node's operations.
def run(self): print("inside run() of ",self.id) #init = 1 while True: txnGenInterarrivalTime = random.expovariate(1/constants.Tk) txnGeneratedAt = self.env.now #self.env.process(self.generateTransaction(txnGeneratedAt)) receiverId = self.network.g...
def hcf(a): amin=min(a) for i in range(1,amin+1): s=1 for j in a: if j%i==0: s=s else: s=0 if s==1: hcf=i return hcf def debye_single(V,E,N,M,s=0.617,Tmax=1000,nat=1,eos_only='False',eos='vinet'): hbar=1.05457180...
This code calculates thermodynamic properties using the Debye model for solids, fitting an equation of state (EOS) to energy-volume data from input files. It computes Debye temperatures, heat capacities, entropy, and other properties, plots results, and optionally writes outputs. The function processes experimental dat...
def debye(ev='e-v.dat',trimve='F',expt='expt',struc='POSCAR',out='Debye-thermo',s=0.617,poisson='poisson',Tmax=1000,Tstep_write=10,show='T',write='T',nat=0,prop='all',eos_only='False',eos='vinet'): hbar=1.054571800e-34;kB=1.38064852e-23;q=1.60217662e-19;NA=6.022140e23 A=(6*np.pi**2)**(1/3)*hbar/kB print('\...
def gen_pages(): page = 1 while True: yield page page += 1 def add_list_id(lst, records): for record in records: record["ListID"] = lst["ListID"] return records def transform(response): return transform_dts(serialize_object(response)) def write_records(tap_stream_id, records)...
The main task of the code is to synchronize subscribed contacts from multiple lists by iterating through pages of data, requesting contact reports for each list since the last update, transforming and storing the results with list identifiers, and updating system bookmarks/state to track progress.
def sync_subscribed_contacts(ctx, lists): start_dt = ctx.update_start_date_bookmark(BOOK.SUBSCRIBED_CONTACTS) for lst in lists: for page in gen_pages(): response = request(IDS.SUBSCRIBED_CONTACTS, ctx.client.service.ReportRangeSubscribedContacts, ...
def gen_pages(): page = 1 while True: yield page page += 1 def add_msg_id(msg, records): for record in records: record["MsgID"] = msg["MsgID"] return records def transform(response): return transform_dts(serialize_object(response)) def write_records(tap_stream_id, records): ...
The function synchronizes messages from a sub-stream by iterating through messages and paginated requests, using the message ID and date range to fetch data, then processing and writing the records to the sub-stream.
def sync_message_sub_stream(ctx, messages, sub_stream): start_dt = ctx.update_start_date_bookmark(sub_stream.bookmark) for msg in messages: for page in gen_pages(): response = request(sub_stream.tap_stream_id, getattr(ctx.client.service, sub_stream.endpoint), ...
def gen_pages(): page = 1 while True: yield page page += 1 def add_msg_id(msg, records): for record in records: record["MsgID"] = msg["MsgID"] return records def transform(response): return transform_dts(serialize_object(response)) def write_records(tap_stream_id, records): ...
The function synchronizes message sends data for selected streams by fetching and writing records. It checks if the MESSAGE_SENDS stream is selected, retrieves a start date bookmark, filters messages by date, paginates through API requests for each message, transforms results, adds message IDs, and writes records. It e...
def sync_message_sends_if_selected(ctx, messages): if not IDS.MESSAGE_SENDS in ctx.selected_stream_ids: return start_dt = ctx.update_start_date_bookmark(BOOK.MESSAGE_SENDS) for msg in messages: if pendulum.parse(msg["SendDate"]) < start_dt: continue for page in gen_pages(...
def gen_intervals(ctx, start_str): start_dt = pendulum.parse(start_str) interval = timedelta(days=ctx.config.get("interval_days", 365)) while start_dt < ctx.now: end_dt = min(start_dt + interval, ctx.now) yield start_dt, end_dt start_dt = end_dt def transform(response): return tr...
The main task of the code is to synchronize message data from multiple lists by fetching message activities over date intervals, transforming the results, writing records, updating maximum send dates, and synchronizing sub-streams and message sends. It also updates bookmarks for sub-streams and message sends, then pers...
def sync_messages(ctx, lists): start_dt = ctx.config["start_date"] max_send_dt = None for lst in lists: for begin_dt, end_dt in gen_intervals(ctx, start_dt): response = request(IDS.MESSAGES, ctx.client.service.ReportListMessageActivity, ...
def transform(response): return transform_dts(serialize_object(response)) def write_records(tap_stream_id, records): singer.write_records(tap_stream_id, records) metrics(tap_stream_id, records) def sync_messages(ctx, lists): start_dt = ctx.config["start_date"] max_send_dt = None for lst in lists...
The main task of the code is to synchronize contact lists from a service by retrieving, transforming, and storing them, then conditionally syncing related messages and subscribed contacts based on selected stream IDs.
def sync_lists(ctx): response = request(IDS.LISTS, ctx.client.service.GetContactListCollection) lists = transform(response) write_records(IDS.LISTS, lists) if IDS.MESSAGES in ctx.selected_stream_ids: sync_messages(ctx, lists) if IDS.SUBSCRIBED_CONTACTS in ctx.selected_stream_ids: syn...
def table_waitlist(): ''' this will generate an enroll table (and priority queue if table is full) it will return the enroll table and priority queue ''' data_list = read_file() # get a nested list table = EnrollTable(51) # create an enroll table waitlist = PriorityQueue() # create a prio...
The code manages a registration and waitlist system via user commands. It loops, prompting for 'R' (register), 'D' (drop), or 'Q' (quit). On 'R' or 'D', it updates the table/waitlist, prints messages, and saves changes. The loop ends when 'Q' is selected, printing a goodbye message.
def main(): user_input = "" quit = False while not quit: while not user_input in ["R","D","Q"]: user_input = input("R for Register, D for Drop, Q for quit: ") if user_input == "Q": print("Goodbye...") quit = True elif user_input == "R": ...
def store_entry(entry, event_buffer, dtype): ''' Convert TTree entry into a numpy type - this is heckin slow.... ''' # create new row event = np.zeros((1,), dtype=dtype) event['event'] = entry.event event['sn'] = entry.sn event['ch'] = entry.ch event['utime_ms'] = entry.utim...
The code processes a ROOT file containing event data, extracts and structures waveform and reconstruction information using NumPy data types, and writes the processed events to an output file. It handles parameters like event count, sample sizes, and data inclusion flags, while efficiently managing buffers and progress...
def main(input_file, output_file, **kwargs): n = kwargs.pop('n', _default_n) # create new event file buffered_file = BufferedEventFile(output_file) buffered_file.write_meta(created=time.time()) buffered_file.write_meta(**kwargs, source_file=input_file, n=n if n is not None else -1) # c...
def get_all_hits_improvements(max_all, ann_to_brute=True, hits_values=None): if hits_values is None: hits_values = [1, 5, 10, 25, 50] improvement = None for k in hits_values: if improvement is None: if ann_to_brute: improvement = create_improve_df_ann_to_brute( ...
(The main task of the code is to generate and save multiple visualizations comparing embedding approaches for different "hits@k" values (1, 5, 10, 25, 50) using input datasets. It creates directories for each hit value, produces comprehensive plots with `create_all_plots`, generates approach-specific plots via `emb_app...
def create_extensive(max_all, max_large, max_small, output_dir): print("Plotting a lot of plots") hits_values = [1, 5, 10, 25, 50] improvement_hits = get_all_hits_improvements(max_all, ann_to_brute=False) improvement_hits_ann_to_brute = get_all_hits_improvements(max_all) hr_to_compare = HUBNESS_ORDE...
def _train_step(self, batch): """Train model one step.""" # parse batch vqidx, aux, mel, prompt, y, xlens, prompt_lens = batch vqidx = vqidx.to(self.device) mel = mel.to(self.device) aux = aux.to(self.device) prompt = prompt.to(self.device) vqvec = torch.c...
The main task of the code is to train a model for one epoch by iterating through training batches, performing training steps, checking intervals for logging/evaluation/checkpointing (on rank 0), handling early termination, updating epoch counters, and configuring distributed training samplers. It logs training progress...
def _train_epoch(self): """Train model one epoch.""" for train_steps_per_epoch, batch in enumerate(self.data_loader["train"], 1): # train one step self._train_step(batch) # check interval if self.config["rank"] == 0: self._check_log_interv...
def get_processed_product_data(self) -> List[Product]: """ remove duplicates from list of products :return: distinct list of products """ products = self.get_raw_product_data() # removing duplicates from here itself return list(set(products)) def sort(self, produc...
The code retrieves and processes product data by removing duplicates, filtering by status using `filter_by`, and sorting the results according to `sort_by`. It returns a tuple containing the filtered/sorted product list and the original unduplicated product data.
def get_products( self, filter_by: Dict[str, Any], sort_by: OrderedDict[str, bool], ) -> tuple[list[Product], list[Product]]: """ get the raw product data, remove duplicates and filter them on status col. Finally, Sort the list. :param filter_by: dict of filter items ...
def get_raw_product_data(self) -> List[Product]: """ gets the raw data by connecting to the URL and assign the status as provided. If the product is deleted we need not bother about whether it is hidden or not. If deleted, change the status to deleted, if hidden then change the status to...
This function calculates and returns statistical metrics for both unfiltered and filtered product datasets. It computes the number of unique products, brands, and average price for each dataset. The unfiltered data uses either provided original products or raw data, while the filtered data applies a status-based filter...
def get_statistics(self, filter_by: Dict[str, Any], org_products=None, filtered_products=None) -> Dict[Any, Any]: """ get statistics for both raw product data and sorted_filtered product data :param filtered_products: (optional) can send filtered products for getting stats :param org_pro...
def close_browser(): time.sleep(2) pg.moveTo(963, 1057, 0.01) pg.click() pg.moveTo(1895, 14, 0.1)#browser exit pos: x = 1895, y= 14 pg.click() def open_browser(): pg.moveTo(955, 1057, 0.01)#browser pos: x= 963, y = 1057 pg.click() time.sleep(2) def open_gpt(): pg.write("https://chat....
The code automates a sequence of browser and GPT interactions: closing and reopening a browser, launching GPT, querying it, waiting for a 20-second response, extracting the answer, copying it, and pausing for 3 seconds. The main task is to automate retrieving and copying an AI-generated response through browser-GPT int...
def run(): close_browser() open_browser() open_gpt() ask_gpt() time.sleep(20) get_to_answer() write_copy() time.sleep(3)
def get_open_max_index(self): max_index = self.open_table[0] max_value = self.all_nodes[max_index]['check_value'] for item in self.open_table: check_value = self.all_nodes[item]['check_value'] if check_value > max_value: max_value = check_value ...
This function performs a search algorithm by selecting the maximum index from the open table, moving it to the closed table, and checking termination conditions. If conditions are met, it ends the search; otherwise, it expands adjacent nodes, updates tables, and recursively continues the search. It tracks search states...
def travel_search(self, first_flag, end_flag): if True == end_flag or 0 == len(self.open_table): end_flag = True return max_index = self.get_open_max_index() self.open_table.remove(max_index) self.close_table.append(max_index) if True == self.match_limi...
def valid_es_geometry(geometry): es_json = copy.deepcopy(geometry) # now for any meridian crossing polygons, add 360 to longitude # less than 0, since ES can handle 0 to 360 # if is_anti_meridian(es_json): # index = 0 # for coord in es_json["coordinates"][0]: # if float(coor...
The function generates metadata for a dataset from input record data, populates fields like acquisition type, filename, location, and sensor details, creates a directory structure, and writes metadata to a JSON file. It returns the folder name for the dataset.
def make_met_file(record): metadata = dict() metadata["acquisitiontype"] = DEFAULT_ACQ_TYPE metadata["archive_filename"] = record["granuleName"] + ".zip" metadata["location"] = valid_es_geometry(get_polygon(record["stringFootprint"])) # metadata["bbox"] = metadata["location"]["coordinates"][0] ...
def not_RAW(product_name): match = re.search(r'([\w.-]+)_([\w.-]+)_([\w.-]+)__([\d])([\w])([\w.-]+)', product_name) if match: product_type = match.group(3) if product_type == "RAW": return False else: return True else: return True def make_met_file(record): ...
This function processes a record to generate a dataset by first extracting the product name from the record's granule name. If the product name is not in RAW format, it creates a metadata file using `make_met_file` and then generates the dataset file using `make_dataset_file` with the updated product name and original ...
def create_dataset_from_asf(record): product_name = record["granuleName"] if not_RAW(product_name): product_name = make_met_file(record) make_dataset_file(product_name, record)
def readln(file): return file.readline().rstrip().split(" ") def raster(file, A: int, B: int): for i in range(A): user_in = readln(file) for j in range(B): grid.append(int(user_in[j])) quick_sort(grid, 0, len(grid) - 1) #outln("RASTER GUARDADO") return grid def amp...
The main task of the code is to process commands from a test file, execute corresponding functions (e.g., raster, amplitude, percent, median), and calculate the total execution time. It reads lines from the input file, identifies commands, performs operations, and accumulates the time taken for each task, returning the...
def main(test_file): run_time = 0 user_in = [""] with open(test_file, "r") as file: try: while True: user_in = readln(file) start_time = time.time() if user_in[0] == "RASTER": raster(file, int(user_in[1]), int(user_in[2]...
def readln(file): return file.readline().rstrip().split(" ") def raster(file,A: int, B: int): for i in range(A): user_in = readln(file) for j in range(B): grid.append(int(user_in[j])) # outln("RASTER GUARDADO") return grid def amplitude(): return str(max(grid) - min(grid)) def percent(num_percent: int, num...
The main task of the code is to process commands from a test file, executing corresponding functions (e.g., `raster`, `amplitude`, `percent`, `median`) based on command-line directives like "RASTER", "AMPLITUDE", "PERCENTIL", or "MEDIANA". It measures and accumulates the runtime of each command's execution, stopping wh...
def main(test_file): run_time = 0 user_in = [""] with open(test_file, "r") as file: try: while True: user_in = readln(file) start_time = time.time() if user_in[0] == "RASTER": raster(file, int(user_in[1]), int(user_in[2])) elif user_in[0] == "AMPLITUDE": amplitude() #outln(amplit...
def get_meta(self): for line in self.source: language_matcher = Lexer.LANGUAGE_PATTERN.match(line[1]) if language_matcher: self.lang = language_matcher.groups()[0] def remove_comments(self): self.source = [item for item in self.source if not...
The main task of the code is to tokenize source code by filtering non-empty lines, removing comments, extracting language-specific keywords, and scanning the processed code. It prepares the source for further processing by handling metadata and language-specific rules, raising an error if the specified language is unde...
def tokenize(self, source): self.source = [(index, line.strip()) for index, line in enumerate(source) if line.strip()] self.get_meta() self.remove_comments() try: self.keywords = LANGUAGE[self.lang] return self.scan(self) except KeyE...
def getObjectDistance(self, bgRemoved: np.ndarray, depthFrame: np.ndarray, triggerAreaBox: List[Tuple[int, int]]) -> float: """ checks middle pixel inside trigger box, if the pixel is not white (the object) than it returns the distance Parameters ---------- bgRemoved : n...
This code processes real-time depth and color images from a camera, detects motion in a specified area, removes background by clipping depth data, calculates object dimensions, and displays results including depth maps and point clouds. It toggles point cloud visualization, handles user inputs, and stops the camera pip...
def displayLoop(self): try: while True: # Get frameset of color and depth frames = self.pipeline.wait_for_frames() # frames.get_depth_frame() is a 640x360 depth image # Align the depth frame to color frame aligned_fram...
def convert_files2char(files, vocab): data = [] for file in files: with open(file) as f: lines = f.readlines() for line in lines: toks = convert_line2char(line, vocab) data.append(toks) return data def genTriAndFourGramDict(vocab_filename, data_folder): ...
The main task of the code is to compute the perplexity of test data using trigram and fourgram language models trained on given training data. It loads vocabulary, generates n-gram frequency counts from training files, processes test data into character sequences, and calculates perplexity by summing log probabilities ...
def getPerplexity(vocab_filename, train_data_folder, test_data_folder): vocab, _ = getVocab(vocab_filename) vocab_len = len(vocab.keys()) test_data_files = utils.get_files(test_data_folder) test_data = convert_files2char(test_data_files, vocab) print("test_data_generated") trigram_cnt, fourgra...
def _setup_data(split='val'): print("Loading weights and data.") for x,y in tqdm(generate_choose_2(num_classes)): file_name = "SVM-guassian-{}-{}.npy".format(x, y) path_name = os.path.join("weights", file_name) f = open(path_name, "rb") alpha = np.load(f) class_pair_to_ap...
This function calculates the accuracy of a multiclass classifier on a specified dataset split (e.g., validation) using a given kernel function. It loads MNIST images/labels, predicts each image's class with `predict_multiclass`, compares predictions to true labels, and returns the accuracy as correct/total predictions.
def calc_acc_multiclass(split='val', kernel_func=_gaussian_kernel): _setup_data(split=split) images, labels = _load_all_mnist(split=split) predictions = [] print("Now running validation on split {}.".format(split)) for i in tqdm(range(images.shape[0])): image = images[i] output = pr...
def setFile(s, fileName): f = open(fileName, 'r+') f.truncate(0) # need '0' when using r+ f.close() file1 = open(fileName, "a") # append mode file1.write(str(s)) file1.close() def setArbitraryInitializations(self): self.root_new = tk.Tk() self.root_new.wm_title("input arbitrary in...
This code initializes a GUI application for managing a network simulation. It reads node color data from a file, sets up a Tkinter window with menus for configuring simulations (initializations, time steps, node analysis), and initializes multiple frames for different interface pages. The menus allow users to set simul...
def __init__(self, *args, **kwargs): global eachNodeColor file1 = open('eachNodeColor.txt', 'r') eachNodeColor = file1.read().splitlines() self.network = [] tk.Tk.__init__(self, *args, **kwargs) #tk.Tk.iconbitmap(self...
def double_swap(self, root, root_left, root_right): """ If the root has 2 children then if left is smaller than right, swap root with left, if right is smaller than left, swap root right, if children are equal then swap with left. Args: root (PathNode): The node we a...
The function determines whether a node requires a swap based on its children's presence, invoking the appropriate helper method: double_swap for two children, left_swap for only a left child, or right_swap for only a right child.
def check_swap(self, root, root_left, root_right): """ Checks if a swap needs to be made by sending the right case to the appropriate swap helper function, ex. 2 children, only left, only right. Args: root (PathNode): The node we are at root_left (PathNode): The ...
def leaf(self, root): """ Checks if the node we are at is a leaf Args: root (PathNode): The node we are currently at """ return root.left is None and root.right is None def check_swap(self, root, root_left, root_right): """ Checks if a swap needs to b...
The function `heapify` recursively transforms a complete binary tree into a min-heap. Starting from the root, it traverses to the last non-leaf nodes, ensuring each parent node is smaller than its children. It recursively processes left and right subtrees, then checks if swaps are needed to maintain the min-heap proper...
def heapify(self, root): """ Heapifys the complete binary tree by going to the last node with children, swapping if necessary, moving to the preceding node, and repeating. Makes a minheap, and traverses nodes recursively. args: root (PathNode): The PathNode to start ...
def read_paths(self, input_file): """ Reads the contents of the files as paths for the PathNodes by adding each line of the file to the temp_path attribute. args: input_file (str): The file to read from raise: ValueError if an input contains a n...
The main task of the code is to read input data, construct a binary tree, generate a pre-heapification graphviz visualization, repeatedly heapify the tree until it satisfies the heap property, and produce a post-heapification visualization. It handles tree structure setup, link maintenance during heapification, and out...
def go(self): """ Acts a starting point for the Heap to be called in the driver, reads the file input, builds and sets binary tree, makes the before file for graphviz, heapifys, and makes the after file for graphviz. """ # read input self.read_paths(self.input_fil...
def init_board(): board = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)] for i in range(NUM_BOMBS): #while count(board) < 40: row = random.randint(1, BOARD_SIZE-1) column = random.randint(1, BOARD_SIZE-1) board[row][column] = 9 # print(np.array(board)) # print(...
This code creates a Minesweeper game using Pygame. It initializes a grid, handles mouse interactions for uncovering cells and flagging bombs, updates the display with numbers and images, and checks win/lose conditions based on revealed cells and flags.
def create_grid(): board = init_board() pg.init() SQUARE_SIZE = 15 win = pg.display.set_mode((HEIGHT, WIDTH)) win.fill(GREY) pg.display.set_caption("Minesweeper") font = pg.font.SysFont('Arial', 15) BOMB_IMG = pg.image.load("bomb.png") FLAG_IMG = pg.image.load("flag.png") rect2 =...
def tl(self): """Shorthand for Turn Left""" turn_left() def put5(self): """Put 5 beepers in a line""" self.put2() self.m() self.put2() self.m() self.put() def tr(self): """Shorthand for Turn Right""" self.tl() self.tl() self.tl() def m(self): """Shorthand for move""" ...
The code defines a method `h` that prints the letter 'H' using a series of movements and beeper placements. It turns left/right, moves forward, and places beepers (likely on a grid) to form the shape of 'H'. The sequence of actions creates vertical and horizontal lines, constructing the letter through precise direction...
def h(self): """Print H using beepers""" self.tl() self.put5() self.tr() self.m() self.m() self.m() self.tr() self.put5() self.ta() self. m() self.m() self.tl() self.m() self.put2() self.tl() self.m() self.m() self.tl() self.m() self....
def tl(self): """Shorthand for Turn Left""" turn_left() def put5(self): """Put 5 beepers in a line""" self.put2() self.m() self.put2() self.m() self.put() def tr(self): """Shorthand for Turn Right""" self.tl() self.tl() self.tl() def m(self): """Shorthand for move""" ...
The code's main task is to print the letter 'E' on a grid using beepers by executing a sequence of movements (turning left/right, moving forward) and placing beepers at specific positions to form the shape of 'E'
def e(self): """Print E using beepers""" self.tl() self.put5() self.tr() self.m() self.put2() self.tr() self.m() self.m() self.tr() self.put2() self.m() self.tl() self.m() self.m() self.tl() self.m() self.put2() self.m() self.m()
def tl(self): """Shorthand for Turn Left""" turn_left() def put5(self): """Put 5 beepers in a line""" self.put2() self.m() self.put2() self.m() self.put() def m(self): """Shorthand for move""" move() def put2(self): """Put 2 beepers in a line""" self.put() self.m() ...
The code defines a method 'l' that sequentially invokes multiple instance methods: 'tl()' (called 5 times), 'put5()', 'put2()', and 'm()' (called 4 times). The primary task is to execute a predefined sequence of operations involving toggling states ('tl'), placing elements ('put5', 'put2'), and repeating actions ('m') ...
def l(self): self.tl() self.put5() self.tl() self.tl() self.m() self.m() self.m() self.m() self.tl() self.m() self.put2() self.m() self.m()
def tl(self): """Shorthand for Turn Left""" turn_left() def put5(self): """Put 5 beepers in a line""" self.put2() self.m() self.put2() self.m() self.put() def tr(self): """Shorthand for Turn Right""" self.tl() self.tl() self.tl() def m(self): """Shorthand for move""" ...
The code's main task is to navigate a grid and place beepers in a specific pattern to form the letter 'A', using a series of turns (tl/tr) and movements (m/m2/m4) to position and drop beepers at calculated intervals.
def a(self): """Print A using beepers""" self.tl() self.put5() self.tr() self.m() self.put2() self.m() self.put() self.tr() self.m() self.put2() self.m() self.put2() self.tl() self.tl() self.m() self.m() self.tl() self.m() self.put2() s...
def tl(self): """Shorthand for Turn Left""" turn_left() def put5(self): """Put 5 beepers in a line""" self.put2() self.m() self.put2() self.m() self.put() def tr(self): """Shorthand for Turn Right""" self.tl() self.tl() self.tl() def m(self): """Shorthand for move""" ...
The main task of the code is to make a robot draw the letter 'R' by sequentially executing movements (turning left/right, moving forward) and placing beepers at specific positions, as defined by the method calls like `put`, `put2`, and `put5`, to form the shape of the letter 'R' in a grid-based environment.
def r(self): """Print R using beepers""" self.tl() self.put5() self.tr() self.m() self.put2() self.tr() self.m() self.put2() self.tr() self.m() self.put() self.tl() self.m() self.put() self.m() self.tl() self.m() self.put() self.m() sel...
def tl(self): """Shorthand for Turn Left""" turn_left() def put5(self): """Put 5 beepers in a line""" self.put2() self.m() self.put2() self.m() self.put() def tr(self): """Shorthand for Turn Right""" self.tl() self.tl() self.tl() def m(self): """Shorthand for move""" ...
The code's main task is to navigate a grid and place beepers in a specific pattern to form the letter 'C', using a series of directional turns (left/right) and movements, along with placing varying numbers of beepers at calculated positions.
def c(self): """Print C with beepers""" self.tl() self.put5() self.tr() self.m() self.put2() self.m() self.put() self.tr() self.m4() self.tr() self.put2() self.m() self.put() self.tl() self.tl() self.m4()
def tl(self): """Shorthand for Turn Left""" turn_left() def put5(self): """Put 5 beepers in a line""" self.put2() self.m() self.put2() self.m() self.put() def tr(self): """Shorthand for Turn Right""" self.tl() self.tl() self.tl() def m(self): """Shorthand for move""" ...
The code's main task is to navigate a grid and place beepers in a specific pattern to form the letter 'M', using a series of turn, move, and beeper placement commands.
def lm(self): """Print M using beepers""" self.tl() self.put5() self.tr() self.m() self.put2() self.tr() self.m() self.put2() self.m() self.put2() self.tl() self.tl() self.m4() self.tr() self.m() self.put2() self.tr() self.m() self.put2() ...
def tl(self): """Shorthand for Turn Left""" turn_left() def put5(self): """Put 5 beepers in a line""" self.put2() self.m() self.put2() self.m() self.put() def tr(self): """Shorthand for Turn Right""" self.tl() self.tl() self.tl() def m(self): """Shorthand for move""" ...
The code's main task is to direct a robot to navigate and place beepers in a specific pattern to form the letter 'O'. It uses movement commands (turn left/right, move) and beeper placement methods to trace the outline and fill the shape of 'O', ensuring precise positioning and sequence of actions to achieve the desired...
def o(self): """Print O using beepers""" self.tl() self.put5() self.tr() self.m() self.put2() self.m() self.put2() self.tr() self.m() self.put2() self.m() self.put2() self.tr() self.m() self.put2() self.m() self.put() self.ta() self.m4() ...
def tl(self): """Shorthand for Turn Left""" turn_left() def put5(self): """Put 5 beepers in a line""" self.put2() self.m() self.put2() self.m() self.put() def tr(self): """Shorthand for Turn Right""" self.tl() self.tl() self.tl() def m(self): """Shorthand for move""" ...
The code's main task is to print the letter 'N' using a robot by placing beepers in a specific pattern. It involves turning, moving, and strategically placing beepers (5 and 2) to form the shape of 'N' on a grid.
def n(self): """Print N using beepers""" self.tl() self.put5() self.tr() self.m() self.put2() self.m() self.tr() self.put5()
def print_header(message: str): """ print a large header to console (RED) :param message represent the header message we want to print """ print(Fore.WHITE) bash('figlet {}'.format(message)) def print_command(message: str): """ print command messages to console :param message repres...
The main task of the code is to manage an "Evil Twin Manager" program by handling user commands for launching evil twin attacks, defending against them, or exiting. It ensures root privileges are used (via `os.geteuid()`), provides a menu-driven interface, and executes corresponding functions based on user input while ...
def manage(): """ This is the main program function , this function is responsible for the program flow. """ print_header('Evil Twin Manager') print_command("Welcome To Evil Twin Manager") if os.geteuid(): # because scapy library must use root privileges. sys.exit('{}Perform exit() , Pl...
def build_priorityQ(self): for key in self.freq: node = HeapNode(key,self.freq[key]) heapq.heappush(self.heap, node) def build_huffman_tree(self): while(len(self.heap)>1): node1 = heapq.heappop(self.heap) node2 = heapq.heappop(self.heap) mergedNode = HeapNode(None, ...
This code compresses a text file using Huffman coding. It reads the input text, builds a Huffman tree, encodes the text into binary, pads the encoded bits, converts them into bytes, and writes the compressed data to a .bin file. It also generates a code mapping dictionary, serialized with pickle, to enable decompressio...
def compress(self): filename, extension = os.path.splitext(self.path) output_path = filename + ".bin" with open(self.path, 'r+') as file, open(output_path, 'wb') as output: text = file.read() text = text.rstrip() self.build_priorityQ() self.build_huffman_tree() ...
def check_vowel(substring): """ Checks if the substring is a vowel. letters: substring to be tested returns BOOLEAN """ return all(letter in VOWELS for letter in substring) def check_consonant(substring): """ Checks if the letter is a consonant. letter: substring to be tested returns BOOLEAN """ r...
The function `clean_stemmed` processes a token by removing invalid characters (non-vowel/consonant letters), correcting affixes, and adjusting specific patterns (e.g., replacing 'u' with 'o', 'r' with 'd', handling 'han' endings). It iteratively trims, validates, and modifies the token based on vowel/consonant rules, r...
def clean_stemmed(token, CLEANERS, REPITITION): """ Checks for left-over affixes and letters. token: word to be cleaned for excess affixes/letters returns STRING """ global PERIOD_FLAG global PASS_FLAG CC_EXP = ['gl', 'gr', 'ng', 'kr', 'bw', 'kl', 'kw', 'ts', 'tr', 'pr', 'sw' ,'sy'] # Consonant + Consonan...
def read_file(source): """ Gets content of a text file. source: file name returns LIST """ with open(source, 'r') as myfile: data = myfile.read().replace('\n', ' ') return data.split(' ') def clean_duplication(token, DUPLICATE): """ Checks token for duplication. (ex. araw-araw = araw) token: word t...
The code performs **token stemming** on input text (from file, string, or list) by applying sequential cleaning steps (prefix, infix, suffix, duplication, repetition, etc.) to derive root forms. It validates results, retries invalid cases, and returns a list of stemmed tokens with metadata. The function handles case no...
def stemmer(mode, source, info_dis=None): """ Stems the tokens in a sentence. mode: if from .txt or string or list source: the string or file name or list returns LIST """ global PERIOD_FLAG global PASS_FLAG word_info = {} stemmed = [] word_root = [] root_only = [] errors = [] ...
def clean_duplication(token, DUPLICATE): """ Checks token for duplication. (ex. araw-araw = araw) token: word to be stemmed duplication returns STRING """ if check_validation(token): return token if '-' in token and token.index('-') != 0 and \ token.index('-') != len(token) - 1: split = token.split...
The code performs stemming on a given token by sequentially applying duplication, prefix, repetition, infix, suffix, and cleaning operations. It validates the result, reprocessing if invalid, and returns the stemmed word along with metadata like root, prefixes, suffixes, and applied rules.
def stemmer_word(token): global PERIOD_FLAG global PASS_FLAG word_info = {} stemmed = [] word_root = [] root_only = [] errors = [] pre_stem = inf_stem = suf_stem = rep_stem = \ du1_stem = du2_stem = cle_stem = '-' PREFIX = [] INFIX = [] SUFFIX = [] DUPLICATE = [] R...
def resample_flow(uv,sz,method='bilinear'): """ RESAMPLE_FLOW Resample flow field RESAMPLE_FLOW(IN, FACTOR[, METHOD]) resamples (resizes) the flow field IN using a factor of FACTOR. The optional argument METHOD specifies the interpolation method ('bilinear' (default) or 'bicubic'). sz (t...
This code estimates optical flow between two images using the Horn-Schunck method with a multi-level pyramid approach. It iteratively refines displacement fields (Dx, Dy) via forward/inverse warping, applies median filtering for smoothing, and updates flow estimates across pyramid levels from low to high resolution. Th...
def Estimate(im1,im2,lamb,uvInitial,PARA): # Run Horn_schunck on all levels and interpolate warp_iter = PARA.warp_iter sizeOfMF = PARA.sizeOfMF isMedianFilter = PARA.isMedianFilter Dx = uvInitial[:,:,0] #delta x Dy = uvInitial[:,:,1] #de;ta y #consruct image pyra...
def assign_to_clusters(self): data_clusters = {} for i in self.data: closest_clsr_index, closest_clsr_distance = self.find_cluster_index(self.data[i]) data_clusters[i] = closest_clsr_index return data_clusters def dicts_are_equal(self, a, b): len_a = len(a) ...
The code performs iterative clustering by assigning data points to clusters, updating centroids, and repeating until convergence or max iterations. It tracks cluster allocations, checks for stability, and returns the final allocation.
def compute_clusters(self): self.cluster_allocation = {} iteration_count = 0 while True: actual_clusters = self.assign_to_clusters() print("Cluster allocation:") print(actual_clusters) if self.dicts_are_equal(self.cluster_allocation, actual_cluster...
def go_to_generator(self): url = "https://www.craiyon.com/" self.user.get(url) # remove ad banners for ad in [ '//div[@id="craiyon_left_rail"]', '//div[@id="craiyon_right_rail"]', '//div[@id="fs-sticky-footer"]', '//div[@id="videoplayer"]',...
The code automates generating and downloading results by repeatedly creating prompts, submitting them, monitoring for outcomes, and downloading data if available. It handles errors, allows infinite generations if unspecified, and closes the browser upon completion.
def automate(self): """Automates generation and download process.""" i = 1 continue_condition = ( lambda: i <= self.num_generations if self.num_generations else lambda: True ) self.go_to_generator() while continue_condition(): try: ...
def enforce_datatypes(df: pd.DataFrame, cat_vars: list=cat_vars, num_vars: list=num_vars) -> pd.DataFrame: """ Enforces the data types of the columns in a pandas DataFrame. Args: df: The pandas DataFrame to be updated. cat_vars: A list of the categorical variables in the DataFrame. ...
The function preprocesses a DataFrame for machine learning, handling both training and inference modes. It cleans data by removing null values, enforcing data types, and engineering features. For training, it splits data, encodes categorical variables, imputes missing values, and rescales features, saving processed dat...
def preprocess_data(df:pd.DataFrame, mode:str, job_id:str=None, rescale=False, ref_job_id:str=None) -> pd.DataFrame: """ Pre-process data and save preprocessed datasets for later use. :param df: DataFrame :param mode: str, 'training' or 'inference' :param job_id: str, job_id for the preprocessed dat...
def model_path(self, epoch_no: int | None = None) -> str: """ Returns the path to a pretrained model's weights. """ if epoch_no is None: epoch_identifier = "" else: epoch_identifier = f"-ep{epoch_no}" return os.path.join( self.weights_...
The main task of this code is to train an image classifier model using a specified dataset. It validates input parameters, handles model resumption from previous training sessions, manages GPU usage, and performs iterative training with evaluation on test data. The code tracks metrics like loss and accuracy, saves the ...
def train(self, batch_size: int, force: bool) -> None: """ Trains the image classifier. """ # PyLint dislikes the "X, y" ML naming convention for data & labels # pylint: disable=C0103 # Cannot train on an unset dataset if self.dataset is None: raise V...
def out(text): sys.stdout.write(text) sys.stdout.flush() def createVar(vars, item_label, module_root_dir, postfix=None, default_ignore=False): default_name = "{module}".format(**vars) if not default_ignore: default_value_star1 = "*" default_value_star2 = "" else: default_value_star1 = "" defa...
This code generates a module by prompting the user for a module name, validating it, and then creating associated files (action, action_labels, container, model, reducer) in specified directories using helper functions createVar and generateItem. The main task is to automate module creation with structured file generat...
def genModule(): vars = {} out("{0:<20} [required]: ".format("Module name?")) vars["module"] = raw_input() if not vars["module"]: raise RuntimeError("Blank not allowed") createVar(vars, "action", module_root_dir="actions") createVar(vars, "action_labels", module_root_dir="actions", postfix="labels") ...
def format_headers(protdir, outdir, threads): #Make folder for labeled protein files labeled_proteins = os.path.abspath(os.path.join(outdir, 'labeled_proteins')) os.system('mkdir ' + labeled_proteins) print("Protdir: ", protdir) print("Labeled proteins dir: ", labeled_proteins) def labeler(fasta...
The code processes nucleotide or protein sequences using HMM profiles to identify hits, applying thresholds and generating output files. It predicts proteins from nucleotides if needed, runs parallel HMM searches, consolidates results into a dataframe, ensures ribosomal synteny, and outputs hit statistics. The task inv...
def main(): args = parser.parse_args() if args.nucdir is not None: nucdir = str(Path(args.nucdir).absolute()) else: nucdir = None if args.protdir is not None: prodigaldir = str(Path(args.protdir).absolute()) else: prodigaldir = None if nucdir is None and prodigal...
def terminal(board): """ Returns True if game is over, False otherwise. """ # If the game is won, then it is definitely over if winner(board) != None or not actions(board): return True # Else, if there are still empty cells on the board, then the game is not over for row in board: ...
This function returns a new board state after applying the specified action (i, j) to the current board, ensuring the move is valid. It creates a deep copy of the board, updates the specified cell with the current player's symbol (X or O), and returns the modified board without altering the original.
def result(board, action): """ Returns the board that results from making move (i, j) on the board. """ global turn # Raises exception if action is invalid if terminal(board) or action not in actions(board): raise Exception else: i = action[0] j = action[1] ...
def terminal(board): """ Returns True if game is over, False otherwise. """ # If the game is won, then it is definitely over if winner(board) != None or not actions(board): return True # Else, if there are still empty cells on the board, then the game is not over for row in board: ...
This function implements the minimax algorithm with alpha-beta pruning to determine the optimal value for the current player in a game. It recursively evaluates all possible moves, returning the utility of terminal states, and updates the best value by maximizing/minimizing outcomes based on the player's turn. Early re...
def calculate_value(board, best_value): if terminal(board): return utility(board) current_player = player(board) value = -math.inf if current_player == X else math.inf for action in actions(board): newVal = calculate_value(result(board, action), value) if current_player == X:...
def terminal(board): """ Returns True if game is over, False otherwise. """ # If the game is won, then it is definitely over if winner(board) != None or not actions(board): return True # Else, if there are still empty cells on the board, then the game is not over for row in board: ...
The main task of the code is to implement the minimax algorithm to determine the optimal action for the current player on a given board state. It evaluates all possible moves recursively, selecting the action that maximizes the current player's chances of winning while minimizing the opponent's opportunities, ultimatel...
def minimax(board): """ Returns the optimal action for the current player on the board. """ if terminal(board): return None if board == initial_state(): return (1,1) current_player = player(board) bestVal = -math.inf if current_player == X else math.inf for action in a...
def construct_state_matrix(df,methyl_names,age,methyl,locations): states_matrix_temp = [] #determine thresholds for age buckets based on quartile analysis age_buckets = [] for buckets in range(age): age_buckets += [(df.age.quantile(1/age*buckets),df.age.quantile(1/age*(buckets+1)))] #come ...
The main task of the code is to build and analyze Markov models for age and condition prediction using methylation data from healthy and diseased individuals. It preprocesses CSV datasets, constructs state and transition matrices for pre- and post-pruned models, evaluates prediction accuracy, saves results as CSVs, and...
def main(): #modify to wherever you have kept the csv file df_disease = pd.read_csv("/Users/raehash/Desktop/CMU Sophomore Year/Fall Semester/02-512 Computational Methods for Biological Modeling and Simulation/Markov_Model_Analysis/Input_Datasets/Diabetes_Set.csv") df_healthy = pd.read_csv("/Users/raehash/D...
def read_config(config_file: Path) -> Config: """Read a yaml config file Args: config_file: Path to config file """ if config_file.exists(): with open(Path.home().joinpath(".rsync-backup")) as f: config = Config(**yaml.load(f, Loader=yaml.FullLoader)) else: con...
This code implements an rsync-based backup tool that manages directory synchronization across hosts using a YAML config file. It parses command-line arguments for backup configurations, handles exclusion rules, deletion policies, and logging. The script validates inputs, checks host connectivity, and executes rsync ope...
def main() -> int: default_config_file = Path.home().joinpath(".rsync-backup") usage = """\tRsync backup tool. \tSimple script to manage backup of similar directory structures across hosts. \tThe directories to backup can be read from a config file and the required \tdirectories can be backed up. \tAdditiona...
def init_weights(self): np.random.seed(1) # Seed the random number generator self.params["W1"] = np.random.randn(self.layers[0],self.layers[1]) self.params['b1'] = np.random.randn(self.layers[1],) self.params['W2'] = np.random.randn(self.layers[1],self.layers[2]) self.params['b2'] = np.random.rand...
This code trains a neural network by iterating over data, performing forward and backward propagation to adjust weights and biases, and recording loss values for each iteration. It initializes weights, updates parameters using gradients from the backward pass, and tracks training progress via the loss history.
def fit(self, X, y): ''' Trains the neural network using the specified data and labels in iteration ''' self.X = X self.y = y self.init_weights() #initialize weights and bias for i in range(self.iterations): yhat, loss = self.forward() self.backward(yhat) self.loss.a...
def init_weights(self): np.random.seed(1) # Seed the random number generator self.params["W1"] = np.random.randn(self.layers[0],self.layers[1]) self.params['b1'] = np.random.randn(self.layers[1],) self.params['W2'] = np.random.randn(self.layers[1],self.layers[2]) self.params['b...
This code trains a neural network by iterating over data, performing forward and backward passes to compute predictions, loss, and update weights, while tracking loss values across iterations.
def fit(self, X, y): ''' Trains the neural network using the specified data and labels in iteration ''' self.X = X self.y = y self.init_weights() #initialize weights and bias for i in range(self.iterations): yhat, loss = self.forward() sel...
def reload_boards_select(boards_ui, lists_ui, cards_ui, card_details_ui, board_id = None): load_boards(boards_ui, lists_ui, cards_ui, card_details_ui) if board_id: try: cmds.textScrollList(boards_ui[LIST_KEY], edit=True, selectUniqueTagItem=board_id) except: pass def rel...
The function `reload_boards` retrieves selected IDs from UI text scroll lists (boards, lists, cards), extracts the first selected item from each, and triggers reload operations in corresponding UI components by calling `reload_boards_select`, `reload_lists_select`, and `reload_cards_select` with the retrieved IDs. This...
def reload_boards(boards_ui, lists_ui, cards_ui, card_details_ui): board_ids = cmds.textScrollList(boards_ui[LIST_KEY], query=True, selectUniqueTagItem=True) list_ids = cmds.textScrollList(lists_ui[LIST_KEY], query=True, selectUniqueTagItem=True) card_ids = cmds.textScrollList(cards_ui[LIST_KEY], query=True...
def checkTempo(strb): global bpm if strb.find("Bpm(") > -1: temp = strb[strb.find("Bpm(")+4:strb.find(")")] if is_number(temp): bpm = int(temp) else: bpm = 140 return def checkText(txt): if txt.find('|') == -1: return True if any(Noot in txt for Noot in nonExistantNotes): return True return False ...
The code converts text-based musical notation into a MIDI file. It processes input text by removing spaces, checking tempo, splitting tracks if brackets are present, extracting instrument and tempo data, and writing the output. If tracks are detected, it handles multiple instruments and tempo multipliers. If conversion...
def ConvertText(txt, ttl=time.strftime("%d_%m_%y_%H_%M_%S")): song = txt title = ttl tracked = False song = song.replace(" ", "") checkTempo(song) global ConvertionNotPossible if "[" in song: song = song.split("[") tracked = True if tracked: songs = [] for track in song: checkText(track) if "Inst(...
def checkItems(path): items = os.path.listdir(path) for item in items: ConvertFile(item) return True def is_convertabletxt(txt): if txt.find("|") > -1: return True return False def ConvertText(txt, ttl=time.strftime("%d_%m_%y_%H_%M_%S")): song = txt title = ttl tracked = False song = song.replace(" ", "") ...
The code processes command-line arguments to convert files or directories, checking if inputs are valid (file/directory) and convertible. If no arguments are provided, it prompts the user to input a title and content, then converts the text using a timestamp or specified title. The main task is to handle text conversio...
def startupRoutine(): if len(sys.argv) > 1: if os.path.isdir(sys.argv[1]): checkItems(sys.argv[1]) else: if is_convertabletxt(sys.argv[1]): if len(sys.argv) > 2: ConvertText(sys.argv[1], sys.argv[2]) else: ConvertText(sys.argv[1]) sys.exit() if os.path.isfile(sys.argv[1]): Conver...
def prepareInputs(n, vec_size): inputs = {} for vec in range(vec_size): # Create a matrix of size (n,n) with random 0s and 1s. matrix = np.random.randint(2, size=(n,n)) for i in range(n): for j in range(n): key = f"n_{i}_{j}" if key not in inputs.keys(): inputs[key] = [matrix[i,j]] else: ...
The code simulates a process that reduces input matrices by minimizing ones using an EVA Program, computes pairwise distances between elements iteratively, tracks computational timings, and returns these metrics. It prepares encrypted inputs, applies configurable parameters for security and efficiency, and updates dist...
def simulate(n, vec_size): N = n * n config = {} config['balance_reductions'] = "true" config['rescaler'] = "always" config['lazy_relinearize'] = "true" config['security_level'] = "128" config['warn_vec_size'] = "false" # Prepare input matrices similar to EVA Input inputs = prepareInputs(n, vec_size) # sel...
def _get_default_runtime_image_name(self): python_version = version_str(sys.version_info) return ibmcf_config.RUNTIME_DEFAULT[python_version] def _generate_runtime_meta(self, docker_image_name): """ Extract installed Python modules from docker image """ action_code = """ ...
This code creates a runtime in IBM Cloud Functions (CF) using a specified Docker image. It handles default image names, generates metadata, prepares a function handler zip, uploads the action with memory/timeout settings, and cleans up temporary files. The main task is deploying a Docker-based runtime on IBM CF with co...
def create_runtime(self, docker_image_name, memory, timeout): """ Creates a new runtime into IBM CF namespace from an already built Docker image """ if docker_image_name == 'default': docker_image_name = self._get_default_runtime_image_name() runtime_meta = self._gen...
def sanitize_title(self, title): return re.sub(r"<.*?>", "", title).strip() def format_dates(self, aspace_json): if aspace_json.get("dates"): inclusive_dates = [] bulk_dates = [] for date in aspace_json["dates"]: expression = date.get("expression", "")...
The main task of the code is to generate a display string by combining a title and dates from an ASpace JSON object. It prioritizes including both title and dates if available, falls back to just the title or dates if one is missing, and optionally appends a parent title from a referenced parent JSON when dates exist b...
def make_display_string(self, aspace_json, add_parent_title=False): if aspace_json.get("title") and aspace_json.get("dates"): return self.sanitize_title(aspace_json["title"]) + ", " + self.format_dates(aspace_json) elif aspace_json.get("title") and not aspace_json.get("dates"): r...
def get_agents_by_role(self, aspace_json, role): agents = [agent["ref"] for agent in aspace_json["linked_agents"] if agent["role"] == role] return agents def get_aspace_json(self, aspace_uri, params={}): url = "{}{}".format(self.backend_url, aspace_uri) return self._get(url, params=param...
This function retrieves the first agent's name associated with a specified role from an archive space JSON. It fetches agent URIs matching the role, extracts the first agent's title, verifies punctuation, and returns the cleaned name. If no agents match the role, it returns an empty string.
def get_first_agent_by_role(self, aspace_json, role): agents = self.get_agents_by_role(aspace_json, role) if agents: agent_uri = agents[0] agent_name = self.get_aspace_json(agent_uri)["title"] return self.verify_punctuation(agent_name) else: return...
def get_resource_archival_object_uris(self, resource_number): resource_tree = self.get_resource_tree(resource_number) archival_object_uris = extract_archival_object_uris_from_children( resource_tree["children"]) return archival_object_uris def get_aspace_json(self, aspace_uri, params...
The function unpublishes expired access restrictions in archival objects linked to a specified resource. It retrieves archival object data, checks each accessrestrict note for a date older than today, sets the note's publish flag to False if expired, logs the change, and updates the archival object via a POST request. ...
def unpublish_expired_restrictions_for_resource(self, resource_number): today = datetime.today().strftime("%Y-%m-%d") archival_object_uris = self.get_resource_archival_object_uris( resource_number) unpublished_log = [] for archival_object_uri in archival_object_uris: ...
def get_resource_archival_object_uris(self, resource_number): resource_tree = self.get_resource_tree(resource_number) archival_object_uris = extract_archival_object_uris_from_children( resource_tree["children"]) return archival_object_uris def get_aspace_json(self, aspace_uri, params...
This function identifies and unpublishes access restrictions in archival objects that match a specified text. It retrieves archival objects for a given resource, checks their "accessrestrict" notes, and un-publishes those notes if they exactly match the provided restriction text. Updated objects are posted back to the ...
def unpublish_restrictions_by_text(self, resource_number, restriction_text=False): if not restriction_text: return "No restriction text provided" archival_object_uris = self.get_resource_archival_object_uris( resource_number) unpublished_log = [] for archival_obje...
def get_resource_tree(self, resource_number): # /repositories/:repo_id/resources/:id/tree uri = self.backend_url + self.repository + \ "/resources/{}/tree".format(resource_number) response = self._get(uri) return response.json() def find_children_with_instances(children, chil...
The main task of the code is to remove associations by identifying and deleting all instance resources linked to a specified resource. It retrieves the resource tree, finds child nodes with instances, collects their URIs, and deletes each unique instance URI using the delete_single_resource_instances method, ensuring a...
def remove_resource_associations(self, resource_number): resource_tree = self.get_resource_tree(resource_number) children_with_instances = find_children_with_instances( resource_tree["children"]) instance_uris = [] for child_uri in children_with_instances: instanc...
def get_valid_dataids(butler, dataset_type): """Return all data Id values that exist for a given data set Args: butler (Butler): A data access butler dataset_type (str): The name of the data set to load Returns: A list of dataID values """ subset = butler.subset(dataset...
The code generates postage stamps for Difference Imaging Analysis (DIA) sources from a pipeline output directory. It initializes a data butler, identifies valid data IDs, cross-matches DIA sources with a truth catalog, saves matched results to a CSV, and creates postage stamps of specified size for each source, storing...
def run(diff_im_dir, out_dir, cutout_size): """Create postage stamps for all DIA sources Args: diff_im_dir (str): Output directory of DIA pipeline out_dir (str): Directory to save postave stamps into cutout_size (float): Side length of postage stamps in pixels """ out_d...
def _serialize(self, data): ''' coerces data into one of the allowed BSON types Input: raw function output data to be cached Returns: data with coerced format ''' data = self._coerce_bson_recursive(data) return data de...
This function updates or inserts a document in a database collection by serializing input data and args into a filter/update pair. It creates a deep copy of the data to avoid modifying the original, constructs a MongoDB update operation with serialized response data and timestamp, then applies the update with upsert=Tr...
def _update_data(self, data, args): try: # make copy of data for processing and cacheing # do not alter original output data = deepcopy(data) filter = self._serialize({key: val for key, val in zip(self.key_names, args)}) update = {"$set": { ...
def _get_timestamp(self): # add timestamp and inc timestamp = datetime.datetime.now() last_second = self.mongo_op_object.get("second", -1) op_count = self.mongo_op_object.get('op_count', 0) if timestamp.second == last_second: op_count += 1 else: ...
The main task of the code is to cache function output data into a MongoDB collection when enabled. It creates a serialized entry with input arguments, timestamp, and deep-copied response data, then inserts it into the collection. If caching is disabled or an error occurs, it logs the issue and disables caching.
def _push_data(self, data, args): ''' Inputs: collection : collection object to push data into data : function output data to cache args : inputs to function ''' if not self._enabled: return self.logger('cacheing da...
def _check_api_key(self): self.addMessage.emit("checking connection to flickr API...") url = f"https://api.flickr.com/services/rest/?api_key={self.apiKey}&method=flickr.test.echo&format=json&nojsoncallback=1" r = requests.get(url) if r.status_code == 200: data = r.json() ...
The code downloads Flickr photo metadata within specified geographic and temporal boundaries, processes paginated results, splits large queries into smaller sub-queries when needed, removes duplicates, and saves the structured data into a CSV file. It uses an API key for authentication, manages download sessions, and e...
def run(self): self.downloadCount = 0 self.running = True # check if api key is valid apiKeyValid = self._check_api_key() if not apiKeyValid: self.addError.emit("Error: invalid API key") self.finished.emit(pd.DataFrame()) return if n...