dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def download_acaps(config): # Get the ACAPS data from HDX acaps_dir = os.path.join(config.INPUT_DIR, config.ACAPS_DIR) Path(acaps_dir).mkdir(parents=True, exist_ok=True) filename = list(query_api(config.ACAPS_HDX_ADDRESS, acaps_dir).values())[0] os.rename(os.path.join(acaps_dir, filename), os.path.j...
The function updates an NPI list by downloading or retrieving ACAPS data for a specified country (via ISO3 code), then integrating the filtered ACAPS data into the NPI list using provided parameters. It conditionally downloads ACAPS data if requested, extracts relevant country-specific data, and applies it to update th...
def update_npi_list(config, parameters, country_iso3, download_acaps_arg): if download_acaps_arg: logger.info('Getting latest ACAPS data') download_acaps(config) df_acaps = get_df_acaps(config, country_iso3) add_new_acaps_data(config, country_iso3, df_acaps[df_acaps['ISO3'] == country_iso3],...
def questionaire(): """User enters the question/Answer session""" with open("Questions.txt","r") as file: i = 0 for line in file: while True: response = input(line.strip()) if not validate(response): print("TRY AGAIN. You couldn'...
The main task of the code is to execute a questionnaire, classify its results into a type, and then generate and print a therapy recommendation based on that classification. The function sequentially collects input, processes it to determine a category, and outputs tailored therapy suggestions.
def main(): questionaire() Classified_Type = classify() print(therapy(Classified_Type))
def prepare_meta_mapper(X_dest=None, colList_meta=None, source_name=None): X = X_dest.copy() X = X[colList_meta].reset_index() X.loc[X.index.max()+1] = [-1, source_name] return X def get_source_vector(X=None, source_name=None, return_df=False, colList_features=None): if return_df: return X.l...
The main task of the code is to perform a matching operation between source and destination datasets based on feature vectors. It calculates the best matches using a specified number of candidates (num_match) and precision setting, then returns the matched destination records (X_match) along with a metadata mapper. The...
def perform_match_wrapper(X_source=None, X_dest=None, source_name=None, num_match=None, precise_match=True, colList_features=None, colList_meta=None): if num_match is None: if len(X_dest) <= 50: num_match = len(X_dest)-2 else: num_match = MAX_MATCH ...
def search(dir_name): file_names = os.listdir(dir_name) return list(map(lambda x: os.path.join(dir_name, x).replace("\\", "/"), file_names)) def preprocess(full_file_names): # GET ID_IDREF_RELATIONS id_idref_relations = get_id_idref_relations(full_file_names) # GET FINAL RELATIONS final_relations = get_fi...
The code processes STIX data by either preprocessing or loading relations from files, then constructs XML packages containing TTPs and observables. It organizes output into directories, tracks progress, and writes results as XML files, handling both preprocessed and raw data workflows.
def dir_1_main(is_preprocessed): for collection_dir, collection_idx in zip(collection_dirs_1, range(len(collection_dirs_1))): print("#{}: ".format(collection_idx + 1) + collection_dir) full_file_names = search(collection_dir) print("[MAKE_RELATIONS] file #: approximately {}".format(len(full_file_names))) prep...
def search(dir_name): file_names = os.listdir(dir_name) return list(map(lambda x: os.path.join(dir_name, x).replace("\\", "/"), file_names)) def preprocess_2(collection_dir, full_file_names): # GET ID_IDREF_RELATIONS # id_idref_relations = get_id_idref_relations_2(full_file_names) print("\tGET ID-IDREF RELAT...
The main task of the code is to process STIX data from multiple directories by either preprocessing or loading preprocessed relations, then generating XML files in chunks of 30,000 entries. It constructs STIX packages by combining TTPs (Tactics, Techniques, Procedures) and observables from input files, handling namespa...
def dir_2_main(is_preprocessed): for collection_dir, collection_idx in zip(collection_dirs_2, range(len(collection_dirs_2))): print("#{}: ".format(collection_idx + 1) + collection_dir) full_file_names = search(collection_dir) print("[MAKE_RELATIONS] file #: approximately {}".format(len(full_file_names) * 10000))...
def rancher_disable_monitoring(self): ''' Disables monitoring on the remote cluster and updates self.results if anything was changed Returns self.results ''' existing_config = self.get_current_monitoring_settings() if existing_config: if self.module....
This code configures Rancher monitoring settings by applying input parameters, setting HTTP headers, and conditionally enabling/disabling monitoring based on the 'enable_monitoring' flag. It checks existing configurations, compares them with new data, and updates monitoring settings only if changes are needed, returnin...
def exec_module(self, **kwargs): for key in list(self.module_spec.keys()): setattr(self, key, kwargs[key]) self.http_headers = { 'Authorization': 'Bearer ' + self.api_bearer_token, 'Content-Type': 'application/json' } if not self.enable_monitoring: ...
def top_half(pop_df_ranked): pop_df_new = pop_df_ranked.head(25) return pop_df_new def rank(pop_df_evaluated): pop_df_evaluated['Rank'] = pop_df_evaluated['Fitness'].rank(ascending=0) pop_df_evaluated = pop_df_evaluated.set_index('Rank') pop_df_evaluated = pop_df_evaluated.sort_index() pop_df_ev...
This function implements a genetic algorithm (GA) to evolve mathematical formulas for classifying normal (x_reg/y_reg) and anomalous (x_anom/y_anom) data. It iteratively selects, crosses over, and mutates formulas in a population, maintaining diversity by avoiding duplicates. The algorithm stops when the misclassificat...
def GA(pop_df,x_reg, y_reg, x_anom, y_anom, rng): # pop_df = initialize(x_reg, y_reg, x_anom, y_anom, rng_mod) pop_df_new = top_half(rank(evaluate(pop_df,x_reg, y_reg, x_anom, y_anom))) pop_df_new = pop_df count = 1 MCR = 100 N = [] while MCR>0.04: print('Genetic Alg...
def is_valid_url(self, url): regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// # domain... r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d...
The main task of the code is to populate each product's "image_file" field in the product JSON data. It checks if the product's image URL is valid; if so, it downloads the image, otherwise it assigns a dummy image. This ensures all products have an image file, either from their URL or a placeholder.
def populate_image(self): for product in self.product_json: if self.is_valid_url(product["images_url"]): product["image_file"] = self.get_image(product["images_url"]) else: product["image_file"] = self.get_dummy_image()
def likelihood_method(self, full_fit=True, max_sum=1000, guess=[10, -5], disp=True): """ Using likelihood method to estimate the parameters of the truncated negative binomial (mup and kp) and the host survival fxn (a, b) Parameters ---------- data...
The function tests for parasite-induced host mortality (PIHM) using a likelihood ratio test. It compares a reduced model (negative binomial distribution) to a full model (negative binomial with PIHM parameters *a* and *b*). By fitting both models to the data, it calculates negative log-likelihoods (full and reduced), c...
def test_for_pihm_w_likelihood(self, guess=[10, -5], k_array=np.linspace(0.05, 2, 100), fixed_pre=False, disp=True): """ Test a dataset for parasite induced host mortality using the likelihood method This method compares a reduced model (n...
def calculate_density_and_energies(potential, wavefunctions, energies, N, h): assert(N <= wavefunctions.shape[2]) density = np.sum(np.square(wavefunctions)[:, :, :N], axis=-1) kinetic_energy_densities = 0.5*derivative_five_point(wavefunctions, h)**2 # == -0.5*wavefunctions*laplace_five_point(wavefunctions)...
This function calculates system properties including density, total energy, potential/kinetic energy components, and their spatial derivatives using wavefunctions and a potential. It computes the Weizsaecker kinetic energy approximation, its density-dependent integrand, and derivatives, returning all key physical quant...
def calculate_system_properties(potential, wavefunctions, energies, N, h): assert(N <= wavefunctions.shape[2]) density, energy, potential_energy, kinetic_energy, potential_energy_density, kinetic_energy_density = calculate_density_and_energies(potential, wavefunctions, energies, N, h) derivative = np.expan...
def SQL(Mainframe,window,username1,password1): global server server = 'hopper.ws.edu' global database database = 'naburke' global password password = password1 global username username = username1 sterile_execute ="Select master_password from [user] WHERE master_username = '" + use...
The code creates a login interface with username/password fields and buttons for login, exit, and new user registration. It uses Tkinter to structure frames, labels, and entry widgets, with the login button triggering an SQL function (currently using hardcoded credentials) and other buttons handling exit or new user ac...
def startingScreen(window): #mainframe Mainframe= Frame(window) Mainframe.pack(fill="both",expand="True") #topframeplaceholder topframeplaceholder = tk.Frame(Mainframe) topframeplaceholder.pack(side="top",fill="both",expand="True") #topframe topframe = tk.Frame(Mainframe) t...
def properName(self, name): name = name.replace("amp", "") return re.sub('[^A-Za-z0-9_\-\.\\\ ]+', "", name) def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") ...
The code processes a web response to extract and convert thumbnail image URLs to larger versions. It identifies gallery codes, replaces specified strings in image URLs, constructs filenames, handles relative URLs by appending base paths, and downloads images to a directory, ensuring non-duplicate downloads.
def thumbToLarge(self, response): strInSrc = response.meta['search'] replaceWith = response.meta['replace'] if "index" in response.meta: index = response.meta['index'] else: index = -1 print("thumbToLarge") websiteName = self.properName(response.ur...
def properName(self, name): name = name.replace("amp", "") return re.sub('[^A-Za-z0-9_\-\.\\\ ]+', "", name) def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") ...
The function processes image URLs from a webpage response by replacing a specified string with another, constructs filenames using gallery codes, and downloads images to a specific directory if they haven't been downloaded before. It extracts image URLs, modifies them, and triggers downloads while tracking completion s...
def thumbToLarge2(self, response): strInSrc = response.meta['search'] replaceWith = response.meta['replace'] if "index" in response.meta: index = response.meta['index'] else: index = -1 print("thumbToLarge") websiteName = self.properName(response.u...
def properName(self, name): name = name.replace("amp", "") return re.sub('[^A-Za-z0-9_\-\.\\\ ]+', "", name) def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") ...
The code extracts image URLs from a webpage, constructs full URLs, checks if images are already downloaded, and downloads them to a specified directory. It handles gallery codes from URLs or meta data, manages pending downloads by renaming/moving files, and logs download completion.
def imgLinks(self, response): if 'index' in response.meta: index = response.meta['index'] else: index = 0 # print("imgLinks " + index) websiteName = self.properName(response.url.split("/")[2]) if 'galleryCodeFromURL' not in response.meta: if 'i...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The code downloads images from a webpage by extracting URLs of JPG files, generates unique filenames based on the page title and incrementing numbers, and saves them locally after checking if they've already been downloaded.
def pentHouse(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css("a").re("href=\"([^\"]*jpg)\"") i = 0 imgCode = "@" + re.search("g/(.*?)/", response.url)[1] + "@" if self.alreadyNotDownloaded("babeGallery", imgCode): for ...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The code downloads images from a webpage by extracting URLs of JPG images, generating filenames based on page title and model name, and saving them to a directory if not previously downloaded.
def eurotica(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css("a").re("href=\"([^\"]*jpg)\"") imgCode = response.css("title").re("<title>(.*?)<")[0] + " " + response.css("a[title*=model]::text").extract()[ 0] i = 0 if se...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The main task of the code is to download images from a webpage by extracting `.jpg` URLs, generate unique filenames based on the URL's identifier, check if they are not already downloaded, and save them locally with a specific naming format. It also registers the completion of the download process.
def babeShow(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css("a").re("href=\"([^\"]*jpg)\"") imgCode = response.url.split("/")[-1].split(".")[0] + "@" i = 0 if self.alreadyNotDownloaded("babeShow", imgCode): for imgUrl ...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The code downloads images from a specific website (dirtyhardcash.com) by extracting URLs from HTML elements, generating unique filenames using a gallery ID, and saving them locally. It checks if images are already downloaded to avoid duplicates, then iterates through extracted image links to save each as a .jpg file wi...
def dirtyHardcash(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css("a").re("href=\"([^\"]*jpg)\"") imgCode = "@" + re.search("gallery_id=([0-9]+)", response.url)[1] + "@" i = 0 if self.alreadyNotDownloaded("dirtyHardcash", imgCode):...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The code downloads images from a specified URL by extracting a base image link, generating sequential filenames based on the page title, and saving 20 variations of the image by modifying numeric patterns in the URL. It checks if the images are already downloaded before processing, ensuring no duplicates, and logs prog...
def aziani(self, response): print("Downloading Pictures from URL:%s" % response.url) StaticImgUrl = response.css("a").re("href=\"([^\"]*\.jpg)\"")[0] i = 0 if self.alreadyNotDownloaded("aziani", response.css("title").re("<title>(.*?)<")[0].split("-")[0]): for picNumber in ran...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The main task of the code is to download images from a specific website (porngals4) by extracting image URLs from the response, checking if they are not already downloaded, and saving them with filenames derived from the page title and a counter. It uses CSS selectors and regex to parse URLs, manages file naming, and r...
def porngals4(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css("a").re("href=\"([^\"]*?jpg)\"") i = 0 if self.alreadyNotDownloaded("porngals4", response.css("title").re("<title>(.*?)<")[0]): for imgUrl in imgUrls: ...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The code downloads images from a webpage by extracting URLs from <img> tags, generates filenames using a counter and numeric parts from the URL, constructs specific image URLs by replacing placeholders, and saves them locally after checking if they haven't been downloaded before.
def photodromm(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css("img").re("src=\"(thumb.*?)\"") i = 0 if self.alreadyNotDownloaded("photodromm", re.findall("[0-9]+", response.url)[0]): for imgUrl in imgUrls: i +=...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The code downloads images from the "alluringvixens" website by extracting .jpg URLs from HTML links, generating unique filenames based on page titles, replacing relative paths with absolute URLs, and saving them locally after checking if they are already downloaded.
def alluringvixens(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css("a").re("href=\"([^\"]*?\.jpg)\"") i = 0 if self.alreadyNotDownloaded("alluringvixens", response.css("title").re("<title>(.*?)<")[0]): for imgUrl in imgUrls: ...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The code extracts and downloads full-size images from a webpage by processing thumbnail URLs, ensuring non-redundant downloads, and saving them with structured filenames.
def dirtynakedpics(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css("img").re("src=\"(.*?-tn\.jpg)\"") i = 0 if self.alreadyNotDownloaded("dirtynakedpics", response.url.split("/")[-2]): for imgUrl in imgUrls: i +...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The code downloads images from "japanesebeauties.net" by extracting URLs from HTML links, checks if the page has not been previously downloaded, saves each image with a filename derived from the URL path, and registers download completion. It processes image links, constructs full URLs, and stores images in a specified...
def japanesebeauties(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css("a").re("href=\"([^\"]*jpg)\"") i = 0 if self.alreadyNotDownloaded("japanesebeauties.net", response.url): for imgUrl in imgUrls: i += 1 ...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The main task of the code is to download images from a webpage by extracting URLs from anchor tags, converting relative paths to absolute URLs, saving them with uniquely generated filenames, and logging completion after downloading, while avoiding redundant downloads using a check for existing files.
def BoundCash(self, response): print("boundCash") imgUrls = response.css("a").re("href=\"([^\"]*jpg)\"") i = 0 if self.alreadyNotDownloaded("lucyZara", response.url): for imgUrl in imgUrls: i += 1 formedUrl = imgUrl.replace("../", "http://www.l...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The code extracts image URLs and actor names from a webpage, checks if images are already downloaded, and downloads them if not. It generates filenames using actor names and image codes, then constructs a third-party URL using a gallery code to fetch additional data, yielding a new request with metadata for further pro...
def EvilAngel(self, response): print("evilAngel") imgUrls = response.css("a[href*=jpg]::attr(href)").extract() i = 0 starName = " and ".join(response.css(".pgTitleActorsText").re("title=\"(.*?)\"")) + " " galCode = imgUrls[0].split("/")[-1].split(".")[0].split("_")[0] if ...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The code extracts image URLs from a webpage, generates filenames using actor names and gallery codes, downloads images if not already downloaded, and yields a request to a third-party URL with metadata for further processing.
def Bskow(self, response): print("Bskow") imgUrls = response.css("a[href*=jpg]::attr(href)").extract() i = 0 starName = " and ".join(response.css(".pgTitleActorsText").re("title=\"(.*?)\"")) + " " galCode = imgUrls[0].split("/")[-1].split(".")[0].split("_")[0] if self.alr...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
This code extracts image URLs and metadata from a webpage, checks if they're already downloaded, and if not, downloads them. It generates filenames using star names and gallery codes, then constructs a third-party URL with the gallery code to yield a follow-up request for further processing.
def DevilFilm(self, response): print("DevilFilm") imgUrls = response.css("a[href*=jpg]::attr(href)").extract() i = 0 starName = " And ".join(response.css(".actorsValue a::text").extract()) + " " galCode = imgUrls[0].split("/")[-1].split(".")[0].split("_")[0] if self.alrea...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The main task of the code is to extract and download images from a website (DevilsFilm) by parsing URLs and star names from HTML responses. It generates sequential image filenames using a loop, checks if the URL is already downloaded, and saves images to a directory. The code manipulates URLs to fetch multiple image va...
def DevilsFilm(self, response): print("DevilsFilm") imgUrl = response.css("a").re("href=\"(.*?nva.*?)\"")[0] i = 0 # starName = response.css("a[href*=pornstar]::attr(title)").extract() starName = " And ".join(response.css("a[href*=pornstar]::attr(title)").extract()) if se...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
This method downloads images from a specified URL by extracting thumbnail URLs, generating unique filenames based on the comic title and image count, and saving them in a structured directory. It avoids re-downloading by checking existing files, processes URLs to remove unnecessary suffixes, and registers completion af...
def downloadPorncomix(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css("img.attachment-thumbnail.size-thumbnail").re("lazy-src=\"([^\"]*jpg)\"") i = 0 comicsCode = re.sub('[^A-Za-z0-9\.\-]+', '', response.css("title").re("<title>(.*?)<")[0]...
def properName(self, name): name = name.replace("amp", "") return re.sub('[^A-Za-z0-9_\-\.\\\ ]+', "", name) def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") ...
The main task of the code is to download images from a webpage, organize them into directories named after the comic's title, and save each image with a sequential filename. It extracts image URLs from the response, constructs full URLs, skips already-downloaded content, and stores images in a structured folder hierarc...
def hBrowse(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css("img::attr(src)").extract() i = 0 comicsCode = self.properName(response.css("title").re("<title>(.*?)<")[0]) if self.alreadyNotDownloaded("hBrowse", response.css("title")....
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The main task of the code is to download images from a webpage (likely 8Muses) by extracting URLs from lazy-loaded elements, processing them to form valid image links, and saving each image with a structured filename in a designated directory. It checks if the comic has already been downloaded to avoid duplicates, then...
def download8Muses(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css(".lazyload").re("data-src=\"([^\"]*jpg)\"") i = 0 comicsCode = re.sub('[^A-Za-z0-9\.\-]+', '', response.css("title").re("\\t\\t(.*)")[1]) if self.alreadyNotDownload...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The main task of the code is to download comic images from a website by extracting URLs from HTML elements, checking if they are already downloaded, saving them with specific filenames, and updating a file to mark them as processed. It uses CSS selectors to parse image links, iterates through them, and manages download...
def comicVine(self, response): imgUrls = response.css(".fluid-width").css("img[src*=scale]::attr(src)").extract() print("Downloading Pictures from URL:%s" % response.url) i = 0 galCode = response.css("title::text").extract()[0] if self.alreadyNotDownloaded("comicVine", galCode): ...
def properName(self, name): name = name.replace("amp", "") return re.sub('[^A-Za-z0-9_\-\.\\\ ]+', "", name) def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") ...
This function downloads images from a gallery by iterating through provided URLs, constructing full URLs if necessary, and saving them to a specified folder. It checks if the gallery is already downloaded or requires individual link checks, then uses either IDM or standard methods to download images, logging progress a...
def downloadGalleryGeneric(self, response, imgUrls, fileNames, galCode="", static=True, folderName= "BabesImgs",cookies=""): folderName = "Babesource\\" websiteName = self.properName(response.url.split("/")[2]) print(response.url) checkEachLinkIndividually = False if galCode != "@" else ...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The code downloads images from a gallery page by extracting URLs of JPG images, checks if the gallery is already downloaded, saves each image with a filename based on the page title and sequence number, and updates download status by removing the URL from a tracking file.
def downloadThisBabesGallery(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css("a").re("href=\"([^\"]*jpg)\"") i = 0 if self.alreadyNotDownloaded("babeGallery", response.css("title").re("<title>(.*?)<")[0]): for imgUrl in imgUrls...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The code's main task is to download images from a specified URL by extracting image URLs using CSS selectors and regular expressions. It generates unique filenames based on extracted text and URL segments, checks if images are already downloaded, and uses `downloadImgWithIDM` to save them locally. The process logs URLs...
def puba(self, response): print("Downloading Pictures from URL puba:%s" % response.request.url) print(response.url) imgUrls = response.css("a").re("href=\"([^\"]*jpg)\"") imgCode = response.css(".vid_text::text").extract()[0] + " " + response.url.split(".")[-4] t = response.url ...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The main task of the code is to download images from a webpage by extracting URLs ending with "_tn.jpg", adjust them to full-resolution ".jpg" links, and save them with filenames derived from the page title. It avoids re-downloading by checking a registry, uses IDM for downloading, and updates a file to track completed...
def ScoreLand(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css("img").re("src=\"([^\"]*_tn.jpg)\"") i = 0 if self.alreadyNotDownloaded("ScoreLand", response.css("title").re("<title>(.*?)<")[0]): for imgUrl in imgUrls: ...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The main task of the code is to download images from a webpage by extracting image URLs using CSS selectors, checking if they are not already downloaded, generating unique filenames based on the page title, and using Internet Download Manager (IDM) to save them in a specified directory.
def ddf(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = response.css("a").re("href=\"([^\"]*?\.jpg)\"") i = 0 if self.alreadyNotDownloaded("ddf", response.css("title").re("<title>(.*?)<")[0]): for imgUrl in imgUrls: i += 1 ...
def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") print("openening file name %s for checking id %s" % (fileName, Id)) except(FileNotFoundError): retu...
The code downloads images from a specified URL by extracting JPEG links from HTML anchors, renames the gallery using the page title, skips already downloaded content, and uses IDM to save images locally while updating a tracking file.
def Brazzer(self, response): print("Downloading Pictures from URL:%s" % response.url) imgUrls = [urllib.request.urljoin(response.url, x) for x in response.css("a").re("href=\"([^\"]*?\.jpg)\"")] i = 0 galName = response.css("title").re("<title>(.*?)<")[0].replace("Free Video With", "Me C...
def properName(self, name): name = name.replace("amp", "") return re.sub('[^A-Za-z0-9_\-\.\\\ ]+', "", name) def alreadyNotDownloaded(self, fileName, Id): dir_path = os.path.dirname(os.path.realpath(__file__)) try: fp = open(dir_path + "\\list\\%s.txt" % fileName, "r") ...
The main task of the code is to process a gallery's images from a third-party website by extracting gallery metadata, parsing image URLs from the response, checking if the gallery is already downloaded, constructing full URLs for images, and downloading them using IDM. It also registers the download completion for trac...
def thirdParty(self, response): galleryCode = response.meta["galCode"] galName = response.meta["galleryName"] websiteName = self.properName(response.url.split("/")[2]) i = 0 imgUrls = response.css("a[href*=\.jpg]::attr(href)").extract() # imgUrls = response.css("a img[src...
def init_train_ok_dl(self): batch_size = self.opt.batch_size if self.use_cuda: batch_size *= torch.cuda.device_count() train_ok_dl = DataLoader( KolektorDataset(self.root_path, transforms_=self.transform_, transforms_mask=self.transform_mask_, ...
The main task of the code is to train a machine learning model using training and validation data loaders, logging training metrics and validating every 5 epochs. It tracks the best validation score, logs metrics, and saves training/validation images. The loop iterates over epochs, performs training, validation, and lo...
def main(self): log.info("Starting {}, {}".format(type(self).__name__, self.opt)) train_ok_dl = self.init_train_ok_dl() train_ng_dl = self.init_train_ng_dl() val_dl = self.init_val_dl() best_score = 0.0 self.validation_cadence = 5 for epoch_ndx in range(self.o...
def search_maze(self): #================================ RUNNING TO THE CENTRE ==================================== rospy.loginfo('moving to goal') # save the bot starting postion self.bot_pos = self.locate_bot(self.pos_topic) # save to traversed nodes self.traversed_no...
The code initializes a robot navigation system for a maze, setting up an occupancy matrix to represent the environment, subscribing to laser scans for real-time updates, and using pathfinding algorithms to navigate towards a goal. It handles maze resets and path corrections if the initial matrix is inaccurate, ensuring...
def __init__(self, laser_topic, pos_topic): # odometry topic for bot localisation self.pos_topic = pos_topic # maze paraeters wall_width = 0.2 self.cell_number = 9 corridor_width = 0.8 # SET THE GOAL self.goal_pos = (3,15) # divisor for cell id...
def pratham(i): global temp,old old=[] if(i=="/" or i=="*" or i=="-" or i=="+" or i=="=" or i=="."): short.clear() short.append(temp) short.append(i) temp="".join(short) def equal(): for i in range(len(temp)): if(...
This code handles the "equals" operation in a calculator application. It processes the current input expression (temp), ensures valid formatting, triggers calculation, updates the display with the result, and resets the input state for the next operation.
def equal0(self): global temp ,result result="" if(len(temp)==0): temp=temp+"0" if(temp[-1]=='*' or temp[-1]=='/' or temp[-1]=='+' or temp[-1]=='-' or temp[-1]=='='): temp=temp[:-1] pratham('=') equal() calculate() self.input2.setVi...
def check_registry_username(self) -> bool: if self.register_username.get().strip() == "" or " " in self.register_username.get(): self.register_username_warning.config(text="* Username can't be blank or space or have spaces") return False if len(self.register_username.get()) < 6:...
The code's main task is to validate user registration entries by checking the username, password, email, and phone number fields. It returns True only if all four validation checks pass, ensuring all required registration details meet specified criteria.
def check_register_entries(self) -> bool: return all( [ self.check_registry_username(), self.check_registry_password(), self.check_registry_email(), self.check_registry_phone(), ] )
def check_login_entry(self) -> bool: return all([self.check_login_username(), self.check_login_password()]) def connect_database(self) -> Tuple[psycopg2.extensions.connection, psycopg2.extensions.cursor]: conn = psycopg2.connect( database="uerj", user=os.environ.get("POSTGRES_USE...
The code authenticates a user by checking if provided login credentials exist in a database. It connects to the database, executes a query to verify the username and password, and either removes a warning and opens an authentication window (if credentials match) or updates the warning message (if they don't).
def login(self) -> None: if self.check_login_entry(): conn, cursor = self.connect_database() cursor.execute( f""" select exists(select username, password from account where username='{self.login_username.get().lower()}' and password='{self.login_password.g...
def check_register_entries(self) -> bool: return all( [ self.check_registry_username(), self.check_registry_password(), self.check_registry_email(), self.check_registry_phone(), ] ) def connect_database(self) -> Tupl...
The main task of the code is to register a new user by validating input, generating a unique user key, storing user details (username, password, email, phone) in a database, creating an authentication QR code, and displaying it. It ensures data is inserted securely into the 'account' table and generates a QR code for v...
def register_user(self) -> None: if self.check_register_entries(): user_key = generate_key() # logger.debug(user_key) authy = self.AUTHY.generate_code(user_key, self.register_email.get()) phone_with_ddi = "+55" + self.register_phone.get() conn, cursor ...
def preprocess_proposals(self, bbox_arr, grid_resolution_arr, img_input_size): num_rows = int(np.ceil(img_input_size[0] / grid_resolution_arr[0])) num_columns = int(np.ceil(img_input_size[1] / grid_resolution_arr[1])) grid = np.frompyfunc(list, 0, 1)(np.empty((num_rows, num_columns), dtype=object)) coo...
The main task of the code is to process proposals (bounding boxes) by filtering low-confidence ones, grouping them by height ranges, merging overlapping regions, generating initial and packed crops with scale factors, and returning structured arrays of crops, weights, and per-height processed data for further analysis ...
def pack_crops(self, proposals, img=[]): initial_crops_arr = np.empty([0, 5]) # the initial crops based on the given proposals initial_net_crops_arr = [] # the initial net crops (without padding) based on the given proposals initial_net_crops_per_height_arr = [] # the initial net crops (without padding) bas...
def prepare_modelnet40(): n_target_faces = [2048] labels2use = model_net_labels for i, name in tqdm(enumerate(labels2use)): for part in ['test', 'train']: pin = 'datasets_raw/ModelNet40/' + name + '/' + part + '/' p_out = 'datasets_processed/modelnet40/' prepare_directory('modelnet40', pathn...
This function prepares 3D datasets by routing the input dataset name to corresponding preparation functions, handling both general datasets (e.g., ModelNet40, Cubes) and semantic segmentation datasets (e.g., PartNet, COSEG). It standardizes the dataset name, checks for matches, and invokes specific preparation routines...
def prepare_one_dataset(dataset_name): dataset_name = dataset_name.lower() if dataset_name == 'modelnet40' or dataset_name == 'modelnet': prepare_modelnet40() if dataset_name == 'modelnet40_normal_resampled': prepare_modelnet40_normal_resampled() if dataset_name == 'shrec11': print('To do later') ...
def set_message(self, message): self.message = message def set_type(self, notification_type: NotificationType): self.type = notification_type def notify(self): self.prepare() if self.need_to_print: rich_print(Panel(self.message)) if self.abort: raise typ...
The code's main task is to set a warning message, specify its type as a warning using NotificationType, and trigger a notification. It calls set_message to store the message, set_type to define the notification category, and notify to alert the system or user. This method handles warning-related notifications in a stru...
def warning(self, message): self.set_message(message) self.set_type(NotificationType.WARNING) self.notify()
def set_message(self, message): self.message = message def set_type(self, notification_type: NotificationType): self.type = notification_type def notify(self): self.prepare() if self.need_to_print: rich_print(Panel(self.message)) if self.abort: raise typ...
The method 'info' processes a message by setting it as the notification content, specifying the notification type as INFO, and then triggering a notification to inform the system or user of the provided information.
def info(self, message): self.set_message(message) self.set_type(NotificationType.INFO) self.notify()
def set_message(self, message): self.message = message def set_type(self, notification_type: NotificationType): self.type = notification_type def notify(self): self.prepare() if self.need_to_print: rich_print(Panel(self.message)) if self.abort: raise typ...
This code sets a notification message, specifies its type as "OK," and triggers the notification process.
def ok(self, message): self.set_message(message) self.set_type(NotificationType.OK) self.notify()
def set_message(self, message): self.message = message def set_type(self, notification_type: NotificationType): self.type = notification_type def notify(self): self.prepare() if self.need_to_print: rich_print(Panel(self.message)) if self.abort: raise typ...
This code defines a 'success' method that sets a notification message, specifies its type as 'OK' (indicating success), and triggers a notification. It is likely part of a notification system to inform users of successful operations, such as form submissions or task completions.
def success(self, message): self.set_message(message) self.set_type(NotificationType.OK) self.notify()
def set_message(self, message): self.message = message def set_type(self, notification_type: NotificationType): self.type = notification_type def notify(self): self.prepare() if self.need_to_print: rich_print(Panel(self.message)) if self.abort: raise typ...
The method 'debug' processes a debug message by setting the provided message, designating the notification type as DEBUG, and triggering a notification. It updates the message content, specifies the notification category, and initiates the notification process to handle or log the debug information.
def debug(self, message): self.set_message(message) self.set_type(NotificationType.DEBUG) self.notify()
def set_message(self, message): self.message = message def set_type(self, notification_type: NotificationType): self.type = notification_type def set_abort(self, abort=False): self.abort = abort def notify(self): self.prepare() if self.need_to_print: rich_print(Panel...
This method handles exceptions by setting a notification message, marking it as an exception type, enabling abort flag, and triggering notification. It configures error state for the system to halt further processing and alert with specified message.
def exception(self, message): self.set_message(message) self.set_type(NotificationType.EXCEPTION) self.set_abort(True) self.notify()
def set_message(self, message): self.message = message def set_type(self, notification_type: NotificationType): self.type = notification_type def set_abort(self, abort=False): self.abort = abort def notify(self): self.prepare() if self.need_to_print: rich_print(Panel...
The method handles error notifications by setting the provided message, specifying the notification type as ERROR, enabling abort flag, and triggering the notification process.
def error(self, message): self.set_message(message) self.set_type(NotificationType.ERROR) self.set_abort(True) self.notify()
def install_package_with_pipenv(package): b = check_package_installed(package) if b: print(f'\n{package} already installed\n') else: print(f'\nInstalling {package}...') try: runSubprocess(f'pipenv install {package}', shell=True, check=True) print(f'\n{package...
The code provides a menu-driven interface for managing Pipenv environments, allowing users to install individual packages, install from requirements.txt, check installed packages, uninstall packages, restart the virtual environment, execute pipenv commands, or delete the environment. It loops until the user exits, offe...
def manage_pipenv(): menu = '1' while menu in ['1', '2', '3', '4', '5', '6']: menu = input('\n*********************************** PIPENV SETTINGS ***********************************\n\n' '\n1. Install an only package' '\n2. Install all packages ...
def __connect_ms_sql( username = '', password = '', db_server = Default_Sql_Connection_Values["Server"], database = Default_Sql_Connection_Values["Database"], driver = Default_Sql_Connection_Values["Driver"], trust_certificates = Default_Sql_Connection_Values["TrustServer...
This function connects to a SQL database, retrieves data from external sources (MTEST, DNS, SanNav), caches ID/Core tables, and updates the storagetooling database with processed stack, customer, and SanNav data. It handles credentials via parameters or Jenkins environment variables, tracks execution time for each step...
def update_data_from_sources( username = '', password = '', db_server = Default_Sql_Connection_Values["Server"], database = Default_Sql_Connection_Values["Database"], driver = Default_Sql_Connection_Values["Driver"], trust_certificates = Default_Sql_Connection_Values["TrustServer...
def clear(): os.system('cls') if os.name == "nt" else os.system('clear') def get_number_to_guess(): NUMFROM = 1000 NUMTO = 10000 number = random.randint(NUMFROM, NUMTO) while has_doubles(number): number = random.randint(NUMFROM, NUMTO) return number def get_player_guess(guess_count): ...
The code implements a number guessing game where a player has a limited number of attempts (LIVES) to guess a four-digit number. It tracks guesses, evaluates each attempt, displays feedback, and declares a win/loss based on whether the player correctly identifies the number within the allowed attempts.
def main(LIVES): clear() guess_count = 0 guess_number = get_number_to_guess() player_guess = -1 guesses = [] while guess_count < LIVES and guess_number != player_guess: clear() print(" Guess a four digit number!") # print(guess_number) p.print_previos_guesse...
def check(): global inpFile global opFile global memory global sortOrder global SINGLE_ROW_SIZE if not os.path.exists('metadata.txt'): print('Metadata not found') return False f = open('metadata.txt').readlines() for line in f: line = line.strip() line =...
The code reads and processes data from an input file in chunks, sorts each chunk, writes them to temporary files, then merges these sorted files into a final output using a heap-based approach to efficiently combine the data while managing memory constraints.
def main(): if not check(): return linesToRead = 100 # memory/SINGLE_ROW_SIZE charToRead = SINGLE_ROW_SIZE + 2 * (len(columnSize) - 1) f = open(inpFile) l = 0 fcount = 1 data = [] print(f'Starting phase 1. Reading {linesToRead} at a time...') for line in f: # tracema...
def generate_real_samples(dataset, n_samples): ix = randint(0, dataset.shape[0], n_samples) X = dataset[ix] y = ones((n_samples, 1)) return X, y def generate_fake_samples(g_model, latent_dim, n_samples): x_input = generate_latent_points(latent_dim, n_samples) X = g_model.predict(x_input) y = zeros((n_samples, 1)...
This code trains a GAN by alternating between updating the discriminator with real/fake samples and training the generator via the GAN model, using batches from the dataset. It prints training losses and evaluates performance every 10 epochs.
def train(g_model, d_model, gan_model, dataset, latent_dim, n_epochs=100, n_batch=128): bat_per_epo = int(dataset.shape[0] / n_batch) half_batch = int(n_batch / 2) for i in range(n_epochs): for j in range(bat_per_epo): X_real, y_real = generate_real_samples(dataset, half_batch) d_loss1, _ = d_model.train_on_...
def path_exists(path="Servicio/"): return db.reference(path).get() def get_required_data(model): if model == 'Products': products = Product.objects.values() return ProductSerializer(products, many=True).data elif model == 'Categories': categories = Category.objects.all() retu...
The function `snippet_detail` processes POST requests by validating a dynamically constructed file path, parsing JSON input, retrieving model-specific data, and executing a query processing task. It returns a 404 error if the path does not exist, otherwise handles the request with the retrieved data.
def snippet_detail(request, model): path = "Servicio/"+model if not path_exists(path): return HttpResponse({'error': 'path not exist'}, status=404) elif request.method == 'POST': body = json.loads(request.body) data = get_required_data(model) return process_query(data, body,...
def path_exists(path="Servicio/"): return db.reference(path).get() def get_required_data(model): if model == 'Products': products = Product.objects.values() return ProductSerializer(products, many=True).data elif model == 'Categories': categories = Category.objects.all() retu...
This function handles a GET request to retrieve and process query data. It fetches a Query object by ID, initializes Firebase with the query's URL, checks if a specified Firebase path exists, retrieves data from the path, and processes the query with the data. If the path doesn't exist, it returns a 404 error; otherwis...
def query_loader(request, id): if request.method == 'GET': object = Query.objects.get(pk=id) query = QuerySerializer(object).data init_firebase(query["url"]) path = "Servicio/"+query["table"] if not path_exists(path): return HttpResponse({'error': 'path not exist'...
def savebtn_active(self, event, trip_name_var): if event.keysym == 'BackSpace': # reads count before button press, had to add this to count right length = len(trip_name_var.get()) - 1 else: # currently counting any button, including 'shift' as input len length =...
This code creates a GUI interface for managing trip details, allowing users to input or edit information such as destination, dates, budget, and notes. It includes save, cancel, and delete functionality, dynamically enabling/disabling features based on whether the trip is new or existing. The interface uses Tkinter wid...
def __init__(self, parent, controller, locatorID=None, costID=None): Frame.__init__(self, parent) self.canvas = Canvas(self, borderwidth=0, height=545) self.frame = Frame(self.canvas) self.canvas.grid(row=1, column=0) self.canvas.create_window((4, 4), window=s...
def Init(populationSize, locations): routes = CreateRoutes(populationSize, locations) return routes def Evaluation(routes): if type(routes) is dict: for (x,y) in routes.items(): temp = (TotalDistance(y[1]), y[1]) routes[x] = temp return routes counter = 0 routeDictionary = {} for x in routes: tempTu...
The code implements a genetic algorithm to find the shortest route in a traveling salesman problem (TSP) by evolving routes through crossover, selection, and mutation. It runs multiple iterations, tracks the best score and route across generations, calculates mean and standard deviation of scores, and displays the opti...
def Start(settings, locations, iterations, problem): shortestScore = 10000000 shortestRoute = [] scores = [] for s in range(iterations): currentShortestScore = 10000000 populationSize = settings.populationSize numberOfGenerations = settings.numberOfGenerations mutationRate = settings.mutationRate initia...
def load_model(self): self.signals.update_progress_LABEL.emit("load_model()", "Loading neural network. This may take a while.") self.model = InpaintNN(bar_model_name = "./models/bar/Train_775000.meta", bar_checkpoint_name = "./models/bar/", m...
The code processes all images in a specified folder by decensoring them using a preloaded model. It checks file validity, handles different decensor types (mosaic/bar), converts images to numpy arrays, tracks progress, and manages errors. Output is saved to a designated directory, with model unloading to prevent memory...
def decensor_all_images_in_folder(self): #load model once at beginning and reuse same model self.load_model() input_color_dir = self.decensor_input_path file_names = os.listdir(input_color_dir) input_dir = self.decensor_input_path output_dir = self.decensor_output_path ...
def __init__(self, R_pz, pos_owner, pos_obs, vel_owner, vel_obs): ''' :param R_pz: radius of protected zone :param pos_owner: position of the aircraft in world frame of X-plane :param pos_obs: position of the obstacle in world frame of X-plane :param vel_owner: velocity of the ai...
The function calculates avoidance velocity (Vavo) for obstacle avoidance using velocity obstacles (VO). It determines if an obstacle lies within the VO, computes the required avoidance maneuver angle (theta), and adjusts the velocity in the world frame. If not in VO or in cruise mode, it retains the original velocity. ...
def cal_Vavo(self, rdata=None, cruise=False, tau=0.1): ''' Calculate avoidance velocity ''' plane_angle, evo, theta = -999, -999, -999 if rdata is not None: pos_owner = rdata[0:3] pos_obs = rdata[6:9] vel_owner = rdata[3:6] vel_obs ...
def create_empty_board(data_board): full_board = [] for column in range(data_board['width']): full_board.append([False] * data_board['height']) return full_board def fill_board_with_snakes(board, data_board): for snake in data_board['snakes']: for point in snake['body']: boar...
The function `choose_move` determines the next move for a Battlesnake by analyzing the game board, avoiding hazards, and prioritizing food proximity. It processes the board state, calculates possible moves, adjusts for latency, removes dangerous paths, weights moves toward food, and selects a direction. The output is a...
def choose_move(data: dict) -> str: """ data: Dictionary of all Game Board data as received from the Battlesnake Engine. For a full example of 'data', see https://docs.battlesnake.com/references/api/sample-move-request return: A String, the single move to make. One of "up", "down", "left" or "right". ...
def get_api_key(): if not os.path.exists(_config_file): return None with open(_config_file, "r") as f: for line in f: if line.startswith("OPENAI_API_KEY="): return line[len("OPENAI_API_KEY="):].strip() return None def prompt_new_key(): apikey_new = Prompt.ask...
The code checks if an OpenAI API key is set; if not, it guides the user to obtain one and stores it. It sets a default model ("chatgpt-3.5-turbo") if none is configured and initializes expert mode to "false" if unspecified. The function ensures required configuration parameters are present for the CLI assistant to func...
def check_config(console): if not get_api_key(): os_uname = os.uname() console.print("--[oai - CLI Assistant]-------\n" "\n" "OpenAI API key not found. Please follow these steps to get the API key:\n" " 1. Go to OpenAI website (http...
def inorder(self, root): """ inorder traversal. traverse from the left subtree to\ the root then to the right subtree. """ inorder = [] if root == self._root.data: self._recurse_for_inorder(self._root, inorder) return inorder def delete_all_nod...
The code rebalances a binary search tree by collecting and sorting its node values, optionally removing a specified value, then reconstructing the tree by recursively adding middle elements of the sorted list as roots to ensure balance.
def rebalance(self, node_val=None): """ changes existing binary search tree. returns new rebalanced tree. """ nodes = self.inorder(self._root.data) nodes.sort() if node_val is not None: try: nodes.remove(node_val) except: ...
def in_hole(self): return mag(self.pos - field.HOLE_POS) <= (-1.0 / 32) * mag(self.v) + field.hole_radius def check_walls(self): if self.pos.y < field.wall_top.y: # middle wall if self.pos.x > field.wall.x > (self.pos + self.v * dt).x: self.collide_with_wall(Vec(1, 0), field...
The main task of the code is to update an object's state in a simulation: if its velocity magnitude exceeds 0.005 and it's not in a hole, it checks walls, moves, and increments time. Otherwise, it calculates fitness metrics and marks the task as complete. The code manages movement, collision detection, and termination ...
def update(self): if mag(self.v) > 0.005 and not self.in_hole(): self.check_walls() self.move() self.t += dt else: if not self.done: self.fitness = self.calculate_fitness() string = "" string += str(self.fitn...
def collision(self): # To check for collision for the player with walls for w in walls: # If player collided with wall if self.rect.colliderect(w.rect): if self.change == 2: # Moving right; Hit the left side of the wall s...
This code handles player movement in a Pygame game, including left/right movement, jumping, collision detection, and view boundary checks. It uses keyboard inputs to adjust the player's position, applies gravity via a separate method, and exits the game on ESC. Jumping triggers a sound and temporary upward motion. Coll...
def move(self): # To get key press k = pygame.key.get_pressed() # To move left if k[pygame.K_LEFT]: self.rect.x -= self.vel self.change = 1 self.collision() self.viewbox() # To move right if k[pygame.K_RIGHT]: ...
def exit_game(self) -> None: """ Shows the final bankroll total and reset the game :return: None """ self.stackedWidget.setCurrentWidget(self.game_over) self.label_final_bankroll.setText(f"Bankroll: ${int(self.bankroll)}") #reset bankroll self.bankroll ...
The code's main task is to deal cards to the dealer until their total reaches 17, determine the winner based on player/dealer totals, update UI elements (labels, buttons), adjust bankroll, and handle game outcomes like wins, ties, or exits if the player's bankroll reaches zero.
def stand(self) -> None: """ Deals cards to the dealer until dealer's total is >= 17 and determines the winner :return: None """ self.label_dealer1.setPixmap(self.pos_2_pixmap) self.button_hit.setEnabled(False) self.button_stand.setEnabled(False) self....
def shuffle(self) -> None: """ Shuffle the cards and displays them on the screen :return: None """ #close shuffle button self.button_shuffle.setEnabled(False) #clear textboxes self.label_result.setText("") self.label_dealer_total.setText("") ...
The code initializes a GUI object, sets up the interface with a window title and icon, connects buttons to methods for navigating between screens (main menu, game, instructions), configures a bet slider, initializes a bankroll, and disables certain buttons initially. It links actions like shuffling, hitting, standing, ...
def __init__(self, *args, **kwargs) -> None: """ Initializes object and connects all the buttons to their methods :return: None """ super().__init__(*args, **kwargs) self.setupUi(self) #set window icon and name self.setWindowTitle("Black Jack!") ...
def menu_analyze_raw_data(): """Menu for analyzing raw dataset.""" # ASCII art for the title tprint("Raw Data Analysis") print("📊 The following plot will help visualize and analyze the relationship between various features (independent variables) and the target variable (dependent variable) in th...
The code defines a main menu function that displays options for analyzing raw data, viewing model training results, predicting insurance costs, or exiting. It loops until the user selects '0' to exit, handling invalid inputs by prompting retries. Each menu option directs to corresponding sub-functions for specific task...
def main_menu(): """Main menu for the program.""" while True: tprint("Main Menu") print("1. Analyze Raw Data") print("2. Show the Models' Training Results") print("3. Predict the Cost of Insurance") print("0. Exit\n") choice = input(str_choiceSelection) ...
def needs_wipe(self, wipe: bool) -> bool: """ requires CMake >= 3.14 uses cmake-file-api https://cmake.org/cmake/help/latest/manual/cmake-file-api.7.html index file is largest in lexiographical order: https://cmake.org/cmake/help/latest/manual/cmake-file-api.7.html#v1-...
This code configures and builds a CMake project by checking for required files, optionally cleaning previous builds via the 'wipe' flag, generating build files, compiling the project, running tests, and installing the resulting binaries or libraries.
def config(self, wipe: bool = False): """ attempt to build using CMake >= 3 """ cmakelists = self.source_dir / 'CMakeLists.txt' if not cmakelists.is_file(): raise FileNotFoundError(cmakelists) # %% wipe if self.needs_wipe(wipe): Path(self.bui...
def takahashi(self, feedback, debug=True): err = self.proportional(feedback) ret = self.f_hist[-1] + self.Kc * (self.feedback_hist[-1] - feedback + self.Ts * err/ self.Ti + self.Td / self.Ts * (2*self.feedback_hist[-1] - feedback - self.feedback_hist[-2])) self.error_hist+=[err] self.f...
This function computes a PID control value based on the specified controller type (Takahashi, discrete, or default), clips it within predefined bounds (F_MIN to F_MAX), and applies a decay adjustment if consecutive feedback zeros are detected. It returns the adjusted PID value while maintaining a history of outputs for...
def pid_clipped(self, feedback, controller=CONTROLLER_TYPE_DISCRETE, debug=True): pid_value = None if controller == CONTROLLER_TYPE_TAKAHASHI: pid_value = self.takahashi(feedback, debug) elif controller == CONTROLLER_TYPE_DISCRETE: pid_value = self.discrete_pid(feedback, ...
def number(): return input("Enter the number- ") def string_obt(dict_,num,n): a='' b=[""] for i in range (0,len(num)): count=1 if i+1!=len(num): while num[i]==num[i+1]: count+=1 i+=1 if i+1==len(num): break ...
The code converts a numeric input into corresponding letters based on a telephone keypad mapping, generating and displaying all possible letter combinations for the given number.
def project(): dict_={1:'', 2:'ABC', 3:'DEF', 4:'GHI', 5:'JKL', 6: 'MNO', 7: 'PQRS', 8: 'TUV', 9: 'WXYZ', 0:''} x=number() y=string_obt(dict_,x,len(x)) display(y)
def event_manage(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit sys.exit() elif self.menu: if event.type == pygame.KEYDOWN: if event.key == pygame.K_SP...
The code defines a `play` method that runs a game loop while `self.running` is True. It controls the frame rate using `self.clock.tick(FPS)`, processes events with `self.event_manage()`, updates game state via `self.update()`, and renders the game screen with `self.render()`. The main task is to maintain the game's exe...
def play(self): while self.running: self.clock.tick(FPS) self.event_manage() self.update() self.render()
def get_notification_policies(self): resp = self.get("api/v1/provisioning/policies") return json.loads(resp.content.decode('utf8')) def get_matcher_value(self, notification_policy_route, label): for matcher in notification_policy_route["object_matchers"]: if matcher[0] == label: ...
The function deletes notification routes and alert rules associated with a specific dashboard UID. It filters out routes matching the dashboard_uid, collects corresponding alert rule IDs, updates the notification policies by removing those routes, saves the modified policies, and deletes the identified alert rules.
def delete_policies_and_alert_rules_by_dashboard_uid(self, dashboard_uid): policies = self.get_notification_policies() new_routes = [] alert_rule_uids_to_delete = [] for route in policies["routes"]: if self.get_matcher_value(route, "dashboard_uid") == dashboard_uid: ...
def voltages(self, power: NumberLike, phase: NumberLike, Cs: Union[NumberLike, None] = None) -> NumberLike: """ Voltages at the antenna front face ports (after capacitors). Parameters ---------- power : list or array Input power at external ports in ...
The function `Rc_WEST` calculates the coupling resistances of both sides of an antenna using the WEST approximation. It computes resistances based on input power, phase, and optional capacitances, deriving voltages, reactance, and coupled power to apply the formula $ R_c = 2P_t / I_s^2 $. The result is an array of resi...
def Rc_WEST(self, power: NumberLike, phase: NumberLike, Cs: Union[NumberLike, None] = None) -> NumberLike: """ Coupling Resistances of both sides of the antenna - WEST Approximation. .. math:: R_c = 2 P_t / I_s^2 where: * Pt is the transmitted (coup...
def Table(self): states = self.getCannonicalCollection() table = [{} for ind in range(len(states))] for state in states: print(state) index = 0 for state in states: FirstRule = 0 SecondRule = 0 ThirdRule = 0 for prod ...
This code parses an input sequence using a parsing table, applying shift, reduce, and accept actions to build a parse output. It maintains stacks for parsing and input symbols, processes grammar rules, and handles errors like invalid symbols. The output tracks reduction steps, which are then formatted and returned as a...
def parse(self, inputSequence): table = self.Table() self.parsingStack = ['0'] self.inputStack = [symbol for symbol in inputSequence] self.output = [] print(table) while len(self.parsingStack) != 0: state = int(self.parsingStack[-1]) if len(sel...
def create_widgets(self): # configure root frame to expand self.root.rowconfigure(0, weight=1) self.root.columnconfigure(0, weight=1) # configure master frame master = tk.CTkFrame(self.root, border_width=1, fg_color=self.ui_bg_color) master.grid(row=0, column=0, sticky="...
This code initializes a GUI application with a custom window size and appearance settings, sets up event bindings for resizing and sending messages, and launches a chatbot interface with a splash screen type.
def __init__(self): self.root = tk.CTk() tk.set_appearance_mode("dark") if DARK_MODE else tk.set_appearance_mode("light") self.ui_text_color = ("black","white") self.ui_bg_color = ("#dedede", "#444444") custom_width = int(self.root.winfo_screenwidth() * 0.2) custom_heigh...
def load_slugs(album_path) -> dict: # iterates over all the songs, and either takes it's 'Directory' field or calculates it # by using normalize_wiki_string, then adds it to a dictionary with 'track:slug' as the key # and the full track name (song['Track']) as the key album_names = [os.path.splitext(alb...
The function processes music data to generate game-compatible songs by filtering tracks based on leitmotif thresholds, combining old and newly filtered songs, sorting motif guesses by rarity, and storing results. It counts attributes like album names, URL types, and rarity, then returns the curated song list for game u...
def get_game_data(store: bool = True) -> List[object]: file_path = os.path.dirname(os.path.realpath(__file__)) hsmusic_data_path = os.path.join(file_path, 'hsmusic-data') album_path = os.path.join(hsmusic_data_path, 'album') slugs_dict = load_slugs(album_path) # check if an old song file exist...
def gen_signal(mac1, mac2, op): return Ether(src=mac2) / ARP(hwdst=mac2, hwsrc=mac1, op=op) def gen_msg(keys, secrets): for c in msg: key = int.from_bytes(gen_key(), "little") secret = gen_secret(ord(c), key) keys.append(key) secrets.append(secret) def gen_mac(secrets, keys): ...
The main task of the code is to generate and transmit a sequence of ARP packets using derived MAC addresses from keys and secrets. It creates start/stop signals, processes data in chunks of three, generates MACs and ARP packets, then sends them via the loopback interface for local testing or simulation.
def main(): keys = [] secrets = [] macs = [] pkt = [] start = gen_signal(signal1, signal2, 1) stop = gen_signal(signal2, signal1, 2) gen_msg(keys, secrets) for i in range(0, len(keys), 3): macs.append(gen_mac(secrets[i:i+3], keys[i:i+3])) if len(macs) % 3 != 0: for i...
def _check_events(self): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pyg...
The code runs the game's main loop, continuously checking for events, updating game elements (ship, bullets, aliens) when active, creating new aliens, and rendering the screen at 60 FPS to maintain gameplay flow and responsiveness.
def run_game(self): """Start the main loop for the game.""" while True: self._check_events() if self.game_active: # Consider creating a new alien. self._create_alien() self.ship.update() self._update_bullets() ...
def normalize_objects(obj_values_lst: list) -> list: """ This func normalize all the objects. it sends single object to sub-function each time. """ normalized_list = [] for obj in obj_values_lst: if type(obj) is str or type(obj) is int or type(obj) is float: obj = list(obj) ...
This function normalizes input data to 1NF form, replaces values with foreign keys based on specified relationships, and inserts the processed data into a database table. It handles normalization, foreign key matching, and database insertion, ensuring data integrity through parameter validation and conditional processi...
def data_to_db(table: MetaData, obj_values_lst: list, normalized: bool = False, unique_column: str = None, inherit_from=None, match_fk_col: list = None, match_val_col: list = None, replace_val_col: list = [1]): """ This is the main function. it accepts all required values for all t...
def get_greys(words, nums): greys = [] for word, coln in zip(words, nums): for index, letter in enumerate(word): col = numtoternary(coln) # any letter on a grey tile is added to the list of grey letters. # (note that this includes tiles which are otherwise green/yello...
The function recursively generates valid solutions by exploring options while adhering to hardmode constraints, returning the first valid solution found or None if none exist. It uses backtracking to build solutions step-by-step, checking each option against rules defined by the 'table' and 'nums' parameters.
def recursive_backtracker(selected, options, nums, table): solutions = [] # if we have reached the target length with options left to play in that position, we may have a solution. if len(selected) == (len(nums)-1) and len(options) > 0: # attempt to play each option. greys = get_greys(selec...
def get_greys(words, nums): greys = [] for word, coln in zip(words, nums): for index, letter in enumerate(word): col = numtoternary(coln) # any letter on a grey tile is added to the list of grey letters. # (note that this includes tiles which are otherwise green/yello...
The function implements a backtracking algorithm to find valid sequences of options that satisfy specific constraints (like "hardmode") while building up a solution. It recursively explores possible options, checks their validity against predefined rules, and collects solutions while avoiding duplicates. If no valid pa...
def recursive_backtracker(selected, options, nums, table): solutions = [] # if we have reached the target length with options left to play in that position, we may have a solution. if len(selected) == (len(nums)-1) and len(options) > 0: # attempt to play each option. greys = get_greys(selec...
def get_dates_between(start_date, end_date): dates = [] current_date = start_date while current_date < end_date: dates.append(current_date) current_date += datetime.timedelta(days=1) return dates def get_dates_from_weather_data(pid): cursor = db.cursor() query = f"SELECT date_t...
The main task of the code is to calculate and store photovoltaic (PV) energy output for a project's products using weather data. It identifies missing weather dates, retrieves existing data, computes irradiance and energy output for each product, and inserts the results into a database. The process involves filling wea...
def start_cal_naturally(project, company_details): cursor = db.cursor() today = datetime.datetime.now().date() # Calculate the date of yesterday daybefore = today - datetime.timedelta(days=2) dates_between = get_dates_between(project['start'].date(), daybefore) dates_already = get_dates_from_...
def set_decay_sparse_layer(net,decay): for mod in net.modules(): if isinstance(mod, SparseConv) or isinstance(mod, SparseLinear): mod.decay = decay def validate(val_loader, model, criterion, epoch, writer): batch_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() ...
The main task of the code is to train a neural network model with distributed computing, incorporating sparsity and pruning strategies. It loads configurations, initializes a model with specific parameters (N, M), sets up distributed training with NCCL, defines optimizers, and processes data with distributed samplers. ...
def main(): global args, best_prec1 args = parser.parse_args() with open(args.config) as f: config = yaml.load(f) for key in config: for k, v in config[key].items(): setattr(args, k, v) # print(args.Ns) # exit(0) print('Enabled distributed training.') ran...
def get_chunk_consumptions_fit_delay(consumption_sign, load_learner, solar_learner, timestep, load_error_24hours_ago): max_chunk_size = 32 if timestep + max_chunk_size > 8759: max_chunk_size = 8759 - timestep loads = load_learner.predict_load(max_chunk_size) solars = solar_learner.predict_sola...
The function calculates the next time chunk's charge loads based on consumption patterns. It uses either negative or positive consumption scenarios, adjusting for date shifts and battery constraints, to determine optimal charge loads for a given timestep and agent.
def calculate_next_chunk(observation, consumption_sign, agent_id, timestep, remaining_battery_capacity, soc, load_learner, solar_learner, load_error_24hours_ago): chunk_consumptions = get_chunk_consumptions_fit_delay(consumption_sign, load_learner, solar_learner, timestep, load_error_24hour...
def set_evaluation_bounds(self, timestep): if timestep == self.evaluation_timesteps[self.evaluation_ind]: self.evaluation_left_bound = self.evaluation_timesteps[self.evaluation_ind] self.evaluation_right_bound = self.evaluation_left_bound + self.evaluation_period self.evaluat...
This function predicts a consumption policy for a battery agent by forecasting load and solar generation, adjusting for historical forecast errors, and determining a charge action based on the difference between predicted load and solar output. It uses machine learning models to update forecasts, evaluates performance ...
def pred_consumption_policy(self, observation, timestep, agent_id, remaining_battery_capacity, soc, write_to_file): if timestep >= 8758: return -1 self.set_evaluation_bounds(timestep) self.update_load_forecasters(agent_id, timestep, observation[20]) self.update_solar_forecas...
def squareUnderAttack(self, r ,c): self.whiteToMove = not self.whiteToMove oppMoves = self.getAllPossibleMoves() self.whiteToMove = not self.whiteToMove for move in oppMoves: if move.endRow == r and move.endCol == c: return True return False def getKin...
This function generates valid castling moves for the king based on current turn and castling rights. It checks if the king's starting square is under attack, then adds kingside/queenside castling moves to the 'moves' list if respective castling permissions exist for the current player.
def getCastleMoves(self, r, c, moves): if self.squareUnderAttack(r, c): return if (self.whiteToMove and self.currentCastlingRights.wks) or (not self.whiteToMove and self.currentCastlingRights.bks): self.getKingsideCastleMoves(r, c, moves) if (self.whiteToMove and self.cur...
def getAllPossibleMoves(self): moves = [] for r in range(len(self.board)): for c in range(len(self.board)): turn = self.board[r][c][0] if (turn == "w" and self.whiteToMove) or (turn == "b" and not self.whiteToMove): piece = self.board[r][c]...
This function generates valid moves by simulating each possible move, checking if it leaves the king in check, and removing invalid moves. It handles castling, en passant, and updates checkmate/stalemate status. Temporarily stores and restores game state variables before returning the filtered list of legal moves.
def getValidMoves(self): tempEnpassantPossible = self.enpassantPossible tempCastleRights = CastleRights(self.currentCastlingRights.wks, self.currentCastlingRights.bks, self.currentCastlingRights.wqs, self.currentCastlingRights.bqs) moves = self.getAllPossi...
def split_plays(input_content: list) -> list[str]: return [play.split() for play in input_content] def translate_plays(input_content: list) -> list[list[str]]: plays = [] for play in input_content: tmp = [] tmp.append(APPOINENT_OPTIONS[play[0].lower()]) tmp.append(ELF_OPTIONS[play[1]...
The code processes a list of game plays by splitting them into individual rounds, translating the play formats into a processable structure, and calculating the total score based on the game's rules. The main task is to determine the final score after evaluating all plays according to the game's scoring system.
def part_one(input_content: list) -> int: split = split_plays(input_content) plays = translate_plays(split) return determine_score(plays)
def split_plays(input_content: list) -> list[str]: return [play.split() for play in input_content] def get_desired_result(plays: list) -> list: new_plays = [] for play in plays: tmp = [] tmp.append(APPOINENT_OPTIONS[play[0].lower()]) if ACTUAL_ELF_OPTIONS[play[1].lower()] == "win": ...
The function processes a list of input content by splitting it into plays, transforming them into a desired format, calculating a score based on the transformed data, and returning that score.
def part_two(input_content: list) -> int: split = split_plays(input_content) new_plays = get_desired_result(split) print(new_plays) return determine_score(new_plays)
def split_chars(input_content: list) -> list: return [*input_content[0]] def part_one(input_content: list) -> int: return find_start_marker(input_content) def part_two(input_content: list) -> int: return find_start_marker(input_content, 14)
The code processes input data for a programming problem, reading either test or actual input from a specified directory, splitting the content into individual characters, and executing two solution parts (part_one and part_two) to compute and print results.
def run(test: bool = None): if not test: test = is_testing() directory = "/Users/markmcwhirter/Documents/personal/adventofcode2022/days/six/" input_file = "test.txt" if test else "input.txt" input_content = filetostringlist(f"{directory}{input_file}") input_content = split_chars(input_conten...
def respond_to_room(self, room_content): """ respond_to_room(self, room_content) method that allows the adventurer to interact with what is in the new room parameters: room_content return: None """ if room_content == "X": self.hp_decrease() print(f"Ain't that the pits! You fell i...
This code handles user movement and actions in a game. It processes input (WASD, H, V, I, Q) to move the adventurer between rooms, use potions, view stats, or quit. It manages enhanced vision cooldowns, potion inventory, and recursive movement retries if directions are blocked.
def move(self, north_room, south_room, west_room, east_room): """ move(self, north_room, south_room, west_room, east_room) method that contains logic for user moves parameters: north_room, south_room, west_room, east_room return: None """ if self.enhanced_vision: self.cooldown -= 1 ...
def printUsage(): print('To run this program please type the following:') print('\tpython duplexCallerModified_AWS.py bamFile=file.bam positionFile=file.bed referenceGenome=file.fa outDIR=Results index=1\n') print('Where:\n') print('\tfile.bam is a bam file.\n') print('\tfile.bed is a bed-like file...
The main task of the code is to process a BAM file to identify variants at specified genomic positions using threading. It parses input parameters, splits the BAM by chromosomes, generates target SAM and flat files, processes reads in parallel, and produces variant reports while cleaning intermediate files.
def myMain(): #check the number of input arguments if len(sys.argv)!=6: printUsage() else: bamFile=sys.argv[1].split('bamFile=') bamFile=bamFile[1] bedFile=sys.argv[2].split('positionFile=') bedFile=bedFile[1] refGenome=sys.argv[3].split('ref...
def patrol(client): # Function to patrol certain parts of the room to find first two QR codes waypoints = [ [-4.0, 0.35], [5.8, -0.13] ] for i in range(len(waypoints)): x = waypoints[i][0] y = waypoints[i][1] print("Going to position X:{}, Y:{} ".format(x,y)) goal = goHere(x,y...
The code navigates a robot to locate and decode five QR codes, using their positions to compute a transformation matrix. It iteratively moves toward predicted QR locations, extracts hidden data, and assembles a secret message from the decoded information. The robot adjusts its path based on previous QR data, ensuring a...
def main(): # The main function - where all the magic happens. global read global place rospy.Subscriber("/visp_auto_tracker/status", Int8, qrStatusCallback) client = actionlib.SimpleActionClient('move_base', MoveBaseAction) client.wait_for_server() read = 0 infoList = [None, None, None, None, N...