dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def print_typewriter(text, delay=0.03): for char in text: sys.stdout.write(char) sys.stdout.flush() time.sleep(delay) def display_objectives(objectives): print("\n--- Objectives ---") for objective, completed in objectives.items(): status = "Complete" if completed else "Incom...
The main task of the code is to create a text-based adventure game where a player explores a cave map, defeats enemies, collects loot, and retrieves a legendary artifact. The game tracks progress through objectives, handles player movement and inventory, and uses typewriter-style text output to enhance immersion. It in...
def main(): player_name = input("Enter your name: ") print_typewriter(f"\nGreetings, {player_name}!\n") print_typewriter("You are an explorer on a quest to find a legendary artifact hidden in a mysterious land.\n") print_typewriter("Rumors speak of a dark cave around the area, where the artifact might b...
def print_typewriter(text, delay=0.03): for char in text: sys.stdout.write(char) sys.stdout.flush() time.sleep(delay) def main(): player_name = input("Enter your name: ") print_typewriter(f"\nGreetings, {player_name}!\n") print_typewriter("You are an explorer on a quest to find a...
The main task of the code is to display a welcome menu for a text-based game, allowing users to choose between starting a new game or quitting. It handles user input validation and directs the flow to the main game function or exits the program accordingly.
def start_menu(): print_typewriter("=== Welcome to the Mysterious Cave ===\n") print("1. Start New Game") print("2. Quit") choice = input("Enter your choice: ") if choice == "1": main() elif choice == "2": print("Goodbye!") sys.exit() else: print("Invalid cho...
def _SplitFullCollectionName(collection): return tuple(collection.split(NAME_SEPARATOR, 1)) def _GetDefaultVersion(api_name): """Gets the default version for the given api.""" # pylint:disable=protected-access api_version = apis_internal._GetDefaultVersion(api_name) if not api_version: raise NoDefaultVers...
The function `GetAPICollection` retrieves a specific API collection by name and version. It splits the input `full_collection_name` into the API name and collection name, determines the API version (using a default if none is provided), fetches all collections for that API and version, and returns the matching collecti...
def GetAPICollection(full_collection_name, api_version=None): """Gets the given collection for the given API version. Args: full_collection_name: str, The collection to get including the api name. api_version: str, The version string of the API or None to use the default for this API. Returns: ...
def _SplitFullCollectionName(collection): return tuple(collection.split(NAME_SEPARATOR, 1)) def _GetDefaultVersion(api_name): """Gets the default version for the given api.""" # pylint:disable=protected-access api_version = apis_internal._GetDefaultVersion(api_name) if not api_version: raise NoDefaultVers...
The function retrieves all available methods for a specified API collection, using the provided or default API version. It processes the collection name, obtains the API client, fetches method configurations, and returns a list of APIMethod objects representing each method's specifications.
def GetMethods(full_collection_name, api_version=None): """Gets all the methods available on the given collection. Args: full_collection_name: str, The collection including the api name. api_version: str, The version string of the API or None to use the default for this API. Returns: [APIMetho...
def _generate_root_certificates(self) -> None: """Generates root certificate to be used to sign certificates. Returns: None """ private_key_password = self._generate_password() private_key = generate_private_key(password=private_key_password.encode()) ca_cert...
The function handles Juju configuration changes by validating certificate settings, generating/self-signed certificates if enabled, revoking old certificates, and updating unit status. It checks for missing config options, ensures CA common name is set when needed, and defers actions until prerequisites like replicas r...
def _on_config_changed(self, event: ConfigChangedEvent) -> None: """Triggered when the Juju config is changed. Args: event (ConfigChangedEvent): Juju event. Returns: None """ if not self._replicas_relation_created: self.unit.status = WaitingS...
def close(self): self.root.destroy() def minimizeRoot(self): self.root.update_idletasks() self.root.overrideredirect(False) self.root.state('iconic') def filterCari(self,sv): self.cari = self.txt_cari.get() self.kategori = '' self.jenis = '' if self.cmb_tb...
This code creates a GUI application for inventory management. It initializes a non-resizable window with a custom header, filter options (search, category, type), data entry fields (name, quantity, price), and CRUD operations (add/edit/delete). It includes a recycle bin button and a table to display inventory items, al...
def __init__(self, username): self.username = username self.root = Tk() self.sv = StringVar() self.root_settings = SettingTheme() self.root.geometry("1000x700") self.root.resizable(False, False) self.root.overrideredirect(True) self.root.attributes('-top...
def setupUI(self): self.content_image_label = QtWidgets.QLabel("Image:") self.content_image_input = QtWidgets.QLineEdit() self.content_image_button = QtWidgets.QPushButton("Browse") self.draw_contours_label = QtWidgets.QLabel("Contours:") self.draw_contours_slider = QtWidgets.QS...
The code initializes a GUI window for an image conversion application named "BrachioGraph Image Converter," sets up the central widget, loads UI components via `setupUI()`, configures the application icon and name, and restores window geometry/state from saved settings. It ensures the interface is ready for user intera...
def __init__(self): super().__init__() self.setWindowTitle("BrachioGraph Image Converter") self.central_widget = QtWidgets.QWidget(self) self.setCentralWidget(self.central_widget) self.setupUI() # Set the application icon and name app_icon = QtGui.QIcon((str(Pa...
def find_intercept(): m = find_slope() mean_x, mean_y = find_mean() c = mean_y - m*(mean_x) return round(c,3) def find_slope(): s_x, s_y = find_std_dev() r = find_correlation_coefficient() m = r*(s_x/s_y) return round(m,3) def find_correlation_coefficient(): sum = 0 mean_x, mean_...
This function uses the Turtle graphics library to display a linear equation (y = mx + c or y = mx - c) and the correlation coefficient (r) on the screen. It calculates the slope, intercept, and correlation coefficient using helper functions, formats the equation based on the intercept's sign, and writes both the equati...
def display_parameters(): w=Turtle() w.up() w.speed(10) w.pensize(4) w.color("white") w.ht() w.clear() w.goto(10,16) c = find_intercept() if c > 0: eqn = "y = " + str(find_slope()) + "x + " + str(c) else: eqn = "y = " + str(find_slope()) + "x - " + str(abs(c))...
def load(image_file): # Read and decode an image file to a uint8 tensor image = tf.io.read_file(image_file) image = tf.io.decode_jpeg(image) # Split each image tensor into two tensors: # - one with a real building facade image # - one with an architecture label image w = tf.shape(image)[1] w = w // 2 ...
The main task of the code is to load an image file, apply random jittering for data augmentation, normalize the images, and return the processed input and real images. This function prepares training data by enhancing variability through random transformations and standardizing pixel values for model training.
def load_image_train(image_file): #print('image_file:',image_file) input_image, real_image = load(image_file) input_image, real_image = random_jitter(input_image, real_image) input_image, real_image = normalize(input_image, real_image) #print('input:',input_image) #print('real:',real_image) return input_i...
def load_c(checkpoint_dir): logging.info(" [*] Reading checkpoints...{}".format(checkpoint_dir)) print(" [*] Reading checkpoints...{}".format(checkpoint_dir)) checkpoint_prefix_load = os.path.join(add_dir_prefix+checkpoint_dir) ckpt = tf.train.get_checkpoint_state(checkpoint_prefix_load) if ckpt and...
The code's main task is to execute different modes based on the 'runmode' argument: 'first' initiates initial training, 'again' resumes training from a checkpoint, and 'generate' produces images using a preloaded model. It handles checkpoint loading, error logging, and data processing for training or generation. The 'g...
def main(args): if args.runmode == 'again' or args.runmode == 'first' or args.runmode == 'generate': if args.runmode == 'again': flag, counter = load_c(checkpoint_dir) if flag: logging.info("# re-learning start") print("# re-learning start") ...
def stitch_get_dims(adata, timepoint_obs, batch_obs=None, vscore_filter_method='majority', vscore_min_pctl=90, vscore_top_n_genes=3000, sig_pcs_n_trials=10, sig_pcs_top_n_genes=20, downsample_cells=False, verbose=True): # Identify highly variable genes and the # of significant PCA dimensions across basis timepoint...
The main task of the code is to integrate single-cell data across multiple timepoints and batches by estimating dimensionality, filtering genes, correcting batch effects using harmony, and constructing a stitch graph to model temporal relationships between cells. This involves dimensionality reduction, visualizing gene...
def stitch(adata, timepoint_obs, # column in adata.obs containing numeric timepoint assignments (required) batch_obs=None, # column in adata.obs containing batch assignments (optional) vscore_filter_method='majority', # vscore batch filtering me...
def determine_winner(self, user_choice, computer_choice): if user_choice == computer_choice: return "It's a tie!" elif ( (user_choice == "rock" and computer_choice == "scissors") or (user_choice == "scissors" and computer_choice == "paper") or (user_choice...
The code's main task is to handle a game round by selecting a random computer choice, determining the winner between user and computer choices, updating the result display, scores, and showing the outcome with both choices.
def play(self, user_choice): computer_choice = random.choice(self.choices) result = self.determine_winner(user_choice, computer_choice) self.result_label.config(text=f"Result: {result}") self.update_scores() self.display_result(user_choice, computer_choice)
def load_raw_data_brain(dataset): raw_data = sio.loadmat('../data/raw/' + dataset + '/' + dataset + '.mat') reg_labels = raw_data['reg_labels'].squeeze() np.save( '../data/preprocessed/' + dataset + '/' + dataset + '_reg_labels.npy', reg_labels) ins_labels = raw_data['label'].squeeze() ...
This function preprocesses time-series or graph datasets by loading raw data, generating features (e.g., adjacency tensors), and splitting data into train/val/test sets. It handles HIV/BP with specific ratios, BikeDC with time-based parameters and tensor generation, and PROTEINS with dimension-specific loading. The cor...
def data_preprocess(dataset='HIV'): if dataset == 'HIV' or dataset == 'BP': load_raw_data_brain(dataset) ratio_list = [24, 6, 40] if dataset == 'HIV' else [33, 8, 56] split_train_val_test(dataset, ratio_list) elif dataset == 'BikeDC': years_list = [ str(year) + '/' + ...
def get_sms_sym(r, phi, Mode, NumModes): ### Symplectic transformation associated to single-mode squeezing. tempMat = np.identity(2 * NumModes) tempMat[Mode, Mode] = np.exp(-r) tempMat[NumModes + Mode, NumModes + Mode] = np.exp(r) tempMat = get_phase_sym(phi, Mode, NumModes)[0] @ tempMat return ...
The function constructs a symplectic transformation matrix for two-mode squeezing (TMS) by sequentially applying single-mode squeezing (SMS), phase shifts, and a beam splitter (BS). It combines these operations—two SMS transformations on modes Mode1 and Mode2, a π/2 phase on Mode2, a BS between Mode1 and Mode2, and a f...
def get_tms_sym(r, phi, Mode1, Mode2, NumModes): ### Symplectic transformation associated to two-mode squeezing. Uses the fact that two SMS states passing through a ### pi/2 phase and a BS gives rise to TMS. tempMat = get_sms_sym(r, 0, Mode1, NumModes) tempMat = get_sms_sym(r, 0, Mode2, NumModes) @ temp...
def computeTransformationMatrices(self, origin, sampling): """ compute transformation matrix between reference atom structure (self.atomStructReference) and the other atom structures (self.otherAtomStructs) read atomic structures identify common AA with first structure ...
The code computes an averaged subunit volume by symmetrically transforming and interpolating voxel data from the input volume. It calculates bounding boxes, generates grid points, applies transformation matrices, performs trilinear interpolation to accumulate averaged values, normalizes by the number of symmetric regio...
def computeAveragedSubUnit(self): """Average the pixel values of the pixels related by symmetry""" # 1) get sampling and origin volume = self.inputVolume.get() origin = np.ones(4) origin[:3] = volume.getShiftsFromOrigin() sampling = volume.getSamplingRate() # 2) ...
def access_user_account(accountARN, region): # Create session using your current creds boto_sts=boto3.client('sts') # Request to assume the role like this, the ARN is the Role's ARN from # the other account you wish to assume. Not your current ARN. stsresponse = boto_sts.assume_role( RoleAr...
The code creates a user with specified policies, generates Terraform access keys, installs Terraform, and executes infrastructure deployment. It accesses an IAM role, attaches default and custom policies to a user, creates a Terraform-specific user, retrieves keys, and runs Terraform plan/apply using the keys.
def lambda_handler(event, context): ## In prod we can pass user_id from request_id or any unique_id from the event access_user_account('arn:aws:iam::629045748974:role/OrganizationAccountAccessRole', 'eu-west-2') user_policy_dict = event["Policies"] name="sbt-user" create_normal_user(name) attac...
def ac_run(pm, ff='gaff2', charge_model='bcc'): mol_atomtypes = [] mol_natoms = [] for i, p in enumerate(pm): resname = 'M{:02}'.format(i+1) molfile = resname + '.mol' mol2file = resname + '.mol2' pdbfile = resname + '.pdb' frcmodfile = resname + '.frcmod' g16...
The main task of the code is to generate and optimize molecular structures using quantum mechanics (QM) and molecular mechanics (MM) methods, then create force field topologies for molecular dynamics simulations. It processes input parameters, sets up computational environments for DFTB, Espresso, and CP2K, generates m...
def crystop_main(conf): inciffile = conf['input_file'] smile = conf['smile'] verbose = conf['verbose'] ff = conf['ff'] charge_model = conf['charge_model'] qe_input = conf['qe_input'] cp2kinp_path = conf['cp2k_input'] xtb_hamiltonian = conf['xtb_hamiltonian'] nxyz = conf['nxyz'] ...
def get_parser(): class customHelpFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawTextHelpFormatter): pass parser = argparse.ArgumentParser( formatter_class=customHelpFormatter, description='Python script easy to make force field topology of m...
The main task of the code is to parse command-line arguments, configure parameters based on the inputs, print the configuration details, and execute the `crystop_main` function with the specified configuration. This involves retrieving arguments, setting up a configuration dictionary, displaying its contents, and initi...
def main(): args = get_parser() print(args) conf = set_config(args) print('======= Input configulations =======') for k, v in conf.items(): print('{}: {}'.format(k, v)) print('====================================') crystop_main(conf)
def ssh(server, command): cmd = "ssh -t " if 'port' in server and server['port'] != '': cmd += " -p " + server['port'] + " " if 'user' in server and server['user'] != '': cmd += server['user'] + "@" cmd += server['host'] + " '" + command.replace("'", r"\'") + "'" run(cmd) def repl...
The main task of the code is to execute a list of commands either remotely via SSH or locally, depending on the 'place' parameter. It replaces variables in each command with specified values before execution, enabling dynamic command processing on a server or local environment.
def user_commands(server, variables, commands, place): if place == 'remote': for command in commands: ssh(server, replace_variables(variables, command)) else: for command in commands: run(replace_variables(variables, command))
def denormalize_obs(self, obs): return { 'uav_locs': ((obs['uav_locs'] + 1) * (self.sim_size / 2)).round(0), 'user_locs': (obs['user_locs'] + 1) * (self.sim_size / 2), 'pref_users': obs['pref_users'], 'cov_scores': (obs['cov_scores'] + 1) / 2 } def normali...
The code simulates UAV movement based on actions, updates their positions within bounds, calculates coverage scores, normalizes the state, computes a reward, and returns the new state, reward, and environment status. It handles UAV positioning, coverage evaluation, and reward calculation for a reinforcement learning en...
def step(self, action: np.ndarray): # gym wrapper will make done = True after 600 timesteps done = False self.timestep += 1 state = self.denormalize_obs(self.state) # unpack state uav_locs = state['uav_locs'] user_locs = state['user_locs'] distances = n...
def get_devices(): access_token = get_access_token() url = "%s/v1/network_elements" % API_ENDPOINT headers = {'Authorization': 'Bearer %s' % access_token} params = {"type": "Device", "expand": True} response = requests.get(url=url, headers=headers, params=params) response.raise_for_status() ...
The function generates Fully Qualified Domain Names (FQDNs) for devices by managing their aliases based on a provided domain. It adds valid aliases to devices if not in deprovisioning mode or removes existing aliases if deprovisioning is enabled. The `dry_run` flag allows simulation without actual changes. Devices with...
def generate_fqdns(domain_name=None, deprovisioning=False, dry_run=False): for dev in get_devices(): device_name = _get_device_name(dev) if not device_name: print("%s doesn't have a device name, skipping" % dev['id']) continue alias = _get_alias(device_name, domain_na...
def get_energy_with_freq(self, data): data_freq = self.GetFreq(data) data_energy = self.getEnerg(data) energy_freq = self.getFreqandEnergy(data_freq, data_energy) return energy_freq def sum_in_band(self,energy_frequencies, start_band, end_band): sum_energy = 0 for f in en...
This code detects speech in an audio signal by analyzing energy in specified frequency bands. It processes audio data in sliding windows, calculates the ratio of speech-band energy to total energy, and generates timestamps with speech probabilities. These probabilities are filtered and transformed using a sigmoid funct...
def detect_speech(self): window = int(self.rate * self.window) hop = int(self.rate * self.hop) data = self.data sample_start = 0 start_band = self.speech_start_band end_band = self.speech_end_band speech_prob = [] timstamps = [] while (sample_start...
def save_examples() -> None: examples = [ ([1, 1, 1, 1, 1], "example_equality"), ([1, 1, 1, 1, 6], "example_inequality"), ] for balance, filename in examples: eg_data = [{"block": 0, "balances": balance}] with open(f"{PROJECT_DIR}/data/{filename}.json", "w") as f: ...
The main task of the code is to generate and save visualizations (plots) related to the distribution of "Punks" (likely NFTs) and their ETH value over time. It creates a "figures" directory if absent, prepares data via `save_examples()` and `save_interactive_data()`, then iterates over predefined plot configurations. E...
def main() -> None: if not os.path.exists(f"{PROJECT_DIR}/figures"): os.mkdir(f"{PROJECT_DIR}/figures") save_examples() save_interactive_data() to_plot = [ # Example 1: Equality ( "Example 1: Equality", ["example_equality"], "example_1", ...
def mine_corner(self): self.mine_4() self.walk_forward() self.mine_4() def turn_right(self): remainder = horr_offset % look_speed step = int(horr_offset / look_speed) for x in range(0, look_speed): sleep(0.001) mouse._os_mouse.move_relative(step, 0...
This code navigates a robotic entity around a corner by adjusting direction based on the parity of input 'y'. It turns right or left, steps forward twice, mines a corner, steps again, reorients, and proceeds forward, implementing a directional adjustment algorithm for grid-based movement.
def corner(self, y): right = y % 2 self.mine_corner() if right: self.turn_right() else: self.turn_left() self.step() self.step() self.mine_corner() self.step() if right: self.turn_right() else: ...
def setup(self): if not self._is_setup: self.logger.debug("%r entering setup", self) if self.filename is None: self.pid = os.getpid() self.filename = self._make_filename() self._register_term_signal() if self.register_atexit: ...
This method creates a PID file by opening the specified file, applying a lock if configured, checking for existing PID conflicts, setting file permissions/ownership, truncating the file, writing the current process ID, and marking it for cleanup.
def create(self): self.setup() self.logger.debug("%r create pidfile: %s", self, self.filename) self.fh = open(self.filename, "a+") if self.lock_pidfile: try: self._flock(self.fh.fileno()) except IOError as exc: if not self.allow_sa...
def process_input(self, guess): ''' Converts the guess to lower case and checks it is a valid guess using the __check_valid_guess() method Parameters ---------- guess : str input from the player to guess a letter in the word Returns ------- ...
This method checks if the player has remaining lives and letters to continue guessing. If lives reach zero, it declares a loss and reveals the word. If all letters are guessed, it calculates the time taken, announces victory, updates the leaderboard, and displays results. The loop breaks upon win/loss conditions.
def win_lose_continue(self): ''' Checks num_letters is greater than 0 and self.ui.num_lives is greater than 0, if either proves True, tells you whether you won or lost. Parameters ---------- None Returns ------- None ''' while True: ...
def _initialize_localpath(self, localpath): self._path = localpath self._detect_source() self._datalibrary = None return True def load_data_using_copy_from_query(self, corepath=None, from_local=False, from_s3=False, **kwargs): """ Load data using copy from query ( https:...
The main task of the code is to load data into OmniSci Core tables from a specified local or S3 path, using either a `COPY FROM` SQL query or an API method, with customizable parameters for data formatting, delimiters, headers, and threading. It supports both local file paths and S3 storage, allowing flexible data inge...
def load_data(self, localpath, corepath=None, use_copy_from_qry=False, **kwargs): """ Load data into the created tables. :param str corepath: (optional) The path to the root of the folder structure containing the data library, absolute or relative to the OmniSci Core server. If this is not passe...
def create_tables(self, localpath): """ Create tables from schema queries """ self._initialize_localpath(localpath) for tblname, tbldetails in self.datalibrary['tables'].items(): self._create_table(tbldetails.get('schema')) def create_views(self, localpath): s...
This method imports and initializes data by creating database tables and views, importing dashboards, and loading data from a specified local path. It uses optional corepath and additional parameters for flexibility, returning True upon successful execution.
def import_all(self, localpath, corepath=None, **kwargs): self.create_tables(localpath) self.create_views(localpath) self.import_dashboards(localpath) self.load_data(localpath, corepath=corepath, **kwargs) return True
def terminate(): pygame.quit() sys.exit() def runGame(): # setup variables for the start of the game board = getBlankBoard() lastMoveDownTime = time.time() lastMoveSidewaysTime = time.time() lastFallTime = time.time() movingDown = False # note: there is no movingUp variable movingLef...
The code initializes a Tetris game with a main menu, displaying theme options (retro/modern) and control instructions. It handles user input for theme selection, plays background music, and transitions to game modes via `runGame()` or `runGame2()`. A control menu shows keybindings and allows returning to the main menu....
def main(): global FPSCLOCK, DISPLAYSURF, BASICFONT, BIGFONT, CLASSICTHEMEBUTTON, MODERNTHEMEBUTTON, CONTROLMENUBUTTON, themefont, themefont2, themeinscription, themeinstruction1, themeinstruction2,controlinstruction pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WIN...
def gather_options(self): # initialize parser with basic options if not self.initialized: parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser = self.initialize(parser) opt, _ = parser.parse_known_args() ...
This function parses and configures model options, sets GPU devices, validates batch size compatibility with GPUs, and returns the processed options. It saves options if in training mode, processes GPU IDs, ensures batch size is a multiple of GPU count, and assigns configurations to self.opt for subsequent use.
def parse(self, save=False): opt = self.gather_options() opt.isTrain = self.isTrain # train or test self.print_options(opt) if opt.isTrain: self.save_options(opt) # set gpu ids str_ids = opt.gpu_ids.split(',') opt.gpu_ids = [] for ...
def type_1_error(x): counter = 0 for i in x: counter +=1 if i[0][-1] == ":": k = 1 else: k = 0 if i[k+0] not in ISA_list: print (x.index(i)) print ("Invalid Syntax") return False return True def type_2_error(x): ...
The function checks for invalid syntax by identifying elements in the list `x` that are single-character strings ending with a colon, printing their index and "Invalid Syntax" if found, then returns `False`. If no such elements exist, it verifies the absence of 10 other error types via helper functions. If all checks p...
def all_errors(x): counter = 0 for i in x: counter +=1 if len(i) == 1 and i[0][-1] == ":": print (x.index(i)) print ("Invalid Syntax") return False if type_1_error(x) and type_2_error(x) and type_3_error(x) and type_4_error(x) and type_5_error(x) and type...
def all_errors(x): counter = 0 for i in x: counter +=1 if len(i) == 1 and i[0][-1] == ":": print (x.index(i)) print ("Invalid Syntax") return False if type_1_error(x) and type_2_error(x) and type_3_error(x) and type_4_error(x) and type_5_error(x) and type...
This code reads assembly-like instructions, processes variables and labels, validates syntax, and converts valid instructions into binary machine code using predefined type handlers. It handles input parsing, address mapping, error checking, and instruction encoding in a multi-pass approach.
def main(): while True: try: line = input() if line != "": instruction_list.append(line) except EOFError: break for i in range(len(instruction_list)): arr = instruction_list[i].split() instruction_list[i] = arr for i ...
def randomMove(self, grid): """ Choose a random move from the available options """ avail = self.empty(grid) return avail[random.randint(0, len(avail)-1)] def win(self, grid, val=None): """ Pick all positions that player will win after taking it :param gr...
The code implements a decision-making strategy for selecting the optimal move in a game (likely Tic-Tac-Toe). With probability $1-\text{self.epsilon}$, it prioritizes moves in a hierarchy: first, winning moves; then blocking opponent's wins; creating forks; blocking forks; center; corners; and finally sides. If no prio...
def act(self, grid, **kwargs): """ Goes through a hierarchy of moves, making the best move that is currently available each time (with probability 1-self.epsilon). A tuple is returned that represents (row, col). """ # whether move in random or not if random.random...
def get_fault_records(fault_record_api_url: str, from_date_days: int, source: str): """Get fault Records from fault-record API for given timedelta Args: fault_record_api_url (str): fault-record API url from_date_days (int): days timedelta source (str): source name "github" or "slack" ...
This function retrieves new Slack message replies not linked to existing fault records, then posts them to an API to update fault record data. It fetches recent fault records, checks Slack replies against existing links, filters unlinked replies, and sends them to a backend API for record updates.
def update_slack_replies( client: WebClient, channel_id: str, fault_record_api_url: str, update_replies_for_last_days: int, fault_record_update_post_url: str, ): """Get new Fault Record Updates from Slack message replies Args: client (WebClient): Slack WebClient channel_id (...
def replace_user_id(inp_str: str, client: WebClient) -> str: """Takes input string and replaces Slack user ID with email Args: inp_str (str): Input string (slack message) client (WebClient): Slack WebClient Returns: str: Message string with replaced user ids to user emails """ ...
This function parses a Slack bot message into a structured dictionary, extracting and formatting fields like URL, title, reporter, date, description, and signal IDs from the raw message data. It processes emojis, user IDs, and timestamps to create a standardized output for further use.
def parse_bot_message(message: dict, channel_id: str, client: WebClient) -> dict: """Parse Slack message from bot Args: message (dict): raw Slack message channel_id (str): id of the channel to get messages from client (WebClient): Slack WebClient object Returns: dict: parse...
def reactions_list(message: dict) -> List: """Get reactions on Slack message (emojis) Args: message (dict): Slack message Returns: List: list of emojis names that were used in the message """ return [reaction["name"] for reaction in message["reactions"]] if message.get("reactions")...
The function processes Slack conversation history by parsing user and bot messages, filtering out channel notifications and success messages, collecting replies for messages with replies, and returning a list of parsed messages along with the oldest message timestamp.
def process_conversation_history( conversation_history: List, client: WebClient, channel_id: str, fault_record_api_url: str ): """Process Slack conversation history Args: conversation_history (List): Slack conversation history (list of messages) client (WebClient): Slack WebClient object ...
def ok_to_split(ys, depth, n_labels): return impurity(ys, n_labels) > 0. and len(ys) > s_min and depth < d_max def values(samples): return np.array([value(sample) for sample in samples]) def node(boundary=None, p=None, left=None, right=None): return SnS(boundary=boundary, p=p, left=left, right=right) def di...
The main task of the code is to recursively construct a decision tree by splitting samples into left and right subtrees using a given `find_split` function. It checks if splitting is permissible at each depth, creates internal nodes with boundary values, and returns leaf nodes with label distributions when splitting is...
def train_tree(samples, depth, n_labels, find_split): if ok_to_split(values(samples), depth, n_labels): left, right, boundary = find_split(samples, n_labels) if len(left) == 0 or len(right) == 0: return node(p=distribution(values(samples), n_labels)) left_subtree = train_tree(lef...
def segment_length(s): return point_distance(s[0], s[1]) def extend_segment(s, by=small_): v = segment_unit_vector(s)[0] return segment(s[0] - by * v, s[1] + by * v) def point_line_signed_distance(p, c): return np.dot(c.w, p) + c.b def intersect_lines(c, d): p = None if np.abs(np.dot(c.w, d.w)) ...
This function computes the intersection between a line `c` and a line segment `s`, determining if the intersection point lies on the segment (internal), at an endpoint, or not at all. It returns a `SnS` object containing the intersection point, a boolean indicating if the point is internal to the segment, and which end...
def intersect_line_and_segment(c, s): p, internal, endpoint = None, False, None if segment_length(s) > 0.: t = extend_segment(s) d = [point_line_signed_distance(q, c) for q in t] if d[0] * d[1] < 0.: p = intersect_lines(c, line_through(s[0], s[1])) if p is not Non...
def segment(p, q): return np.array((p, q)) def intersect_line_and_segment(c, s): p, internal, endpoint = None, False, None if segment_length(s) > 0.: t = extend_segment(s) d = [point_line_signed_distance(q, c) for q in t] if d[0] * d[1] < 0.: p = intersect_lines(c, line_t...
This code splits a polygon into two sub-polygons using a boundary line. It identifies intersection points between the polygon edges and the boundary, then partitions the original polygon into 'left' and 'right' segments relative to the boundary. The partitioning uses centroid position relative to the boundary to determ...
def cut_polygon(poly, boundary): partition = SnS(segment=None, left=None, right=None) if poly is not None: n = len(poly) if n > 2: candidates = [] for k, p in enumerate(poly): q = poly[(k + 1) % n] side = segment(p, q) i = i...
def data_exists(self, key: str): for metadata in [self.exif, self.iptc, self.xmp]: if key in metadata: return True return False def modify_metadata(self, key: str, value: str | None): try: if not self.__update_metadata(key, value): return ...
This method adds a new key-value pair to metadata after validating non-empty inputs and ensuring the key doesn't already exist. If inputs are empty or the key exists, it logs errors/warnings and exits. If valid, it updates metadata and refreshes the displayed information.
def __add_info(self): key = self.gui["new_key"].get() value = self.gui["new_value"].get() if not key or not value: print(f"Scorpion: [ INFO ] __add_info({key}, {value}): Empty key or value.") return if self.data_exists(key): print(f"Scorpion: [ ERROR ]...
def CheckChangedPR(pr, repo, counter): """ Check if PR (still open) has been changed since creation time """ print(f"Checking PR:{pr}") pr = repo.get_pull(counter) CREATED = pr.created_at commits = pr.get_commits() # Sort the commits by the commit timestamp in descending order sorted...
The main task of the code is to check for new or modified open pull requests (PRs) in a GitHub repository. It authenticates using a token, retrieves open PRs from the main branch, compares them against a list of already built PRs stored in files, and identifies new or changed PRs requiring processing. It handles duplic...
def Finder(): """ Check if any new (not built) pull requests exists in defined repo (fro main branch """ print("------------------------------------------------------------------------------------------") ######################################################################### # Authorization...
def print_board(board: list, msg: str = ""): # print a board os.system("cls") print(msg) try: for row in board: temp = [str(x) for x in row] [print(f"{x:^5s}",end = " ") if x!="0" else print(" --- ",end = " ") for x in temp] print() except: pass d...
The function `game_round` handles a single turn in a sliding tile game. It captures user input (w/s/a/d) to move tiles, checks for valid moves, and updates the board. If no valid moves are made, it ends the game. If a move is successful, it adds a new '2' tile at a random empty position and returns the updated board. E...
def game_round(board: list): # get zero position print_board(board) init_board = copy.deepcopy(board) # user input (w/s/a/d) while True: key_pressed = "" while True: key_pressed = keyboard.read_key() if key_pressed in ['w', 's', 'a', 'd', "esc"]: ...
def _add_mutexes(self): self._next_beat_event = threading.Event() self._startup_event = threading.Event() def reset(self): self.groups = [] self.tracks = [] self.scenes = [] def scan(self, mode: str = "auto") -> None: """ Queries the currently-open Live set and po...
This code initializes a Set object to manage Live's tracks, clips, and devices. If 'scan' is True, it connects to Live, queries its contents, and sets up caching, threading, and event listeners for synchronization. It configures attributes like scanning status, caching, track limits, and initializes data structures for...
def __init__(self, scan: bool = False): """ Create a new Set object. If scan is True, automatically connects to Live and queries the full set of tracks, clips and devices in the set. Args: scan: If True, automatically scans the contents of the set. """ ...
def load(self, filename: str = "set"): """ Read a saved Set structure from disk. """ filename = "%s.pickle" % filename try: data = pickle.load(open(filename, "rb")) except (pickle.UnpicklingError, FileNotFoundError): raise LiveIOError self...
This function attempts to load data from a file; if the file is outdated or loading fails, it scans the data, then saves it. It checks file modification times to determine if a rescan is needed and handles errors by rescanning and saving.
def load_or_scan(self, filename: str = "set", **kwargs): """ Load from file; if file does not exist, scan, then save. """ try: set_file = self.currently_open() if set_file: set_file_mtime = os.path.getmtime(set_file) cache_file_mtim...
def load_hs_codes(file_path): with open(file_path, 'r', encoding="utf-8") as file: json_contents = json.load(file) hs_codes = [content["code"] for content in json_contents if len(content["code"]) == 6 and content["code"].isdigit()] print("HS codes created successfully") return hs_codes def fetc...
The main task is to generate a sitemap index file containing URLs for HS code matches, import duties, customs regulations, and DG goods. It loads HS codes from a JSON file, fetches country codes via an API, retrieves product titles from a PostgreSQL database, and writes dynamic URLs into the sitemap index, ensuring pro...
def main(): # Load HS codes hs_codes = load_hs_codes('wto-hs-desc-202405.json') # Fetch country codes api_url = 'https://moaah-api.com/web-app/smart-hs/getHsCountries' headers = { 'X-User-Sub': 'p9o4k94y4pn6uihkpak2es1ettxkbdfu', 'X-User-Email': 'foxhy@example.com' } cou...
def rotateClockwise(self): savedValues = self.blockX, self.blockY, self.currentBlock.copy() # lists are pass by reference and therefore must be copied for i in range(4): self.currentBlock[i] = self.rotation[(self.currentBlock[5] - 2) * 32 + self.currentBlock[i]] self.setBounds() # mo...
This code handles keyboard input for game controls, detecting key presses (e.g., arrow keys, Z, space) to trigger actions like rotating, moving, and dropping game pieces. It checks if a key is newly pressed, executes the corresponding method (e.g., rotateClockwise, moveLeft), and manages a key state list to prevent rep...
def control(self): if turtools.keyPressed(111) or turtools.keyPressed(38): if self.keyPressed.count('up') < 1: self.rotateClockwise() self.refillKey('up') else: self.removeKey('up') if turtools.keyPressed(52) or turtools.keyPressed(90): ...
def piece(self, x, y, size): for i in range(4): self.block(x + size * ((self.currentBlock[i] + 3) % 4 - 1), y + size * (int((self.currentBlock[i] - 1) / 4) * -1 + 1), size, self.currentBlock[4]) def grid(self, size): for i in range(self.boardSizeY): # new system, just check if there's a [1] ...
The main task of the code is to update a Tetris-like game state each tick. It handles block movement, collision detection, game over conditions, and rendering. When the game is active, it clears the screen, draws the current piece and grid, updates scores/levels, and manages block spawning. If a collision occurs during...
def tick(self): if not self.gameOver: self.sp.clear() self.piece(self.blockX, self.blockY, self.size) self.grid(self.size) self.write(self.oldLevel != self.level, self.oldScore != self.score, self.oldLines != self.lines) if self.newBlock == 1: ...
def load_component_pfb(self, var_meta, name): """ These filetypes have dimensions (component, x, y, z) where component represents an anisotropy """ all_da = {} if var_meta['domain'] == 'surface': dims = ('x', 'y') elif var_meta['domain'] == 'subsurface...
This function loads PFB (Parallel File Binary) data from metadata, determining the appropriate loading method based on the 'type' in var_meta. It handles component-based data, time-varying datasets, and standard PFB files, constructing xarray Datasets. It also resolves file paths and delegates to specialized loader met...
def load_pfb_from_meta(self, var_meta, name='_', parallel=False): base_type = var_meta['type'] if base_type == 'pfb': # Is it component? if len(var_meta['data']) > 1 and 'component' in var_meta['data'][0]: ret_das = self.load_component_pfb(var_meta, name) ...
def read_header(self): """Reads the header""" self.f.seek(0) header = {} header['x'] = struct.unpack('>d', self.f.read(8))[0] header['y'] = struct.unpack('>d', self.f.read(8))[0] header['z'] = struct.unpack('>d', self.f.read(8))[0] header['nx'] = struct.unpack('>i...
This code initializes an object by reading a binary file's header, setting grid parameters (p, q, r) from input or computed values, and optionally precomputing subgrid information. It opens the file, reads the header, calculates missing grid dimensions if not provided, and triggers subgrid computation if enabled.
def __init__( self, file: str, precompute_subgrid_info: bool=True, p: int=None, q: int=None, r: int=None, header: Mapping[str, Number]=None ): self.filename = file self.f = open(self.filename, 'rb') if not he...
def is_meta_or_pfb(self, filename_or_obj, strict=True): def _check_dict_is_valid_meta(meta): assert 'parflow' in meta.keys(), \ ('Metadata file missing "parflow" key - ', 'are you sure this is a valid Parflow metadata file?') if not strict: # Jus...
This method loads ParFlow datasets (pfb or pfmetadata files) into xarray DataArrays/Datasets, handling parameters like base directory, variable selection, chunking, and parallel processing. It identifies file types, reads pfb files directly, or uses pfmetadata to load full simulation data, returning structured xarray o...
def open_dataset( self, filename_or_obj, *, base_dir=None, drop_variables=None, name='parflow_variable', read_inputs=True, read_outputs=True, parallel=False, inferred_dims=None, inferred_shape=None, chunks={}, strict...
def _find_error( root ): if root.tag == 'Error': num = root.find('Number') desc = root.find('Description') return num , desc def _get_error( error ): (num , desc) = error return ValueError( '{num}: {desc}'.format( num=num.text , desc=desc.text , ...
The function parses an XML response by checking for errors, extracting ZipCode elements, and returning processed results. If no ZipCode is found, it raises an error; if one exists, it processes it individually; if multiple, it handles them collectively.
def _parse_response( res ): # General error, e.g., authorization error = _find_error(res.getroot()) if error is not None: raise _get_error(error) results = res.findall('ZipCode') length = len(results) if length == 0: raise TypeError( 'Could not find any address or er...
def _find_error(root): if root.tag == 'Error': num = root.find('Number') desc = root.find('Description') return (num, desc) def _get_error(error): (num, desc) = error return ValueError( '{num}: {desc}'.format( num=num.text, desc=desc.text, ...
This function parses a response object by checking for errors, extracting 'Address' elements, and returning processed results. It raises errors if none or multiple addresses are found, handling single/multiple cases via _process_one/_process_multiple.
def _parse_response(res): # General error, e.g., authorization error = _find_error(res.getroot()) if error is not None: raise _get_error(error) results = res.findall('Address') length = len(results) if length == 0: raise TypeError( 'Could not find any address or erro...
def _create_xml( user_id, *args ): root = etree.Element('CityStateLookupRequest', USERID=user_id) if len(args) > zipcode_max: # Raise here. The Verify API will not return an error. It will # just return the first 5 results raise ValueError( 'Only {address_max} addresses are ...
The function `verify` generates an XML request using `user_id` and additional arguments, retrieves a response, parses it, and returns the parsed result. Its main task is to validate or process user-related data by interacting with a system that requires XML-based communication and response parsing.
def verify(user_id, *args): xml = _create_xml(user_id, *args) res = _get_response(xml) res = _parse_response(res) return res
def _create_xml( user_id, *args ): root = etree.Element('AddressValidateRequest', USERID=user_id) if len(args) > address_max: # Raise here. The Verify API will not return an error. It will # just return the first 5 results raise ValueError( 'Only {address_max} ad...
The main task of the code is to verify a user's information by generating an XML request with the provided user ID and arguments, fetching a response from a service, parsing the result, and returning the processed outcome.
def verify(user_id, *args): xml = _create_xml(user_id, *args) res = _get_response(xml) res = _parse_response(res) return res
def smoothed_density_moments(self): fourier_kernel = self.smoothing_kernel_3D norm_fourier_kernel = fourier_kernel / self.boxsize**3 real_space_kernel = norm_fourier_kernel.c2r() real_space_kernel.value = np.real(real_space_kernel.value) xi_R_field = self.smoothed_pk_3D.c2r() ...
The function calculates a weighted integral of the density distribution over each bin interval, adjusting for shot noise if specified. It computes the integral using the trapezoidal rule and multiplies it by a factor involving variance terms (sigma_R and sigma_RR). The result is an array of these adjusted integrals, re...
def nbar_R_DS(self, density_bins, shot_noise=False, p=4): res = list() self.density_bins = density_bins self.nsplits = len(density_bins)-1 if not hasattr(self, 'density_moments'): self.smoothed_density_moments() split_delta_tilde = self.compute_delta_tilde(density_b...
def smoothed_density_moments(self): fourier_kernel = self.smoothing_kernel_3D norm_fourier_kernel = fourier_kernel / self.boxsize**3 real_space_kernel = norm_fourier_kernel.c2r() real_space_kernel.value = np.real(real_space_kernel.value) xi_R_field = self.smoothed_pk_3D.c2r() ...
The function computes the cross-correlation function (CCF) of tracers using density bins, considering shot noise or not. It calculates a result array by evaluating statistical terms (delta1, delta2, delta3) and prefactors, handling shot noise corrections with specialized variables. The output is an array of CCF values ...
def ccf_tracers(self, density_bins, shot_noise=False, p=4): prefactor_num = np.sqrt(2/np.pi) * self.xi_R / (self.sigma_RR * self.xi) prefactor_denom = np.sqrt(2/np.pi) * self.sigma_R**2 / self.sigma_RR res = list() self.density_bins = density_bins self.nsplits = len(density_bins)...
def load_images_from_directory(self, directory, scale=None, factor=False): """ Loads all images from the specified directory. Args: directory (str): Path to directory containing images to load. scale (tuple[float, float], optional): Scale factors in the ...
The main task of the code is to load and scale essential game assets (player run/jump animations, obstacles, ground, and background images) from specified directories. It uses predefined scales for different elements, initializes glow effects, and handles missing files by exiting the program with an error message. The ...
def initialize_images(self): """ Loads and scales all images. Raises: FileNotFoundError: If an image file could not be loaded. """ try: self.run_imgs = self.load_images_from_directory( self.paths_config.get("run"), PLAYER_SCALE, Tr...
def init_table(self): # add slack variables slack_matrix = np.identity(len(self.b)) # A matrix with slack variables new_A = np.concatenate((self.A, slack_matrix), axis = 1) # Concatenate A with b b = np.reshape(self.b, (-1,1)) table_AB = np.concatenate((new_A, b),...
This code implements the simplex algorithm for solving linear programming problems. It adjusts the objective function based on maximization/minimization, constructs an initial tableau, iteratively finds pivot elements to improve the solution, and retrieves the optimal solution once no further improvements are possible.
def run(self, A, b, c, obj_type): # print("simplex") self.obj_type = obj_type self.A = A self.b = b if self.obj_type == 'max': self.c = -c if self.obj_type == 'min': self.c = c # add variable and build the initial table ...
def init_table(self): # add slack/artifical variables slack_matrix = np.identity(len(self.b)) # A matrix with slack/artifical variables new_A = np.concatenate((self.A, slack_matrix), axis = 1) # Concatenate A with b b = np.reshape(self.b, (-1,1)) table_AB = np.con...
This code implements the simplex algorithm for linear programming. It initializes a simplex tableau, iteratively selects pivot elements to optimize the objective function (handling both maximization and minimization via sign adjustment), performs row operations to update the tableau, and terminates when optimality is r...
def run(self, A, b, c, obj_type): # print("simplex") self.obj_type = obj_type self.A = A self.b = b if self.obj_type == 'max': self.c = c else: self.c = -c # add variable and build the initial table table = self.init_table(...
def get_stations(self, dataset_id: str, geometry: dict = None, lat: float = None, lon: float = None, distance: float = None, ): """ Method to return the stations associated with ...
The function retrieves and processes dataset results based on parameters like dataset_id, station_ids, geometry, and date ranges. It handles spatial queries, filters data by time/versions, combines chunks using threading, applies encodings, converts data formats, and returns results as xarray objects or other specified...
def get_results(self, dataset_id: str, station_ids: Union[str, List[str]] = None, geometry: dict = None, lat: float = None, lon: float = None, from_date: Union[str, pd.Timestamp, datetime] = None, ...
def move_up(grid, curr_scor): # to move up we just take # transpose of matrix new_grid = transpose(grid) # then move left (calling all # included functions) then (new_grid, changed, score) = move_left(new_grid, curr_scor) # again take transpose will give # desired results new_g...
The function `get_valid_moves` checks if any cell in the 4x4 matrix contains 2048, returning "WIN" if so. Otherwise, it identifies valid moves ("w", "a", "s", "d") by testing if moving in each direction would alter the board state. It returns a list of valid moves or "WIN" based on the matrix's current state. Your retu...
def get_valid_moves(mat): # if any cell contains 2048 we have won for i in range(4): for j in range(4): if mat[i][j] == 2048: return "WIN" valid_moves = [] # check if moving in each direction will change anything if move_up(mat, 0)[1]: valid_moves.append...
def get_curr_state(self,agent_host): state_matrix = self._get_entities_position(agent_host) cur_state = [] if(state_matrix['life']==20): cur_state.append(2) elif(state_matrix['life']==0): cur_state=[0,(-1,-1),(-1,-1)] return tuple(cur_state) elif(state_matrix['li...
The code determines the best move for an agent by simulating actions in a game environment. It iteratively retrieves the current state, selects a move from possible options, executes it, and updates the state. Rewards are adjusted based on state conditions: -1000 if reaching a terminal state (state[0]=0), -50 for state...
def best_move(self,agent_host): curr_r = 0 curr_state = self.get_curr_state(agent_host) while(curr_state[0]!=0): pm = self.get_possible_move(agent_host) move = self.choose_move(curr_state,pm,-1) self.act(agent_host,move) curr_state = self.get_curr_sta...
def get_curr_state(self,agent_host): state_matrix = self._get_entities_position(agent_host) cur_state = [] if(state_matrix['life']==20): cur_state.append(2) elif(state_matrix['life']==0): cur_state=[0,(-1,-1),(-1,-1)] return tuple(cur_state) elif(state_matrix['li...
This code implements a Q-learning agent that interacts with an environment via agent_host, collects experience (states, actions, rewards), and updates its Q-table using a sliding window of experiences. It calculates rewards based on specific state conditions, terminates on a predefined state (temp_s[0]==0), and applies...
def run(self, agent_host): print(len(self.q_table)) S, A, R = deque(), deque(), deque() present_reward = 0 done_update = False reward = 0 while not done_update: s0 = self.get_curr_state(agent_host) possible_actions = self.get_possible_move(agent_h...
def vectorize_text(self, text, tokenizer): ''' Tokenizes words, converts them into padded sequences for preprocessing ''' words = word_tokenize(text) tokenizer.fit_on_texts(words) seq = tokenizer.texts_to_sequences(words) sent = [x[0] for x in seq] padded ...
This code retrieves or generates state and action data for a given state. If the state exists in stored data, it extracts precomputed vectors and actions; otherwise, it vectorizes the state, extracts nouns, generates actions, calculates probabilities, and stores results. It returns probabilities, actions, state vectors...
def get_data(self,state): if(state in list(self.state_data['state'])): statevec = list(self.state_data[self.state_data['state'] == state]['statevec'])[0][0] try: nouns = list(self.state_data[self.state_data['state'] == state]['nouns'])[0][0] e...
def checkMoreOffer(self): """ Method Name: checkMoreOffer Description: This method checks whether more offer links is provided for the product or not. Output: None On Failure: Raise Exception Version: 1.0 Revisions: None """ self.logging.log('Ente...
The method `getAvailableOffer` retrieves available product offers from a webpage by checking specific locators. It first verifies if more offers exist, then uses predefined locators to extract offer details from the page source. If no valid locators are found, it returns "No Offer For the product." Exceptions during ex...
def getAvailableOffer(self): """ Method Name: getAvailableOffer Description: This method returns offers available. Output: Available offer On Failure: Raise Exception Version: 1.0 Revisions: None """ self.logging.log('Entered the getAvailableOffer...
def actualProductLinks(self): """ Method Name: actualProductLinks Description: This method returns the actual product links after filtering. Output: individual product link On Failure: Raise Exception Version: 1.0 Revisions: None """ self.logging....
The main task of the code is to find and return a product link from a list of product links that has a review count exceeding a specified expected value. It randomly selects product links, checks their review pages, and continues looping until a product meets the review threshold. If successful, it logs the process and...
def getLinkForExpectedReviewCount(self, expected_review, searchString): """ Method Name: getLinkForExpectedReviewCount Description: This method extracts the link of product having more than expected count. Output: None On Failure: Raise Exception Version: 1.0 Rev...
def consume_while(self, predicate: Callable[[str], bool]) -> str: """Consume characters from the text while the predicate is true.""" start = self.pos while self._peek_char() is not None and predicate(self._peek_char()): self._next_char() return self.text[start:self.pos] def ...
This function parses the next token from input text, categorizing it as integer, identifier, operator, assignment, or parenthesis based on the current character, while skipping whitespace and raising an error for illegal characters.
def _next_token(self) -> Token | None: """Parse the next token from the text.""" self.consume_while(str.isspace) start = self.pos char = self._peek_char() if char is None: return None if char.isdigit(): return Token("int", self.consume_while(str.is...
def darknet_53(name=None): x = inputs = Input([None, None, 3]) x = conv_block(x, 32, 3) x = darknet_block(x, 64, 1) x = darknet_block(x, 128, 2) x = route1 = darknet_block(x, 256, 8) x = route2 = darknet_block(x, 512, 8) x = darknet_block(x, 1024, 4) return tf.keras.Model(inputs, (route1...
The code defines a YOLOv3 model for object detection. It uses Darknet-53 as the backbone, processes multi-scale features via convolutional blocks, generates detection outputs at three scales, applies bounding box conversion, and performs non-max suppression (NMS) to refine predictions. The model takes 416x416 RGB image...
def yolo_v3_model(): x = inputs = Input([416, 416, 3], name='input') route1, route2, x = darknet_53(name='yolo_darknet')(x) x = yolo_conv_block(512, name='yolo_conv_0')(x) output_0 = yolo_detection_output(512, len(yolo_anchor_masks[0]), num_classes, name='yolo_output_0')(x) x = yolo_conv_block(25...
def getCurrTime(): curr = time.localtime() curr24 = int(time.strftime("%H%M%S", curr)) currDay = time.strftime("%A", curr) if currDay == "Thursday": currDay = "R" elif currDay == "Sunday": currDay = "Sunday" else: currDay = currDay[0] return curr24, currDay def conve...
The function retrieves room schedule information for a selected hall on a specified day and time, processes availability, and returns a list of available and occupied rooms. It handles weekend cases by returning "Weekend", converts class times to integers, checks room availability, and compiles results into a structure...
def get_info(selectedHall, cDay="Curr", cTime="Curr"): # return roomScheduleInfo = {} current, currDay = getCurrTime() if cDay != "Curr": if cDay == "Thursday": cDay = "R" elif cDay == "Sunday": cDay = "Sunday" else: cDay = cDay[0] c...
def find_most_likely_spotify_map_to_youtube_videos( youtube_videos: List[Dict], spotify_episodes: List[Dict] ) -> Dict[str, Dict]: youtube_to_matching_spotify_episode: Dict[str, Dict] = {} # loop through all the YouTube videos, find most likely Spotify match for youtube_video in youtube_videos: ...
This function maps YouTube videos to Spotify podcast episodes by identifying bijective matches (one-to-one correspondences) between the two platforms. It uses matching algorithms to align content based on metadata (names, descriptions) and verifies reciprocal mappings. Once valid pairs are confirmed, it enriches them w...
def map_episodes( youtube_videos: List[Dict], spotify_episodes: List[Dict], mapped_channels: List[MappedChannel], ) -> List[Dict]: """Map a given channel's YouTube videos against possible Spotify podcast versions of those same videos. """ youtube_to_matching_spotify_episode: Dict[ st...
def create_always_on_top_toggle(self, row=0, column=0): self.always_on_top_button = tk.Button(self.master, text="Enable Always on Top", command=self.toggle_always_on_top) self.always_on_top_button.grid(row=row, column=column, columnspan=3, padx=10, pady=10) def create_timezones(self, row=0, column=0): ...
The code defines a method `setup_ui` that initializes a user interface with various interactive elements. It creates a toggle for "always on top," timezone selectors, labels for local time and Bitcoin prices, a city dropdown, a chart display area, and ETF-related buttons. The layout positions these components in a grid...
def setup_ui(self): self.create_always_on_top_toggle(row=0, column=0) self.create_timezones(row=1, column=0) self.create_local_time_label(row=len(self.timezones)+2, column=0) self.create_bitcoin_price_label(row=len(self.timezones)+3, column=0) self.create_city_dropdown(row=len(se...
def create_always_on_top_toggle(self, row=0, column=0): self.always_on_top_button = tk.Button(self.master, text="Enable Always on Top", command=self.toggle_always_on_top) self.always_on_top_button.grid(row=row, column=column, columnspan=3, padx=10, pady=10) def create_timezones(self, row=0, column=0): ...
The main task of the code is to set up a user interface by arranging UI components in a grid layout. It initializes elements like an always-on-top toggle, timezone selectors, time labels, Bitcoin price display, city dropdown, chart frame, and ETF buttons, positioning them at specific rows and columns to create a struct...
def setup_ui(self): self.create_always_on_top_toggle(row=0, column=0) self.create_timezones(row=1, column=0) self.create_local_time_label(row=len(self.timezones)+2, column=0) self.create_bitcoin_price_label(row=len(self.timezones)+3, column=0) self.create_city_dropdown(row=len(se...
def debug(msg: str, caller: Any = None) -> None: if not logger.level == logging.DEBUG: return message = _format_msg(msg, caller) logger.debug(message) def warn(msg: str, caller: Any = None, sleep: int = 0) -> None: message = _format_msg(msg, caller) logger.warning(message) if sleep: ...
The function calculates the descaling error of a video clip using a specified kernel by comparing the original and rescaled video. It computes the difference (error) via PlaneStatsDiff, handling both progressive and interlaced (field) processing. The result is a dictionary mapping kernel configurations to their respect...
def get_error( clip: vs.VideoNode, width: float = 1280.0, height: float = 720.0, line_mask: vs.VideoNode | None = None, crop: int = 8, kernel: KernelT | None = None, ) -> dict[str, float]: """Get the descale error.""" debug(kernel, get_error) if not issubclass(kernel if isinstance(kernel, t...
def init_clip(file: str, files: list, trim_dict: dict, trim_dict_end: dict, change_fps: dict = {}, analyze_clip: str = None, files_info: list = None, return_file: bool = False): #evaluate analyze_clip if it hasn't been already if analyze_clip is not None and file is None and first_file is None: file = ...
The code processes video files to generate and upload screenshots for comparison on slow.pics. It analyzes video metadata, trims clips, adjusts FPS, selects frames, generates screenshots, and uploads them with metadata. It ensures consistent parameters, handles errors, and provides a URL for the uploaded comparison. Ke...
def actual_script(): global first_file first_file = None #first file is only determined by analyze_clip if it is called #find video files in the current directory, and exit if there are less than two files = [file for file in os.listdir('.') if file.endswith(('.mkv', '.m2ts', '.mp4', '.webm'))] ...
def warn(msg: str, caller: Any = None, sleep: int = 0) -> None: message = _format_msg(msg, caller) logger.warning(message) if sleep: time.sleep(sleep) def debug(msg: str, caller: Any = None) -> None: if not logger.level == logging.DEBUG: return message = _format_msg(msg, caller) ...
The code processes a video clip by validating input file existence, setting default dimensions, handling edge cases for scaling parameters, extracting a frame's luma plane, generating an edge mask, and evaluating reconstruction errors using multiple kernels to assess quality.
def main() -> None: if not (p := SPath(args.input_file)).exists(): raise FileWasNotFoundError(f"Could not find the file, \"{p}\"!", main) clip = source(p) if args.native_height == -1 and args.native_width == -1: warn(f"You cannot set both \"--native-height\" and \"--native-width\" to \"-1\...
def get_prime(size: int) -> int: """getting q, a strong pseudo prime of the form 2*prime + 1""" passed = False while not passed: passed = True # random number q divided by 2 bits long prime = secrets.randbits(size // 2) # a list of 10 different random numbers between [2, prim...
The code implements the Diffie-Hellman key exchange protocol to securely generate a shared secret between two parties. It selects a large prime (P) and generator (G), generates random private keys (X, Y), computes public keys (A = G^X mod P, B = G^Y mod P), then derives shared secrets (Key1 = B^X mod P, Key2 = A^Y mod ...
def main() -> None: # Choose a prime number P # prime = 9974897320593393323034444433565936803804995634370485307 prime = get_prime(365) print(f"Prime (P): {prime}") # Choose a generator G # generator = 5938482824295760067713474569266958157940183991385599526 generator = get_generator(prime) ...
def parse_SNP_tag(SNP_tag): #annot_locs += [int(SNP_tag[1:-1])] #annot_names += [SNP_tag matches = re.match('(\D)(\d+)(\D)', SNP_tag) if not matches: raise RuntimeError("Invalid SNP tag: {}".format(SNP_tag)) wild_char, loc, mut_char = matches.group(1), int(matches.group(2)), matches....
The main task of the code is to process a wild-type DNA sequence and a SNP tag to generate wild-type and mutant sequence contexts around a specific SNP position. It validates input parameters, adjusts context length if necessary, creates mutant sequences, extracts query regions, and prepares FASTA files for downstream ...
def run_all_SNP(fasta_wt, SNP_tag, query_context_len=20, out_dir='./'): # todo: check +-1 boundary cases of position and lenghts in this method wild_char, snp_loc, mut_char = parse_SNP_tag(SNP_tag) rec_wt = SeqIO.read(fasta_wt, "fasta") wild_seq = rec_wt.seq if len(wild_seq) < 200: ...
def plot_heat_maps(mfe_probs, bp_probs_whole, filename='', what='all', inverse=False, interactive=False, gene_loc=None, title_suffix='',vmin=1e-2,vmax=1.0, out_dir='./', upper_triangle_txt='',lower_triangle_txt='',colormap='hot',mutation_pos=None,cutout_min_max=[None,None]): i...
The function generates heatmaps for RNA sequences by combining the input RNA sequence with a context region. It constructs a full sequence context, determines gene location, and plots heatmaps using either base pair probability matrices (BPPM) or minimum free energy (MFE) probabilities, depending on the 'what' paramete...
def my_heatmaps(rna_seq, context_all, context_len, insert_pos=None, filename='heatmap', what='all', inverse=True, interactive=False, motif_len=None): if context_all == None: print ("Full sequence and context given") whole_seq_context = rna_seq gene_loc = [insert_pos, insert...
def _update(self, t): # update the auxiliary variables self._M_inv = self.M_inv() self._T = self.T() # compute SW and SL self._SW = 0 for t_n in t.T: self._SW += self.SW_n(t_n) self._SW = self._SW / t.shape[1] self._SL = self.SL() def W_tilde(s...
This function performs a single EM algorithm iteration by updating model parameters (M, T, SW), the latent matrix W, and standard deviation (sg). It calculates the parameter change (delta) as the norm of W's update plus sg's absolute difference, then returns this delta as the convergence error measure.
def em_step(self, t): ''' single step of the EM algorithm ''' # update M, T, and SW self._update(t) # update latent matrix W W = self.W_tilde() delta = np.linalg.norm(W - self.W) self.W = W # update standard deviation sg = self.sg_t...
def d(self): ''' dimension of the feature space t ''' return self.W.shape[0] def tr_n(self, t_n): ''' computes the trace of the covariance matrix of a single data point. Mean of t_n is assumed to be 0 ''' return sum(t_n**2) def em_step(self, t): ...
(The code implements the EM algorithm on input data `t` with a convergence threshold `epsilon`. It first computes the empirical covariance matrix, then iteratively updates model parameters via `em_step` until the change in parameters (`delta`) falls below `epsilon`. The loop prints intermediate `delta` values, and a fi...
def em_algo(self, t, epsilon): ''' EM algorithm on the data t ''' # slight consistency check assert t.shape[0] == self.d() # get empirical variance self._tr_S = sum([self.tr_n(t_n) for t_n in t.T]) / t.shape[1] # EM algorithm ...
def isEmpty(self): return self.__head == None def insert_head(self, new_head: Node) -> None: if not self.isEmpty(): self.__head.set_prev(new_head) new_head.set_next(self.__head) self.__head = new_head def insert_tail(self, new_tail: Node): if self.isEmpty(): ...
The function inserts a new node at a specified position in a linked list. If the list is empty, it adds the node as the head. Otherwise, it traverses to the given position, inserting the node before the target node if possible; if the position exceeds the list length, it appends the node to the tail.
def insert_at_position(self, pos: int, new: Node) -> None: if self.isEmpty(): self.insert_head(new) return curr = self.__head for i in range(pos): if (next := curr.get_next()) is not None: curr = next else: self.inse...
def name_fetch(EID): """ It takes an email ID as input and returns the corresponding username :param EID: Email ID of the user :return: The name of the user. """ sqlconnection = sqlite3.Connection("AlgoTrade.db") cursor = sqlconnection.cursor() query1 = "SELECT * FROM User WHERE email =...
The code handles user sign-in by verifying email/password credentials against a SQLite database. If valid, it fetches user data, predicts stock prices using LSTM, analyzes news sentiment, retrieves financial metrics, and renders a dashboard with visualizations, forecasts, and analysis for the authenticated user.
def signin(): if request.method == "POST": EID = request.form['email'] PW = request.form['password'] sqlconnection = sqlite3.Connection("AlgoTrade.db") cursor = sqlconnection.cursor() query = "SELECT email,password From User WHERE email = \'" + EID+"\'" +" AND password=\'"+P...
def get_match(t1, s1): for t2 in tiles: if t1==t2: continue for j in range(4): orientation = compare_sides(t1,s1, t2,j) if orientation: return t2, j, orientation return 0,0,False def rotate_index(frame, side, endside, reverse): if frame == ...
This code recursively explores and maps tiles in a grid by checking their sides for matches, rotating tiles as needed, and placing them in the correct positions. It tracks visited tiles to avoid cycles, builds a dictionary of tile connections, and populates a grid with tiles based on directional offsets. The main task ...
def explore_tiles(t1, x=0, y=0): if t1 in visited: return visited.append(t1) sides = {} for side in range(4): t2, s2, orientation = get_match(t1, side) #print(side,':',t2, s2, orientation) if orientation: rotate_index(t2, side, s2, orientation) si...
def get_match(t1, s1): for t2 in tiles: if t1==t2: continue for j in range(4): orientation = compare_sides(t1,s1, t2,j) if orientation: return t2, j, orientation return 0,0,False def rotate_index(frame, side, endside, reverse): if frame == ...
This function explores a grid by recursively traversing connected tiles, marking visited positions, and determining adjacent tile orientations. It uses directional offsets to navigate the grid, rotates tiles as needed, and builds a mapping of tile connections. The exploration starts at tile t1, checks all four possible...
def explore_direction(t1, x=0, y=0, *, d=0): if t1 in visited: return grid[x,y] = t1 visited.append(t1) sides = {} for side in range(4): t2, s2, orientation = get_match(t1, side) if t2 in alltiles: continue #print(side,':',t2, s2, orientation) if...
def get_user_input_choice(): try: user_input = int(input("> ")) except ValueError: user_input = -1 return user_input def classic_cryptosystems(): user_input = -1 while user_input != 0: print("===CLASSIC CRYPTOSYSTEMS===") print("---Affine") print(" 1: Encryp...
The main task of the code is to present a menu-driven interface for selecting cryptographic operations, including Classic Cryptosystems, Cryptomath utilities, DES, and RSA. It loops until the user selects "Return to Main Menu" (0). However, DES and RSA options only display test/status messages, while the other options ...
def crypto_library(): user_input = -1 while user_input != 0: print("===CRYPTO LIBRARY===") print("1: Classic Cryptosystems") print("2: Cryptomath and Utilities") print("3: DES") print("4: RSA") print("0: Return to Main Menu") user_input = get_user_input_ch...
def abort_program(text, error_code=-1): """Log critical error @text and exit program with @error_code.""" logging.critical(text) sys.exit(error_code) def is_admin(): """Check whether script is executed using root privileges.""" if os.name == "nt": try: import ctypes ...
The function performs preflight checks to ensure required tools (e.g., nmap, curl) are available, validates queuefile existence/permissions, disables tools if missing or requiring elevated rights, and sets tool versions. It handles resume/force flags, checks for admin privileges, and aborts or disables features when de...
def preflight_checks(options): """Check if all tools are there, and disable tools automatically.""" try: if options["resume"]: if ( not os.path.isfile(options["queuefile"]) or not os.stat(options["queuefile"]).st_size ): abort_progr...
def get_binary(tool): """Convert tool command to its environment variable, if it is set.""" if tool.split(".")[0].upper() in os.environ: tool = os.environ[tool.split(".")[0].upper()] return tool def read_parameters(settings, host, port): """Read tuning dictionary per host-port combination from t...
This function performs a Nikto vulnerability scan on a specified host and port, configuring scan parameters like timeout, SSL, proxy, authentication, and custom settings. It executes the scan, captures results, and checks output for security alerts, logging progress and storing findings in host_results.
def do_nikto(host, port, options, logfile, host_results): """Perform a nikto scan.""" command = [ get_binary("nikto"), "-ask", "no", "-host", f"{host}:{port}", "-maxtime", f'{options["maxtime"]}s', "-nointeractive", "-vhost", f"{hos...
def get_binary(tool): """Convert tool command to its environment variable, if it is set.""" if tool.split(".")[0].upper() in os.environ: tool = os.environ[tool.split(".")[0].upper()] return tool def read_parameters(settings, host, port): """Read tuning dictionary per host-port combination from t...
(The function `do_testssl` runs the `testssl.sh` tool to analyze SSL/TLS configurations and vulnerabilities on a specified host/port. It constructs a command with default or user-defined parameters, handles protocol-specific settings (e.g., SMTP), applies timeouts, and checks for security alerts in the output. Results ...
def do_testssl(host, port, protocol, options, logfile, host_results): """Check SSL/TLS configuration and vulnerabilities.""" # --color 0 Don't use color escape codes # --warnings off Skip connection warnings # --quiet Don't output the banner # # The following settin...
def parse_arguments(banner): """Parse command line arguments.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, fromfile_prefix_chars="@", ) parser.add_argument( "target", nargs="?", type=str, ...
This code executes a network scanning task by parsing arguments, configuring logging, performing preflight checks, preparing Nmap scan parameters, managing a host queue, reading settings, initializing results, scanning targets, and saving output to JSON. It handles resume options, dry runs, and exits with status codes,...
def main(): """Main program loop.""" banner = f"{NAME} version {__version__}" options = parse_arguments(banner) options["exit"] = 0 setup_logging(options) logging.log(STATUS, "%s starting", banner) preflight_checks(options) prepare_nmap_arguments(options) if not options["resume"]: ...
def requests_get(url, options, headers=None, allow_redirects=True): """Generic wrapper around requests object.""" # Don't try this at home, kids! Disabling SSL verification verify = False if not headers: headers = {"User-Agent": options["user_agent"]} if not verify: # pylint: disable...
The function `analyze_url` automates website technology detection and vulnerability scanning. It uses Wappalyzer to identify CMS (e.g., Drupal, Joomla, WordPress) on a given URL. If the site returns a 400 error via HTTP, it retries with HTTPS. Upon successful retrieval (status 200), it logs analysis results and trigger...
def analyze_url(url, port, options, logfile, host_results): """Analyze a URL using wappalyzer and execute corresponding scans.""" wappalyzer = Wappalyzer.Wappalyzer.latest() page = requests_get(url, options) if not page: logging.debug("%s Got no reply - cannot analyze that", url) return ...
def do_nikto(host, port, options, logfile, host_results): """Perform a nikto scan.""" command = [ get_binary("nikto"), "-ask", "no", "-host", f"{host}:{port}", "-maxtime", f'{options["maxtime"]}s', "-nointeractive", "-vhost", f"{hos...
The function `http_checks` performs HTTP/HTTPS security assessments by executing various checks based on provided options. It determines SSL usage, constructs the target URL, and triggers tasks like Nikto scanning, URL analysis, compression, header, redirect, and trace checks. Results are logged and stored in `host_res...
def http_checks(host, port, protocol, options, logfile, host_results): """Perform various HTTP checks.""" ssl = False if "ssl" in protocol or "https" in protocol: ssl = True url = f"https://{host}:{port}" else: url = f"http://{host}:{port}" if options["nikto"]: do_nik...
def do_portscan(host, options, logfile, stop_event, host_results): """Perform a portscan. Args: host: Target host. options: Dictionary object containing options. logfile: Filename where logfile will be written to. stop_event: Event handler for stop event ...
The main task of the code is to process each host atomically by scanning open ports, checking against allowed port configurations, performing HTTP/TLS protocol-specific checks, logging results to temporary files, and adding output/results to respective queues. It handles host processing in a worker thread, respects sto...
def process_host( options, host_queue, output_queue, finished_queue, stop_event, results ): """ Worker thread: Process each host atomic, add output files to output_queue, and finished hosts to finished_queue. """ while host_queue.qsize() and not stop_event.wait(0.01): try: ho...
def svn_lang_dirs(git_repo_name, work_directory): # Find all the places the language files have lived in gtsvn print(f"checking {git_repo_name}: {datetime.datetime.now()}") svn_name = git_repo_name.split("-")[1] lang_map = {"lut": ["slh", "lut"], "rmf": ["rom", "rmf"], "cor": ["kor", "cor"]} # rmf...
This code processes the migration of language files from SVN to Git. It checks if a language's files exist in multiple SVN directories; if so, it prepares and executes a Git replacement. If only one SVN directory exists, it skips processing. The function handles the transition by replacing Git repos with SVN content wh...
def fix_a_lang(git_repo_name, work_directory): svn_elements = set(svn_lang_dirs(git_repo_name, work_directory)) if len(svn_elements) < 2: # The language files have only lived in one svn directory. # The previous svn2git process has covered this case print("No need to process", git_repo_n...
def prepare_old_svn(work_directory): # 191058 here = os.path.abspath(os.path.dirname(__file__)) commands = [ ( f"git svn clone -r1:191058 --authors-file {here}/svn2git-authors.txt " "https://gtsvn.uit.no/langtech/trunk langtech_upto_removed_langs", work_directory,...
This script converts SVN repositories to Git by preparing an old SVN working directory, processing valid Git repositories from a specified home directory, fixing language-specific configurations, and applying SVN-to-Git transformations for Estonian language tools (utee and plamk) in the target work directory.
def main(): if len(sys.argv) != 3: print( "usage: ./langs_svn_to_git.py <dir-where-giellalt-is-clone> <dir-where-work-is-done>" ) sys.exit(1) work_directory = os.path.abspath(sys.argv[2]) if not os.path.exists(os.path.join(work_directory, "lt")): try: ...
def poker_round(self): """ Simulate a round of poker (Pre-flop, Flop, Turn, River) """ stages = ['Pre-flop', 'Flop', 'Turn', 'River'] cards_shown = [0, 3, 4, 5] def players_in(): players = [] for player in self.decision_holder.keys(): ...
The main task of the code is to repeatedly play rounds of poker until the game ends (e.g., one player remains or the user stops). It starts a round, checks if the game is over, and prompts the user to continue. If the user inputs 'y', it resets the game state and plays another round. The loop terminates when the game i...
def play(self): """ Play rounds of poker until the player decides to stop or only one player is left. """ ctn = True self.poker_round() # TODO remove players with no money left # TODO distribution of pot while ctn: if self.is_game_over...
def fold(self, player : int): """ If fold is called, the player is out of the game. """ # check if player is either small blind or big blind if self.order_of_play[player] == self.n_players - 2 and self.player_bets[player] < self.small_blind: amount = self.small_blind...
This function processes a player's action in a game, executing corresponding operations like folding, checking, raising, or going all-in based on the input action. It validates the action, triggers the relevant method, and records the decision in a tracking dictionary. Invalid actions raise an error.
def player_action(self, player : int, action : str): """ Action of a player """ if action == 'fold': self.fold(player=player) elif action == 'check': self.check(player=player) elif action == 'raise': self.raise_money(player=player) ...
def player_input(self): """ Player action """ action = input('(f)old, (c)heck, (r)aise, (a)ll-in): ') print('\n') if action == 'f': return 'fold' elif action == 'c': return 'check' elif action == 'r': return 'raise' ...
The code manages a betting round in a poker game by evaluating player hands, processing decisions (fold, all-in), and determining when the round ends based on player actions, money status, or remaining players. It handles human input for player 0 and uses bot logic for other players, updating decisions and checking for...
def player_moves(self, table_cards : list = None, cards_shown : int = 0): """ Round of betting """ players = list(self.decision_holder.keys()) bot_hands = {player: self.player_hands[player] for player in self.decision_holder.keys() if player != 0} ranks = PokerR...
def crawl_yahoo(self): res = {} Name = self.keyword.replace(" ", "+") search_url = ( f"https://movies.yahoo.com.tw/moviesearch_result.html?keyword={Name}&type=movie&movie_type=movie") search_res = requests.get(search_url) search_sp = bs4.BeautifulSoup(search_res.text...
The code's main task is to aggregate movie data from Yahoo, Rotten Tomatoes, and IMDb by calling their respective crawler methods, then return the consolidated data stored in `self.data` for further processing or analysis.
def crawl(self): self.crawl_yahoo() self.crawl_rotten_tomatoes() self.crawl_imdb() return self.data
def advancePos(self) -> None: """Advances position for the lexer. The function moves `_readPos` and `_curPos` attributes. Also calculates if input is exhausted and sets `_eof` to True. """ self._curPos = self._readPos if self._curPos >= len(self.input): self...
This function generates and returns a `token.Token` by consuming input, handling numbers, identifiers, strings, and symbols. It advances the input position, skips whitespace, checks for EOF, and uses helper methods to parse complex tokens. It returns appropriate token types like NUMBER, IDENT, STRING, or specific symbo...
def nextToken(self) -> token.Token: """Consume the current input and return a TOKEN. Returns a `token.Token` object at every call. This lexer advances the position of the input before consuming it. This means - `_curPos` is uninitalized before calling this function for the fir...
def get_chat_id(update, context): chat_id = -1 if update.message is not None: chat_id = update.message.chat.id elif update.callback_query is not None: chat_id = update.callback_query.message.chat.id elif update.poll is not None: chat_id = context.bot_data[update.poll.id] re...
The code processes a Telegram update by retrieving a user's chat ID, fetching historical search data, and sending formatted deal information (prices, discounts, URLs) to the user's chat. It logs progress, formats messages with bold text and HTML, and sends each deal as a separate message. The function also prepares for...
def process(update: Update, context: CallbackContext): # context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!") # context.bot.send_message(chat_id, text) chat_id = get_chat_id(update,context) log.info(f'chat_id= {chat_id}') search_history = dbhelper.get_s...