dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def edit_movie(self, movie_treeview): selected_item = movie_treeview.selection() if selected_item: item_values = movie_treeview.item(selected_item, "values") selected_movie_id = item_values[0] selected_movie = self.collection_manager.get_item_by_id(selected_movie_id,...
The main task of the code is to create a GUI tab for managing a movie database. It sets up a labeled frame with a Treeview table to display movie details, implements CRUD operations (add/edit/delete/view), includes search functionality, and adds vertical scrolling. The tab is initialized with predefined columns and but...
def create_movie_tab(self): self.table_name = 'movies' key = 'recent' self.movie_frame = ttk.LabelFrame(self.movie_tab, text=f"{self.recent_all_labels[key]} Movie") self.movie_frame.pack(fill="both", expand=True, padx=10, pady=10) tree_frame = ttk.Frame(self.movie_frame) ...
def edit_book(self, book_treeview): selected_item = book_treeview.selection() if selected_item: item_values = book_treeview.item(selected_item, "values") selected_book_id = item_values[0] selected_book = self.collection_manager.get_item_by_id(selected_book_id, self.t...
This code creates a GUI tab for managing a books database, featuring a Treeview table with columns for book details (ID, Name, Date, etc.), scrollbars, CRUD operation buttons (Add/Edit/Delete/Show All), and a search bar. It initializes the UI components and loads book data into the table for user interaction.
def create_book_tab(self): self.table_name = 'books' key = 'recent' self.book_frame = ttk.LabelFrame(self.book_tab, text=f"{self.recent_all_labels[key]} Books") self.book_frame.pack(fill="both", expand=True, padx=10, pady=10) tree_frame = ttk.Frame(self.book_frame) tree_...
def create_game_tab(self): self.table_name = 'games' key = 'recent' self.game_frame = ttk.LabelFrame(self.game_tab, text=f"{self.recent_all_labels[key]} Games") self.game_frame.pack(fill="both", expand=True, padx=10, pady=10) # Using Treeview to display games as a table ...
This code initializes a GUI application with tabs for managing games, movies, and books. It sets up a notebook interface with three tabs, initializes UI components for each category, and binds tab change events. The class integrates with a database and collection manager to handle media data, creating frames and treevi...
def __init__(self, root, collection_manager, db): self.root = root self.collection_manager = collection_manager self.db = db self.table_name = 'games' self.game_frame = None self.game_treeview = None self.movie_frame = None self.movie_treeview = None ...
def write_to_file(filepath, s): f = open(filepath, 'a') f.write(s + "\n") f.close() def walk(api, v, samplinglist, friends_dict, followers_dict, neighbors_dict, visit, log_file_path, samplinglist_file_path): # Retrieve neighbors and record them with adding the previous node if v in visit: if...
This function performs random walk sampling to collect a specified number of samples starting from a given node. It logs the process, tracks visited nodes, and optionally calculates bot population metrics using bot scores. The walk continues until the sample size is met, with error handling for neighbor retrieval failu...
def randomwalk_for_samplesize(api, bom, samplesize, startnode, log_file_path, samplinglist_file_path, calc_bot_ppl=False, threshold=0.95, cut=0, botscore_file_path="", est_file_path=""): write_to_file(log_file_path, "Target sample size: %d" % samplesize) visit = {} friends_dict...
def write_to_file(filepath, s): f = open(filepath, 'a') f.write(s + "\n") f.close() def walk(api, v, samplinglist, friends_dict, followers_dict, neighbors_dict, visit, log_file_path, samplinglist_file_path): # Retrieve neighbors and record them with adding the previous node if v in visit: if...
The function performs a random walk on a network for a specified duration (timedelta), starting from a given node. It collects samples, logs timestamps, and optionally calculates bot population statistics (bot scores and labels) using a provided API and BOM data. The walk continues until the time limit is reached, with...
def randomwalk_for_timedelta(api, bom, timedelta, startnode, log_file_path, samplinglist_file_path, calc_bot_ppl=False, threshold=0.95, cut=0, botscore_file_path="", est_file_path=""): write_to_file(log_file_path, "Experiment time: %s" % str(timedelta)) visit = {} friends_dict =...
def get_twitter_api_instance(): auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) return tweepy.API(auth, wait_on_rate_limit=True, timeout=60) def get_botometer_instance(): twitter_app_auth = { 'consumer_key': consumer_key, ...
The code performs a random walk analysis on Twitter data using the Botometer API, either for a specified sample size or time duration. It generates timestamped file paths to save logs, sampling lists, bot scores, and estimates. The task involves traversing user networks, calculating bot probabilities, and storing resul...
def command_rw(args): now = datetime.datetime.now() filepath_base = now.strftime("%Y-%m-%d-%H-%M-%S") + \ "-initial" + str(args.initial_user) if args.samplesize: filepath_base += "-samplesize" + str(args.samplesize) else: filepath_base += "-time" + \ str(args.days) + ...
def dealer_turn(self): index = 0 for card in self._cards: if card == 7: self._cards[index] = 1 index += 1 d = self.evaluate_hand(self.obs_to_hand(1)) while d < 17: self.random_draw(1) d = self.evaluate_hand(self.obs_to_hand(...
This code handles player actions in a card game, updating game state based on the chosen action (stand, hit, double down, or bet amounts). It modifies the player's bet, draws cards, checks hand values, and transitions to the dealer's turn or resets the game when conditions are met, ensuring proper game flow and state m...
def turn(self, action): """action: 0: Stand 1: Hit 2: Double down 3: bet 10 4: bet 25 5: bet 50""" if action == 0: self._p1turn = False self.dealer_turn() self.reset() if action == 1: ...
def isWorkflow(driver, build_version, version_series, search, dashboard): search(driver, dashboard, "HPCC-" + build_version) try: # find element by text textElem = driver.find_element(By.LINK_TEXT, "Create Workflow") textElem.click() print("New item and workflow needed: No") ...
The main task of the code is to automate Jenkins build configuration and execution for HPCC platform versions using command-line parameters. It parses version details, initializes Selenium for web interactions, and conditionally sets up builds, plugins, and views on a Jenkins server, with options to trigger runs and ha...
def main(): py_version = sys.version_info parser = OptionParser() parser.set_usage( "Usage: hpcc-build.py -s <server ip> v <version> -r <prev_platform_rc_version> -g <prev_platform_gold_version> --run") parser.add_option("-v", "--version", type="string", dest="build_ver_seq", ...
def write_job_file(job_file, job_name, srr, dir_str): mem = check_mem(srr, default_mem) with open(job_file, 'w+') as j: j.writelines('#!/bin/bash\n') j.writelines('memSize="40G"\n') j.writelines('OUTDIR="/tmp"\n') j.writelines('jobName="' + job_name + '"\n') j.writelines(...
The function checks if FastQ files for a given SRR ID are correctly downloaded and compressed. It verifies metadata presence, compresses uncompressed files, and handles directory movements. It returns True on success, False otherwise, with error categorization.
def test_file(srr, ls_results, dir_str): if ((srr + "_1.fastq.gz" in ls_results) and (srr + "_2.fastq.gz") in ls_results) or (srr + ".fastq.gz") in ls_results: #if fastq files are gzip, in proper directory, and metadata present, case is correct if ((srr + "_info.json") in ls_results): go...
def perceptron(train, test, learning_rate, n_epoch): predictions = list() weights = train_weights(train, learning_rate, n_epoch) # train the perceptron # then use it on the test data for row in test: prediction = predict(row, weights) if prediction == -1.0: prediction = 0.0 predictions.append(prediction) ...
This function runs a perceptron algorithm on a training set, predicts outcomes on a test set, calculates accuracy by comparing predicted results with actual target outputs, generates a confusion matrix for performance analysis, and returns the computed accuracy metric.
def run_algorithm(train_set, test_set, learning_rate, n_epoch): predicted = perceptron(train_set, test_set, learning_rate, n_epoch) target_outputs = [row[-1] for row in test_set] accuracy = accuracy_metric(target_outputs, predicted) generate_confusion_matrix(test_set, learning_rate, n_epoch, predicted) return accu...
def nine_lines(): three_lines() three_lines() three_lines() def three_lines(): new_line() new_line() new_line() def new_line(): print('*')
The main task of the code is to clear the screen by printing 25 lines (2×9 lines from nine_lines(), 2×3 lines from three_lines(), and 1 line from new_line()) to overwrite previous content, simulating a screen-clearing effect.
def clear_screen(): nine_lines() nine_lines() three_lines() three_lines() new_line()
def documentWeight(url): documentsWords ,documentList = readDocument(url) tf = matrix_tf(documentList,documentsWords) idf = weightVector_idf(documentList, documentsWords) return makeMatrix(tf,idf,lambda x , y : x * y,documentList) def queryWeight(url,a=0.5): querysWords ,queryList = readDocument(url...
The main task of the code is to perform information retrieval by ranking documents based on query relevance, using weighted document and query representations. It calculates evaluation metrics like precision, recall, and F-measure (beta=1) to assess the ranking effectiveness against predefined answer sets. The process ...
def main(): # urlQuery = 'collections/CISI.QRY' # urlDocument = 'collections/CISI.ALL' # urlAnswers = 'collections/CISI.REL' urlQuery = 'collections/cran.qry' urlDocument = 'collections/cran.txt' urlAnswers = 'collections/cranqrel' dw = documentWeight(urlDocument) qw = queryWeight(url...
def _open_cv_video(filepath): cap = cv.VideoCapture(filepath) try: yield cap finally: cap.release() def _parallel_ocr(frames): with ThreadPool(multiprocessing.cpu_count()) as pool: return pool.map(_ocr, frames, chunksize=multiprocessing.cpu_count()) def _filter_redundant_frames(f...
The function processes a video file by extracting frames at a specified sample rate, applying OCR to identify text, filtering out redundant or empty frames, and returning a list of frames with non-empty text. It optionally saves debug data to a specified directory.
def perform_video_ocr(filepath: str, sample_rate: int = 1, debug_dir: str = ""): f""" :param filepath: {FILEPATH_DOC} :param sample_rate: {SAMPLE_RATE_DOC} :param debug_dir: {DEBUG_DIR_DOC} """ frames = [] with _open_cv_video(filepath) as cap: frames = _parallel_ocr(_filter_redundant...
def esearch_mtdna_json(taxon): return esearch_json(FORMAT_MITOCHONDRIA(taxon)) def esummary_nucleotide_xml(itr): ids = ",".join(map(str, itr)) resp = eutils("esummary", db="nucleotide", id=ids) if resp.status_code != 200: return return xml.etree.ElementTree.fromstring(resp.text) def filter_x...
The function retrieves mitochondrial DNA (mtdna) data for a given biological term by querying a database. It processes the results into a structured dictionary with accession numbers, full names, and sequence reads. If a filename is provided, it saves the data as a FASTA file. The function returns the processed diction...
def download_taxa_mtdna(term, filename=None): res = esearch_mtdna_json(term) ids = res["esearchresult"]["idlist"] xml = esummary_nucleotide_xml(ids) dct = filter_xml(xml) append_fullnames(dct) append_reads(dct) if isinstance(filename, str): tmp = { "{} {}".format(v["acc...
def getBooking(num,ucomm): #Function to handle booking related queries global booking, souc, dest, trdate, counter URL = '' if counter == 0: ret = 'Hi, my name is trainBot. I can help you with train booking. Please let me know your name first.' counter += 1 return ret, None e...
The main task of the code is to process user commands by checking for keywords in `ucomm` against predefined lists (`book_list`, `delay_list`, `cont_list`). Depending on matches, it triggers corresponding functions (`getBooking`, `getDelay`, `getContingency`), sets flags, and returns a response and URL. If no matches, ...
def getResp(num,ucomm): #Function to be called from UI to get response global booking, souc, dest, trdate, counter, cntg_flag, delay_f # Get booking Syntaxes trbk = [ele for ele in book_list if(ele in ucomm)] if trbk or booking == True: booking = True res = getBooking(counter...
def toml_check(toml_file_path): """ Checks if the TOML file has at least one "layers" key. Args: toml_file_path (str): Path to the TOML file. Returns: bool: True if the TOML file has at least one "layers" key, False otherwise. """ with open(toml_file_path, 'r') as file: ...
The code exports layers specified in a TOML file by validating the file, parsing its content, importing layers, squashing them into a single layer using a temporary directory, generating an output filename, and saving the result to the specified output directory. It handles errors like missing files or invalid TOML for...
def toml_export(toml_file_path, output_dir): """ Exports layers specified in a TOML file. Args: toml_file_path (str): Path to the TOML file. output_dir (str): Path to the output file where the squashed layer will be exported. """ # Convert input paths to absolute paths toml_fil...
def toml_check(toml_file_path): """ Checks if the TOML file has at least one "layers" key. Args: toml_file_path (str): Path to the TOML file. Returns: bool: True if the TOML file has at least one "layers" key, False otherwise. """ with open(toml_file_path, 'r') as file: ...
The function processes a TOML file to export and squash specified layers into a single output file. It validates the TOML file, parses its content, imports layers, uses a temporary directory to squash them, generates a filename, and exports the result to the specified output directory.
def toml_upgrade(toml_file_path, output_dir, image_path): """ Exports layers specified in a TOML file. Args: toml_file_path (str): Path to the TOML file. output_dir (str): Path to the output file where the squashed layer will be exported. """ # Convert input paths to absolute paths...
def make_board(sides): """ Create a square board with specified sides. :param sides: integer :postcondition: create a 2D list of tuples with the same amount of rows and columns :return: list of tuples >>> make_board(3) [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)...
The main task of the code is to run a text-based game where the player navigates a board, battles enemies, uses transportation, and progresses until victory. It initializes the game, handles encounters, processes movement, and prints a scripted ending from a text file when the player wins.
def start_game(): """ Starts the game. """ board = make_board(10) display_title() character = make_character(input("Enter your name: ")) display_prologue() while not character["win"]: # Tell the user where they are current_situation(character) is_encounter, enemy ...
def get_wallet(user: User) -> Wallet: return Wallet.objects.get(user=user) def have_sufficient_balance_to_pay( user: User, wallet_balance: int, amount: int ) -> bool: calculated_balance = (wallet_balance) - ( amount + (int(amount * (0.03 if user.is_premium_user else 0.05))) ) print("total to...
The code processes a payment by checking if the recipient's wallet has sufficient balance. If not, it sets an error detail; otherwise, it initiates the payment transfer between wallets.
def pay(self, amount: int) -> None: paying_user_wallet: Wallet = get_wallet(user=self.paying_user) current_user_wallet: Wallet = get_wallet(self.with_user) if not have_sufficient_balance_to_pay( self.with_user, current_user_wallet.balance, amount ): detail = {"s...
def prepared_data(self): ''' Prepares the Data for Backtesting''' self.get_data() df = self.data.copy() df['returns'] = df.returns.shift(self.holding_period) df = df.dropna() f = df.drop(columns=['returns'], axis=1) #print(f.columns) #print(f.head()) ...
The code's main task is to backtest a trading strategy using specified SMAs (SMA_S, SMA_M, SMA_L). It prepares data, executes the backtest, calculates cumulative returns and strategy performance via exponential growth of returns, and generates performance reports. The results are stored in `self.results`, with cumulati...
def test_strategy(self): ''' Prepares the data and backtests the trading strategy incl. reporting (wrapper) Parameters *********** SMAs: tuple (SMA_S, SMA_M, SMA_L) Small, Medium and Large SMA to be used for the strategy ''' self.prep...
def sample(self, feature, max_len=50): # greedy sample embed = self.embed lstm_cell = self.lstm_cell fc_out = self.fc_out attend = self._attention_layer batch_size = feature.size(0) sampled_ids = [] alphas = [0] words = embed(self.to_var(torch.on...
This code implements a forward pass for a caption generation model using an attention-based LSTM. It processes image features and captions, applying attention to focus on relevant image regions, then generates word predictions step-by-step with an LSTM and fully connected layers. If not in test mode, it returns predict...
def forward(self, features, captions, lengths, isTestRun=False): """ :param features: batch_size * 196 * 512 :param captions: batch_size * time_steps :param lengths: :return: """ if isTestRun: return self.sample(features) batch_size, time_step...
def copyFile(sName,dName): ''' - This function makes copy of a single file - file <sName> is copied to the destination <dName> ''' try: shutil.copyfile(sName,dName) except OSError as e: sys.exit(e) def mergeConsensus(numClusters,oName,tp,mArgs,log): ''' This func...
This function generates a consensus alignment from long sequence clusters. It merges cluster alignments using consensus methods, optionally adds sequences from 'long.bad.fas' if specified, and outputs the final alignment. For single clusters, it directly copies files; for multiple clusters, it uses merging functions. T...
def longSeqAlignmentConsensus(numClusters,mArgs): ''' Creates alignment from only long sequence clusters - adds sequences from <long.bad.fas> if -b flag is used ''' msg = '[' + time.strftime('%d %b %H:%M:%S') + ']' msg += ' Merging long sequence clusters using consensus\n' print(msg) ...
def darknet(name): x = inputs = Input([None, None, 3]) x = conv_block(inputs, 32, 3) x = conv_block(x, 64, 3, 2) x = res_block(x, [32, 64], 1) x = conv_block(x, 128, 3, 2) x = res_block(x, [64, 128], 2) x = conv_block(x, 256, 3, 2) x = x_36 = res_block(x, [128, 256], 8) ...
This code constructs a YOLOv3-like object detection model using Darknet53 backbone, creating three detection heads (13x13, 26x26, 52x52) with varying feature maps and convolutional layers to predict bounding boxes and class probabilities at multiple scales.
def build_model(num_classes, shape=(416, 416, 3)): x = inputs = Input(shape=shape, name='input') #Darknet53 x_36, x_61, x = darknet('yolo_darknet')(x) # 13 by 13 detection head x = yolo_conv(x, [512, 1024, 512, 1024, 512, ], [1,3,1,3,1], [...
def invincible(self): if self.invinc_length < 100 and self.invinc: self.invinc_length += 1 else: self.invinc = False self.invinc_length = 0 def die_animate(self, stats, level, sound): self.image = self.small_mario[12] if self.timer <= 100: ...
This code updates a character's state in a game, handling animations and effects based on conditions like death, power-ups (mushroom, star), and invincibility. It selects appropriate animation methods (e.g., update_small, update_star) and manages a star power timer, resetting it after 750 frames to deactivate the star ...
def update(self, stats, level, sound): self.invincible() if self.dead: self.image = self.small_mario[12] self.die_animate(stats, level, sound) else: if not self.mush and not self.star_pow: self.update_small(sound) elif self.star_pow...
def exp1(g, L, T, N): return N*eThresh(g,L,T) def exp2(g, L, T, N): return N*eThresh(g,L,T)*(1 + (-1 + N)*eThresh(g,L,T)) def exp3(g, L, T, N): return float((eThresh(g,L,T)*(-((-1 + N)*(-1 + eThresh(g,L,T))**2* (1 + (-2 + N)*eThresh(g,L,T)*(3 + (-3 + N)*eThresh(g,L,T)))) - (1 - e...
The function `meanL23` computes a weighted sum of three exponential terms involving parameters $g, L, T, N$. Each term includes an exponential factor $e^{kT/g}$ (for $k=1,2,3$), polynomial coefficients in $g$ and $T$, and contributions from helper functions `exp1`, `exp2`, `exp3`. The result is normalized by powers of ...
def meanL23(g, L, T, N): return np.e**(T/g)*exp1(g,L,T,N)/N + np.e**(2*T/g)*(g-T)*exp2(g,L,T,N)/(2*g*N**2) + \ np.e**(3*T/g)*(4*g**2-8*g*T+5*T**2)*exp3(g,L,T,N)/(12*g**2*N**3)
def _set_random_seed(self, random_seed: int) -> None: np.random.seed(random_seed) random.seed(random_seed) def sample_n_shots(self, n_shots: int) -> npt.NDArray[int]: few_shots_df = self.train_df.sample(n_shots) assert few_shots_df.index.is_unique, "few shots samples were not unique!" ...
This function evaluates model accuracy across varying numbers of training examples (n_shots) by running multiple trials (n_runs). For each n_shots, it samples training data, constructs prompts, checks token limits to avoid exceeding the model's context window, and records accuracy if valid. Retries if inputs are too lo...
def run_experiment_across_shots(self, n_shots_to_test: List[int], n_runs: int, too_long_patience: float = 0.2): accuracies = np.zeros((len(n_shots_to_test), n_runs)) for i, n_shots in enumerate(tqdm(n_shots_to_test)): _logger.info(f"starting with n = {n_sh...
def _Decimals_field(self): return models.PositiveIntegerField(self.verbose_model_field_name(Primitive.Decimals), blank=True, null=True) def _EndTime_field(self): return models.DateTimeField(self.verbose_model_field_name(Primitive.EndTime), ...
This function dispatches handling of different 'Primitive' types by matching the input 'primitive' argument to specific cases, then delegating to corresponding private methods like _Decimals_field() or _StartTime_field() to process each primitive type, returning the result of the matched method.
def _primitive_field(self, primitive: Primitive): match primitive: case Primitive.Decimals: return self._Decimals_field() case Primitive.EndTime: return self._EndTime_field() case Primitive.Precision: return self._Precision_fiel...
def model_field_name(self, p: Primitive): if self.use_primitive_names: return p.name return f'{self.name}_{p.name}' def _primitive_field(self, primitive: Primitive): match primitive: case Primitive.Decimals: return self._Decimals_field() case P...
The code generates a dictionary mapping each primitive field to its corresponding value by iterating over self.primitives(), applying self.model_field_name() to create keys and self._primitive_field() to generate values.
def model_fields(self): return {self.model_field_name(p): self._primitive_field(p) for p in self.primitives()}
def get_super_dist(chain: blockchain_structs.Blockchain, difficulty: int, k: int): """ Returns a dictionary representing the distribution of blocks at varying superblock levels. It discounts the last k blocks since the history of these blocks remain to be solidified. """ distribution_dict = {} ...
This function identifies and collects blocks from the blockchain that belong to superblock levels not part of the main superblock chain. It filters these blocks based on predefined thresholds (m, k) and difficulty, ensuring they are higher than the top chain's level. These blocks are essential for constructing a valid ...
def get_extra_sblocks(blockchain: List[blockchain_structs.Block], m: int, k: int, difficulty: int): """ accumulates all blocks higher than the main superblock chain these are needed in order to make a valid chain for a proof """ blocks = [] extra_levels = [] distribution = get_super_dist(blo...
def find_top_chain(blockchain: blockchain_structs.Blockchain, m: int, difficulty: int, k: int): """ Returns index of highest level superchain with at least m blocks""" assert(m >= 0) # get last block interlink # get a dictionary representing the distribution of superblock levels within a chain block...
The function generates a blockchain proof by collecting blocks from super chains at varying levels of difficulty. It starts at the genesis block, iterates through super chains from highest to lowest, extracts up to m blocks from each level (or fewer if available), and appends the last k unconfirmed blocks as a suffix. ...
def suffix_proof(blockchain: blockchain_structs.Blockchain, k: int, m: int, difficulty: int): """ Full node proof generation. Steps: -Start at genesis block -For each super block chain (starting highest first (most rare)) going to 0 -remove k from end -take all the blocks at highest level in...
def find_txn_block(blockchain: blockchain_structs.Blockchain, txn_hash: str): for block in blockchain.chain: for txn in block.txs: if txn.tx_id == txn_hash: return block return False def suffix_proof(blockchain: blockchain_structs.Blockchain, k: int, m: int, difficulty: int):...
The function generates an infix proof for a transaction in a blockchain by locating the transaction's block, constructing a suffix proof chain, and ensuring the transaction block is included. If not present, it extends the chain downward from a higher block. Returns proof blocks or False if the transaction is missing.
def infix_proof(blockchain: blockchain_structs.Blockchain, k: int, m: int, difficulty: int, txn_hash: str): # find block with transaction predicate_block = find_txn_block(blockchain, txn_hash) # print(f"txn found in block {predicate_block.height}") if predicate_block: # print("BLOCK FOUND:", pre...
def loadNewConnection(selector, key): sock = key.fileobj conn, addr = sock.accept() conn.setblocking(False) data = { 'out':b'', 'in':b'', 'addr':addr } events = selectors.EVENT_READ | selectors.EVENT_WRITE selector.register(conn, events, data=data) return conn def processExistingConnection(s...
The code defines an event loop that continuously monitors I/O events using a selector. It processes new connections by calling `loadNewConnection` and handles existing connections via `processExistingConnection`. Errors during processing are caught and logged, ensuring the server remains operational. The loop runs inde...
def eventLoop(selector): while True: events = selector.select(timeout=None) for key, mask in events: #using a try because one failure shouldnt stop the server try: if key.data is None: loadNewConnection(selector, key) el...
def get_random_w(low = -0.5, high = 0.5): dim = num_features if "bias" in sys.argv: dim += 1 return np.array([(high-low)*np.random.random()+low for i in range(dim)]) def gradient_descent(train_x, train_y, train_w, lr, lmd): train_size = train_x.shape[0] gradient = sum([(sigmoid(train_w.dot(t...
This function trains a model using either gradient descent (GD) or stochastic gradient descent (SGD) on 80% of the data, evaluates accuracy on both training and test sets (20% split), and prints training time and accuracy metrics. It initializes random weights, iterates over epochs, applies the specified optimization m...
def simple_train(num_epochs, lmd, gd=True, label=""): # First 20% of data is the test set # Remaining 80% is the train set block_size = num_instances // 5 test_x = x[:block_size,:] test_y = y[:block_size] train_x = x[block_size:,:] train_y = y[block_size:] start_time = time() w = ge...
def get_random_w(low = -0.5, high = 0.5): dim = num_features if "bias" in sys.argv: dim += 1 return np.array([(high-low)*np.random.random()+low for i in range(dim)]) def gradient_descent(train_x, train_y, train_w, lr, lmd): train_size = train_x.shape[0] gradient = sum([(sigmoid(train_w.dot(t...
The code performs cross-validation to determine the optimal regularization term (lambda) for both Gradient Descent (GD) and Stochastic Gradient Descent (SGD). It splits data into folds, trains models with each lambda value, evaluates accuracy, and selects the term yielding the highest average performance. The function ...
def get_best_regularization_term(num_epochs, terms): # Split the data into <fold> many blocks fold = len(terms) block_size = num_instances // fold x_blocks = [x[start:(start+block_size),:] for start in range(0, num_instances, block_size)] y_blocks = [y[start:(start+block_size)] for start in range(...
def get_random_w(low = -0.5, high = 0.5): dim = num_features if "bias" in sys.argv: dim += 1 return np.array([(high-low)*np.random.random()+low for i in range(dim)]) def gradient_descent(train_x, train_y, train_w, lr, lmd): train_size = train_x.shape[0] gradient = sum([(sigmoid(train_w.dot(t...
The main task of the code is to train a model using either Gradient Descent (GD) or Stochastic Gradient Descent (SGD) on an 80-20 train-test split of the data, evaluate its accuracy on both splits, and report training time and performance. It initializes random weights, iterates for a specified number of epochs, applie...
def simple_train(num_epochs, lmd, gd=True, label=""): # First 20% of data is the test set # Remaining 80% is the train set block_size = num_instances // 5 test_x = x[:block_size,:] test_y = y[:block_size] train_x = x[block_size:,:] train_y = y[block_size:] start_time = time() w = ge...
def get_random_w(low = -0.5, high = 0.5): dim = num_features if "bias" in sys.argv: dim += 1 return np.array([(high-low)*np.random.random()+low for i in range(dim)]) def loss(train_x, train_y, train_w, lmd) -> float: size = train_x.shape[0] result = lmd/2.0 * train_w.dot(train_w) for i i...
The main task of the code is to compare the training time and number of epochs required for Gradient Descent (GD) and Stochastic Gradient Descent (SGD) to achieve a specified target accuracy on a dataset. It splits data into training and test sets, trains both models until the target accuracy is met, records the time a...
def get_training_time(gd_lmd, sgd_lmd, target_accr): # First 20% of data is the test set # Remaining 80% is the train set block_size = num_instances // 5 test_x = x[:block_size,:] test_y = y[:block_size] train_x = x[block_size:,:] train_y = y[block_size:] gd_w = get_random_w() gd_lo...
def get_random_w(low = -0.5, high = 0.5): dim = num_features if "bias" in sys.argv: dim += 1 return np.array([(high-low)*np.random.random()+low for i in range(dim)]) def gradient_descent(train_x, train_y, train_w, lr, lmd): train_size = train_x.shape[0] gradient = sum([(sigmoid(train_w.dot(t...
This code performs cross-validation to determine the optimal regularization parameter (lambda) for both Gradient Descent (GD) and Stochastic Gradient Descent (SGD). It splits data into folds, trains models with each lambda in 'terms', evaluates accuracy on held-out test sets, averages results across folds, and returns ...
def get_best_regularization_term(num_epochs, terms): # Split the data into <fold> many blocks fold = len(terms) block_size = num_instances // fold x_blocks = [x[start:(start+block_size),:] for start in range(0, num_instances, block_size)] y_blocks = [y[start:(start+block_size)] for start in range(...
def predict_class(sentence, model): p = bot_search(sentence, words, show_details=False) res = model.predict(np.array([p]))[0] ERROR_THRESHOLD = 0.25 results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD] results.sort(key=lambda x: x[1], reverse=True) return_list = [] for r in r...
The main task of the code is to handle user inputs in a chatbot by classifying messages, extracting names or PO creation details, and generating responses using a model and predefined intents. It processes inputs like name introductions, PO creation requests, and general queries, replacing placeholders or returning str...
def chatbot_response(): msg = request.form["msg"] print("The User Input: %s" % msg) if msg.startswith('my name is'): name = msg[11:] ints = predict_class(msg, model) res1 = getResponse(ints, intents) res =res1.replace("{n}",name) return res elif msg.startswith('hi...
def train_val_epochs(start_epoch, total_epoch, global_epoch, train_loader, valid_loader, model, model_idx, criterion, w_scheduler, w_optimizer, show_alpha=False, enable_valid=True ): best_a_...
The main task of the code is to perform neural architecture search (NAS) using the TNAS (Tree-based Neural Architecture Search) method. It initializes a supernet, trains it with a warmup phase, then iteratively explores and prunes architecture branches by training and evaluating sub-models, selecting optimal paths base...
def main(config): train_data, valid_data, xshape, class_num = get_datasets( config.data.dataset, config.data.data_path, -1) config.xshape = xshape config.class_num = class_num # create nats-bench search_space = get_search_spaces("cell", config.search_space) model_config = dict2config( ...
def my_train_test_split(dataset, split_ratio=.80): total_rows = dataset.shape[0] split = int(split_ratio * total_rows) training_data = dataset.iloc[:split].reset_index(drop=True) testing_data = dataset.iloc[split:].reset_index(drop=True) return training_data,testing_data def id3_a...
The main task of the code is to validate an input dataset, load and split it into training/testing sets, train a custom ID3 decision tree and a Scikit-Learn decision tree classifier, evaluate both models' performance using a custom evaluation function, generate ROC curves for comparison, and save results. It validates ...
def main(): # Taking the input data set file and validation of the file print("Checking for the input file path..") if len(sys.argv) == 2: input_file = sys.argv[1] input_file = os.path.abspath(input_file) if os.path.isfile(input_file): print("Checking for the input ...
def chk_inputstate_correct(self, node): arr_of_node = np.reshape(node, 9) for c in range(9): rep = 0 e = arr_of_node[c] for r in range(9): if e == arr_of_node[r]: rep += 1 if rep >= 2: print("Invalid inpu...
The code solves a puzzle by iteratively exploring states from a start configuration to a goal state. It checks initial validity and solvability, then uses a loop to generate subsequent states until the goal is reached. The process tracks the number of iterations and path depth, printing intermediate states and final re...
def run(self): # output the start state print("start state !!!!!") print(self.current.tile_seq) self.chk_inputstate_correct(self.current.tile_seq) self.chk_state_solvable(self.current.tile_seq) path = 0 while not self.current.equals(self.goal): sel...
def neighbors(self, objs): return [obj for obj in objs if distance(self.x, self.y, obj.x, obj.y) <=self.vision and id(self)!=id(obj)] def update_blob(self): self.attention = False self.update_sight() self.explore() if random.random() <= 0.0001 else None if self.score == 0: ...
This code updates an agent's state in a simulation. It identifies neighboring objects, updates a blob property, and decides actions based on the agent's score: if score < 2, it acts on neighbors and checks for encounters; else, it returns home. Finally, it checks energy status to manage survival or movement logic.
def update(self, world, objs): neighbors = self.neighbors(objs) self.update_blob() if self.score < 2: self.act(neighbors) self.check_encounter(world, objs) else: self.go_home() self.check_energy()
def backward_propagation(self, x, y): Zs, As = self.forward_propagation(x) loss_deriv = self.loss_fn_deriv(y, As[-1]) loss = self.loss_fn(y, As[-1]) dZ = loss_deriv for i in range(len(self.network)): current_index = int(-(i+1)) previous_index = int(-(i+2))...
This code trains a neural network model using gradient descent (GD) or stochastic gradient descent (SGD), dynamically selecting the optimal learning rate by evaluating loss across predefined rates. It executes external code mid-epoch if specified, logs training duration and loss per epoch, and supports pausing/resuming...
def train(self, x, y, epochs=1, batch_size=32): for epoch in range(epochs): if self.mid_epoch_codes_dir != None: code = open(self.mid_epoch_codes_dir, 'r').read() exec(code) start = time() loss = 0 if not self.pauser: ...
def normalize(text): timepat = re.compile("(\d{1,2}[:]\d{1,2})") pricepat = re.compile("(\d{1,3}[.]\d{1,2})") # lower case every word text = text.lower() # replace white spaces in front and end text = re.sub(r'^\s*|\s*$', '', text) # hotel domain pfb30 text = re.sub(r"b&b", "bed and b...
The code processes four entity databases (attraction, restaurant, hotel, hospital), normalizes and maps attributes (e.g., addresses, phones) to entities, handles duplicate entity names, and saves structured entity information, attribute-to-entity mappings, and name normalization rules into JSON files for downstream use...
def generate_info(input_path): entity_info = {} attr_ent_map = { "attraction_address": {}, "attraction_phone": {}, "attraction_postcode": {}, "restaurant_address": {}, "restaurant_phone": {}, "restaurant_postcode": {}, "hotel_phone": {}, "hotel_pos...
def generate_info(input_path): entity_info = {} attr_ent_map = { "attraction_address": {}, "attraction_phone": {}, "attraction_postcode": {}, "restaurant_address": {}, "restaurant_phone": {}, "restaurant_postcode": {}, "hotel_phone": {}, "hotel_pos...
The main task of the code is to process entity data by generating graph structures and mappings, disambiguate utterance-entity relationships in JSON data, and split the processed data into train/validation/test sets for downstream tasks like NLP or knowledge graph applications.
def main(): entity_info, attr_ent_map, entity_name_map = generate_info("./graph_data") generate_graph(entity_info) generate_data(attr_ent_map, entity_name_map) data = json.load(open("./preprocess_utt_ent.json")) new_data = disambiguate(data) new_data = generate_final_res(new_data) json.dum...
def perceptron(x, w=[], activation='Erf'): if len(w)>0: x = linear(x, w) if activation=='Erf': output = Erf(x/(2**0.5)) elif activation=='ReLU': output = ReLU(x) elif activation=='SReLU': output = SReLU(x) elif activation=='Linear': output = x else: ...
The code trains a student perceptron to align with a teacher model while minimizing a combined cost of control (action magnitude) and error (misalignment with the target). It optimizes a "future weight" parameter (fut_pref) via grid search, simulates dynamics with poisoned data, and tracks metrics like accuracy, cost, ...
def exp_greedy_perceptron(x_incoming, x_past, x_buffer, x_test, eta, w_teach, w_target, dim_input, weight_future=[], w_stud_0=[], a_min=0, a_max=1, beta=0.001, control_cost_weight=1., batch_size=1, n_gridpoints=int(1e2), buffer_size=250, transient_th=5000, ...
def perceptron(x, w=[], activation='Erf'): if len(w)>0: x = linear(x, w) if activation=='Erf': output = Erf(x/(2**0.5)) elif activation=='ReLU': output = ReLU(x) elif activation=='SReLU': output = SReLU(x) elif activation=='Linear': output = x else: ...
The code simulates and optimizes a multi-dimensional control system using a perceptron model. It trains a student network (w_stud) to approximate a teacher model (w_teach) while applying greedy control actions (a) to minimize a combined cost of neural error and control effort. The dynamics of weights, actions, and cost...
def exp_greedy_perceptron_multidimcontrol(x_incoming, x_past, x_buffer, x_test, eta, w_teach, w_target, dim_input, weight_future=[], w_stud_0=[], a_min=0, a_max=1, beta=0.001, control_cost_weight=1., batch_size=1, n_gridpoints=int(1e2),...
def NN2L(X, W, v, activation='Erf', output_scaling='inv_sqroot'): if len(X.shape)<2: raise ValueError('NN2L admits X inputs as 2D arrays of shape (n_samples, dim_input)') hlayer_size = v.shape[-1] dim_input = W.shape[-1] if output_scaling=='inv': pref_hlayer_size = hlayer_size #np.sqr...
This function optimizes a future weight parameter (fut_pref) for a neural network student model (NN2L) to approximate a target network while minimizing control costs. It trains the student network using perturbation and nefarious cost functions, balances accuracy with control effort, and returns dynamics of parameters,...
def exp_greedy_NN2L(x_incoming, x_past, x_buffer, x_test, eta, W_teach, v_teach, W_target, v_target, dim_input, weight_future=[], W_stud_0=[], v_stud_0=[], a_min=0, a_max=1, beta=0.001, control_cost_weight=1., batch_size=1, n_gridpoints=int(1e2), buffer_size=250, ...
def model_to_device(self, net): net = net.to(self.device) return net def init_training_settings(self): self.net_g.train() self.ema_decay = self.train_val_opt.get('ema_decay', 0) if self.ema_decay > 0: print('Use Exponential Moving Average with decay: {self.ema_decay}...
The main task of the code is to initialize a model with given configurations, set up computational device (GPU/CPU), configure training parameters if in training mode, and load a pre-trained checkpoint if specified. It prepares the model architecture, optimizers, and training settings, while handling device placement f...
def __init__(self, model_opt, train_val_opt, is_train=True): self.model_opt = model_opt self.train_val_opt = train_val_opt if torch.cuda.is_available(): self.device = torch.device('cuda') else: self.device = torch.device('cpu') # raise Exception("No GP...
def player_input(): marker='' while marker!='X' and marker!='O': marker=input('Player1:Choose X or O:').upper() if marker == 'X': return ('X','O') else: return ('O','X') def choose_first(): flip = random.randint(0,1) if flip == 0: return 'Player1' else: ...
The main task of the code is to run a Tic Tac Toe game where two players take turns marking the board. It initializes the game, determines the starting player, handles player input, alternates turns, checks game status after each move, and allows replay or exit. The loop continues until the game ends or the player choo...
def play(): print('Welcome to Tic Tac Toe') while True: board = [' ']*10 player1_marker,player2_marker = player_input() turn = choose_first() print(turn + ' will go first') play_game = input('Ready to play? y or n? ') if play_game == 'y': game_on...
def is_full_board(self): for list_ in self.backing_board: for num in list_: if num == 0: return False return True def is_valid_board(self): return not self.has_duplicate_in_rows() and not self.has_duplicate_in_cols() and not self.has_duplicate_in_b...
The code recursively finds all valid solutions of a board by checking if the board is full, validating it, and collecting solutions from next possible states while avoiding duplicates through set operations.
def get_solutions(self): if self.is_full_board(): print("thinking") if self.is_valid_board(): print("Solution found") print(self) return {self} else: return set() else: solutions = set() ...
def cero() -> Nat: return Cero() def suma(x: Nat, y: Nat) -> Nat: if es_cero(x): return y else: return suma(pred(x), suc(y))
The main task of the code is to recursively compute the product of two natural numbers x and y by breaking down y into its predecessor (y-1) until reaching the base case of y=0, using repeated addition (suma) to achieve multiplication. The print statement tracks intermediate steps.
def producto(x: Nat, y: Nat) -> Nat: if isinstance(y, Cero): return cero() else: print(f'x={x},y={y}') return suma(x, producto(x, y.pred))
def create_request_identifier(url, params_diction): sorted_params = sorted(params_diction.items(),key=lambda x:x[0]) params_str = "_".join([str(e) for l in sorted_params for e in l]) total_ident = url + "?" + params_str return total_ident.upper() def get_from_cache(identifier, dictionary): identifie...
The main task of the code is to retrieve data either from a cache or by making an API request if not cached. It generates a request identifier, checks the cache for existing data, fetches new data from the provided URL if needed, and stores it in the cache with an expiration period. Debug logs indicate whether data was...
def get_data_from_api(request_url, service_ident, params_diction, cache_diction, cache_fname, expire_in_days=7): ident = create_request_identifier(request_url, params_diction) data = get_from_cache(ident, cache_diction) if data: if DEBUG: print("Loading from data cache: {}... data".forma...
def game_setup(): """ Set up the game environment and return the curses window, maze, and player objects. Returns: tuple: A tuple containing the curses window (stdscr), maze, and player objects. """ stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(True) ...
The main task of the code is to run a text-based maze game where the player navigates using arrow keys, updates the game state, checks for win conditions, handles invalid moves with error messages, and displays a win screen upon success. The loop continuously refreshes the screen, processes input, and terminates when t...
def main(stdscr): stdscr, maze, player = game_setup() while True: try: stdscr.clear() stdscr.addstr(0, 0, state(maze.state, player.position)) stdscr.addstr(12, 0, "Use the arrow keys to move. Press q to quit.") stdscr.refresh() key = stdscr.g...
def results_table(self): """ Returns a dataframe of results for all visual metrics. Input: self. Output: Pandas dataframe. """ names = ['aVGF', 'Steroid', 'Both(aVGF,Steroid)', 'Improved', 'Not_Improved', 'Overall'] df_lst = DataSeparator.get_dataframes(self) ...
The code generates and saves three dataframes as CSV files: 'visual_metrics.csv' from `results_table()`, 'drug_dist_table.csv' from `va_dist_table()`, and 'va_distributions.csv' from `va_distributions()`, all stored in the `general_path` directory for further analysis or reporting.
def upload_results_table(self): dataframe = self.results_table() dataframe.to_csv(general_path + '/visual_metrics.csv') drug_dist = self.va_dist_table() drug_dist.to_csv(general_path + '/drug_dist_table.csv') va_dist = self.va_distributions() va_dist.to_csv(general_path +...
def results_table(self): """ Returns a dataframe of results.. Input: self. Output: Pandas dataframe. """ names = ['aVGF', 'Steroid', 'Both(aVGF,Steroid)', 'Improved', 'Not_Improved', 'Overall'] mean_list, std_list = self.mean_intervals() dict = {'Drug': na...
The code exports four dataframes generated by different methods to CSV files: 'drug_int_metrics.csv' from self.results_table(), 'interval_metrics.csv' from self.ext_red_results(), 'interval_distribution.csv' from self.interval_distribution(), and 'int_dist_plot.csv' from self.int_dist_plot(). The main task is to save t...
def upload_results_table(self): dataframe = self.results_table() dataframe.to_csv(general_path + '/drug_int_metrics.csv') df = self.ext_red_results() df.to_csv(general_path + '/interval_metrics.csv') interval_length = self.interval_distribution() interval_length.to_csv(ge...
def setup_cluster_infra(self): """ Init cluster infra. Returns: cluster_data (dict): Created cluster data. """ logging.info("Creating new cluster with id {}".format(self.cluster_id)) # Build images images_to_build = ["statsd", "lb", "elsa", "backend", "prom"...
The `invoke` method handles CLI commands for cluster management: initializing infrastructure, displaying cluster info (all or specific), deleting clusters, and adding/removing nodes based on the command in `self.args.cmd`, with actions conditional on preparation checks.
def invoke(self): """ Helper method for cli """ if "init" in getattr(self.args, "cmd"): self.setup_cluster_infra() elif "show" in getattr(self.args, "cmd"): if not self.prepare(): self.show_cluster(show_all=True) else: ...
def get_all_prom_backends(): """ Helper function to filter targets from prometheus targets.json file Returns (list): List of monitored instances """ return load_targets_file()[0]["targets"] def load_targets_file(): """ Load prometheus targets.json file. On missing file new file will be created. ...
The function adds a specified backend instance to Prometheus scraping targets if it's not already present. It checks existing targets, appends the new backend with port 9273 to the targets list in a configuration file, and updates the file. Logging confirms the addition and target structure.
def add_prom_target(backend): """ Adds backend instance for prometheus scraping Args: backend (str): Backend instance name to add Returns: """ backends = list(map(lambda x: x.split(":")[0], get_all_prom_backends())) if backend not in backends: logging.info("Adding {} to {}".fo...
def get_all_prom_backends(): """ Helper function to filter targets from prometheus targets.json file Returns (list): List of monitored instances """ return load_targets_file()[0]["targets"] def load_targets_file(): """ Load prometheus targets.json file. On missing file new file will be created. ...
This function removes a specified backend instance from Prometheus scraping targets by updating the targets configuration file, ensuring the backend's target entry is excluded from future scrapes.
def remove_prom_target(backend): """ Removes backend instance from prometheus scraping Args: backend (str): backend name to remove Returns: """ backends = list(map(lambda x: x.split(":")[0], get_all_prom_backends())) if backend in backends: logging.info("Removinf {} from {}".f...
def get_all_nginx_backends(): """ Helper function to filter out from nginx.conf backend servers Returns (str): List of backned servers """ parsed_conf = crossplane.parse(NGINX_CONFIG_FILE) config_backends = parsed_conf['config'][0]['parsed'][1]['block'][0]['block'] return list(map(lambda x: x[...
The main task of the code is to monitor Docker container events for a specific cluster, dynamically updating Nginx and Prometheus configurations when backend services start or stop. It listens for Docker events, checks if they belong to the cluster, and triggers Nginx reloads and Prometheus target updates by adding or ...
def elsa_docker_event_worker(): logging.info("Elsa is alive!") logging.info("Cluster ID: {}".format(os.environ.get("MDH_CLUSTER_ID"))) cli = docker.from_env() while True: try: for event in cli.events(): event = json.loads(event.decode('utf-8')) config...
def insertNumber(self, number): centerRow = 4 #fifth row and fifth col is center of the board centerCol = 4 for i in range(-3, 4, 3): #to iterate over 3x3 boxes in 9x9 board for j in range(-3, 4, 3): randomRow = self.randomList(-1, 1) randomCol = self...
The main task of the code is to generate a new 9x9 Sudoku board by initializing it with zeros, inserting numbers 1-4, solving the board recursively, and copying the solved state back to the original board. This creates a partially filled Sudoku puzzle with a valid solution.
def __newBoard(self): #base case -> board filled completely #recursive -> board not filled self._board = [[0 for i in range(9)] for i in range(9)] for number in range(1,5): self.insertNumber(number) self.solve() self.copyBoard(self._solvedBoard, self._board)
def validPositions(piece, grid): ''' Calcs all of the valid positions for the piece on the board Parameters ---------- piece : instance of Piece class grid : Matrix Returns ------- list of the lowest valid positions on the board ''' pos = [] counter = 0 fo...
The function evaluates all valid positions for a game piece on a grid, simulates placing the piece at each position, calculates a score for the resulting grid configuration, and returns the position with the lowest score along with its x-coordinate.
def best_position(piece,grid): ''' tests the positions that are valid and decides which one is the best. returns the score and x value of the best position ''' bestscore = 100000 #lower the score the better best_x = 9 #moves it to the far right in case of an error pos = validPositions(piece,...
def most_common_label(y): # Finds most common label for val counter = Counter(y) # Counts number of elements most_common = counter.most_common(1)[0][0] # Gets most common return most_common def _best_criteria(self, X, y, feat_idxs): # Selects best criteria best_gain = -1 # Default value is worse tha...
This function recursively builds a decision tree by selecting the optimal feature and threshold for splitting data based on information gain. It applies stopping criteria (max depth, single class, or insufficient samples) to create leaf nodes with the most common label. Random feature subsets are chosen at each node, a...
def _grow_tree(self, X, y, depth=0): # Function to grow tree, starts at depth 0 n_samples, n_features = X.shape # Gets shape of X to identify number of features and samples n_labels = len(np.unique(y)) # Gets labels (classes) # Stopping Criteria if (depth >= self.max_depth ...
def make_next(d): d_new = make_copy(d) d_new.prev = d d_new.actions = [] return d_new def move_card(d, i, j): """ move the i-th card to the j-th position in the deck, shift the cards inbetween Game rules applicable: Pull: Move the closest enemy card in range X to the bottom of the d...
The function `adjust_deck` generates all possible new deck configurations by moving cards up to `p` positions based on target side `t`, applying game rules like Venom's prevention of position changes and Trap Master's damage. It checks for hero features, filters valid moves, and returns unique resulting decks after pro...
def adjust_deck(d, p, t): """ move_card() any possible card by p (int) positions within the deck Game rules applicable: hero: Quicken: Move any card up to X spaces towards top of the deck. Delay: Move any card up to X spaces towards top of the deck. Feature: Trap Master ...
def get_health_accounts(health_client, event, event_arn): affected_accounts = [] event_accounts_paginator = health_client.get_paginator('describe_affected_entities') event_accounts_page_iterator = event_accounts_paginator.paginate( filter = { 'eventArns': [ event_arn ...
The main task of the code is to monitor AWS Health events by filtering them based on time, event type (issue/investigation), and specified regions. It retrieves event details, affected accounts/entities, and stores relevant data in DynamoDB if events are found. If no events are detected, it logs a message and continues...
def describe_events(health_client): str_ddb_format_sec = '%s' # set hours to search back in time for events delta_hours = os.environ['EVENT_SEARCH_BACK'] health_event_type = os.environ['HEALTH_EVENT_TYPE'] delta_hours = int(delta_hours) time_delta = (datetime.now() - timedelta(hours=delta_hours)...
def get_health_org_accounts(health_client, event, event_arn): affected_org_accounts = [] event_accounts_paginator = health_client.get_paginator('describe_affected_accounts_for_organization') event_accounts_page_iterator = event_accounts_paginator.paginate( eventArn=event_arn ) for event_acco...
This function retrieves AWS Health events for an organization, filters them by time, type (issue/investigation), and region, then processes each event to extract details, affected accounts/entities, and updates DynamoDB with event data if conditions are met. It checks for errors, filters accounts based on environment v...
def describe_org_events(health_client): str_ddb_format_sec = '%s' # set hours to search back in time for events delta_hours = os.environ['EVENT_SEARCH_BACK'] health_event_type = os.environ['HEALTH_EVENT_TYPE'] dict_regions = os.environ['REGIONS'] delta_hours = int(delta_hours) time_delta = (...
def get_sts_token(service): assumeRoleArn = get_secrets()["ahaassumerole"] boto3_client = None if "arn:aws:iam::" in assumeRoleArn: ACCESS_KEY = [] SECRET_KEY = [] SESSION_TOKEN = [] sts_connection = boto3.client('sts') ct = datetime.now() ...
The main task of the code is to check if AWS Organizations is enabled, then retrieve either Service Health Dashboard events (if disabled) or both Personal/Service Health Dashboard events (if enabled) using AWS Health API, printing corresponding status messages.
def main(event, context): print("THANK YOU FOR CHOOSING AWS HEALTH AWARE!") health_client = get_sts_token('health') org_status = os.environ['ORG_STATUS'] #str_ddb_format_sec = '%s' # check for AWS Organizations Status if org_status == "No": #TODO update text below to reflect current fun...
def recursiveFill(inp): global goBackToRoot global n data = {} for i in range(n, len(inp)): if goBackToRoot or n >= len(inp): return data l = inp[n].split() n = n + 1 if l[0] == "$": if l[1] == "cd": if l[2] == "..": ...
The main task of the code is to parse a directory structure from an input file, calculate disk space usage, and identify the smallest directory that can be deleted to free up at least 30,000,000 units of space, given a total disk capacity of 70,000,000 units. It uses recursive processing to build the directory tree, tr...
def main(): global n global goBackToRoot f = open("input.txt", "r") inp = f.readlines() data = {} while n < len(inp): data = recursiveFill(inp) n = n + 1 goBackToRoot = False print(findSmallestDirectory(data, 30000000 - (70000000 - countAllDirectories(data)))) f.c...
def _generate_full_connectivity(self): """ Returns ------- dict a dictionary whose keys are position (x, y) as tuples of 2 integers and values are the set of positions not separated by walls. """ x_dim, y_dim = self._grid_shape connectivity...
This code initializes a grid-based environment with specified dimensions, walls, and reward parameters. It sets up grid connectivity, applies walls to restrict movement, and prepares a reward grid based on the given reward chance. The main task is to configure a navigable grid world for tasks like pathfinding or reinfo...
def __init__(self, x_dim, y_dim, walls: set = None, reward_chance=0): if walls is None: walls = set() self._grid_shape = (x_dim, y_dim) self._walls = walls self._connectivity = self._generate_full_connectivity() self.add_walls(self._walls) self._reward_grid = ...
def str2int(video_path): try: return int(video_path) except ValueError: return video_path def detectCounter(frame, counter_model): image = prepImageForDetection(frame) detection = darknet.detect_image(counter_model['network'], counter_model['class_names'], image) for label, confidenc...
This code processes a video to detect game rounds and champions using three Darknet models. It analyzes frames to identify champion counters, determines rounds, and tracks champions. Results are stored in JSON files, updating game data, champion popularity, and locations. The video is released and deleted after process...
def vid_detecion_feed(video_path, player, place_ended, date, region): rounds_model = {} champs_model = {} counter_model = {} champs_model['network'], champs_model['class_names'], champs_model['class_colors'] = darknet.load_network( champs_model_files['config'], champs_model_files['d...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def put_seq_on_board(board, y, x, d_y, d_x, length, col): for i in range(length): board[y][x] = col y += d_y x += d_x def print_board(board): s = "*" for i in range(len(b...
This test case checks if the `detect_rows` function correctly identifies the number of open and blocked rows of a specified length for a given color on a game board. It sets up a board with a sequence of 'w' pieces, then verifies that `detect_rows` returns (1,0), indicating one open row and no blocked rows for the give...
def test_detect_rows(): board = make_empty_board(8) x = 5; y = 1; d_x = 0; d_y = 1; length = 3; col = 'w' put_seq_on_board(board, y, x, d_y, d_x, length, "w") print_board(board) if detect_rows(board, col,length) == (1,0): print("TEST CASE for detect_rows PASSED") else: print("TES...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def put_seq_on_board(board, y, x, d_y, d_x, length, col): for i in range(length): board[y][x] = col y += d_y x += d_x def print_board(board): s = "*" for i in range(len(b...
The main task of the code is to test a board analysis function by placing specific sequences of stones on an 8x8 board and verifying the counts of open/semi-open rows for black and white stones. It initializes the board, adds predefined stone placements, prints the board state, and uses the analysis function to check r...
def some_tests(): board = make_empty_board(8) board[0][5] = "w" board[0][6] = "b" y = 5; x = 2; d_x = 0; d_y = 1; length = 3 put_seq_on_board(board, y, x, d_y, d_x, length, "w") print_board(board) analysis(board) # Expected output: # *0|1|2|3|4|5|6|7* # 0 | | | | |w...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def is_win(board): # Returns one of: ["White won", "Black won", "Draw", "Continue playing"] # start by checking for a win win_length = 5 # 5 stones in a row wins the game white_status = dete...
The code tests a game board by placing sequences of 'w' and 'b' pieces in specific positions and directions, then prints the board, analyzes the state, and checks for a winner. It verifies the functionality of board creation, piece placement, and win detection logic in a 3x3 grid game.
def my_test1(): board = make_empty_board(3) print("Who won?", is_win(board)) y = 0; x = 0; d_x = 0; d_y = 1; length = 2 put_seq_on_board(board, y, x, d_y, d_x, length, "w") y = 0; x = 1; d_x = 0; d_y = 1; length = 2 put_seq_on_board(board, y, x, d_y, d_x, length, "b") y = 0; x = 0; d_x = ...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def is_win(board): # Returns one of: ["White won", "Black won", "Draw", "Continue playing"] # start by checking for a win win_length = 5 # 5 stones in a row wins the game white_status = dete...
The code tests a game board by placing sequences of "w" and "b" pieces, then checks for a winner and analyzes the board state. It initializes a 5x5 board, adds a horizontal "w" sequence of 5 and a "b" sequence of 4, prints the board, and evaluates the game outcome.
def my_test2(): board = make_empty_board(5) print("Who won?", is_win(board)) y = 0; x = 0; d_x = 0; d_y = 1; length = 5 put_seq_on_board(board, y, x, d_y, d_x, length, "w") y = 0; x = 1; d_x = 0; d_y = 1; length = 4 put_seq_on_board(board, y, x, d_y, d_x, length, "b") print_board(board) ...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def print_board(board): s = "*" for i in range(len(board[0])-1): s += str(i%10) + "|" s += str((len(board[0])-1)%10) s += "*\n" for i in range(len(board)): s += str(i%10...
This code implements a Gomoku game where the computer and player alternate turns. The computer uses a search algorithm to select moves, while the player inputs coordinates. After each move, the board is updated, and the game checks for a win or draw. The loop continues until a terminal state is reached, returning the r...
def play_gomoku(board_size): board = make_empty_board(board_size) board_height = len(board) board_width = len(board[0]) while True: print_board(board) if is_empty(board): move_y = board_height // 2 move_x = board_width // 2 else: move_y, move_...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def put_seq_on_board(board, y, x, d_y, d_x, length, col): for i in range(length): board[y][x] = col y += d_y x += d_x def print_board(board): s = "*" for i in range(len(b...
The code tests the `search_max` function by setting up a game board with specific piece placements, then verifying if `search_max` correctly identifies the optimal move as `(4,6)`. If the function returns this coordinate, the test passes; otherwise, it fails. The main task is to validate the correctness of the `search_...
def test_search_max(): board = make_empty_board(8) x = 5; y = 0; d_x = 0; d_y = 1; length = 4; col = 'w' put_seq_on_board(board, y, x, d_y, d_x, length, col) x = 6; y = 0; d_x = 0; d_y = 1; length = 4; col = 'b' put_seq_on_board(board, y, x, d_y, d_x, length, col) print_board(board) if searc...
def test_is_empty(): board = make_empty_board(8) if is_empty(board): print("TEST CASE for is_empty PASSED") else: print("TEST CASE for is_empty FAILED") def test_is_bounded(): board = make_empty_board(8) x = 5; y = 1; d_x = 0; d_y = 1; length = 3 put_seq_on_board(board, y, x, d_...
The code defines a function `easy_testset_for_main_functions` that executes a series of unit tests, including checking if a structure is empty, bounded, detecting rows, and finding maximum values. Its main task is to validate the correctness of core functionalities through automated testing, ensuring each function beha...
def easy_testset_for_main_functions(): test_is_empty() test_is_bounded() test_detect_row() test_detect_rows() test_search_max()
def load_email(f): lines = open(f).read().splitlines() return proc_block(lines) def pw(s, code): return f"[3{code}m{s}" def block_summary(b): at = test_attachment(b[0]) if at: print(pw(f"{at} {len(b[1])}", 4)) else: ct = llget(b[0], "content-type")[0][1] print(pw(f"non-at block: {ct}", 4))
This function extracts and prints key email metadata (sender, recipient, subject, body type/size) from a file path, using fallback fields when primary headers are missing. It handles both single and list-based body content, printing summaries with index, sender, recipient, body type, length, and file path for each emai...
def summary(idx, path): # print(path) (h, bs) = load_email(path) h_from = llget(h, "from") if not h_from: h_from = llget(h, "x-from-email") h_from = h_from[0][1] h_to = llget(h, "to") if not h_to: h_to = llget(h, "reply-to") h_to = h_to[0][1] h_sub = llget(h, "subject") if not h_sub: h_sub = "No Subje...
def getvalus(parser,idname): tag = parser.find(id=idname) valusOut = tag.text.split(" ")[0] try: res = float(valusOut) except Exception as e: res = 0 return res def rmse(actual: np.ndarray, predicted: np.ndarray): """ Root Mean Squared Error """ return np.sqrt(mse(actual, pre...
The code compares reference heart rate (HR) data from ATR files with computed HR values from HTML files, calculating RMSE errors for minimum, maximum, and average HR. It reads annotations from HTR/ATR files, extracts HTML-derived HR metrics, and outputs comparison results with RMS errors for evaluation.
def hrComparison(only_name,full_path ,htmpath): hr_ext = "htr" ref_ext = "atr" htmlFulPath = os.path.join(htmpath, only_name, only_name + ".html") htr_path = full_path+"."+hr_ext mean_data =[] min_data =[] max_data =[] flag = False if os.path.isfile(htr_path) and os.path.isfile(htm...
def getvalus_(parser,idname): tag = parser.find(id=idname) valusOut = tag.text.split(" ")[0] try: out1 = valusOut.split(" sec") res = float(out1[0]) except Exception as e: res = 0 return res def get_ref_data(ext,full_path): annotationFull = wfdb.rdann(full_path, ext) ...
The function compares parsed ECG interval values (P, PR, QRS) from an HTML file with reference data stored in files. It calculates root mean square errors (RMSE) between parsed and reference values, returning success status and computed metrics. The task involves file path construction, HTML parsing, data retrieval, st...
def compar_tool(htmpath,only_name,full_path,resultpath): htmlFulPath = os.path.join(htmpath, only_name, only_name + ".html") Dpath = os.path.join(resultpath,only_name) p_d = [] pri_d =[] qrs_d =[] flag =False if os.path.isfile(Dpath+".p") and os.path.isfile(Dpath+".pri") and os.path.isfile(D...
def creat_htr(fileDir,cygwin_bat,only_name): HR_tolerance = "500" db_name = fileDir#os.path.basename(fileDir) ref_dir = os.path.join(fileDir, 'ref') if os.path.isdir(ref_dir): pass else: os.makedirs(ref_dir) p = subprocess.Popen(cygwin_bat, shell=True, stdin=subprocess.PIPE, ...
The main task of the code is to process ECG data files by checking for valid .dat, .hea, and .atr file sets in the input directory. It generates HR comparisons (min, max, mean) between reference and test data, stores results in structured dictionaries, and creates a report using these aggregated metrics. The function i...
def mainHR(inputpath,cygwin_bat,htmpath): finalData_min = {"Name": {}, "Ref": {}, "test": {}, "Rms error": {}} maxdata_f = {"Name": {}, "Ref":{}, "test": {}, "Rms error": {}} meandata_f = {"Name": {}, "Ref": {}, "test": {}, "Rms error": {}} count = 0 for (dirpath, dirnames, filenames) in walk(inputp...
def dataConvert(filename,leadname,overallsec,ResultDir): out_header = wfdb.rdheader(filename) signal_length = out_header.sig_len frequency_per_sec = out_header.fs limitdata = overallsec * frequency_per_sec if signal_length >= limitdata: pass else: ResultDir_,filename_ = dataEx...
The code processes ECG data files (dat, hea) by comparing reference and test signals for QRS, P, and PR intervals, calculating RMS errors, and generating a report. It iterates through input directories, validates file pairs, converts data, and stores results in dictionaries for structured output.
def measurementMain(inputpath,leadname,overallsec,ResultDir,htmpath): f_qrs = {"Name": {}, "Ref": {}, "test": {}, "Rms error": {}} f_p = {"Name": {}, "Ref": {}, "test": {}, "Rms error": {}} f_pri = {"Name": {}, "Ref": {}, "test": {}, "Rms error": {}} count = 0 for (dirpath, dirnames, filenames) in w...
def init_params(lmbda_max): """ Initialize the parameters p and lmbda. p_{ii} is the probability of staying in the same class. p_{i,i+1} = 1 - p_{ii} is the probability of transitioning to the next class. lmbda_{ij} is a parameter for the entry in row i and column j of the transition matrix A. ...
This function implements the EM algorithm to estimate parameters p and λ by iteratively performing the M-step (maximization) until convergence. It initializes parameters, computes initial log-likelihood, and iterates to update p and λ while tracking their values and log-likelihood history. The loop stops when the chang...
def EM_algorithm(lmbda_fix, lmbda_max, ptime_diff, observed_seq, tol=1e-8): """ Run update procedures of the EM-algorithm. """ p_hist = [] lmbda_hist = [] loglik_hist = [] p, lmbda = init_params(lmbda_max) p_hist.append(p.copy()) lmbda_hist.append(lmbda.copy()) loglik_hist.appen...
def hmt_init_params(lmbda_max): """ Initialize the parameters p and lmbda. p_{ii} is the probability of staying in the same class. p_{ik} is the probability of transitioning from class i to class k. lmbda_{ij} is a parameter for the entry in row i and column j of the transition matrix A. """ ...
The function implements the EM algorithm to estimate parameters p and λ (lmbda) by iteratively performing the M-step, updating parameters using observed data (X_obs, tree_obs) and auxiliary information (pt_diff, dev_map). It tracks parameter values, log-likelihood, and convergence until the likelihood change falls belo...
def hmt_EM_algorithm(lmbda_fix, lmbda_max, X_obs, tree_obs, pt_diff, dev_map, tol=1e-8): """ Run update procedures of the EM-algorithm. """ p_hist = [] lmbda_hist = [] loglik_hist = [] p, lmbda = hmt_init_params(lmbda_max) p_hist.append(p.copy()) lmbda_hist.append(lmbda.copy()) ...
def check_age(self): """ Add 1 year of age to each animal in state, if age of animal > max_age, animal becomes dead. :return: None """ for animal in self.state: if animal: animal.add_year_to_age() if animal.time_to_kill(): ...
The main task of the code is to simulate the next state of a river ecosystem by resolving animal movements and conflicts. It updates positions based on animal behavior, handles collisions through conflict resolution, adds newborn animals, and ensures population constraints are maintained.
def next_state(self): """ changes configuration in river :return: None """ self.check_age() new_state = [[] for i in range(self._length)] new_animals = [] for i, cell in enumerate(self.state): if cell: new_state[cell.choose_sid...
def preprocess_cardio_dataset( normalization = True, exclusive_all_did_wrong=True, is_clean_blood_pressure = True, save = False, new_filename = None, PCA = False, is_using_onehot = True, include_gender = False, secondary_label = None): raw_dataset_location = 'datasets/' # cardio...
The code conducts a machine learning experiment on a cardiovascular dataset, preprocessing data with options for normalization, feature encoding, and data cleaning. It evaluates model performance using F1 scores, checks class distribution, and logs instances misclassified by classifiers if specified. The function retur...
def exp(preprocess_again = True, exclusive_all_did_wrong = False, normalization = True, PCA = False, is_clean_blood_pressure = False, is_using_onehot = True): from sklearn.model_selection import train_test_split dataset = 'normalized.csv' # X, y_true, feature_names = preprocess_cardio_dataset(normalization ...
def truth_combination(num_of_variable): import itertools l=[False,True] return [list(i) for i in itertools.product(l,repeat=num_of_variable)] def exp(preprocess_again = True, exclusive_all_did_wrong = False, normalization = True, PCA = False, is_clean_blood_pressure = False, is_using_onehot = True): fro...
The code evaluates multiple preprocessing configurations on a dataset by running experiments with varying parameters (e.g., normalization, PCA, data cleaning). It generates test cases, executes experiments for each, records F1 scores, and compiles results into a table comparing parameter combinations and their performa...
def main(): # outlier_exp() # preprocess_cardio_dataset( # normalization = True, # exclusive_all_did_wrong=False, # save = False, new_filename = None, # PCA = True, # secondary_label = 'gender') testcases = truth_combination(5) cols = ['is_clean_blood_pressure...
def feed_forward(self, input_batch): print("Perfoming feed forward") self.z = [] self.a= [input_batch] curr_input = input_batch for weights, bias in zip(self.weights, self.biases): curr_output_without_activation, curr_output_with_activation = \ self.layer_...
The main task of the code is to train a neural network model using mini-batch gradient descent. It iterates over batches of input-output data, performs forward propagation to generate predictions, computes weight/bias updates via backpropagation, and applies these updates over multiple epochs to minimize the loss funct...
def fit(self, X, Y, learning_rate, epochs, batch_size): self.X = X self.Y = Y self.learning_rate = learning_rate for batch_start_index in xrange(0, len(X), batch_size): input_batch = self.X[batch_start_index:(batch_start_index+batch_size)] output_batch = ...
def randfunct(): 'Create a random Boolean function. Individuals are represented _directly_ as Python functions.' re = randexpr(DEPTH) rf = eval('lambda ' + ', '.join(vars) + ': ' + re) # create function of n input variables rf = memoize(rf) # add cache to the function rf.geno = lambda: re # store ge...
The code implements a simple evolutionary algorithm to optimize a unimodal landscape. It initializes a random individual, iteratively mutates it, evaluates fitness, and replaces the current solution if the offspring's fitness is better. After a set number of generations, it outputs the best individual's genotype and qu...
def main(): 'Main function. As the landscape is always unimodal the climber can find the optimum.' curr = randfunct() # initial individual curr.fit = fitness(curr) # evaluate fitness #for gen in xrange(GENERATIONS+1): for gen in range(GENERATIONS+1): #4py3 off = mutation(curr) # create off...
def set_up_screen(): ################################ # set up the grid layout and board # ################################ global turn_lbl, board root.title("Tic-Tac-Toe") #set up window size window_width, window_height = 400, 400 screen_width = root.winfo_screenwidth() screen_height = ro...
The main task of the code is to initialize a graphical user interface (GUI) by setting up the screen, main menu, and starting a new game, then launching the Tkinter main event loop to display and manage the application window.
def main(): global root set_up_screen() set_up_main_menu() new_game() root.mainloop()
def clear_directory_csv(directory): ''' function to clear a directory of all csv files ''' filelist = glob.glob(os.path.join(directory, "*.csv")) for f in filelist: os.remove(f) def remove_glob_filepath(file_with_path): ''' gets rid of weird backspaces generated by glob ''' nopath = file_with_path.split(...
This function processes CSV files from an input directory by adding information to each file and saving them in an output directory. It clears existing files in the output folder, iterates through each CSV in the input folder, extracts filenames, and appends metadata. Progress is printed every 10th file or for the last...
def iterate_addinfo2(root): in_folder = root + '/Data/Converted' out_folder = root + '/Data/AddedInfo' # start off by emptying the addinfo file of csv files previously generated clear_directory_csv(out_folder) ###glob loop function with a printing of the numbers if statement infilelist = glob.glob(os.path.join...
def _instance_rating(self): return 1 / self.ds["rating"].values def _instance_proportion(self): _, score = self.get_group_rankings() self.ds["proportion"] = (self.lda_matrix * score).sum(axis=1) return self.ds["proportion"].values def _instance_time(self): times = self._get_time(...
The main task of the code is to calculate a weighted score for an instance by combining four metrics: rating (r), proportion (p), time (t), and duplication (d). These metrics are computed via private methods (_instance_rating, _instance_proportion, etc.), multiplied by corresponding weights from `self.instance_weights`...
def get_instance_score(self): r = self._instance_rating() p = self._instance_proportion() t = self._instance_time() d = self._instance_duplicate() r = self._instance_rating() p = self._instance_proportion() t = self._instance_time() return self.instance_w...
def build_generator(self): self.enhanced_patch = self.generator_network(self.phone_patch) self.enhanced_test = self.generator_network(self.phone_test) self.enhanced_test_unknown = self.generator_network(self.phone_test_unknown) variables = tf.trainable_variables() self.g...
This code initializes a neural network model for image processing tasks, setting up placeholders for training/test data, building generator and discriminator networks, and configuring loss functions (content, texture, color, TV) for training using phone and DSLR datasets.
def __init__(self, sess, config, dataset_phone, dataset_dslr): # copy training parameters self.sess = sess self.config = config self.batch_size = config.batch_size self.patch_size = config.patch_size self.mode = config.mode self.channels = config.channels ...
def load(self): checkpoint_dir = os.path.join(self.checkpoint_dir, self.dataset_name) ckpt = tf.train.get_checkpoint_state(checkpoint_dir) print("Loading checkpoints from ",checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: ckpt_name = os.path.basename(ckpt.model_checkpo...
This code trains a generative model (likely a GAN) to enhance images by iteratively optimizing a generator and discriminator network. It loads pre-trained weights if specified, runs 100,000 training iterations, computes multi-component losses (color, texture, content, TV), prints progress every 1000 steps, and periodic...
def train(self, load = True): if load == True: if self.load(): print(" [*] Load SUCCESS") else: print(" [!] Load failed...") else: print(" Overall training starts from beginning") start = time.time() for i in range(0, 10...
def create_bounding_box(self,center,rotation,extent): return open3d.geometry.OrientedBoundingBox(center,rotation,extent) def recolor_points_and_keep_by_bbox(self,vector_1_user,vector_2_user, array_of_colors,c_cloud_selection): array_of_colors = array_of_colors * 255 array_of_unique_colors = np.u...
The main task of the code is to recolor or delete points in a point cloud based on predefined bounding boxes and user-defined modes (e.g., bounding box, spherical, or color-based deletion). It translates the point cloud, processes each bounding box to identify and recolor/delete points, visualizes intermediate results,...
def range_recolor_point_cloud(self): if self.status_runnable != [True,True,True]: print("Error: Files not loaded") pass #Local var boxes_geometry = [] #Start start_time = datetime.now() #Move the point c...
def _get_download_catalogue(update=False, confirmation_required=True, verbose=False): path_to_downloads_catalogue = cd_dat(GeofabrikDownloadsCatalogue.replace(" ", "-") + ".pickle") if os.path.isfile(path_to_downloads_catalogue) and not update: subregion_downloads_catalogue = load_pickle(path_to_downl...
This function retrieves the download URL for a specified subregion and file format by validating inputs, fetching a download catalog, and indexing it by subregion. It returns the validated subregion name and corresponding URL.
def _get_subregion_download_url(subregion_name, osm_file_format, update=False,verbose=False): # Get an index of download URLs subregion_downloads_index =_get_download_catalogue(update=update, verbose=verbose) subregion_downloads_index.set_index('Subregion', inplace=True) subregion_name_ = _validate_in...
def _validate_input_subregion_name(subregion_name): assert isinstance(subregion_name, str) # Get a list of available subregion_names = _get_list_of_subregion_names() if os.path.isdir(os.path.dirname(subregion_name)) or urllib.parse.urlparse(subregion_name).path: subregion_name_ = find_similar_...
This function generates a default filename for an OpenStreetMap (OSM) file based on a specified subregion and file format. It validates inputs, retrieves a download URL, and returns the filename extracted from the URL's path if available. If no data is found, it prints an error message.
def _get_default_osm_filename(subregion_name, osm_file_format, update=False): subregion_name_ = _validate_input_subregion_name(subregion_name) osm_file_format_ =_validate_input_file_format(osm_file_format) _, download_url = _get_subregion_download_url( subregion_name_, osm_file_format_, update=upd...
def _validate_input_subregion_name(subregion_name): assert isinstance(subregion_name, str) # Get a list of available subregion_names = _get_list_of_subregion_names() if os.path.isdir(os.path.dirname(subregion_name)) or urllib.parse.urlparse(subregion_name).path: subregion_name_ = find_similar_...
This function determines the default file path and name for an OSM file based on a subregion and format. It validates inputs, retrieves a download URL, parses the URL path, adjusts directory structure, and constructs the file path. If data is unavailable, it returns None.
def _get_default_path_to_osm_file(subregion_name, osm_file_format, mkdir=False,update=False, verbose=False): subregion_name_ = _validate_input_subregion_name(subregion_name) osm_file_format_ = _validate_input_file_format(osm_file_format) subregion_name_, download_url = _get_subregion_download_url( ...
def _validate_input_subregion_name(subregion_name): assert isinstance(subregion_name, str) # Get a list of available subregion_names = _get_list_of_subregion_names() if os.path.isdir(os.path.dirname(subregion_name)) or urllib.parse.urlparse(subregion_name).path: subregion_name_ = find_similar_...
This function generates a standardized subdirectory path for downloading OSM files, validating inputs, creating a directory structure based on region name and file format, and returning the path with optional directory creation.
def _make_sub_download_dir(subregion_name, osm_file_format, download_dir=None, mkdir=False): subregion_name_ =_validate_input_subregion_name(subregion_name) osm_file_format_ =_validate_input_file_format(osm_file_format) default_filename, default_file_path = _get_default_path_to_osm_file( subregion...
def _validate_input_subregion_name(subregion_name): assert isinstance(subregion_name, str) # Get a list of available subregion_names = _get_list_of_subregion_names() if os.path.isdir(os.path.dirname(subregion_name)) or urllib.parse.urlparse(subregion_name).path: subregion_name_ = find_similar_...
This function checks if an OpenStreetMap (OSM) file for a specified subregion and format exists in a given directory. It validates inputs, constructs the file path, and returns `True`/`False` or the file path based on existence and update flag. If the file exists and `update=False`, it confirms availability; otherwise,...
def osm_file_exists(subregion_name, osm_file_format, data_dir=None,update=False,verbose=False, ret_file_path=False): subregion_name_ = _validate_input_subregion_name(subregion_name) osm_file_format_ =_validate_input_file_format(osm_file_format) default_filename, path_to_file = _get_default_path_to_osm_file...