dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def __run(self): self.__setup_con() self.__process_mailbox(self.__data, self.__messages_data) def __start_cleanup(self): try: if ELK_MODE == "read": print("ELK_MODE is read, not deleting mail") elif ELK_MODE == "write": self.__cleanup()...
The main task of the code is to execute the `__run()` method, print "Done mailbox", and initiate cleanup via `__start_cleanup()`. If an exception occurs, it logs the error, logs out using `__M.logout()`, and recursively restarts `start_run()` to retry the process. The code ensures process execution, error handling, and...
def start_run(self): try: self.__run() print("Done mailbox") self.__start_cleanup() except Exception as e: print(e) self.__M.logout() self.start_run()
def init(self, size): self.root = [i for i in range(size)] self.rank = [1]*size self.size = size def union(self, x, y): rootX = self.find(x) rootY = self.find(y) if rootX != rootY: if self.rank[rootX] > self.rank[rootY]: ...
The code determines the number of provinces (connected components) in a graph represented by an adjacency matrix. It uses a Disjoint Set Union (DSU) structure to group connected nodes, iterating through the matrix to union nodes with connections, then returning the count of distinct provinces.
def findCircleNum(self, isConnected: List[List[int]]) -> int: size = len(isConnected[0]) self.init(size) for i in range(size): for j in range(size): if isConnected[i][j] == 1: self.union(i, j) return self.provinces()
def query(cmd): """ Input: Query we want to send to psql Calls _query with an argument to fetch something. Output: _query """ return _query(cmd, True) def make_safe(s): """ Input: String Makes a string safe by ensuring that it is not empty and replacing ' with " so that the strin...
The function registers a new user by validating non-empty inputs, checking for existing usernames in a PostgreSQL database, hashing the password with bcrypt, and inserting the user data into the 'users' table, returning success/failure messages accordingly.
def register_user(uname, psword): """ Input: Strings (Username, Password) Checks whether a username already exists and if the user filled out all fields. Then it hashes the password and stores all the data in the psql table 'users' Output: String that indicates the success of this function """ ...
def dicto(self): #dictionary of stock global pcode pcode = {self.searched1.get():self.searched11.get(), self.searched2.get():self.searched12.get(), self.searched3.get():self.searched13.get(), self.searched4.get():self.searched14.get(), ...
This code initializes a GUI application with sections for stock count, wastage, meal planning, and reporting. It creates input fields for product codes and quantities, organizes them into labeled frames, and adds submit buttons to process data. The 'Report' section includes buttons to generate reports, meal lists, stoc...
def __init__(self, workspace): global f4 workspace.title("{}".format(site)) l1 = Label (workspace, text = "Welcome to {}".format(site)).grid(row = 0, column =0, columnspan =3) f1 = LabelFrame (workspace, text = "Stock Count", width = 3, bd = 5, padx = 5, pady = 5) ...
def myprint(print_str, logfile): with open(logfile, 'a') as fp: fp.write(print_str + '\n') def computepD(data, R, return_fit=False, fit_length=5): if len(data) == 0: return 0 rr = [] Sqr = [] for j in range(R+1): r = 1/np.power(2.0, j) Sr = computeSr(data, r) ...
The main task of the code is to iteratively prune non-essential attributes from a group $ G $ based on statistical significance thresholds defined by $ \epsilon $, recursively checking each attribute's contribution to the group's predictive density. It constructs a correlation base $ B $, then removes attributes from $...
def findGroup(data, SG, R, epsilon): print('<findGroup> SG:', SG) myprint('<findGroup> SG: {}'.format(SG), log_file) # step 1 G = np.copy(SG) # {a1, a2, ..., ak} B = np.array([], dtype=np.int32) pd_k = computepD(data[:, [SG[-1]]], R) # iC(ak) for attr_indx in range(len(SG)-1): G_rem...
def myprint(print_str, logfile): with open(logfile, 'a') as fp: fp.write(print_str + '\n') def computepD(data, R, return_fit=False, fit_length=5): if len(data) == 0: return 0 rr = [] Sqr = [] for j in range(R+1): r = 1/np.power(2.0, j) Sr = computeSr(data, r) ...
The FD_ASE algorithm identifies correlation groups (Gs) and their associated bases (Bs) from a dataset by iteratively selecting attributes based on statistical criteria. It processes attributes in descending order, using pD values and epsilon thresholds to determine relevance. The algorithm checks if adding attributes ...
def FD_ASE(data, R, epsilon, A_): valid_result = True N, E = np.shape(data) print('start to run the FD_ASE algorithm to search correlation groups !\n\n') myprint('start to run the FD_ASE algorithm to search correlation groups !\n\n', log_file) Gs = [] # the correlation groups Bs = [] # the co...
def get_opening(self, line): try: temp = re.search(self.st, line).group except AttributeError as e: temp = None if temp: #res = self.clean_group(temp) if not self.already_exists('OPENING', temp(1)): try: self.conn.execute('INSERT INTO OPENING VALUES("' + temp(1) +'", "' + self.name + '")') ...
The code scans a script file to identify and process specific rules (e.g., decomposition, reassembly, substitution) and keywords. It reads lines sequentially, triggers processing after detecting an opening marker, and checks each line against predefined methods to determine its type. The function closes the connection ...
def scan_file(self, script): with open(script) as f: start = False for line in f: line = line.strip() if self.get_opening(line) and start == False: start = True else: if self.get_keyword(line): pass elif self.get_decomposition_rule(line): pass elif self.get_reassembly...
def create_script(self, name): if not self.already_exists('SCRIPT', name): self.conn.execute('INSERT INTO SCRIPT VALUES("' + self.name + '")') self.conn.commit() def compile_re(self): self.st = re.compile(r'START: (.*)') self.kw = re.compile(r'Keyword: (.*)') self.dr = re.compile(r'D-Rule: (.*)') self.a...
The code initializes a class instance by connecting to an SQLite database, setting the script name, creating a database structure, compiling regular expressions, and scanning the script file for processing.
def __init__(self, script): self.conn = sqlite3.connect('testdb') self.name = script self.create_script(self.name) self.compile_re() self.scan_file(self.name)
def sub_specials(self, user_input): specials = [',', '.'] user_input = re.sub(r'\?', '', user_input).lower() for special in specials: if special in user_input: user_input = user_input.split(special)[-1] self.user_inputs = user_input.strip().split(' ') def substitute(self): #Substitute selected words be...
The code processes user input by checking for an 'exit' command to terminate the program, otherwise it passes the input through a series of methods (`sub_specials`, `substitute`, and `transform`) for analysis and transformation. The main task is to handle user input, execute exit logic, and apply processing steps to th...
def parse_input(self): #Collect the user input for analysis. self.keystack = [] capture = input() if capture.lower() == 'exit': self.conn.close() sys.exit() else: self.sub_specials(capture) self.substitute() self.transform()
def get_model(): map_col = dict() map_col['traffic_volume_past'] = 0 set_seed(33) ### encoder ### inp = Input(shape=(sequence_length, 1)) inp_original = Input(shape=(sequence_length, 1)) cat_inp = [] cat_emb = [] for cat, i in map_col.items(): inp_c = Input(shape=(sequen...
The code trains a Variational Autoencoder (VAE) model for time-series data. If retraining is enabled, it loads a pre-trained model. Otherwise, it processes input data into sequences, scales them, and trains the VAE from scratch using early stopping. The model is saved post-training for future use.
def Train_Model(vae, es, matrix, sets_training, retraining, dataset): if retraining: es = EarlyStopping(patience=10, verbose=1, min_delta=0.001, monitor='loss', mode='auto', restore_best_weights=True) vae, enc, dec = get_model() vae.load_weights(f"trained_models...
def unpack_bool(self) -> bool: base = self._xdrfile.unpack_uint() return base != 0 def get_obj_type(self) -> Optional[int]: try: typ = self._xdrfile.unpack_uint() # XDR does not support short return typ except EOFError: return None def process_materia...
This method processes a file's data by reading and handling different object types (materials, centers, headers, etc.), ensuring it's only processed once unless forced. It resets the file position if forced, reads version info, configures precision handling, and iterates through objects, appending them to lists or rais...
def process(self, force: bool = False): if self._processed and not force: return if self._processed and force: self._xdrfile.set_position(0) self._processed = True self._file_ver = self._xdrfile.unpack_uint() self._allow_double_precision = self.unpack_b...
def load_and_create(): """ Load habits from json file and create habit class objects. Data contains no decreasing dates, but dates can be repeated (many times practicing during one day or one week). """ with open('HabitTrackerData.json') as a: data = json.load(a) for ind...
The main task of the code is to run a Habit Tracker application that loads and creates habit data, presents user habits in a loop, and saves progress to a JSON file before exiting. It initializes the interface, manages habit display, and ensures data persistence.
def main(): os.system('cls') print("\n \nWelcome to Habit Tracker v.2.1 \n \nTrack, maintain and support good habits!\n****************************************") load_and_create() quit_check = False while quit_check == False: quit_check = presenting_habits() print("Saving data t...
def get_skype_token(): token_bundle = get_access_token_with_refresh_token( "00b41c95-dab0-4487-9791-b9d2c32c80f2", "https://api.spaces.skype.com" ) headers = { "Host": "teams.microsoft.com", "Authorization": "Bearer {0}".format(token_bundle["access_token"]), "Connection": "cl...
The main task of the code is to download recent Skype conversations by retrieving the user's token and conversation IDs, then saving each conversation's messages into uniquely named folders under the "./teams" directory. It prints progress updates and uses API calls to fetch data and store messages locally.
def download_recent_chats(): print(Fore.GREEN +"[+] Getting recent conversations") path = "./teams" skype_token = get_skype_token() skype_user_id = get_skype_id_from_jwt(skype_token) conversations = skype_api_get_recent_conversations(skype_token) for conversation in conversations: conve...
def ms_graph_get_all_paginated_data_via_nextLink(token, url): headers = { "Host": "graph.microsoft.com", "Authorization": "Bearer {0}".format(token), } graph_results = [] url = url while url: graph_result = request_retry(url, headers).json() graph_results.extend(gra...
This function recursively retrieves and creates local directory structures mirroring Microsoft Mail folders, downloading emails while preserving folder hierarchy. It uses the Microsoft Graph API to fetch child folders, creates corresponding local folders, downloads emails from each folder, and recursively processes nes...
def get_and_create_mail_child_folders(token, folder_id, parent_folder_path): graph_results = ms_graph_get_all_paginated_data_via_nextLink(token,"https://graph.microsoft.com/v1.0/me/mailFolders/{0}/childFolders?includeHiddenFolders=true".format(folder_id)) for folder in graph_results: full_path = o...
def ms_graph_get_all_paginated_data_via_nextLink(token, url): headers = { "Host": "graph.microsoft.com", "Authorization": "Bearer {0}".format(token), } graph_results = [] url = url while url: graph_result = request_retry(url, headers).json() graph_results.extend(gra...
The code synchronizes a user's mailbox structure from Microsoft Graph by creating local folders, downloading all emails within each, and recursively handling nested child folders to mirror the remote mailbox hierarchy locally.
def create_mail_root_folders(token): main_folders = ms_graph_get_all_paginated_data_via_nextLink(token,"https://graph.microsoft.com/v1.0/me/mailFolders?includeHiddenFolders=true") for folder in main_folders: folder_path = os.path.normpath("./mails/" + folder["displayName"]) create_folder(folde...
def greeting(): title = " * U.S. Notify Python Client Demo * " short_stripe = " " * 26 long_stripe = " " * 37 c = Console() print("") c.print(" ********* ", style="white on navy_blue", end="") c.print(short_stripe, style="black on white") c.print(" ********* ", style="white on navy_blue...
The main task of the code is to send notifications via a NotificationsAPIClient by allowing user input to select between SMS or email templates, retrieve a chosen template's ID and personalization details, and prompt the user to confirm sending the notification. The code initializes an API client, greets the user, coll...
def main(): # must pass in base_url, as the default is notify.uk's production URL client = NotificationsAPIClient(concat_api_key, base_url=base_url) # introduce yourself greeting() # and ask if SMS or email template is desired template_type = intro() # present selections for SMS/email tem...
def useVision(): global fightDeck fightDeck = [] for i in range(0, 3): fightDeck.append(drawFightCard()) displayFightCard(fightDeck[i]) choice1 = int(input("Enter the first card you want to see in deck")) fightDeck.insert(0, fightDeck.pop(choice1 - 1)) for i in range(0, 3): ...
The code allows a user to select a card from a list, checks if it's already tapped, and either displays its ability or triggers specific actions based on the card's type (e.g., Vision, Realization). If not tapped, it activates the card's ability by calling corresponding functions like `useVision()` or `usePhase()`, wit...
def useAbility(hazardCard): global missionList, fightDeck choice = int(input("Which card do you want to use")) if missionList[choice - 1].isTapped(): print(missionList[choice-1].ability) print("Card already tapped") else: missionList[choice - 1].tapCard() if missionList[c...
def drawHazardCard(): global hazardsDeck, hazardDiscards drawnCard = hazardsDeck[0] hazardDiscards.append(drawnCard) hazardsDeck.pop(0) return drawnCard def refillHazards(discards): deck = list(discards) for i in deck: i.increaseAlert() shuffle(deck) discards.clear() retu...
The main task of the code is to handle hazard card selection during a game. It checks if the hazards deck needs refilling, displays the top two hazard cards, lets the player choose one, starts a mission with the selected card, and discards the unused card. The function manages deck refilling, card display, player input...
def startHazard(): global hazardsDeck, hazardDiscards, fightDeck, fightDeckDiscards, missionList # Refilling Deck doesn't work with end game if len(hazardsDeck) == 1: drawHazardCard() cards = list(refillHazards(hazardDiscards)) if len(hazardsDeck) == 0: cards = list(refillHazards...
def _read_project(root): result = {'root': root} _safe_read(result, 'setup.py') _safe_read(result, 'setup.cfg') requirements = {} result['requirements'] = requirements target_files = [ 'requirements.txt', 'tools/pip-requires', 'test-requirements.txt', 'tools/test-requires', ]...
The function processes a project's dependencies by reading its configuration, parsing global requirements from a file, generating update actions based on parameters like suffix and softupdate, and then applying these changes to the project structure, with options for output and verbosity.
def _do_main( root, source, suffix, softupdate, hacking, stdout, verbose, non_std_reqs): """No options or environment variable access from here on in.""" project = _read_project(root) global_req_content = open( os.path.join(source, 'global-requirements.txt'), 'rt').read() global_...
def configure_env_file(env_file: Path) -> None: """Set a different environment variable file if different one is given""" global ENV_FILE if ENV_FILE == env_file: print(f"Using preconfigured ENV: {env_file}") else: ENV_FILE = env_file print(f"Using given ENV: {env_file}") def add...
The main task of the code is to handle environment file operations based on user-specified actions. It configures an environment file, then processes commands like adding, showing, editing, or deleting entries using key-value pairs or patterns. The function executes corresponding operations (add_entry, show_entries, ed...
def main(args): configure_env_file(args.env_file) match args.action: case "add": print(f"~> Add a new entry '{args.key}' -> '{args.value}'") add_entry(args.key, args.value) case "show": print(f"~> Showing entries by pattern '{args.pattern}'") show_...
def fit(self, data, silent=False): """ Fit the MMSBM with the given data. :param data: {dataframe} of shape (n_samples, 3) The input data. The first column has to be the user identifier, the second column the item identifier and the third the rating. :param silent...
The main task of the code is to perform cross-validation for the MMSBM model by splitting data into folds, training the model on each training subset, evaluating its accuracy on the test subset, and retaining the best model parameters (theta, eta, pr, prediction matrix) corresponding to the highest accuracy across all ...
def cv_fit(self, data, folds=5): """ Fit MMSBM with 'folds' fold cross-validation. :param data: {dataframe} of shape (n_samples, 3) The input data. The first column has to be the user identifier, the second column the item identifier and the third the rating. :par...
def crossValidation(dataset, k=5): dataset_copy = list(dataset) fold_size = int(len(dataset) / k) folds = [] for i in range(k): fold = [] while len(fold) < fold_size: index = random.randrange(len(dataset_copy)) fold.append(dataset_copy.pop(index)) folds.ap...
The code evaluates a logistic regression algorithm using cross-validation. It splits the dataset into folds, iterates through each fold as a test set, trains on the remaining data, predicts outcomes, calculates accuracy scores for each fold, and returns a list of these scores to assess algorithm performance.
def evaluateAlgorithm(dataset, epochs, alpha): scores = [] folds = crossValidation(dataset) for fold in folds: train = list(folds) train.remove(fold) train = sum(train, []) test = [] for row in fold: rowcopy = list(row) rowcopy[-1] = None ...
def administer_test(problem_set): # this function will take in a problem set and administer it and return an operation_incorrect_dictionary if len(problem_set) == 0: print("you're too smart for my services.") print("come back with someone dumber.") print("bye-bye!") return to...
The main task of the code is to generate a diagnostic test, analyze incorrect answers to create a personalized test, and administer the personalized test. The `main()` function first uses `diagnostic_test_generator()` to create an initial test, then collects results in `operation_incorrect_dictionary`. It subsequently ...
def main(): operation_incorrect_dictionary = administer_test(diagnostic_test_generator()) personalized_test = personalized_test_generator(operation_incorrect_dictionary) administer_test(personalized_test)
def simulation_step(self): for uav in self.uavs.values(): uav.simulation_step() for car in self.cars.values(): if car.reached_segment_end: # No explicit looping different_segments = self.topology.neighbor_segments_to(car.segment) d...
This function simulates a process step-by-step, generating visualizations of each step's state (main simulation and network topology) as PNG images. It compiles these into GIFs, stores detailed simulation data (network structure, vehicle positions, metrics) in a dictionary, and saves this data to a pickle file. The pro...
def save_simulation_with_graphics(self, steps: int, filename: str = "out.gif", data_out_filename: str = None): with Bar("Processing", max=steps+2) as bar: images = list() topo_images = list() sim_iters = dict() for step_index in range(1, steps + 1): ...
def get_years(self): """ Figure out the start and end of the met file, the number of times we need to recycle the met data to cover the transient period and the start and end of the transient period. """ pre_indust = 1850 ds = xr.open_dataset(self.met_fname) ...
The main task of the code is to orchestrate a multi-phase simulation process, including spin-up (reaching equilibrium), transient runs, and main simulations. It initializes parameters, runs iterative spin-up cycles with steady-state checks, executes transient scenarios, and performs final simulations, managing log file...
def main(self, SPIN_UP=False, TRANSIENT=False, SIMULATION=False): num = 1 not_in_equilibrium = True (st_yr, en_yr, st_yr_trans, en_yr_trans, st_yr_spin, en_yr_spin) = self.get_years() self.initial_setup(st_yr_spin, en_yr_spin, st_yr, en_yr) if SPIN_UP == Tru...
def updOrgs(self): self.orgs = self.dashboard.organizations.getOrganizations() return def updOrgNetworks(self): for o in self.orgs: orgid = int(o['id']) nets = self.dashboard.networks.getOrganizationNetworks(orgid) self.org_networks[orgid] = nets self....
The main task of the code is to sequentially execute three update methods: `updOrgs()` for organizations, `updOrgNetworks()` for organizational networks, and `update()` for general updates, ensuring coordinated data synchronization or state changes within the system.
def updAll(self): self.updOrgs() self.updOrgNetworks() self.update() return
def get_expo_model(args): if isinstance(args.expo_mdl_name, list): all_expo_mdls = [] for e in args.expo_mdl_name: expo_mdl = _get_expo_model(e, args.q) if isinstance(expo_mdl, list): all_expo_mdls.extend(expo_mdl) else: all_expo_md...
The function `get_models` initializes and returns four models—`expo_mdl`, `rand_mdl`, `outcome_mdl`, and `estimator`—using input arguments `args`, matrix `A`, and distance data `dists`. It sequentially constructs each model by passing relevant parameters, ultimately aggregating them for further processing or analysis i...
def get_models(args, A, dists): expo_mdl = get_expo_model(args) rand_mdl = get_rand_model(args, A, dists, expo_mdl) outcome_mdl = get_outcome_model(args, expo_mdl, A) estimator = get_estimator(args) return expo_mdl, rand_mdl, outcome_mdl, estimator
def index_data(doc_to_index, deployment_env_key=None, model_env_key="MODEL_GROUP1", indexing_structure=os.environ['INDEXING_METHOD']): """ Method to get Service Context Parameters ---------- doc_to_index : Document Document to index deployment_en...
The main task of the code is to extract inactive ingredients from an SPL document by querying multiple groups (1–5) using vector search, alias matching, and rule-based filtering. It processes document content, identifies ingredient IDs, applies group-specific rules, and aggregates results. The function returns extracte...
def extract_ingredients(_setid, _ndc, _ndcs, _ndc_setid, _inactive_ing, _inactive_groups, _inactive_ids, _doc_to_index, _filter_groups, _logger=None, _true_ing=None): """ Main extract ingredients method to extract all the inactive ingredients from an SPL Parameters ---------- _s...
def __compute_frequency(self): return compute_frequency(wavelength=self.__wavelength, unit=self.__wavelength_unit, output=self.__frequency_unit) def __compute_wavelength(self): return compute_wavelength(frequency=self.__frequency, unit=self.__frequency_unit, output=self....
The main task of the code is to update three instance variables—frequency, wavelength, and wave number—by calling their respective computation methods. The function `__update_variables` assigns computed values to `self.__frequency`, `self.__wavelength`, and `self.__k0`, ensuring these properties are dynamically recalcu...
def __update_variables(self): self.__frequency = self.__compute_frequency() self.__wavelength = self.__compute_wavelength() self.__k0 = self.__compute_wavenumver()
def select_region(region, output="GHz"): """ Select a region from the electromagnetic field. Parameters ---------- region : str Region of the EM field. Possible combinations: * 'RADAR' : Output from L - X band. * 'OPTIC' : Output from VIS, NIR and SWIR band. ...
This class converts between frequency and wavelength units for electromagnetic waves, determining their band/region and calculating properties like wavenumber. It accepts input as frequency or wavelength with specified units, performs unit conversion using predefined factors, and stores results along with metadata like...
def __init__(self, input, unit='GHz', output='cm'): """ A class to describe electromagnetic waves. Parameters ---------- input : int, float or array_like Frequency or wavelength unit : {'Hz', 'PHz', 'kHz', 'daHz', 'MHz', 'THz', 'hHz', 'GHz'} or {'nm', 'um', '...
def __compute_wavelength(self): return compute_wavelength(frequency=self.__frequency, unit=self.__frequency_unit, output=self.__wavelength_unit) def __compute_wavenumver(self): return compute_wavenumber(frequency=self.__frequency, unit=self.__frequency_unit, output=self.__wavelength_unit) def which_regi...
The code sets the frequency value and updates related properties like wavelength, wavenumber, region, and band by calling internal methods and external functions. It ensures consistency between frequency and derived parameters, categorizing the frequency into a region and band based on its value and unit. This function...
def frequency(self, value): self.__frequency = value self.__wavelength = self.__compute_wavelength() self.__k0 = self.__compute_wavenumver() self.__region = which_region(self.__frequency, self.__frequency_unit) self.__band = which_band(self.__frequency, self.__frequency_unit)
def __compute_frequency(self): return compute_frequency(wavelength=self.__wavelength, unit=self.__wavelength_unit, output=self.__frequency_unit) def __compute_wavenumver(self): return compute_wavenumber(frequency=self.__frequency, unit=self.__frequency_unit, output=self....
This method sets the wavelength of an electromagnetic wave, computes its corresponding frequency and wavenumber, and determines the wave's region (e.g., radio, microwave) and band (e.g., UHF, VHF) based on the computed frequency. It updates internal attributes to reflect these properties, enabling classification and an...
def wavelength(self, value): self.__wavelength = value self.__frequency = self.__compute_frequency() self.__k0 = self.__compute_wavenumver() self.__region = which_region(self.__frequency, self.__frequency_unit) self.__band = which_band(self.__frequency, self.__frequency_unit)
def create_lattice(lattice_size, seed = 0, test = False): #Randomly initialise lattice based on the seed and the lattice class #or use test configuration #output the lattice #print(seed) np.random.seed(seed) if(not test): lattice = np.array([latticePoint([float(t),float(x),float(...
The code performs a Monte Carlo simulation on a lattice system, thermalizing the lattice and measuring the average plaquette observable. It initializes the lattice, writes system parameters to a file, runs thermalization updates, and then collects N_o measurements after N_c updates per observation. The vacuum expectati...
def main(lattice_size, beta, suggested_change, N_t, N_c, N_o, output_filename, seed = 0): #initialise lattice lattice = create_lattice(lattice_size, seed = seed) #open output file and output system variables output_file = open(output_filename, 'a') output_file.write('\nBEGIN') output_file.w...
def _rescale(self, x, min, max): """ Rescale x from [0, 1] to [min, max]""" return x * (max - min) + min def _update_episode_info(self): self.current_best_agent_idx = np.argmin(self.obj_values) if self.minimize else np.argmax(self.obj_values) self.current_worse_agent_idx = np.argmax(self...
This function simulates one step of a multi-agent environment by updating agent states based on actions, calculating rewards from objective functions, determining episode termination conditions when agents reach near-optimal values, and tracking progress through state/history logs. It enforces state bounds, freezes top...
def step(self, actions:np.ndarray)->Tuple[np.ndarray, np.ndarray, np.ndarray, dict]: """ Args: actions: the actions taken by the agents Returns: obs: the observation of the agents rewards: the rewards of the agents done: whether the episode is done...
def face_detector(img_path): ''' Decription: Converts a provided image to grayscale, detects whether the image contains a face, and then returns True if a face is detected. Input: img_path - a string indicating the filepath of the image Ouput: result - True or False for whether a face was found ...
The function analyzes an image to detect a human face or dog. If a face is detected, it predicts a dog breed and appends a grammatically correct message to the results. If no face is found, it checks for a dog, adds confirmation, and predicts its breed. If neither is detected, an error message is displayed. The task in...
def run_app(img_path): ''' Description: Checks a provided image for the presence of a human face using the face_detector function. If a human face is detected, it is added to a results list along with with a predicted dog breed. If a human face is not detected, the presence of a dog is checked using the dog_det...
def read_template_html(template_dir=".", template_file_path=""): ''' Read from a template html file and return a Jinja Template object parameter: template_file_path: string to path to a template html file return: A Jinja Template object ''' loggerName = inspect.stack()[0][3] ...
This function generates HTML files from Jinja2 templates and content files (Markdown/HTML). It reads templates, processes content into pages, combines data with metadata, renders templates, and writes output to a target directory. It handles base templates and blog-specific pages, using dynamic data to create structure...
def build_html_files(template_dir='templates', content_dir='content', content_type='md', target_dir='docs'): ''' This function does: 1. Read jinja template files(e.g. base.html, blog_base.html ) 2. Create a page list 3. Read each content html from page list 4. Render a jinja te...
def zeros(i,j): mat=rnum(i,j,0) return mat def fScalInv(Pob_float,lim,ne,LC,Nr): Pob_10=[0]*Nr*ne for i in range(Nr): for j in range(ne): r=(i)*ne+j Pob_10[r]=int(round((Pob_float[r]-lim[j][0])*(2**LC-1)/(lim[j][1]-lim[j][0]),0)) return Pob_10 def fPobDecInv(Pob_10,ne...
The code implements a **Genetic Algorithm (GA)** for optimization, handling multi-objective scenarios. It initializes a population, evaluates fitness using a provided function, applies selection, crossover, mutation, and elitism. It uses parallel processing for efficiency, checks termination conditions (e.g., max gener...
def GA(functionanalysis,otherdata,lim,NumIndiv,MutationPorc,LengthChromosome,NGenerations,Nstopelite,elite,\ NumberCores,initialdata,Daughtercomputers,tolbest,tolmean,multiobjectives): import sys import os #### IMPORTACION LIBRERIA NUMPY if not 'numpy'in sys.modules.keys(): import su...
def getKeyByValue(dict, value): return {i for i in dict if dict[i] == value}.pop() def getWallLocations(self): world = self.parsed_world.world wall_locations = [] # loop without border for i in range(2, self.x_max): for j in range(2, self.y_max): if world[...
The code converts a parsed world into a PRISM MDP file, mapping grid locations to indices, handling stochastic tiles, defining transitions for actions, and adding labels (Init, death, GOAL) and rewards. It writes the structured MDP to a file for model checking or analysis.
def parse_world(self): self.parsed_world = PartiallyObservableWorld(self.input_file, False, True, False, True) self.x_min = 1 self.y_min = 1 self.x_max = len(self.parsed_world.world) - 2 self.y_max = len(self.parsed_world.world[0]) - 2 # Initialize location dictionary by ...
def target_labels_at_level(str_labels, hierarchy, level): if level == 0: # go through list of children and find for which children the labels are present ret = [] if len(hierarchy["children"]) == 0: for tag in hierarchy["content"]: ret.append(1 if tag in str_label...
This function maps input labels to their corresponding positions in a hierarchical tree structure. It converts each label to text using label names, then determines target labels at specific levels within the hierarchy, adjusting for the tree's depth to organize labels according to their hierarchical relationships.
def map_labels_to_tree_order(labels, hierarchy, label_names): return [target_labels_at_level(binlabels_to_text(test_label, label_names), hierarchy, tree_depth(hierarchy) - 1) for test_label in labels]
def find_EP_ED_dates_OLR_3TS(var, run, out_plot_dir, plotCC=False): runid = run['runid'] var = var.intersection(latitude=(-30, 30), longitude=(0,360)) var = var[51:-51] # to avoid missing values ################################# time = var.coord('time') year, month, day = mu.getDates(time) ...
This function analyzes propagating weather events by filtering outgoing longwave radiation (OLR) data and related variables (wind, precipitation) using a Lanczos filter. It identifies event dates, generates composites for unfiltered and filtered data, and plots regional composites (ALL, IO, MC, WP) to study propagation...
def diagnos_level4_prop(outgoing_longwave_cubes, u_wind_850_cubes, u_wind_200_cubes, precip_cubes, run, out_plot_dir=None): runid = run['runid'] label = run['label'] varname = outgoing_longwave_cubes.long_name # filter OLR data filt_olr_cube = mu.lanczos_filter(outgoing_longwave_cub...
def write_log(log_level, log_string): log_label = { "OFF" : 0, "ERROR" : 1, "WARN" : 2, "INFO" : 3, } if log_label[log_level] <= log_label[DEBUG_LEVEL]: print("{}: {}".format(log_level,log_string)) def replace_decimals(obj): if isinstance(obj, list): f...
The code handles API requests for managing endpoints and stock media in DynamoDB, supporting CRUD operations (POST, GET, DELETE) for endpoints, retrieving stock media items, and copying S3 objects. It logs events, validates environment variables, and returns JSON responses with status codes and messages.
def handler(event, context): DYNAMODB_TABLE_NAME = os.environ.get('DYNAMODB_TABLE_NAME', 'not-set') STOCK_BUCKET = os.environ.get('STOCK_BUCKET') write_log("INFO", "event: {}".format(json.dumps(event))) status_code = 500 message = { 'state': 'fail' } if DYNAMODB_TABLE_NAME == 'not-se...
def check_possibilities(hole_cards, board_cards, big_omaha = False): '''returns a list of booleans of whether or not some hands are possible. This is a quick test before actually exhaustively reading hands to save time and resources. list of booleans looks like [board_pair, flush, low] ex: [False, Tr...
The function evaluates the best possible 5-card poker hand from given hole cards and board cards by exhaustively checking all valid combinations. It considers scenarios using both hole cards with board cards, one hole card with four board cards, and only board cards. Each combination is ranked, and the highest-ranking ...
def read_holdem_hand(hole_cards, board_cards): '''read holdem hand. 21 combination of 5 cards. current implementation is an exhaustive approach; checks every possible combination of 5 card hands and evaluates the hand, keeping track of the largest hand found. returns the "code" of the best possible h...
def check_possibilities(hole_cards, board_cards, big_omaha = False): '''returns a list of booleans of whether or not some hands are possible. This is a quick test before actually exhaustively reading hands to save time and resources. list of booleans looks like [board_pair, flush, low] ex: [False, Tr...
The function evaluates all possible 60 combinations of 2 hole cards and 3 board cards in Omaha poker, determining the strongest hand by comparing each combination's code. It returns the highest-ranking hand code based on predefined rules, distinguishing between standard and Big Omaha formats.
def read_omaha_hand(hole_cards, board_cards, big_omaha = False): '''read omaha hand, same way as holdem hand. check all 60 combinations of using 2 from your hand, 3 from the board''' possibilities = check_possibilities(hole_cards, board_cards, big_omaha) if big_omaha: hole_card_1 = [0...
def _update_inputs(self): self.data_folder = self.parent.data_folder.text() self._load_eggnog() self.annotations = read_annotations(path.join(self.data_folder, 'annotations.tsv')) if not self.afdb: self.afdb = read_m8(path.join(self.data_folder, 'foldseek', ...
The main task of the code is to load a pre-trained model (deeptmhmm.pkl), read protein data from .pdb files in a directory, extract and sort protein names numerically, update a UI result list with these names, and open the first protein. It processes input files, manages data structures, and interacts with a graphical ...
def read_proteins(self): self._update_inputs() self.deeptmhmm = load_obj(path.join(self.data_folder, 'deeptmhmm.pkl')) self.protein_list = [] for file in glob(path.join(self.data_folder, 'pdbs', '*.pdb')): # TODO Add support for mmcif name = file.split('/')[-1][:-4] ...
def save_annotations(self): protein = self.parent.result_list.currentText() annotation = self.parent.annotation.text() self.annotations[protein] = annotation annotation_list = list(self.annotations.items()) annotation_list.sort(key=lambda x: int(x[0][1:x[0].index('.')])) ...
This function navigates to the next protein entry in a list. It saves current annotations, updates the selection index in a result list, clears display tables, and loads the next protein data.
def next_protein(self): self.save_annotations() current_index = self.parent.result_list.currentIndex() items = self.parent.result_list.count() new_index = min(current_index + 1, items - 1) self.parent.result_list.setCurrentIndex(new_index) self._clear_tables() sel...
def save_annotations(self): protein = self.parent.result_list.currentText() annotation = self.parent.annotation.text() self.annotations[protein] = annotation annotation_list = list(self.annotations.items()) annotation_list.sort(key=lambda x: int(x[0][1:x[0].index('.')])) ...
This function navigates to the previous protein entry in a result list. It saves current annotations, decrements the list index (ensuring it doesn't go below zero), clears display tables, then loads the new protein data.
def previous_protein(self): self.save_annotations() current_index = self.parent.result_list.currentIndex() new_index = max(current_index - 1, 0) self.parent.result_list.setCurrentIndex(new_index) self._clear_tables() self.open_protein()
def knapsack_recursive(weights, values, capacity, n): # Base case, if either the capacity is 0 or there are no items left if capacity == 0 or n == 0: return 0 # If the weight of the nth item is more than the remaining capacity, skip it if weights[n - 1] > capacity: return knapsack_recur...
The code compares four knapsack problem solutions (recursive, memoized recursive, dynamic programming, and greedy) for a fixed capacity of 100. It measures each method's execution time, verifies their results, and prints maximum values. The goal is to evaluate efficiency and correctness across approaches, highlighting ...
def run_knapsack(weights, values): capacity = 100 n = len(values) memo = [[-1] * (capacity + 1) for _ in range(n + 1)] # cada iteracao cria uma lista ==> matriz ########## RECURSIVE SOLUTION start_time = time.time() # start clock max_value = knapsack_recursive(weights, values, capacity,...
def construct_query(self, query, page=1): """Construct a Google search engine query. :param str query: space separated query :param int page: the page number to request :raises ValueError: when page number invalid :returns: a fully formed Google query url :rtype: str ...
The main task of the code is to fetch search results from Bing's SERP (Search Engine Results Page) based on a query, parse the HTML response to extract links, and return them as a list. It handles dry runs, constructs URLs, manages HTTP requests, checks for consent page redirects, and logs errors or dumps HTML if parsi...
def fetch(self, query, page=1, dry_run=False): """Fetch a query. :param str query: the query to search for :param int page: the results page of the query :param bool dry_run: dry run flag :return: an array of links from Bings SERP :rtype: list[str] """ ou...
def get_csp(): f = open(input("Enter file name: ")) #initialize bools FC = False AC3 = False MAC = False NC = False MRV = False LCV = False # get bools if 'True' in f.readline(): FC = True print(f'FC: {FC}') if 'True' in f.readline(): AC3 = True ...
The code solves a Constraint Satisfaction Problem (CSP) by initializing a grid, applying the AC3 algorithm for constraint propagation if enabled, performing backtracking search to find a solution, printing the solved grid, and measuring the execution time.
def run(): # set start time st = time.process_time() # make grid and do preprocessing step if selected grid, bools = get_csp() if bools[1]: AC3(grid) # run backtracking search backtracking_search(grid, bools) # print finished tree for i in range(len(grid)): for j in...
def conv_layer(x, depth, kernel_size=3, strides=1, dropout_rate=0.1, is_training = False): x = conv(x, depth = depth, kernel_size=kernel_size, strides=strides) x = batch_norm(x, is_training) x = relu(x) x = drop_out(x, rate = (dropout_rate), is_training = is_training) return x def hardblock(x, in_ch...
The code implements a neural network for image segmentation, processing input images through convolutional layers, group convolutions, and skip connections. It uses a series of hardblock modules with dynamic channel configurations, followed by upsampling and final sigmoid activation to output a probability map.
def hardnet(input_img, is_training = False): first_ch = [16,24,32,48] depth_conv1 = [64, 96, 160, 224, 320] grmul = 1.7 gr = [ 10,16,18,24,32] n_layers = [ 4, 4, 8, 8, 8] up_sample = [126,238,374,534] skip_connections = [] blks = len(n_layers) x = conv_layer(input...
def merge_all_tables_in_dataset(coinpair, dict_with_structure): if coinpair in dict_with_structure.keys(): all_tables_in_coinpair_dataset = dict_with_structure[coinpair] final_dataframe_coinpair = extract_dataset(coinpair, all_tables_in_coinpair_dataset[0],1581012000000.0) #create a dataframe from t...
The main task of the code is to merge multiple datasets related to a specific cryptocurrency pair (coinpair) into a unified dataset. It combines data from the same dataset, split coin data, and general information tables using 'last_start_time' as the key. The merged dataset is sorted, saved as a CSV file with a timest...
def final_merger(coinpair): print('Merging process started') print('') dict_with_structure = return_dataset_names(list_not_to_merge) print('The structure on Google Bigquery look as follows:') for i in dict_with_structure.items(): print(i) print('') print('First the tables in', coinpa...
def data_single_label(train_dir, columns=['doc_id', 'start', 'end', 'text']): train_df = read_articles(train_dir, columns) train_df['label'] = "None" for filename in os.listdir(train_dir): if filename.endswith(".tsv"): tmp_df = pd.read_csv(train_dir + filename, sep='\t', names = ['id', 'type', 'start'...
The main task of the code is to process articles based on command-line parameters, generate a structured dataset with specified columns (e.g., text, labels, metadata), and save the output as a TSV file. It validates input arguments, dynamically constructs DataFrame columns, and selects appropriate data-processing funct...
def main(): columns = ['doc_id', 'start', 'end', 'text'] warnings.filterwarnings("ignore") if par.labelsType not in ['propaganda', 'persuasion']: print("Please, set the --labelsType argument to a value [propaganda | persuasion]") sys.exit(-1) if par.title: columns.append('title') if par.lengt...
def loadmat(filename): # ''' # this function should be called instead of direct spio.loadmat # as it cures the problem of not properly recovering python dictionaries # from mat files. It calls the function check keys to cure all entries # which are still mat-objects # ''' data = spio.loadmat...
This code initializes an object to load and process a MATLAB (.mat) file. It sets a default file path if none is provided, loads the file using `loadmat`, extracts keys from the data, and generates submodels based on the loaded content. The main task is to handle MATLAB file input, extract relevant keys, and create sub...
def __init__(self, mat_filepath=0): self.default_filepath = 'default_DA_settings.mat' self.daKeys = None self.save_filepath = None if mat_filepath == 0: mat_filepath = self.default_filepath self.filepath = mat_filepath da = loadmat(self.filepath) sel...
def get_SM_PG(filter_str): all_human_files = glob.glob(filter_str) #'ProteinGym_substitutions/*')#HUMAN*') # I forgot these are only human genes filtered_files = [f for f in all_human_files if 'indel' not in f] ls_of_df = [] for file in filtered_files: # read in file df = pd.read_csv(fil...
The function `assemble_full_df` integrates ESM (Evolutionary Scale Modeling) embeddings and LLR (Likelihood Ratio) scores into a unified DataFrame for mutated sequences. It filters sequences using `filter_str`, generates FASTA files for ESM and LLR processing, loads precomputed ESM embeddings from `.pt` files, retrieve...
def assemble_full_df(filter_str, ESM_fasta_name, LLR_fasta_name, ESM_dir_name, folder=False, esm_model="esm1b_t33_650M_UR50S", embed_type="mean", repr_layers=33): all_sm = get_SM_PG(filter_str) print(1) unique_mut_seqs = create_ESM_fasta(all_sm, ESM_fasta_name,)# n...
def get_splits(input_df, SEED, splits): # Set a static test set of 20% of the entire dataset train_overall, test = train_test_split(input_df, test_size=0.2, random_state=SEED) # Set the various sizes for the training splits # splits = [0.1, 0.3, 0.5, 0.8, 10, 25, 50, 100, 250, 500] # Generate traini...
The `training_loop` function evaluates multiple regression estimators across varying data splits and assay sizes. It filters assays by size threshold, iterates over seeds and splits, trains models (Ridge, KNN, LLR), computes Spearman correlations, and aggregates results. It returns assay categories and averaged perform...
def training_loop(human_assays_only, splits, seed_number, threshold, estimator_list, alpha, beta, gamma, yotta): seed_list = [i for i in range(seed_number)] unique_assays = human_assays_only['assay'].unique() subset = [] # filter the assay list by index len and threshold for assay in unique_assays:...
def create_parser(): parser = argparse.ArgumentParser( description="Trains regressor to predict DMS score from Protein Gym Variants" # noqa ) parser.add_argument( # ["esm_only", "esm_vae", "all", "None"] "--already_trained", #type=bool, action="store_true", help="Boo...
The code's main task is to perform a hyperparameter sweep across multiple machine learning models (e.g., ridge, LLR, ESM) on protein assay data. It trains models with varying alpha values, data splits (int/float), and weight combinations (beta, gamma, yotta). Results are saved as CSVs for analysis, using tqdm for progr...
def main(): # weight them st yotta + beta + gamma = 1 # make this is an input to the script so we can parallelize across 12 cases # keep unweighted (0.33, 0.33, 0.33) # 1e-05, 1e-04, 1e-03, 1e-02, 0.1, 0.2, ..., 0.5, 0.6, .., 0.9, 0.99, 0.999, 0.9999, 0.99999 # 1e-05, 1e-05, 1 -2*1e-05 all th...
def threadeddeletechannels(): threads = [] channels = getchannels() for channel in channels: t1 = threading.Thread(target=deletechannel, args=(channel, )) threads.append(t1) for thread in threads: thread.start() for thread in threads: thread.join() def threadcreatecha...
The code provides a menu-driven interface for mass Discord server manipulation, allowing users to delete/create channels, roles, and webhooks via threaded operations. It displays a colored logo, waits for input, and executes corresponding functions to perform bulk actions on a specified guild, likely for testing or adm...
def main(): os.system("title Koala Nuker && clear || cls") print(Colorate.Diagonal(Colors.yellow_to_red, logo, 1)) time.sleep(random.randint(1,5)) print("press any key to continue") input() while True: os.system("clear || cls") print(f"""{yellow}LOCKED{white} {guild_id} [1] Delet...
def get_project_dir(options): override_dir = None files = get_config_path_from_options(options, os.environ) if files: if files[0] == '-': return '.' override_dir = os.path.dirname(files[0]) return options.get('--project-directory') or override_dir def set_parallel_limit(envir...
This function configures and returns a project instance by processing input options, loading environment variables, handling context/host parameters, and initializing project settings with specified configurations, profiles, and interpolation settings.
def project_from_options(project_dir, options, additional_options=None): additional_options = additional_options or {} override_dir = get_project_dir(options) environment_file = options.get('--env-file') environment = Environment.from_env_file(override_dir or project_dir, environment_file) environme...
def _contribution_based_sampling( self, sample_size: int, client_manager: ClientManager ) -> List[ClientProxy]: """Sample clients depending on their past contributions.""" # Get all clients and gather their contributions all_clients: Dict[str, ClientProxy] = client_manager.all() ...
The main task of the code is to configure the next round of federated learning training by selecting clients based on sampling strategies (e.g., contribution-based, importance-based, or 1/k sampling) and assigning training instructions (FitIns) with parameters and timeout configurations. It ensures sufficient clients a...
def configure_fit( self, rnd: int, parameters: Parameters, client_manager: ClientManager ) -> List[Tuple[ClientProxy, FitIns]]: """Configure the next round of training.""" # Block until `min_num_clients` are available sample_size, min_num_clients = self.num_fit_clients( ...
def generate_enemy_place(clients): global enemy_x global enemy_y for i in range(enemy_count): enemy_x[i]=random.randint(60, 730) enemy_y[i]=random.randint(20, 120) message = { "type":"enemy", "x":enemy_x, "y":enemy_y, "enemy_index":enemy_index, "en...
The code sets up a multiplayer game server using sockets, managing client connections, game state synchronization, collision detection, and enemy/power-up generation. It listens for two players, initializes game elements upon connection, handles incoming data, updates positions, and broadcasts messages to maintain real...
def main(): global is_collide MAX_MSG_LENGTH = 1024 SERVER_PORT = 5000 SERVER_IP = "0.0.0.0" print("Setting up server...") server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((SERVER_IP, SERVER_PORT)) server_socket.listen(5) print("Listening for clien...
def stop(self): move_cmd = Twist() move_cmd.linear.x = 0.0 move_cmd.angular.z = 0.0 self.cmd_vel_pub.publish(move_cmd) def turn_left(self, angle): self.is_turning = True # Set the flag to indicate the robot is turning if self.current_pose is None: rospy.logwa...
The code implements obstacle avoidance navigation for a robot using distance sensors. It continuously checks front, left, and right distances, triggering turns or adjustments when obstacles are detected within 0.6m. If no obstacles are detected for 5 seconds (tracked via no_obstacles counter), it stops for 5 seconds. T...
def navigate(self): start_time=rospy.Time.now() while not rospy.is_shutdown(): if not self.is_turning: # Execute navigation logic only if the robot is not turning print(f"Front Distance: {self.front_distance:.2f} m") print(f"Left Distance: {self.left_distance...
def get_digit_display(self): return self.__digit_display_store.get() def push_digit_to_memory(self): # get digit store = self.get_digit_display() # convert to number first num = PythonCalculator.str_to_number(store) # push number to memory array self.memory_arra...
This function handles operator input in a calculator. It stores current digits in memory, evaluates expressions if two operands exist, updates the display with the operator and operands, and resets the digit display for next input.
def press_operator(self, operator): # if digit display not clear push it if self.get_digit_display() != "": self.push_digit_to_memory() # if memory length greater than 2 press equal if len(self.memory_array) >= 2: self.press_equal() self.memory_array....
def update_link(self, mod="c"): update_link(mod) self.read_available_links() def use_scihub_url(self, index): self.scihub_url = self.scihub_url_list[index] print(STD_INFO + "Choose the available link %d: %s" % (index, self.scihub_url)) if self.scihub_url[-3:] == "red": ...
The code's main task is to download a scientific paper's PDF using a DOI via SciHub. It automatically selects a valid SciHub URL, checks for response validity, handles CAPTCHAs, and either directly downloads the PDF or parses HTML to locate it. The result is saved to a specified path, with logging of the PDF URL and ti...
def download(self, choose_scihub_url_index=-1): """Download the pdf of self.doi to the self.out path. params: choose_scihub_url_index: (int) -1: Auto-choose the scihub urls. >=0: index of scihub url in scihub url links. """ # Auto choose scih...
def prod_(a, b): if a == [0] or b == [0]: return 0 a = toPoly(a) b = toPoly(b) a.reverse() results = [] for i in range(len(a)): if a[i] == 1: results.append(b + [0] * i) res = reduce(lambda x, y: sum_(x, y), results, []) return res def sum_(a, b): a.revers...
This code performs division of two numbers represented as lists, returning the quotient and remainder. It uses a long-division-like algorithm: repeatedly subtracting scaled multiples of the divisor from the dividend, updating the quotient and adjusting the dividend until it's smaller than the divisor. The base case han...
def div_(a, b): if b == [1]: return (a, [0]) quotient = [0] while len(a) >= len(b): grade = len(a) - len(b) multiplicand = [1] + [0] * grade p = prod_(b, multiplicand) a = sum_(p, a) quotient = sum_(quotient, multiplicand) red(a) return [quotient, ...
def div_(a, b): if b == [1]: return (a, [0]) quotient = [0] while len(a) >= len(b): grade = len(a) - len(b) multiplicand = [1] + [0] * grade p = prod_(b, multiplicand) a = sum_(p, a) quotient = sum_(quotient, multiplicand) red(a) return [quotient, ...
This code implements the Extended Euclidean Algorithm to find Bezout coefficients (m, n) such that a*m + b*n = gcd(a, b). It recursively computes coefficients by backtracking through divisions, returning [m, n] where m and n satisfy the equation.
def bez_(a, b): q, r = div_(a, b) if r == [0]: return (0, 1) [u, v] = bez_(b, r) m = v n = sum_(prod_(q, v), u) return [m, n]
def toNum(p): if type(p) == int: return p if p == []: return 0 return int(''.join(map(str, p)), 2) def expG_(a, n, g): if n == 0: return [1] if n == 1: return a if n % 2 == 0: e = expG_(a, n // 2, g) return prodG_(e, e, g) else: return ...
This function computes the discrete logarithm of 'numeral' with respect to 'base' modulo 'g', iterating up to 2^m where m is the floor of log2(toNum(g)). It returns the smallest non-negative integer i such that expG_(base, i, g) equals the remainder of numeral divided by g, or None if no such i exists within the limit.
def logG_(base, numeral, g): i = 0 m = math.floor(math.log(toNum(g), 2)) while expG_(base, i, g) != div_(numeral, g)[1]: i += 1 if (i > 2**m): return None return i
def set_seed(name): random.seed(int(hashlib.sha256(name.encode('utf-8')).hexdigest(), 16)) def get_result(name=None): if name is None: path = get_input_name("./input.txt") else: path = get_input_name(f"./{name}_input.txt") create_file(path) answer_1 = run_test(path, "altranmas.py") ...
The code's main task is to generate and save results using a provided seed value. It initializes a seed if a name is given, collects results via get_result(), and writes them to a file. The commented loop suggests potential for batch generation, but currently only one result is processed and stored.
def run(name=None): if name is not None: set_seed(name) answers = [] # for _ in range(int(input("number of inputs to generate: "))): answers.append(get_result(name)) write_answers(answers)
def get_topics_scores(self, sequences, candidate_labels): results = [] if isinstance(sequences, list): for sequence_to_classify in sequences: results.append(self.get_related_topics(sequence_to_classify, candidate_labels)) elif isinstance(sequences, str): r...
This function generates initial and follow-up questions for job experiences by analyzing job responsibilities and requirements. It processes up to two job experiences, extracts key responsibilities, and creates level-0 questions using topic scores. It then generates follow-up questions based on session context and labe...
def work_questions_response(self, job_exp_list, job_req, questions_text, questions_text_follow_up, questionslv0, session, labels): for work_exp in job_exp_list[0:2]: # For demo only ask 2 job job_responsibilitys = work_exp.responsibility job_title = work_exp.title job_organ...
def clone(self, remote_url, local_dir): """Clone the repository from remote_url and save in local foler.""" # # Make sure the directory is empty # if os.path.exists(self.local_dir): # try: # shutil.rmtree(self.local_dir) # except: # raise V...
The code initializes a repository by cloning from a remote URL, using a local directory, or downloading via SFTP. It determines storage location and cleanup behavior based on input parameters: permanent storage if both remote_url and local_dir are provided, temporary storage for remote_url or SFTP sources. It raises er...
def __init__(self, remote_url='', local_dir='', sftp_compressed='',sftp_uncompressed=''): """ Args: remote_url: Remote address to clone the repository from. local_dir: Local directory where the repository is stored. sftp_compressed: Url of a tar-co...
def norm_wrt_domain(self, x, norm_fn): b = x.shape[0] return rearrange( norm_fn(rearrange(x, 'b h n d -> (b h) n d')), '(b h) n d -> b h n d', b=b) def apply_2d_rotary_pos_emb(t, freqs_x, freqs_y): # split t into first half and second half # t: [b, h, n, d] # freq_x/y...
This code implements a forward pass for an attention mechanism with configurable position embeddings. It processes input tensors (q, k, v) through normalization, applies rotary or concatenated positional embeddings based on parameters, computes attention scores with optional association, and outputs transformed feature...
def forward(self, x, pos=None, not_assoc=False): qkv = self.to_qkv(x).chunk(3, dim=-1) q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h=self.heads), qkv) if pos is None and self.relative_emb: raise Exception('Must pass in coordinates when under relative position embedd...
def norm_wrt_domain(self, x, norm_fn): b = x.shape[0] return rearrange( norm_fn(rearrange(x, 'b h n d -> (b h) n d')), '(b h) n d -> b h n d', b=b) def apply_2d_rotary_pos_emb(t, freqs_x, freqs_y): # split t into first half and second half # t: [b, h, n, d] # freq_x/y...
This code implements a multi-head attention mechanism with optional relative positional embeddings and domain-specific normalization. It processes input tensors x and z, applies query-key-value projections, handles positional information for rotary embeddings, and computes attention scores. The output is transformed vi...
def forward(self, x, z, x_pos=None, z_pos=None): # x (z^T z) # x [b, n1, d] # z [b, n2, d] n1 = x.shape[1] # x [b, n1, d] n2 = z.shape[1] # z [b, n2, d] q = self.to_q(x) kv = self.to_kv(z).chunk(2, dim=-1) k, v = map(lambda t: rearrange(t, 'b n (h d)...
def _build(self): tf.reset_default_graph() # Placeholders self.rho = tf.placeholder(self.tf_float_type) self.alpha = tf.placeholder(self.tf_float_type) self.lr = tf.placeholder(self.tf_float_type) self.X = tf.placeholder(self.tf_float_type, shape=[self.n, self.d, self.x_...
This code initializes a neural network model with configurable parameters such as encoder/decoder layers, hidden dimensions, and latent space size. It sets up TensorFlow variables, reproducibility seeds, and initializes model components like session and saver. The primary task is to construct a variational autoencoder ...
def __init__(self, n, d, x_dim, seed=8, num_encoder_layers=1, num_decoder_layers=1, hidden_size=5, latent_dim=1, l1_graph_penalty=0, use_float64=False): self.print_summary = print_summary # Print summary for tensorflow variables self.n = n self.d = d self.x_dim = x_d...
def on_calendar1_day_selected(self,window): self.set_header_title() self.listbox_remove_all() yearx, monthx, dayx = self.get_date_from_cal () tasks = self.dbx.get_tasks_on_date_inlist(self.current_list,int(dayx),int(monthx),int(yearx)) for rows in tasks: for t in rows: self.add_label(t) mlbl = self....
The code initializes a GUI application using Gtk, loads a UI file, sets up a calendar to the current date, retrieves tasks from a database for that date, and displays them. It also initializes task lists, connects signals, and configures interface elements like menus and labels to prepare the application's interface an...
def __init__(self): self.current_list = prefs.start_list self.builder = Gtk.Builder() self.builder.add_from_file(UI_FILE) self.builder.connect_signals(self) menu = self.builder.get_object('menubar1') self.hb.add(menu) self.last_button = None self.on_calendar1_day_selected (None) window = self.buil...
def deal_cards(self, num_cards): cards = random.sample(self.deck, num_cards) for card in cards: self.deck.remove(card) return cards def play_round(self): print("Player's hand:", self.player_hand) player_score = self.calculate_score(self.player_hand) if self.h...
The main task of the code is to play a card game by initializing a shuffled deck, dealing two cards each to the player and dealer, executing a game round, and prompting the user to replay the game if desired. It recursively restarts the game upon the player's confirmation to continue.
def play_game(self): self.deck = self.deck_template * 4 random.shuffle(self.deck) self.player_hand = self.deal_cards(2) self.dealer_hand = self.deal_cards(2) self.play_round() play_again = input("Do you want to play again? (y/n): ") if play_again.lower() == 'y'...
def add_helm_repo(name, repo): subprocess.run([sys.argv[3], "repo", "add", name, repo], stdout=subprocess.DEVNULL) def template_helm_release(chart, repo, version, values=None): result = subprocess.run( [sys.argv[3], "template", chart, f"{repo}/{chart}", "--version", version], stdout=subprocess.P...
The function compares resources between two Helm chart versions (old and new) by generating and formatting their Kubernetes resources, then computing and concatenating the differences between corresponding resources from both versions.
def diff_release(release): chart = release["chart"] old = release["old"] new = release["new"] add_helm_repo("old", old["repo"]) add_helm_repo("new", new["repo"]) old_resources_string = template_helm_release(chart, "old", old["version"]).decode( "utf-8" ) new_resources_string =...
def get_location_details(word): global df_name global api_call_dict response = requests.get(api_endpoint+"locations?query="+word, headers=header) response=response.json() df_name=str(list(response.keys())[0]) getDetails(response,0) def get_cusine_details(location): global df_name api_endpoint="https://developer...
This code checks if a user input contains exactly one valid city name. It uses POS tagging to identify proper nouns, verifies if they are cities using geograpy, and processes location/cuisine/establishment details if valid. It returns True for a single valid city, False otherwise.
def check_validity(user_input): global tagged_sent global updated_user_input tagged_sent = pos_tag(user_input.split()) tagged_sent=dict(tagged_sent) for key,value in tagged_sent.items(): if(value != 'NNP'): updated_user_input.append(key) nouns=[k for k,v in tagged_sent.items() if v == 'NNP'] cities=[] for ...
def check_validity(user_input): global tagged_sent global updated_user_input tagged_sent = pos_tag(user_input.split()) tagged_sent=dict(tagged_sent) for key,value in tagged_sent.items(): if(value != 'NNP'): updated_user_input.append(key) nouns=[k for k,v in tagged_sent.items() if v == 'NNP'] cities=[] for ...
The function processes user input by cleaning and validating it, constructs an API endpoint, fetches data, extracts relevant information, handles cookies, and returns a formatted output. If invalid input is detected, it prompts the user to enter a query with a city name.
def final_api_call(user_input): global df_name global api_call_dict global updated_user_input user_input=tc.clean(user_input) print(user_input) para=user_input[0] user={'user':'para'} if(check_validity(user_input)): update_api_call_dict(user_input) endpoint=form_api() print(endpoint) response = requests...
def map_swagger_paths_for_xcode( paths: dict[str, dict["SwaggerPathMethods", "SwaggerPathMethod"]] ): mapped_paths = {} for path, data in paths.items(): mapped_path_data = {} for key, value in data.items(): mapped_path_data[key] = omit_empty( { ...
The function converts a Swagger API specification into an Xcode-compatible format by mapping paths, processing schemas, and generating YAML output. It processes the input SwaggerDict to extract and transform paths, definitions, and array responses, then structures them into a standardized OpenAPI 3.0.3 format before se...
def map_swagger_data_for_xcode(swagger_dict: "SwaggerDict"): mapped_paths = map_swagger_paths_for_xcode(swagger_dict["paths"]) return yaml.dump( remove_types_from_path_schemas( { "openapi": "3.0.3", "info": swagger_dict["info"], "paths": mappe...
def split_outputs(all_layers_cls_scores: Tensor, all_layers_cls_scores_obj: Tensor, all_layers_bbox_preds: Tensor, dn_meta: Dict[str, int], gt_query=False) -> Tuple[Tensor]: """Split outputs of the den...
The function computes multi-task losses for a detection model, including classification, bounding box regression, and IoU losses for both encoder and decoder outputs. It splits predictions into denoising and matching parts, calculates losses for each, and aggregates them into a dictionary. Encoder losses (enc_loss) and...
def loss_by_feat( self, all_layers_cls_scores: Tensor, all_layers_cls_scores_obj: Tensor, all_layers_bbox_preds: Tensor, enc_cls_scores: Tensor, enc_cls_scores_obj: Tensor, enc_bbox_preds: Tensor, batch_gt_instances: InstanceList, batch_img_metas: ...
def welcome_game_message(): """ Display Welcome Message """ print("Welcome to Ten Thousand") def start_game(num_rounds): """ start the game """ round_number = 1 total_score = 0 while True: # start round round_score = start_round(round_number) # stop game...
The code defines the 'play' function to initiate the Ten Thousand dice game, allowing customization of the dice roller function and number of rounds. It displays a welcome message, prompts user input to start or decline the game, and triggers gameplay or a decline message based on the response, using a global variable ...
def play(roller=GameLogic.roll_dice,num_rounds=20): """ start Ten Thousand game Args: roller : rolled dice values (optional) """ # save roller in global to keep track the rollers global ROLLER_FUNC ROLLER_FUNC = roller #print welcome message welcome_game_message() # prompt ...
def load_training_data(filepath): ''' Read the training data from the given file path ''' with h5py.File('{}/train_128.h5'.format(filepath),'r') as H: X = np.copy(H['data']) with h5py.File('{}/train_label.h5'.format(filepath),'r') as H: y = np.copy(H['label']) return X, y def model_tra...
The main task of the code is to train and evaluate a neural network model (`he_and_relu`) on a dataset, splitting it into training, validation, and test sets. It standardizes the data, trains the model, and evaluates its performance. If enabled, it also predicts labels for a test dataset and saves them in an H5 file fo...
def main(): # List of models to compare; keep 1 model only when submitting models_to_test = [he_and_relu] model_names = ['he_and_relu'] for model, model_name in zip(models_to_test, model_names): print('\nTraining model: {}'.format(model_name)) X, y = load_training_data(config.DATA_PATH...
def dining_suggestions_intent(intent_request): cuisine_type = get_slots(intent_request)["cuisine"] location = get_slots(intent_request)["location"] time = get_slots(intent_request)["time"] number_of_people = get_slots(intent_request)["numberofpeople"] phone_number = get_slots(intent_request)["p...
The main task of the code is to route user intents to corresponding handler functions. It logs the intent name, checks if it matches supported intents (DiningSuggestionsIntent, GreetingIntent, ThankYouIntent), and invokes the respective function. If the intent is unsupported, it raises an exception. This serves as a di...
def dispatch(intent_request): """ Called when the user specifies an intent for this bot. """ logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] print(intent_name) ...
def eval_preliminaries(P, model, source_loader, tgt_known_loader, tgt_unknown_loader, eval_layer="simclr", source_stats=None, logger=None): """ All eval procedures requires to gather source stats and target features """ if source_stats is None: source_stats,_ = compute_source_stats(P, model, sou...
This function generates a mask identifying target samples confidently labeled by comparing their features to source prototypes. It computes pseudo-labels for known classes when the maximum similarity to any prototype exceeds a threshold. The output includes a boolean mask, pseudo-labels, and adjusted ground-truth label...
def compute_confident_known_mask(P, model, source_loader, target_loader, logger, eval_layer="simclr", source_stats=None, target_feats=None, target_gt_labels=None): """ for each target sample we measure distance from nearest prototype. If ditance is lower than a threshold we select this sample and the proto...
def eval_preliminaries(P, model, source_loader, tgt_known_loader, tgt_unknown_loader, eval_layer="simclr", source_stats=None, logger=None): """ All eval procedures requires to gather source stats and target features """ if source_stats is None: source_stats,_ = compute_source_stats(P, model, sou...
The function `openset_eval` evaluates a model's performance in an open-set recognition task, distinguishing between known (source) and unknown (target) classes. It computes prototypes from source data, compares target samples to these prototypes using similarity thresholds, and classifies samples as known or unknown. M...
def openset_eval(P, model, source_loader, target_loader, logger, eval_layer="simclr", save_dir=None, source_stats=None): """ Compute openset eval metrics """ log_or_print("Running openset eval", logger) source_stats, target_feats, target_gt_labels, paths = eval_preliminaries(P, model, source_loader...
def eval_preliminaries(P, model, source_loader, tgt_known_loader, tgt_unknown_loader, eval_layer="simclr", source_stats=None, logger=None): """ All eval procedures requires to gather source stats and target features """ if source_stats is None: source_stats,_ = compute_source_stats(P, model, sou...
The code evaluates a model's open-world recognition (OWR) performance by comparing target samples' features against source prototypes. It calculates metrics like AUROC, closed-set accuracy (with/without rejection), unknown accuracy, and HOS, using cosine similarity thresholds to distinguish known vs. unknown classes.
def OWR_eval(P, model, source_loader, tgt_known_loader, tgt_unknown_loader, logger, eval_layer="simclr", source_stats=None): """ Compute openset eval metrics """ log_or_print("Running OWR eval", logger) source_stats, tgt_known_feats, tgt_unknown_feats, tgt_known_labels, tgt_unknown_labels, _, _ = \...
def get_root(self, state): main_board = state.board[:self.env.DIAGONAL].sum(axis=0) key = hash(main_board.tostring()) if key in self.nodes.keys(): root = self.nodes[key] # This makes this node root root.parent = None else: # Create a node ...
The code determines the best action for a given state by simulating possible moves in a decision tree. It retrieves the root node, performs simulations to explore outcomes, selects the optimal child node using an evaluation function, and returns the corresponding action. This process is typical in algorithms like Monte...
def get_action(self, state): root = self.get_root(state) self.simulate(root) best_child = self.best(root, final=True) return best_child.action_in
def place_possible(self, board, player, action): if len(action) == 5: idx, r, f, i, j = action elif len(action) == 3: layer, i, j = action idx, r, f = self.layer2irf[layer] piece = self.pieces[idx] if (r, f) in piece.keys(): block = piece[...
This method applies a given action to the game state, updates the board by placing a piece, validates the move, updates neighbors and diagonals, checks game completion, and returns the next state, reward, and game status following OpenAI's gym API. It handles piece placement, board transformations, and scoring logic fo...
def step(self, state, action, actions): """ Arguments: state {np.ndarray} -- self.NUM_STATE_LAYERS * self.SIZE * self.SIZE action {tuple} -- rank 5 or 3 actions {np.ndarray} -- list of actions Raises: ValueError -- if action is invalid ...
def recalculate_results(self): parts = self._search_text.split(' ') self._topic_results.clear() for t in self._topics: if t.startswith(parts[0]): self._topic_results.append(t) if len(self._topic_results) == 1: self._selection = self._topic_results[...
This code handles keyboard input for a search interface, modifying the search text and cursor position based on key presses (backspace, delete, arrow keys, etc.), updating selections in a result list, and triggering command execution on Enter. It ensures text editing, navigation, and result recalculations, then redraws...
def handle(self, ch): if ord(ch) == 410: # resize pass elif ord(ch) == 127: # backspace self._search_text = self._search_text[:max(0, self._search_cursor_idx - 1)] + \ self._search_text[self._search_cursor_idx:] self._search_cursor_idx = max(0, sel...
def recalculate_results(self): parts = self._search_text.split(' ') self._topic_results.clear() for t in self._topics: if t.startswith(parts[0]): self._topic_results.append(t) if len(self._topic_results) == 1: self._selection = self._topic_results[...
The code's main task is to run a continuous loop that clears the screen, recalculates results, redraws the interface, and processes user input. It refreshes the display, captures key presses, and handles them via the `handle` method, maintaining an interactive UI cycle.
def run(self): self._screen.clear() self.recalculate_results() self.redraw() while True: self.refresh() c = self._screen.getch() self.handle(chr(c))
def generate_samples(self, cnt_round, multi_process, isTest=True, num_gen=1): process_list = [] generator_start_time = time.time() dic_agent_conf = self.dic_agent_conf_test if isTest else self.dic_agent_conf if multi_process: for cnt_gen in range(num_gen): p ...
The code's main task is to execute training rounds for a machine learning model, logging time spent on generating samples, updating the network (with optional multiprocessing), and testing evaluation. It iterates through specified rounds, records each phase's duration in a CSV file, and repeats until completion, adjust...
def run(self, multi_process=False): f_time = open(os.path.join(self.dic_path["PATH_TO_WORK_DIRECTORY"],"running_time.csv"),"w") f_time.write("generator_time\tmaking_samples_time\tupdate_network_time\ttest_evaluation_times\tall_times\n") f_time.close() cnt_round = self.dic_exp_conf["STAR...
def clear(self): self.keep_ls = [] self.update_ls = [] self.empty_ls = [] self.alarm_ls = [] def region_classify(self, boxes): center_region, cover_region, occupy_region = [], [], [] for box in boxes: center = cal_center_point(box) center_region.ap...
The code processes detected boxes in an image by classifying regions into center, cover, and occupy categories, then updates region data, triggers alarms, and visualizes results. It clears previous data, copies the input image, handles non-empty boxes with region classification and processing, or marks regions as empty...
def process_box(self, boxes, rd_block, rd_cnt): self.clear() self.img = copy.deepcopy(rd_block) if len(boxes) > 0: center_ls, cover_ls, occupy_ls = self.region_classify(boxes) self.region_process(occupy_ls, cover_ls, center_ls) else: self.empty_ls = se...
def check_line_horizontal(self): last_hex_row = self.last_move_hex.row last_hex_column = self.last_move_hex.column line_counter = 1 line_left = [hex for hex in BoardState.valid_hexagons if hex.row == last_hex_row and hex.column < last_hex_column and hex.column >= last_hex_column - 4] line_left.sort(key=lambd...
The code evaluates the game state's value by checking horizontal, ascending, and descending lines, then adjusts the value based on enclosure wins and adjacency of the last move to the same player's hexagons, penalizing if no adjacent same-player hexes exist.
def evaluate_state(self): horizontal = self.check_line_horizontal() ascending = self.check_line_ascending() descending = self.check_line_descending() value = max(horizontal, ascending, descending) win_by_enclosing = self.check_if_enclosing() if win_by_enclosing: value += 5 last_move_neighbours = sel...
def table_load(self) -> float: """ returns the current hash table load factor """ return self._size / self._capacity def resize_table(self, new_capacity: int) -> None: """ changes the capacity of the hash table to 'new_capacity' if 'new_capacity' is a prime number, or the...
This code updates or inserts a key-value pair into a hash table. It ensures the load factor remains below 0.5 by doubling the table size if necessary before inserting. The 'into_empty_index' method handles the actual placement of the key-value pair in the resized or existing table.
def put(self, key: str, value: object) -> None: """ updates the key/value pair in the hash table. if 'key' is already in the hash table, its corresponding value is updated to 'value', otherwise the key/value pair is added to the hash table. """ while self.table_load() >= 0.5: ...
def preprocess_image(img): return grayscale(downsize(img)) def init_state(self, image): return np.stack((image, image, image, image), axis=-1) def act(self, state): epsilon = self.get_epsilon_for_iteration() #epsilon = 0.01 env = self.env #print ("State shape: ", state.shape)...
This code trains a reinforcement learning agent using experience replay to maximize cumulative rewards in a game environment (likely ALE-based). It runs multiple episodes, collects transitions (state, action, reward, next_state) into memory, handles game lives for reset logic, and periodically updates the model via rep...
def run(self): for index_episode in range (0, self.episodes): #print("Iteration start: ", env.apreprocessed_imagepreprocessed_imagection_space.n) image = self.env.reset() preprocessed_image = preprocess_image(image) state = self.init_state(preprocessed_image) ...
def initialize_with_zeros(dim): #return np.zeros(dim).reshape(dim,1),b return np.random.randn(dim,1),b def optimize(w,b,X,Y,num_iterations,learning_rate,print_cost=False): costs=[] for i in range(num_iterations): grads,cost=propagate(w,b,X,Y) dw=grads["dw"] db=grads["db"] ...
The code trains a logistic regression model using gradient descent on training data, evaluates it on test data, calculates training and test accuracies, and returns parameters, costs, and predictions in a dictionary.
def model(X_train,Y_train,X_test,Y_test,num_iterations=2000,learning_rate=0.5,print_cost=False): w,b=initialize_with_zeros(X_train.shape[0]) parameters,grads,costs=optimize(w,b,X_train,Y_train,num_iterations,learning_rate,print_cost=True) w=parameters["w"] b=parameters["b"] Y_prediction_test=predict...
def processInput(self): self.move_command = None for event in pygame.event.get(): if event.type == pygame.constants.QUIT: self.running = False break elif event.type == pygame.constants.KEYDOWN: if event.key == pygame.constants.K_...
The code defines a game loop that continuously processes input, updates game state, renders graphics, and maintains a 60 FPS frame rate while `self.running` is True.
def run(self): while self.running: self.processInput() self.update() self.render() self.clock.tick(60)
def scan_360(speech_input): flag=0 speech_input = "cup" label1,mid_x1,mid_y1,h,w=object_detection() #object_detection_loop() for i in label1: if speech_input in i or 'toilet' in i: flag=1 if flag==1: return() else: Fright.forward() Bright.backward...
The main task of the code is to control a robot's movement and servo angles. It scans the environment, moves forward, adjusts servos to specific angles (10° and 160°), performs two cycles of angular adjustments via PWM, waits, then moves backward. The code integrates sensor scanning, motor control, and precise servo po...
def main(txt): scan_360(txt) scan(txt) move_forward() pwm=GPIO.PWM(21,100) pwm.start(5) angle1=10 duty1=float(angle1)/10 + 2.5 angle2=160 duty2=float(angle2)/10 + 2.5 ck=0 while(ck<=1): pwm.ChangeDutyCycle(duty2)...
def sunrise(self) -> datetime: """Calculates the time of the sunrise. Returns: A datetime object, containing the time of the sunrise. """ return self.calculate_time() def sunset(self) -> datetime: """Calculates the time of the sunset. Returns: A ...
This code initializes a Sun object to determine solar positions (sunrise/sunset) for a specified date and location, validating latitude/longitude bounds. It optionally creates a tomorrow's Sun instance if conditions are met, using zenith angle definitions for twilight calculations.
def __init__(self, day: int, month: int, year: int, latitude: int, longitude: int, offset: float, date: datetime=date.today(), zenith: t.Union[str, float]="official", ...
def sunset(self) -> datetime: """Calculates the time of the sunset. Returns: A datetime object, containing the time of the sunset. """ return self.calculate_time(False) def sunrise(self) -> datetime: """Calculates the time of the sunrise. Returns: ...
The main task of the code is to calculate the duration between sunrise and sunset, convert the time difference into minutes, and return a formatted string displaying the day length in hours and minutes.
def day_length(self) -> str: """Calculates the day length. Returns: The day length, formatted to hours and minutes. """ minutes = (self.sunset()-self.sunrise()).total_seconds() / 60 return f"Day length: {format_time(minutes)}"
def time_to_sunset(self, now: datetime, sunset: datetime) -> str: """Calculates the time to the next sunset. Args: now (datetime). sunset (datetime). Returns: The time to the next sunset, represented as a ...
The function determines the time until the next sunset or sunrise. If it's daytime, it returns the time to the next sunset; otherwise, it calculates the time to tomorrow's sunrise. The result is formatted as "Sunset in: HH:MM" or "Sunrise in: HH:MM", depending on which event occurs first.
def time_to_change(self) -> str: """Calculates the time to the next sunset or sunrise. Returns: If the next sunset is closer than the next sunrise, returns the time to the next sunset. Otherwise, returns the time to the next sunrise [=tomorrow's sunrise]. ...