dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def __dFrame_check(self, obs): """ Checks dataFrame for correct formatting :type obs: pandas.Series """ if ('DATE_OBS' not in obs.index or 'RA' not in obs.index or 'DEC' not in obs.index or 'MAG' not in obs.index or 'BAND' not in obs.index): indices =...
This code initializes an object with observational data, validates input parameters (e.g., note1/note2 length), and sets attributes using helper methods. It checks data types, enforces format rules, and processes observation details like discovery, identifiers, and astronomical measurements.
def __init__(self, obs, obsNum=' ', provNum=' ', discovery=' ', note1=' ', note2='C', observCode='W84', newObj=True): """ :type newObj: bool :type provNum: str :type obs: pandas.Series """ self.__dFrame_check(obs) self.newObj = newObj ...
def attach(self): """ Attach to the game """ try: self.m.open_process_from_name("DarkSoulsRemastered") self.module = process.module_from_name(self.m.process_handle, "DarkSoulsRemastered.exe") if not hasattr(self.module, "lpBaseOfDll"): raise exception.ProcessNotFound("DarkSouls...
The code's main task is to initiate a process by attaching to a game, reading its memory if successfully attached, and then printing the retrieved memory data. This sequence enables interaction with or analysis of the game's runtime memory state.
def start(self): self.attach() if self.game_attached: self.read_memory() self.print_memory()
def feature_eng(pos, poi, add_pois=False): """Add and transform features in the positions dataset to facilitate the analysis. Parameters ---------- pos : pd.DataFrame A data frame with the available position and state measurements from all vehicles. poi : pd.DataFrame ...
The function `get_results` calculates the total and stopped time each vehicle spends in Points of Interest (POIs) by processing position data (`pos`) and POI definitions (`poi`). It applies feature engineering to enrich the position data with POI information, iterates over each vehicle, computes time spent in POIs usin...
def get_results(pos, poi): """Get consolidated results. Parameters ---------- pos : pd.DataFrame A data frame with the available position and state measurements from all vehicles. poi : pd.DataFrame A data frame with all positions of interest with name, radius and ...
def _get_parent_transform(self, link): """ Returns the transformation from parent to child given the child link @param link - child link of joint @return transformation from parent to child """ joint = self._get_parent_joint(link) T = np.eye(4, dtype="float64") ...
This method constructs lists of links, joints, and their transformation matrices by traversing from the end effector to the base frame. It populates link_list, tf_list, and joint_list while identifying revolute joints, storing their axes in axis_list. It calculates cumulative joint poses and records origins of revolute...
def _build_link_lists(self): """ Builds the transformation and link lists Iterates from the specified end effector link to the base frame """ self.link_list.insert(0, self.body_frame) self.tf_list.insert(0, self._get_parent_transform(self.body_frame)) current_lin...
def _populate(self): """ Populates relevant variables and lists """ self.links = self.robot.links self.joints = self.robot.joints # init empty lists self.link_list = [] self.tf_list = [] self.axis_list = [] self.joint_list = [] sel...
(The code's main task is to execute a sequence of operations to construct necessary data structures and compute matrices. It first populates internal data, builds link lists for relationships, calculates the M matrix (likely a transformation or connection matrix), and then computes the Slist matrix (possibly representi...
def run(self): """ Builds relevant lists and calculates the M and Slist matrices """ self._populate() self._build_link_lists() self._calc_M() self._calc_Slist()
def setup(self): pygame.init() def create_display(self): return pygame.display.set_mode((self.windowWidth,self.windowHeight), pygame.FULLSCREEN) def useMainBackground(self): self.setup_background(self.main_background_image_path)
This code initializes a Pygame application by setting up a display window with dynamic resolution, loading background images, configuring fonts for text rendering, and defining color schemes. It prepares the main interface for a dispensing system, storing paths, font styles, and color parameters for later use in render...
def __init__(self, main_background_image_path, dispensing_background_image_path, font, font_size_bottles, font_size_ounces, bg_color_dark, bg_color_light, text_color): self.setup() self.info = pygame.display.Info() self.windowWidth = self.info.current_w self.windowHeight = self.info.current_h self.d...
def Search_department(self): try: query = "select * from departments_table where Department_Head like %s" rewcount = self.current.execute( query, (self.SearchDepartmentHeadEntry.get() + "%") ) data = self.current.fetchall() self.Departm...
This code initializes a GUI window for managing department data, setting up input fields, buttons for CRUD operations (add, update, delete, fetch), and a table to display department records. It configures window properties, frames, labels, entry widgets, and a Treeview table, linking UI elements to database operations ...
def __init__(self, win): # ================== Defining Global variables ================== self.entry_list = [] self.combobox_list = [] # =================== Defining Global variables =================== # ================== Creating window ================== self.Depart...
def GetCourses(self): try: query = "select * from courses_table where Department = %s" rowcount = self.current.execute(query, (self.Department_entry.get())) data = self.current.fetchall() self.course_list = [] if data: self.Course_entry...
This code creates a student management GUI application with input fields for personal, contact, and subject details, a table to display student records, and buttons to add, update, delete, or search student data, while setting up a window with background images and interactive widgets for database operations.
def __init__(self, win): # # ================== Defining Global variables ================== self.entry_list = [] self.combobox_list = [] # =================== Defining Global variables =================== # ================== Creating window ================== self.Stud...
def GetPkVaue(self): rowID = self.CourseTable.focus() data = self.CourseTable.item(rowID) StudentData = data["values"] pkValue = StudentData[1] self.fetchCourse(pkValue) def Search_course(self): try: query = "select * from courses_table where Course like %...
This code initializes a GUI window for managing course data, featuring input fields for department, course name, duration, and fee, along with buttons to fetch, save, update, or delete courses. It includes a searchable table (Treeview) to display course records and integrates background images. The window allows user i...
def __init__(self, win): # ================== Defining Global variables ================== self.entry_list = [] self.combobox_list = [] # =================== Defining Global variables =================== # ================== Creating window ================== self.Course...
def GetPkVaue(self): rowID = self.UserTable.focus() data = self.UserTable.item(rowID) UserData = data["values"] pkValue = UserData[0] self.fetchUser(pkValue) def Search_User(self): try: query = "select * from usertable where Username like %s" r...
This code initializes a GUI window for managing user data, creating input fields for user type, username, and password, along with CRUD buttons. It sets up a table to display user records, implements search functionality, and integrates with a database. The interface includes background images, frames for organization,...
def __init__(self, win): # ================== Defining Global variables ================== self.entry_list = [] self.combobox_list = [] # =================== Defining Global variables =================== # ================== Creating window ================== self.User_...
def roll(self) -> None: """ return None what if player rolls into teleport -> stop rolling ig what if player hits border """ self._move(roll=True) self._move_help() self.roll_frame += 1 if self.roll_frame > 10: self.roll_frame...
The main task of the code is to update the player's state based on input and game logic, handling movement, animations, and returning the sword's hitbox when active. It processes keys, updates timers, moves the player, and checks if the sword's hitbox exists to return it for collision detection.
def update(self, dt: float, keys: dict) -> (None | pygame.Rect): """ returns the swords hitbox where all player events are held dt: delta time keys: keys pressed mapInfo: information about the maps teleport places """ if keys is None: return None # this i...
def load_read_mids(folder): fname = os.path.join(folder, READ_MID_FILE) if not os.path.exists(fname): return set() with open(fname) as f: return set(l.strip() for l in f) def get_emails(mail, search='ALL', exclude_mids=None): resp = mail.search(None, search) check_response(resp) ...
The code downloads and processes email items from a given mail object, saving them to a specified folder. It ensures each email is processed only once by tracking read message IDs (MIDs) in the folder. If the folder doesn't exist, it creates it. The function iterates through emails, excludes already-read MIDs, prints e...
def download_email_items(mail, folder): if not os.path.exists(folder): os.makedirs(folder) read_mids = load_read_mids(folder) try: for mid, email in get_emails(mail, exclude_mids=read_mids): print(mid) # Do Something read_mids.add(mid.decode()) finall...
def remove_weight_partial_name(self, partial_name): removed = set() for name in list(self.masks.keys()): if partial_name in name: print('Removing {0} of size {1} with {2} parameters...'.format(name, self.masks[name].shape, ...
This function adds a neural network module to a pruning system, creating masks for weight parameters based on specified pruning type. For unstructured pruning, it generates masks for 2D/4D tensors while skipping biases and Gumbel layers. For structured pruning, it creates separate masks for attention (qkv) and MLP (fc)...
def add_module(self, module, density, sparse_init='ER', pruning_type="unstructure", mask_path=None): if pruning_type == 'unstructure': self.modules.append(module) index = 0 for name, tensor in module.named_parameters(): name_cur = name + '_' + str(index) ...
def truncate_weights(self, pruning_type="unstructure", indicator_list=None): if pruning_type=="unstructure": self.gather_statistics() # count each of module's zeros and non-zeros #prune index = 0 for module in self.modules: for name, weight in mod...
This method performs pruning operations at the end of an epoch, applying different strategies based on the specified pruning type. For "unstructure" pruning, it truncates weights, updates masks, and prints nonzero counts. For "structure" or "structure_new" types, it adjusts weights and masks with structure-specific par...
def at_end_of_epoch(self, pruning_type="unstructure", indicator_list=None): if pruning_type == "unstructure": self.truncate_weights() _, _ = self.fired_masks_update() self.print_nonzero_counts() elif pruning_type == "structure": self.truncate_weights(pruni...
def dw(inp,trainning,nLay): """ This is the Dw block as defined in the Fig. 1 of the MoDL paper It creates an n-layer (nLay) residual learning CNN. Convolution filters are of size 3x3 and 64 such filters are there. nw: It is the learned noise dw: it is the output of residual learning after addin...
This function constructs a multi-layer model using TensorFlow, iteratively applying gradient-based operations (AG/MG) to input data 'atb' with parameters 'csm' and 'mask'. It generates intermediate outputs 'dc' and 'dw' across K layers, using either automatic or manual gradient computation depending on 'gradientMethod'...
def makeModel(atb,csm,mask,training,nLayers,K,gradientMethod): """ This is the main function that creates the model. """ out={} out['dc0']=atb with tf.name_scope('myModel'): with tf.variable_scope('Wts',reuse=tf.AUTO_REUSE): for i in range(1,K+1): j=str(i) ...
def select_layers(self): layer_index = max(len(self.selected_sources) - 1, 0) while True: try: if layer_index >= len(self.selected_sources): random_source_path = random.choice(self.source_paths) random_source = VideoSource(random_sourc...
The main task of the code is to mash multiple video sources into a single output video by blending frames from selected sources. It initializes a video writer, processes frames in a loop, combines them using `mash_frames`, and writes the result. The process includes frame preview checks, progress tracking, and metadata...
def mash(self): try: # Randomly select source videos and channel indices # if len(self.selected_sources) < 1: self.select_layers() if self.preprocess: self.preprocess_selected_sources() for selected_source in self.selected_sources: pri...
def gen_tariff_dict(self): """generates dictionary structure of heading""" tariff_dict = {} level = 0 heading = self.heading tariff_dict[heading] = self._base_dict(self.tariffs[0], level) ##print(f"DEBUG: {tariff_dict}") for tariffObj in self.tariffs[1:]: ...
This function recursively prints a hierarchical book view of tariff data to the terminal, formatting each entry with indentation, dashes, and descriptions. It handles nested dictionaries by checking key lengths (even/odd) to apply specific formatting rules, including HS code formatting for even-length keys, and recursi...
def book_view_terminal(self, _dict=None): """ prints to terminal book view format of heading recursively""" d = _dict or self.gen_tariff_dict() for k, v in d.items(): if isinstance(v, dict): if len(k) % 2 != 0: print("\t" * v['level'] +...
def get_current_orbit_scheme(madx: Madx, accel: str, year: int = 2018): """ Get the current values for the orbit variales. Args: madx: Madx instance accel (str): 'lhc' or 'hllhc' year (int): year of the models/optics (for 'lhc') Returns: Dictionary of all orbit variables an...
The function `log_orbit` retrieves orbit data from a `Madx` instance and a `TwsDataFrame`, logging configuration details for each interaction point (IP). If `twiss` data is not provided, it generates it from the `Madx` table. It fetches orbit parameters via `get_current_orbit_scheme` and iterates over IPs using `_get_i...
def log_orbit(madx: Madx, accel: str, year: int = 2018, twiss: TfsDataFrame = None, ip: Union[Iterable[int], int] = None): """ Get the orbit from madx-instance and twiss-dataframe and log the configuration per IP. """ if twiss is None: twiss = get_tfs(madx.table.twiss, columns=['NAME', 'S', 'X', 'Y'...
def _get_middle_tunes(qx: float, qy: float) -> Tuple[float, float]: """ Get the tunes with the factional part in the middle between the qx and qy fractional parts, but with the same integer part. """ qx_frac, qy_frac = qx % 1, qy % 1 qmid_frac = 0.5 * (qx_frac + qy_frac) qx_mid = int(qx) + qmid_frac...
The function corrects coupling in a beam optics model by optimizing specified knobs (tune, chromaticity, and coupling) to match target tunes (qx, qy) and chromaticity (dqx, dqy). It uses analytical and empirical methods to iteratively adjust knob settings, minimizing the closest tune approach (CTA) as a coupling indica...
def correct_coupling_with_knobs(madx: Madx, sequence: str, tune_knobs: List[str], chroma_knobs: List[str], coupling_knobs: List[str], qx: float, qy: float, dqx: float, dqy: float, ...
def find_style_rules(tree): """Find the style rules in ``tree``.""" for stylesheet in find_stylesheets(tree, tree.url): # TODO: warn for each stylesheet.errors for rule in find_stylesheets_rules(tree, stylesheet, tree.url): yield rule def get_declarations(rule): """Get the declar...
The function applies CSS styles from a tree's stylesheet to its elements by processing each style rule, matching selectors to elements, and prioritizing styles based on specificity and importance. It combines declarations into a computed style for each element, storing them as an attribute. Conflicts are resolved by re...
def apply_stylesheets(tree): """Apply the stylesheet in ``tree`` to ``tree``.""" style_by_element = {} for rule in find_style_rules(tree): declarations = list(get_declarations(rule)) for element, specificity in match_selector(rule, tree.xml_tree): style = style_by_element.setdefa...
def Obtain_amazonprice(links): #it finds the price in the amazon web page driver.get(links) try: amasearch = driver.find_element_by_id('priceblock_ourprice') #Its where is located the price of the game. amaprice= amasearch.text #It converts the object to a string except: a...
The main task of the code is to read game data from 'games.txt', process each game's information (title, Amazon/Steam prices, Metascore, and playtime) using helper functions, and write the extracted data into 'game_data.txt' in a structured format. This file is later used in a Flask web application to display game pric...
def Generate_info(): #It is the main function where by a loop it returns all the data of the functions to variables that will be written in game_data.txt #The file game_data.txt will be used in the file Flask-web.py to be integrated in another web page with all the prices of the games,scores,titles...
def get_args(): """ Get command line args: - The GME spreadsheet file - The names table file both of which should be text files in csv format. Returned as a namespace. """ parser = argparse.ArgumentParser(description="Combine groups in GME file") parser.add_argument('gme'...
The main task of the code is to process and summarize group ratings data. It retrieves command-line arguments, groups ratings using `group_ratings`, and generates an HTML summary via `html_summarize`. The function prepares structured output for analysis or reporting, focusing on transforming raw rating data into a summ...
def main(): args = get_args() groups = group_ratings(args.gme) # list_groups(groups) # summarize(args.summary, groups) html_summarize(args.summary, groups)
def generate_ptp_instructions(a, b, direction): """Generate point to point instructions for the turtle to follow Parameters: a (tuple): a tuple representing the starting point b (tuple): a tuple representing the ending point direction (int): the direction the turtle is facing Returns: list...
The function generates movement and placement instructions for a turtle to build a specified path, managing item usage and refueling. It creates instructions for navigating coordinates, placing items, and returning to (-1, 0, 0) to collect items when depleted. It also handles slot changes for item selection, ensuring c...
def path_to_instructions(path, layer, direction, items, slot): """Generates a list of instructions for the turtle to follow to build the path The path generated will take into account the amount of items the turtle has, and will return to (-1, 0, 0) to collectItems when it runs out of items Parameters...
def path_to_instructions(path, layer, direction, items, slot): """Generates a list of instructions for the turtle to follow to build the path The path generated will take into account the amount of items the turtle has, and will return to (-1, 0, 0) to collectItems when it runs out of items Parameters...
The function converts a list of coordinate paths into turtle movement instructions, generating step-by-step commands for navigation, layer transitions, directional adjustments, and positioning. It processes each path sequentially, updates turtle state variables (direction, item count, slot), and appends "up()" between ...
def paths_to_instructions(paths): """Given a list of paths, generate a list of instructions for the turtle to follow Parameters: paths (list): a list of paths, where each path is a list of tuples representing coordinates Returns: list: a list of instructions for the turtle to follow """ p...
def generate_sql(question: str, model_name: str = "gemini-1.5-flash") -> str: """Generates SQL query using an LLM""" schemas_and_rows = _get_schemas_and_sample_rows(TABLE_NAMES, 3) prompt = _render_prompt( "generation_prompt", schemas_and_rows=schemas_and_rows, question=question ) gen_llm = ...
The main task of the code is to generate an SQL query from a natural language question using an LLM, optionally refine it via reflection with a Gemini model, execute the query on BigQuery, and return the results as a Markdown-formatted string. It handles query generation, validation, execution, and output formatting in...
def generate_sql_and_retrieve_as_markdown(question: str, use_reflection=True) -> str: """Generates SQL query using an LLM, runs the query against BigQuery, and returns the result as a Markdown-formatted string""" logger.info(f"Generating query...") query, schemas_and_rows = generate_sql(question) if use...
def getBatchesData(semester, students, mergeBelow): subjects = {} for batch, secData in students.items(): batch = int(batch) subjects[batch] = {'subjects': [], 'sections': [], 'merge': []} merging = [] mergedStuds = 0 overMerge = False for sec, studs in sorted(sec...
The code generates a feasible schedule for subjects based on room availability, ECTS requirements, and trial runs. It validates required ECTS against available space, applies a 5% buffer, and attempts up to 500 scheduling trials. If successful, it returns the schedule details; otherwise, it reports errors or requests r...
def makeSchedule(data): subjectsData = getBatchesData(data['semester'], data['students'], data['mergeBelow']) ectsAvail = {} periods = data['periods'][0] + data['periods'][1] for label, rooms in data['rooms'].items(): ectsAvail[label] = len(rooms) * len(data['days']) * periods ectsSpaces = e...
def choose_market(): default_market = 'stock' if default_market in market_list: market = questionary.select( "What market are you looking at?", choices=market_list, qmark='', default=default_market, ).ask() else: market = questionar...
The function `choose_product_type` determines and retrieves a user-selected product type (currency for crypto markets or stock type for stock markets) based on the provided or default market/exchange. It uses default values where applicable, generates options from dataframes, and employs a questionary interface for use...
def choose_product_type(market=None, exchange=None): if market == None: market = choose_market() if exchange == None: exchange = choose_exchange(market) if market == 'crypto': default_base = 'USD' ticker_df = gen_crypto_df(exchange) base_list = sorted(ticker_df['bas...
def choose_functions(function_dict, function_name, default=None): function_list = [] function_df = pd.DataFrame( list(function_dict.items()), columns=['Index', function_name], ) function_df = function_df.set_index('Index') functions_list = list(function_df[function_name]) choice ...
The function adds technical indicators called "overlap studies" to a DataFrame using the talib library. It prompts the user to confirm adding studies, selects functions from a list, retrieves parameters like time periods and moving average types, applies each function to the DataFrame's 'Close' (or other) prices, and u...
def add_overlap_studies(df): if(questionary.confirm('Add overlap study?').ask()): function_list = choose_functions( ti.overlap_studies, 'Overlap Study', default='Bollinger Bands') for f in function_list: function = getattr(talib, f) if f == 'BBANDS': ...
def choose_functions(function_dict, function_name, default=None): function_list = [] function_df = pd.DataFrame( list(function_dict.items()), columns=['Index', function_name], ) function_df = function_df.set_index('Index') functions_list = list(function_df[function_name]) choice ...
The function adds selected momentum indicators to a DataFrame based on user confirmation and input parameters using TA-Lib functions. It dynamically sets parameters for each indicator, computes values, and stores them as new columns in the DataFrame, enabling technical analysis of financial time series data.
def add_momentum_indicators(df): if(questionary.confirm('Add momentum indicator?').ask()): function_list = choose_functions( ti.momentum_indicators, 'Momentum Indicator', default='Moving Average Convergence/Divergence') for f in function_list: function = getattr(talib, f) ...
def choose_market(): default_market = 'stock' if default_market in market_list: market = questionary.select( "What market are you looking at?", choices=market_list, qmark='', default=default_market, ).ask() else: market = questionary.se...
The main task of the code is to prompt the user to select a product type (currency for crypto or stock type for stocks) based on the specified market. It uses default options when available, dynamically generates choices from dataframes, and returns the user's selection. The function handles both 'crypto' and 'stock' m...
def choose_product_type(market=None, exchange=None): if market == None: market = choose_market() if exchange == None: exchange = choose_exchange(market) if market == 'crypto': default_base = 'USD' ticker_df = gen_crypto_df(exchange) base_list = sorted(ticker_df['bas...
def choose_market(): default_market = 'stock' if default_market in market_list: market = questionary.select( "What market are you looking at?", choices=market_list, qmark='', default=default_market, ).ask() else: market = questionar...
The function generates a DataFrame of product symbols (stocks or crypto) based on input parameters or defaults. It selects market, exchange, and product type, then filters stock/crypto data accordingly, returning symbol/displaySymbol lists for the specified product type.
def gen_product_df(market=None, exchange=None, product_type=None): if market == None: market = choose_market() if exchange == None: exchange = choose_exchange(market) if product_type == None: product_type = choose_product_type(market, exchange) if market == 'stock': prod...
def choose_market(): default_market = 'stock' if default_market in market_list: market = questionary.select( "What market are you looking at?", choices=market_list, qmark='', default=default_market, ).ask() else: market = questionary.se...
The main task of the code is to generate a DataFrame of product symbols (stocks or cryptocurrencies) based on specified or defaulted market, exchange, and product type parameters. It dynamically selects missing parameters using helper functions, filters data using market-specific logic, and returns a list of relevant p...
def gen_product_df(market=None, exchange=None, product_type=None): if market == None: market = choose_market() if exchange == None: exchange = choose_exchange(market) if product_type == None: product_type = choose_product_type(market, exchange) if market == 'stock': prod...
def bath_conductivity(self): w_Al2O3 = self.w_Al2O3.get() w_AlF3 = self.w_AlF3.get() w_CaF2 = self.w_CaF2.get() w_MgF2 = self.w_MgF2.get() w_KF = self.w_KF.get() w_LiF = self.w_LiF.get() temperature = self.bath_temp_K.get() # Calculate the bath conductivi...
The main task of the code is to compute various bath-related parameters (conductivity, resistivity, solubility factors, saturation values, equilibrium potential, and bath ratio) by calling internal methods, then update corresponding GUI labels with formatted numerical results, ensuring real-time visualization of calcul...
def update_results(self): conductivity = self.bath_conductivity() resistivity = self.bath_resistivity() solub_A = self.Al2O3_solub_A_factor() solub_B = self.Al2O3_solub_B_factor() Al2O3_sat = self.Al2O3_sat() Al2O3_rel_sat = self.Al2O3_rel_sat() Equil_potential = ...
def add_to_process_queue(self, filename): a_path = self.locale_dir / filename if not a_path.exists(): self.warnings.append("File not found: {}".format(a_path)) return self.strings_txt.append(StringsTxt(a_path)) def create_locale_folders(self): paths = map(self.pat...
The code processes localization files by adding "strings.txt" and "countries.txt" to a queue, aggregates supported languages, creates locale folders, generates PO files, validates string formatting (spaces, placeholders), and collects/warnings. It ensures proper localization structure and consistency across files.
def process(self): self.add_to_process_queue("strings.txt") self.add_to_process_queue("countries.txt") self.all_langs = set() for st in self.strings_txt: self.all_langs.update(st.all_langs) self.create_locale_folders() self.write_po_files() for strin...
def get_quaternion_vals(theta, ax, ay, az): """ Compute the quaternion representation for a given rotation in angle-axis representation params: theta: the angle of the rotation in radians ax, ay, az: three floats in a way that *ax, ay, az) shows the 3d axis of the rotation retrun: ...
The code implements a Stochastic Gradient Descent (SGD) algorithm to optimize quaternions for aligning 3D point clouds. It iteratively computes optimal transport (OT) between source and target point sets, calculates gradients via sampled points, and updates quaternions using a learning rate while enforcing normalizatio...
def SGD(x, y, z, xr, yr, zr, lr=0.005, max_iter=100, reg=0.1, num_samples=1, verbose=False, random_seed=None): px = Quaternion(Polynomial([Term(coef=0, exps=[0,0,0,0,1,0,0,0])]), Polynomial([Term(coef=1, exps=[0,0,0,0,0,1,0,0])]), Polynomial([Term(coef=1, exps=[0,0,0,0,0,0,1,0])]), Polynomial([Term...
def match(email): if email in self.ignore_responses: return '' email = self.aliases.get(email) or email if email.lower() in domain_emails: return email[:strip].lower() else: return '' def matched_roster(self): r"""pr...
The function generates a roster table with participation, correctness, and total score columns based on configuration. It calculates summed scores, maps emails to roster IDs, determines max scores, adds "Points Possible" rows, and combines data into a sorted table with specified columns.
def roster_table(self): r"""produce a score table in roster format. This is a roster table with some/all columns for participation, correctness, and total score. The points possible row is filled in with the max score for the relevant column. Configuration determines which columns are i...
def navigate_to_scheduler(): find_and_click_button('menu_SCH', By.ID, True) # book courts find_and_click_button('divContainer', By.ID, True) # court reservations find_and_click_button('divContainer', By.ID, True) def select_court_time(desired_court_time): find_and_click_button('ui-datepicker-trigger', B...
The code checks court availability for a specified time, books it if available, and sends a notification email. It navigates to a scheduler, selects the desired time, retrieves availability, books the court if possible, and triggers a notification.
def get_availabilities(desired_court_time, notify_email=None): navigate_to_scheduler() select_court_time(desired_court_time) available_court_time = get_availabile_court_time(desired_court_time) if available_court_time: book_court(available_court_time, notify_email) notify_me(desired_cour...
def load_shifts_from_file(self, filename): if not exists(filename): with open(filename, 'w+') as f: f.write('{}') with open(filename, 'r') as f: shifts = json.loads(f.read()) return shifts def get_shift_calendar(self): date_str = date.today().strft...
The main task of the code is to update a shift schedule file by comparing existing shifts with a new calendar, removing outdated entries, adding new shifts, and saving the result. It logs the number of shifts processed, deleted, and active shifts, then writes the updated JSON data back to the file with indentation for ...
def write_shifts_to_file(self, filename): shifts = self.load_shifts_from_file(filename) new_shifts = self.get_shift_calendar() ts = datetime.now().strftime('%Y-%m-%dT%H:%M:%S') deleted_shift_count = \ self.delete_shifts_from_collection(shifts, new_shifts, ts) real_new...
def reset_trade_count(self, date): # Check if it's the start of the week, and reset trade_count if date.weekday() == 0: # Monday self.trade_count = 0 def _analyze_stock(self, ticker, date_index): data = self.historical_data[ticker] # Compute indicators macd, macd_si...
The main task of the code is to execute trading decisions by iterating through historical data, analyzing each stock for buy/sell signals, placing orders based on calculated positions, and managing trailing stop-loss mechanisms. It processes each date and ticker, resets trade counts, determines order quantities, and tr...
def execute_trades(self): for date_index in range(self.lookback_period, len(self.historical_data[next(iter(self.historical_data))])): current_date = self.historical_data[next(iter(self.historical_data))].index[date_index].date() self.reset_trade_count(current_date) for ticke...
def reset_trade_count(self, date): # Check if it's the start of the week, and reset trade_count if date.weekday() == 0: # Monday self.trade_count = 0 def _check_max_loss(self, initial_balance, date_index): if self.portfolio['cash'] < initial_balance * (1 - self.max_loss_percentage):...
The code simulates trading decisions based on historical stock data, analyzes each stock for buy/sell signals, enforces risk management rules (max loss, stop-loss), executes trades, and calculates the final portfolio value including cash and asset holdings. It skips conflicting TQQQ/SQQQ signals and records closing pri...
def run(self): closing_prices = {} for date_index in range(self.lookback_period, len(self.historical_data[next(iter(self.historical_data))])): date = self.historical_data[next(iter(self.historical_data))].index[date_index] self.reset_trade_count(date) self._check_max...
def _init_optimizer(self): # Initialize and train the optimizer self.optimizer = IndicatorWeightOptimizer(self.historical_data) self.optimizer.train_model() self.indicator_weights = self.optimizer.get_weights() def reset_trade_count(self, date): # Check if it's the start of the w...
The code simulates a trading strategy by iterating through historical stock data, analyzing each ticker for buy/sell decisions, executing trades with position sizing, managing risk via stop-loss/trailing stop-loss mechanisms, and tracking portfolio value. It processes each trading day, updates trade counts, and logs pr...
def run(self): self._init_optimizer() min_length = min(len(self.historical_data[ticker]) for ticker in self.historical_data) # Debug: Print the total number of days in the iteration total_days = len(self.historical_data[next(iter(self.historical_data))]) - self.lookback_period prin...
def defined_thread(thread, i, score_next): """ Defined_thread: to defined the threads number """ #print("score: {}".format(score_next)) thread_count = threading.active_count() res_time = 0 try: start = time.time() req = requests.get(url, verify=False) end = time.time(...
The function `tryUrl` tests URLs in a dictionary using multithreading to check for vulnerabilities, backups, and directory structures. It handles HTTP requests, verifies WAF protections, processes redirects, logs status codes (e.g., 200, 403, 301), and executes tasks like backup scanning, error logging, and dynamic thr...
def tryUrl(self, i, q, threads, manager=False, directory=False, forced=False, u_agent=False, nLine=False): """ tryUrl: Test all URL contains in the dictionnary with multi-threading. This script run functions: - create_backup() - dl() - suffix_backup() - ma...
def __get_attr_names(self, tablename): return list(map(itemgetter(0), self.read(f'DESC {tablename}'))) def read(self, query, args=None): self.__open() if args: self.cursor.execute(query, args) else: self.cursor.execute(query, ) result = self.cursor.fetchal...
The code retrieves purchase history for a user (uid) by querying a database table 'historial', extracts relevant attributes, processes the results into a structured format, formats date-time fields, and returns the processed data as a dictionary.
def get_purchases(self, uid): attrs = self.__get_attr_names('historial') select = "SELECT " + ', '.join(attrs) + " FROM historial WHERE idSocio = %s" result = self.read(select, (uid)) result = self.__flat_tuples(result, attrs) result['fecha_hora'] = [x.strftime("%Y-%m-%d %H:%M:%S...
def extract_single_template(anchor_cadastre , top_left_corner_coordinates , template_w=500 , template_h=500 ): """ Extract a template from an image given its top left corner coordinates, width and heig...
The function performs template matching between anchor and target images, evaluates the best match visually, and updates a graph (G) with the match if approved by the user. It extracts regions, applies orientation-based matching, composes images, and stores spatial relationships in a directed graph for network construc...
def test_match_network(targets , anchor_label , target_label , path_match , path_compose , img_ext , match_method = cv2.TM_CCOEFF_NORMED , annot=True ...
def compute_pairwise_homographies(G): """ Turns top left and bottom right tagged coordinates to homographies """ # compute all pairwise homographies for edge in G.edges(): anchor_tl = G.edges[edge]["anchor_tl"] target_tl = G.edges[edge]["target_tl"] anchor_br = G.edges[edge][...
The main task of the code is to generate a composite image from a network of images by computing pairwise homographies, building a centered network structure, and composing images using specified paths and file extensions. The function returns the final composed image representing the covered area.
def network2Image(G , img_ext , path_compose , init_label=None ): """ Pipeline from network to image of the covered area """ # compute homographies G_homo = compute_pairwise_homographies(G.copy()) # Build ne...
def create_left_frame(self): self.left_frame = tk.Frame(self, bg="pink") self.left_frame.grid(row=0, column=0, sticky="nsew") self.create_left_header() self.create_left_content() def create_right_frame(self): self.right_frame = tk.Frame(self, bg="white", width=2*self.settings.width//3) self.right_frame.grid...
This code initializes a GUI component by setting up attributes for application settings, database management, and layout configuration. It configures a grid layout for responsiveness, creates left and right frames, and prepares the interface for database-related operations.
def __init__(self, parent, App): self.app = App self.settings = App.settings self.current_Database = self.settings.Database[0] self.last_current_Database_index = 0 self.update_mode = False self.Databases_index = [] super().__init__(parent) # window.conteiner self.grid(row=0, column=0, sticky="nsew") ...
def RegisterVoter(name_var, group_var, key_var): global managerSOCK global managerCONN name = name_var.get() group = group_var.get() key = Base64Encoder.decode(key_var.get()) try: if name not in Voters.keys(): Voters[name] = (group, key) SyncSend() Pop...
The code defines a GUI thread for managing voter registrations. It creates a window with input fields for voter name, group, and public key, displays existing voters in a list, and provides 'Register'/'Unregister' buttons. The interface includes a scrollable frame for election-related components. The loop waits for use...
def RegisterThread(): command = "" while command == "": reg_win = tk.Tk() reg_win.title("Voter Management") reg_win.geometry('640x520') # Input Voter name name_label = tk.Label(reg_win, text='Voter name :', font=("Arial", 12)) name_label.place(relx=0.1, rely=0.1,...
def Button_CreateElection(self): self.create_win = tk.Toplevel() self.create_win.title("Create an election") self.create_win.geometry('640x560+200+200') #Title create_title = tk.Label(self.create_win, text='Create an election', font=("Arial", 20, 'bold')) create_title.pl...
The code creates a Tkinter GUI window titled "Home" with a personalized welcome message for a voter. It includes three buttons allowing users to create an election, cast a vote, or view results. The interface is designed for a voting system, providing navigation options for different user actions.
def HomePage(self): self.home_win = tk.Tk() self.home_win.title("Home") self.home_win.geometry('640x280') #Title home_title = tk.Label(self.home_win, text='Welcome, '+self.voter_name+"!", font=("Arial", 20, 'bold')) home_title.place(relx=0.5, rely=0.15, relwidth=0.5, hei...
def read_domain_name(buf): domain = [] while True: byte = buf.read(1) int_char = unpack('B', byte)[0] if int_char == 0: break elif int_char & 0b11000000 == 0b11000000: second_byte = buf.read(1) second_byte_unpacked = unpack...
This code initializes a DNS resource record by parsing data from a buffer. It reads the domain name, extracts type, class, TTL, and rdata length, then processes the rdata. The `to_s()` method likely generates a string representation of the parsed record.
def __init__(self,buf): self.buf = buf self.name = read_domain_name(buf) self.type, self.cls, self.ttl, self.rdlength = unpack('>HHHH', buf.read(8)) self.read_rdata(buf,self.rdlength) self.to_s()
def skyscraper_optimization_step(self): """Optimizes skyscrapers until the score is 0.""" best_score = self.calculate_score() for row1 in range(self._city.rows): for col1 in range(self._city.cols): if self._city.get_building_type(row1, col1) == BuildingType.SKYSCRAPE...
The code performs a single optimization step for a city layout, prioritizing skyscraper and high-rise optimization, followed by office placement to ensure each skyscraper/high-rise has a nearby office. If unoptimized, it swaps offices and checks adjacency. Once optimized, it prints the updated score and layout if enabl...
def step(self, print_info=True): """Performs a single optimization step.""" if not self._skyscraper_optimized: self.skyscraper_optimization_step() return True if not self._office_optimized: # Skyscraper optimization is complete, now optimize...
def add_like_count(stories_df): stories_df['like_count'] = stories_df['likes'].apply(len) return stories_df def vectorize_stories(stories_df): vectorizer = TfidfVectorizer(stop_words='english') return vectorizer.fit_transform(stories_df['rich_text']), vectorizer def cluster_stories(X): if X.shape[0]...
The code recommends stories to a user by calculating label, location, and followed-user similarity scores, normalizing them, and combining with cluster-based recommendations from the user's preferred story group. It returns top 'top_r' unique story IDs with their recommendation reasons, prioritizing content similarity ...
def recommend_stories(user_id, top_r): add_like_count(stories_df) X, vectorizer = vectorize_stories(stories_df) stories_df['Cluster'] = cluster_stories(X) non_user_stories = stories_df[stories_df['user_id'] != user_id].copy() non_user_stories.loc[:, 'label similarity'] = calculate_label_similarity(...
def fetch_users(): return fetch_data("SELECT * FROM users") def fetch_stories(): stories_df = fetch_data("SELECT * FROM stories") stories_df['rich_text'] = stories_df['rich_text'].apply(extract_text_from_html) return stories_df def fetch_locations(): return fetch_data("SELECT * FROM locations") def ...
The main task of the code is to aggregate data from multiple sources by calling several fetch functions (users, stories, locations, followers, comments) and returning their results as a tuple, consolidating all retrieved data for further processing or analysis.
def fetch_all_data(): users = fetch_users() stories = fetch_stories() locations = fetch_locations() followers = fetch_followers() comments = fetch_comments() return users, stories, locations, followers, comments
def fetch_all_data(): users = fetch_users() stories = fetch_stories() locations = fetch_locations() followers = fetch_followers() comments = fetch_comments() return users, stories, locations, followers, comments def followed_users(user_id, stories_df): followed_users = followers_df[followers...
The code provides personalized story recommendations based on user interactions (likes, follows, comments) and social connections. It handles cold-start scenarios by suggesting top-liked stories for low-interaction users, combines social interaction-based recommendations for active users without story creation, and use...
def get_recommendations(): user_id = request.args.get('user_id', type=int) if not user_id: return jsonify({"error": "User ID is required"}), 400 users_df, stories_df, locations_df, followers_df, comments_df = fetch_all_data() if user_id not in users_df['id'].values: return jsonify({"erro...
def config_info(): experimentName='amo86615' detInfo='pnccdBack' return experimentName, detInfo def retrieve_background_image(): """ """ experimentName, detInfo = config_info() ds = DataSource('exp='+experimentName+':run='+str(190)+':idx') run = ds.runs().next() det = Detector(detInf...
The function processes a specified experimental run by retrieving background and signal data, then generates an image using timestamps and fiducial information. It returns the processed image and the count of detected hits for analysis.
def average_run(runNumber, singleHits, output_dir="./"): """average_run """ experimentName, detInfo = config_info() print("Run # {}".format(runNumber)) print("retrieving background") background_img = retrieve_background_image() print("retrieving timestamps") timestamps, fiducials = ret...
def print_instructions(self): # TODO: Print the instructions to the game print("Welcome to TicTacToe!") print("Player 1 is X and Player 2 is O") print("Take turns putting your pieces down, and the first player to have 3 in a row wins!") def print_board(self): # TODO: Print the bo...
The code's main task is to run a tic-tac-toe game by alternating turns between players "X" and "O", checking for win/tie conditions after each move, printing the board state, and switching players until a win or tie is detected. It initializes the game, handles player input, updates the board, and terminates when a pla...
def play_game(self): # TODO: Play game self.print_instructions() self.print_board() player = "X" while self.check_win(player) == False and self.check_tie() == False: self.take_turn(player) self.print_board() self.check_win(player) s...
def check_win(self, player): # TODO: Check win if self.check_row_win(player) == True or self.check_col_win(player) == True or self.check_diag_win(player) == True: return True else: return False def check_tie(self): # TODO: Check tie for i in range(0, 3): ...
This code implements the minimax algorithm for a Tic-Tac-Toe game, determining the optimal move for a player. It recursively evaluates all possible game states, maximizing scores for player "O" and minimizing for player "X", while checking win/tie conditions. The function returns the best score and corresponding move c...
def minimax(self, player): opt_row = -1 opt_col = -1 if self.check_win("O") == True: return 10, None, None if self.check_tie() == True: return 0, None, None if self.check_win("X") == True: return -10, None, None if player == "O": ...
def check_win(self, player): # TODO: Check win if self.check_row_win(player) == True or self.check_col_win(player) == True or self.check_diag_win(player) == True: return True else: return False def check_tie(self): # TODO: Check tie for i in range(0, 3): ...
This code implements a depth-limited minimax algorithm for a Tic-Tac-Toe-like game. It recursively evaluates all valid moves for the current player ("O" or "X"), calculates scores based on win/tie conditions, and selects the optimal move (row, column) by maximizing/minimizing scores. The function returns the best score...
def depth_minimax(self, player, depth): opt_row = -1 opt_col = -1 if self.check_win("O") == True: return 10, None, None if self.check_tie() == True: return 0, None, None if self.check_win("X") == True: return -10, None, None if depth ==...
def check_win(self, player): # TODO: Check win if self.check_row_win(player) == True or self.check_col_win(player) == True or self.check_diag_win(player) == True: return True else: return False def check_tie(self): # TODO: Check tie for i in range(0, 3): ...
This function implements the Minimax algorithm with alpha-beta pruning for a Tic-Tac-Toe game. It evaluates the optimal move for the current player ("O" or "X") by recursively exploring all valid board states, scoring terminal conditions (win/tie), and pruning suboptimal branches using alpha-beta values. It returns the...
def minimax_alpha_beta(self, player, depth, alpha, beta): opt_row = -1 opt_col = -1 if self.check_win("O") == True: return 10, None, None if self.check_tie() == True: return 0, None, None if self.check_win("X") == True: return -10, None, None ...
def print_instructions(self): # TODO: Print the instructions to the game print("Welcome to TicTacToe!") print("Player 1 is X and Player 2 is O") print("Take turns putting your pieces down, and the first player to have 3 in a row wins!") def print_board(self): # TODO: Print the bo...
This code implements a game loop for a two-player game, alternating turns between "X" and "O", checking for a win or tie after each move. It prints instructions, updates the board, and ends the game when a player wins or the game ties, displaying the result.
def play_game(self): # TODO: Play game self.print_instructions() self.print_board() player = "X" while (True): self.take_turn(player) self.print_board() if self.check_win(player): print(player, " wins!") break ...
def getSpectrumFromPulse(time,pulse_amplitude): pulseEnergy=getEnergy(time,pulse_amplitude) #Get pulse energy f=getFreqRangeFromTime(time) dt=time[1]-time[0] spectrum_amplitude=fftshift(fft(pulse_amplitude))*dt #Take FFT and do shift return spectrum_amplitude def getPower(amplitude): ...
The main task of the code is to simulate the propagation of a light pulse through an optical fiber using the Split-Step Fourier Method (SSFM). It models nonlinear effects (via gamma parameter), dispersion, and loss by iteratively applying these physical processes in both time and frequency domains. The function returns...
def SSFM(fiber:Fiber_config,sim:SIM_config, pulse): #Initialize arrays to store pulse and spectrum throughout fiber pulseMatrix = np.zeros((fiber.nsteps+1,sim.number_of_points ) )*(1+0j) spectrumMatrix = np.copy(pulseMatrix) pulseMatrix[0,:]=pulse spectrumMatrix[0,:] = getSpectrumFromPulse(sim....
def make_arm(args): arm = Robot( ArmDynamics( num_links=args.num_links, link_mass=args.link_mass, link_length=args.link_length, joint_viscous_friction=args.friction, dt=args.dt ) ) arm.reset() return arm def random_goals(args, ...
The main task of the code is to simulate an arm robot environment, load a pre-trained PPO policy model, and execute either the policy or random actions based on command-line arguments. It initializes the robot and environment with a fixed random seed, optionally enables GUI rendering, and evaluates the policy's perform...
def main(args): set_random_seed(seed=100) # Create arm robot arm = make_arm(args) # Create environment env = ArmEnv(arm) env.seed(100) renderer = None if args.gui: renderer = Renderer() time.sleep(1) if (not args.random_actions): # Load and test policy ...
def getTemplateID(tree): return "returnsExpected" def getArgumentIDs(tree): argIDs = set() subtree = tree.get('args').get('args') if subtree: #Check if arguments are empty for i in range(len(subtree)): argIDs.add(subtree[i].get('arg')) return argIDs def getArgType(argID, tree): ...
The code generates a template by identifying argument types and attributes from a tree structure, then selects a template method based on the template ID and input parameters, returning the resulting template.
def getTemplate(tree, comments): templateID = getTemplateID(tree)#Select template to use argIDs = getArgumentIDs(tree)#Find names of each argument argTypes = list()#List of type for each argument argAttributes = list()#List of sets of attributes for each argument for a in argIDs:#Find the types and ...
def prepareTmpFolder(path: str, *, forceDelete: bool = False) -> None: if os.path.exists(path): if forceDelete: deletePath(path) else: raise FileExistsError(f"Temporary folder ({path}) is required but folder " + "with this name already exists...
The function decrypts an encrypted file using RSA private key decryption, extracts its contents from a ZIP archive, and manages output handling. It prepares a temporary directory, decrypts the file, checks for existing files (with override option), extracts decrypted files to the specified output path, and cleans up te...
def decrypt(path: str, rsaPrivateKey: rsa.RSAPrivateKey | None = None, output: str | None = None, *, tmpFolderName: str = 'tmp', override: bool = False, archivePassword: bytes | None = None, rsaKeyPassword: bytes | None = None, verificationKey: rsa.RSAPublicKey | None = N...
def prepareTmpFolder(path: str, *, forceDelete: bool = False) -> None: if os.path.exists(path): if forceDelete: deletePath(path) else: raise FileExistsError(f"Temporary folder ({path}) is required but folder " + "with this name already exists...
The function encrypts a file using symmetric encryption, secures the key with RSA, and packages encrypted data into an archive (ZIP or pyminizip). It handles key generation, temporary file management, optional signing, compression, and error checks for existing files or non-ASCII paths. The result is an EncryptedFile o...
def encryptFile(path: str, rsaPublicKey: rsa.RSAPublicKey | None = None, output: str | None = None, *, tmpFolderName: str = 'tmp', override: bool = False, archivePassword: bytes | None = None, compressionLevel: int = 9, noCompression: bool = False, archive...
def parseArgs() -> Atributes: parser = argparse.ArgumentParser() parser.add_argument('filename', type=str, help="File or folder to" + "encrypt/decrypt/save key") parser.add_argument('-cl', '--archive-compression-level', type=int, action='store', default=COMPRESSION_LEVEL, help=f"Leve...
The main task of the code is to handle encryption/decryption operations using RSA keys, manage password inputs from files, and perform key generation or password changes based on command-line arguments. It validates file paths, reads passwords from files if specified, executes the appropriate cryptographic operation (e...
def main() -> None: args = parseArgs() args.filename = os.path.normpath(args.filename.strip('"')) if args.password is None and args.password_file is not None: if not os.path.exists(args.password_file): print(f"{args.password_file} does't exist") return if not os.path....
def getFileTree(path: str) -> list[str]: if not os.path.exists(path): raise FileNotFoundError(f'File {os.path.normpath(path)} not found') if os.path.isfile(path): return [os.path.normpath(path)] ans = list() files = os.listdir(path) for file in files: ans.extend(getFileTree(o...
This function recursively decrypts files with a specified extension in a given directory using an RSA private key. It processes each file, skips those with mismatched extensions, and yields decryption results. If decryption fails due to missing keys or files, it handles errors and returns appropriate status codes.
def decryptRecursively(path: str, rsaPrivateKey: rsa.RSAPrivateKey | None = None, output: str | None = None, *, tmpFolderName: str = 'tmp', encryptedFilesExtension: str = '.encrypted', override: bool = False, archivePassword: bytes | None = None, ...
def prepareTmpFolder(path: str, *, forceDelete: bool = False) -> None: if os.path.exists(path): if forceDelete: deletePath(path) else: raise FileExistsError(f"Temporary folder ({path}) is required but folder " + "with this name already exists...
(The function encrypts multiple files by creating a ZIP archive of them in a temporary directory, then encrypting the ZIP file using RSA public key encryption. It handles output path validation, compression settings, and temporary folder cleanup, returning an encryption result status. The process involves zipping files...
def encrypt(paths: list[str], rsaPublicKey: rsa.RSAPublicKey | None = None, output: str | None = None, *, tmpFolderName: str = 'tmp', wrapperName: str = 'wrapper', override: bool = False, archivePassword: bytes | None = None, compressionLevel: int = 9, noC...
def loading(): done = False def animate(): for c in itertools.cycle(['.', '..', '...', '....']): if done: break sys.stdout.write('\rloading ' + c) sys.stdout.flush() time.sleep(0.2) threading.Thread(target=animate).start() time.slee...
The function `showShoes` displays shoe data either fully or filtered by user-specified criteria. When `req` is "all", it prints all shoes in a table. For other `req` values (e.g., "series" or "collection"), it searches for a user-provided keyword in the corresponding shoe attribute, filters matches, and displays them. ...
def showShoes(req): global shoes global shoesCount print() if req == "all" : loading() tableHeader() for i in range (shoesCount): showOneShoe(i, i+1) else: key = _inputStr(f"I want to search this {req}", "search") if req == "series" : ...
def _inputStr(prompt, inputType): global shoesCount true = False while not true: __input = input(f" >> {(start + prompt + end)}: ") if inputType == "search": # __input = __input.capitalize() true = True elif inputType == "buyCode" or i...
The code's main task is to handle a shoe purchase process by updating inventory. It prompts users for product code, size, and quantity, deducts the purchased pairs from stock, writes changes to a file, and displays the updated inventory. The function ensures real-time stock adjustments and provides visual feedback thro...
def buy(): global shoes global shoesCount # one series, one size, several pairs every buy os.system("cls") print("=====================================================================") print(start + " ♥ ShoeShoe ♥" + end) print("==================================...
def _inputStr(prompt, inputType): global shoesCount true = False while not true: __input = input(f" >> {(start + prompt + end)}: ") if inputType == "search": # __input = __input.capitalize() true = True elif inputType == "buyCode" or i...
The main task of the code is to add new shoe entries or update stock quantities for existing shoes based on the input type ("new" or "stock"). It collects user inputs, modifies the global `shoes` data structure, updates the `shoesCount`, saves changes to a file, and displays the updated stock information in a formatted...
def add(ty): global shoes global shoesCount idx = 0 os.system("cls") print("=====================================================================") print(start + " ♥ ShoeShoe ♥" + end) print("=====================================================================") ...
def selectSport(des): row_id = 0 try: connection=pymysql.connect(host=dbServerName, user=dbUser, password=dbPassword, db=dbName) with connection.cursor() as cursor: # Read a single record sql = "SELECT `id` FROM `sport` WHERE `des`=%s " ...
The code extracts sports betting market data from a webpage, parsing date, game details, sport/league hierarchies, and odds. It uses HTML parsing to identify events, their associated markets, and odds, then stores this structured data via database functions like selectSport, selectLeague, and selectOdd.
def extractMarkets(link): try: headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3'} reg_url = link page = requests.get(reg_url) soup2 = BeautifulSoup(page.text, 'html.parser') date_time =...
def classify(sentence): results = model.predict([makeInputArray(sentence, words)]) # print(results) results = results[0] # print(results) results = [[i, r] for i, r in enumerate(results) if r > MIN_ACC] results.sort(key=lambda x: x[1], reverse=True) returnList = [] for r in results: ...
The main task of the code is to process a user input sentence by classifying it, then selecting an appropriate response from predefined contexts based on tags and filters. It stores the interaction in a database, returns a randomized response if conditions match, or returns an empty value if no valid context is found. ...
def response(sentence, chatID=0): results = classify(sentence) print("results : ",results) if results: while results: for i in contexts['contexts']: if i['tag'] == results[0][0]: if 'contextSet' in i: context[chatID] = i['contex...
def get_data(name1, name2): """ This method retrieves the data and returns the filtered tweet dataframe """ stock_data, tweet_data = load_data(name1, name2) tweet_data = filter_data(tweet_data) return stock_data, tweet_data def plot_r_squared(stock_data, tweet_data): """ This meth...
The main task of the code is to analyze the impact of Elon Musk's tweets on Doge (DOGE-USD) stock price by testing two trading strategies: (1) buying only on positive tweets and (2) buying on all Doge-related tweets. It processes stock and tweet data, calculates profitability, performs statistical tests, and visualizes...
def main(): """ This method plots the graph and runs the training model """ # Unpack tuple of time series dataframes stock_data, tweet_data = get_data('DOGE-USD.csv', 'elonmusk.csv') plot_r_squared(stock_data, tweet_data) plot_volatility(stock_data, tweet_data) example_trade(stock_data,...
def compute_ddt(): global DIFFER_APPROXIMATION_TABLE for i in range(16): for j in range(16): d_in = i ^ j d_out = present.S_BOX[i] ^ present.S_BOX[j] DIFFER_APPROXIMATION_TABLE[d_in][d_out] += 1 def compute_differ_out(): global USABLE_DIFFER res = list() r...
The main task of the code is to initiate a sequence of computations involving differential distribution tables (compute_ddt), output difference calculations (compute_differ_out), and probability analysis (compute_prob). The function `compute_start` orchestrates these tasks, passing parameters like `out_differ`, `round_...
def compute_start(out_differ: int, round_num: int, prob: float, record_list: list, total_active_num: int): compute_ddt() compute_differ_out() compute_prob(out_differ, round_num, prob, record_list, total_active_num)
def getSuperTriangle(edgePoints : MinMax) -> Triangle: ''' Returns a triangle that covers the given edge points :param edgePoints: a MinMax object with min and max X,Y locations that forms a square around the whole triangle :type edgePoints: MinMax(Coordinate, Coordinate) :return: a triangle that c...
The function performs Delaunay triangulation using the Bowyer-Watson algorithm. It begins by enclosing all points in a super triangle, then iteratively inserts each point. For each point, it identifies and removes triangles whose circumcircles contain the point, forming a polygonal hole. New triangles are created by co...
def delaunayTriangulation(points : List[Coordinate]) -> List[Triangle]: ''' Creates delaunay triangulation using bowyer and watson algorithm https://en.wikipedia.org/wiki/Delaunay_triangulation https://en.wikipedia.org/wiki/Bowyer%E2%80%93Watson_algorithm :param points: list of points to form the ...
def clear(): for _ in range(65): print() def add_item(): clear() print('Add New Item - Screen') print('-'*100) item_name = input('Enter new Item Name :') item_price = input('Enter Item Price :') sql = 'select * from items where item_name like "%{}%"'.format(item_name) cursor.exec...
The main task of the code is to display a menu-driven interface for managing items and generating reports. It loops indefinitely, showing options to add, modify, bill, search, view reports, or exit. User input directs execution to corresponding functions, terminating only when the "Exit" option (6) is selected.
def main_menu(): while True: clear() print(' M A I N M E N U') print('-'*100) print('1. Add New Item') print('2. Modify Existing Item') print('3. Billing') print('4. Search Menu') print('5. Report Menu') print('6. Exit') ...
def initial_point_m(lam: np.ndarray, sigma: np.ndarray, xi: np.ndarray): """ This is how we compute the initial point for iterations that eventually converge to the true optimal m :param lam: :param sigma: :param xi: :return: """ sigma_hat = co...
The function iteratively computes `m_til` (a transformed parameter) and derives `m` from it, using a covariance matrix `sigma`, parameters `capital_g` and `lam`, and shrinkage. It initializes `m_til` based on `g_bar`'s values, then updates it through `num_iterations` via `map_f_for_tilde_m`. Finally, it converts `m_til...
def solve_m_tilde_through_iterations(g_bar: np.ndarray, capital_g: np.ndarray, sigma: np.ndarray, initial_value: str, num_iterations: int, ...
def get_m_matrix_for_slice(returns: np.ndarray, lam: np.ndarray, risk_aversion: float, lam_scale: float, start_low: bool = True, shrinkage_for_m: float = 0., ...
This function constructs a transaction-cost-aware portfolio using Markowitz optimization, incorporating historical returns, signals, and shrinkage parameters. It iteratively updates portfolio weights to balance risk, returns, and transaction costs, using a parametric approach that adjusts for myopic or averaged target ...
def build_ml_tcost_aware_portfolio_for_slice(returns_slice: np.ndarray, signals_indexed_by_time: dict, list_of_shrinkages: list, dates: list, ...
def drawBlankTable(self, row, col): return(self.wholeTable(row,col,Person("","",False))) def splitTable(self, row, col, student1, student2): widthOffs = self.getWidthOffs(col) heightOffs = self.getHeightOffs(row) returnString = self.createTable(self.tableWidth/2, self.tableHeight, widthO...
This method generates LaTeX code for seating arrangements in a room, arranging students in a grid with specified rows and columns. It handles cases where students exceed single-column capacity by using double columns, ensuring proper distribution. It also includes time information if specified, and validates against ro...
def generateLatexCodeForSeating(self, students, includeTimes): print("Room " + self.name + " has " + str(len(students)) + " students") colsNeeded = math.floor(len(students) / self.rows) if(colsNeeded > 2 * self.cols): raise ValueError('Too many students assigned to room ' + self.name...
def send(message): client.send(message.encode("utf-8")) def receive(): return(client.recv(1024).decode("utf-8")) def addtoinventory(self, Mode, category): send("Please enter item name: ") self.choice = receive() self.category =category self.mode = Mode if self.uservalidat...
This function allows a user to join an existing order by specifying an item and amount. It validates the user, updates inventory quantities, and records the order. If the item isn't found, it offers to create a new order. If the item's stock reaches zero, it finalizes the order. The process includes user input, invento...
def joinorder(self): send("Please enter item name: ") self.choice = receive() send(str(Operation.Inventory[self.choice].duration)) send("Please enter item amount: ") self.amount = receive() if self.choice not in Operation.Inventory: send("Item not found\nWould...
def UpdateVertex(self, s): """ update the status and the current cost to come of state s. :param s: state s """ if s in self.OPEN: self.OPEN.pop(s) if s in self.obs: self.g[s] = math.inf return if s != self.s_start: ...
The main task of the code is to iteratively improve a path in a dynamic environment using a modified LPA* algorithm. It handles environmental changes by updating affected vertices, recalculating path costs, and adjusting the OPEN list. The function searches for an e'-suboptimal path by expanding nodes, avoiding obstacl...
def ImprovePath(self): """ :return: a e'-suboptimal path """ visited_each = [] while True and len(self.OPEN) != 0: if self.new_env_changes: # print("NEW ENV CHANGES") # TODO: MAKE EDGES CONSISTENT HERE BY CALLING LPA* ALGO ...
def init(self): """ initialize each set. """ self.g[self.s_start] = 0.0 self.g[self.s_goal] = math.inf self.OPEN[self.s_start] = self.f_value(self.s_start) self.PARENT[self.s_start] = self.s_start def ImprovePath(self): """ :return: a e'-suboptima...
The code performs an iterative path improvement algorithm. It initializes the search, updates the OPEN set's f-values, refines the path in a loop until convergence (when update_e() ≤ 1), and returns the optimized path along with visited nodes. The loop adjusts weights, manages open/closed states, and repeatedly enhance...
def searching(self): self.init() self.ImprovePath() self.path.append(self.extract_path()) while self.update_e() > 1: # continue condition self.e -= 0.4 # increase weight se...
def init(self): """ initialize each set. """ for i in range(self.Env.x_range): for j in range(self.Env.y_range): self.g[(i, j)] = math.inf self.g[self.s_start] = 0.0 self.OPEN[self.s_start] = self.f_value(self.s_start) self.PARENT[sel...
The code performs an iterative path improvement algorithm, adjusting exploration parameters (self.e) while updating OPEN set priorities and obstacle configurations. It visualizes progress if enabled, repeatedly refining paths through INCONS handling and CLOSED set management, returning the optimized path, visited nodes...
def searching(self): self.init() # self.fig.canvas.mpl_connect('button_press_event', self.on_press) if self.plot: self.Plot.plot_grid("LPARA*") self.ImprovePath() self.path.append(self.extract_path()) if self.plot: self.plot_progress() whi...
def peakData(self, peakRange): return (self.x[peakRange[0]:peakRange[1]+1], self.y[peakRange[0]:peakRange[1]+1], self.u[peakRange[0]:peakRange[1]+1]) def integrate(xvec, yvec): return abs(scipy.integrate.simps(yvec, x=xvec)) def distrParFromDistrib(mean, var, N=1.): # SAS...
This function processes each peak in a dataset to calculate distribution parameters (mean, variance) and their uncertainties. It computes moments from peak data, adjusts for uncertainty ranges (y±u), and generates distribution parameters for each. If plotting is enabled, it visualizes peaks with their moments and param...
def peakDistrPar(self, plotAxes=None, plotAxisStart=0, **plotPeakKwargs): distrPar = [] moments = [] for i, peakRange in enumerate(self.peaks): # for each peak x, y, u = self.peakData(peakRange) N = integrate(x, y) mom = Moments.fromData(x, y) momL...
def get_cache_files(self, year: int): prefix = self.hash_string.encode()+str(str(self.date_start)+str(self.date_end)+str(self.date_start2)+str(self.date_end2)).encode()+self.lat_lon.encode()+self.sensor.encode()+str(self.morph_op).encode()+str(self.morph_op_iters).encode()+str(gee.indice_selected).encode...
The code processes time series data by either retrieving precomputed results from a cache or generating them by iterating through years, extracting image pixels, merging data, and cleaning/transforming it. It handles data types, removes invalid entries, calculates occurrence/cloud percentages, and stores the final stru...
def process_timeseries_data(self, force_cache: bool = False): # warning print() print("Starting time series processing ...") # attributes df_columns = self.df_columns+['pct_occurrence', 'pct_cloud', 'instants'] df_timeseries = pd.DataFrame(columns=df_columns) # check timeseries is alread...
def validate_queries(queries): pattern = re.compile("^\?[A-Z]+$") if not pattern.match(queries): display_error_with_exit("Queries must contain at least 2 symbols. Sign '?' and facts. Example: '?ADF'") return True def validate_initialized_facts(initialized_facts): pattern = re.compile("^=([A-Z]+)?$") if not patte...
The main task of the code is to validate and categorize input lines into equations, initialized facts, and queries. It checks that the file has at least three lines, processes each line based on its token (QUERY, INITIALIZED_FACTS, or equation), validates their formats, and collects them into separate variables. If no ...
def validate_lines(lines): if len(lines) < 3: display_error_with_exit("File must contain at least 3 lines with equation, initialized facts and queries") initialized_facts = '' queries = '' equations = [] for line in lines: if line[0] == QUERY_TOKEN and validate_queries(line): queries += line.replace('?', '...
def opening_sequence(screen, clock): try: tankImg = pygame.image.load('Tanks/images/tank_main.jpg') tankImg = pygame.transform.rotozoom(tankImg, 0, WIDTH / 700) except pygame.error as message: tankImg = pygame.Surface(SCREEN_DIMS) tankImg.fill(GREEN) i = 0 while True: ...
The code initializes a "Battle Tanks" game using Pygame, runs an opening sequence, generates players and maps via a main menu, and executes a game loop. It handles rounds by running the game sequence, resetting player stats, shuffling players, and reloading maps. The loop continues until the game_sequence returns False...
def main(): # Initialize pygame and create window round_num = 1 pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Battle Tanks") clock = pygame.time.Clock() #Run the opening sequence opening_sequence(screen, clock) #Generate the players and...
def get_head_branch_name(): return run_std_command("git rev-parse --abbrev-ref HEAD") def get_version_from_json() -> str: with open(PACKAGE_JSON, "r+", encoding='utf-8') as f: data = json.load(f) return data["version"] def increment_by_branch(v:str, branch:str): if branch == "main": ...
The main task of the code is to automatically increment a version number based on the current Git branch, log the branch name and version change, and return the updated version. It retrieves the current branch, fetches the existing version from a JSON file, applies branch-specific increment logic, records the change, a...
def auto_increment_by_branch(): branch = get_head_branch_name().stdout.strip() old_v = get_version_from_json() new_v = increment_by_branch(old_v, branch) log = f"[LOG] {branch}\n[LOG] {old_v} -> {new_v}" print(log) return new_v
def auto_increment_by_branch(): branch = get_head_branch_name().stdout.strip() old_v = get_version_from_json() new_v = increment_by_branch(old_v, branch) log = f"[LOG] {branch}\n[LOG] {old_v} -> {new_v}" print(log) return new_v def set_version_to_json(v:str): with open(PACKAGE_JSON, "r+", en...
The main task of the code is to automatically increment a version number based on the branch, update it in a JSON file, stage the `package.json` file, and commit changes with the provided message. If the commit fails, it logs an error and returns.
def inrement_before_commit(commit_msg:str): new_v =auto_increment_by_branch() set_version_to_json(new_v) print("[LOG] Version set successful") do_stage_file(PACKAGE_JSON) print("[LOG] package.json staged successful") resp = do_commit(commit_msg) if resp.returncode != 0: print...
def initialize_parameters(X, Y, nb_units_per_hidden_layer): """ Initialize the parameters for each layer. Make sure that you have the right size. Refer to the neural network figure in the lab pdf. To initialize a random gaussian matrix use np.random.randn(d1, d2) * 0.05 To initialize the zeros...
The function `L_layer_model` trains a multi-layer neural network to minimize a cross-entropy cost using gradient descent. It initializes parameters, iterates for a given number of steps, performing forward propagation to compute activations, calculates the error between predictions and labels, executes backpropagation ...
def L_layer_model(X, Y, layers_dims, learning_rate=0.0075, num_iterations=3000, print_cost=False): """ Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID / TANH. Arguments: X -- data, numpy array of shape (number of examples, num_px * num_px) Y --The label of the data : Bina...
def on_session_started(session_started_request, session): """ Called when the session starts """ def on_launch(launch_request, session): """ Called when the user launches the skill without specifying what they want """ # Dispatch to your skill's launch return get_welcome_response() def on_inten...
This code defines an AWS Lambda handler for an Alexa skill, routing incoming requests to appropriate functions based on their type: LaunchRequest, IntentRequest, or SessionEndedRequest. It initializes a new session if required and delegates processing to on_launch, on_intent, or on_session_ended functions, enabling int...
def lambda_handler(event, context): if event['session']['new']: on_session_started({'requestId': event['request']['requestId']}, event['session']) if event['request']['type'] == "LaunchRequest": return on_launch(event['request'], event['session']) elif event['...
def receive_packet(sock): try: packet, addr = sock.recvfrom(PACKET_SIZE) header, data = parse_packet(packet) seq_num, ack_num, flags, _ = parse_header(header) return seq_num, ack_num, flags, data, addr except socket.timeout: return None, None, None, None, None def stop_an...
The code defines a UDP server that listens on a specified port, receives a client's address, and transfers a file using a reliability method (stop-and-wait, go-back-N, or selective repeat). It initializes a socket, waits for client connection, selects the appropriate reliability protocol based on input, and executes th...
def server(port, file, reliability_method): server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_socket.bind(('localhost', port)) server_socket.settimeout(TIMEOUT) client_address = None while not client_address: _, _, _, _, client_address = receive_packet(server_socket) ...
def stop_and_wait(sock, sender, receiver, file): if sender: # If the application is running as the sender with open(file, 'rb') as file: seq_num = 0 while True: data = file.read(DATA_SIZE) if not data: break # Send...
The code defines a client function that sends a file to a server using UDP, employing different reliability protocols based on the specified method. It initializes a socket, sets a timeout, and delegates file transmission to either stop-and-wait, go-back-N, or selective repeat protocols. The function closes the socket ...
def client(server_addr, server_port, file, reliability_method): client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client_socket.settimeout(TIMEOUT) server_address = (server_addr, server_port) if reliability_method == 'stop_and_wait': stop_and_wait(client_socket, server_address, f...
def argument_parser(): parser = argparse.ArgumentParser(description='UDP file transfer with reliability layer') parser.add_argument('-c', '--client', action='store_true', help='Start the application as a client') parser.add_argument('-s', '--server', action='store_true', help='Start the application as a ser...
The main task of the code is to execute either a server or client based on command-line arguments. It parses input arguments, then starts a server (if `--server` is specified) with given port, file, and reliability method, or initializes a client (if `--client` is specified) with server address, port, file, and reliabi...
def main(): args = argument_parser() if args.server: server(args.port, args.file, args.reliability_method) elif args.client: client(args.server_addr, args.server_port, args.file, args.reliability_method)
def binary_norm_Z(self, thetas, partition): """Computes the normalization constant Z(theta) for a given partition Args: thetas: The parameters for the given partition partition: List of feature indices indicating that they all belong in the same feature-partition. ...
The function `solver_optimize` performs optimization using the L-BFGS-B algorithm to estimate parameters (thetas) for feature partitions. For single-feature partitions, it computes Maximum Likelihood Estimates (MLE) directly. For multi-feature partitions, it constructs data statistics and constraint matrices, then mini...
def solver_optimize(self): """Function to perform the optimization uses l-bfgsb algorithm from scipy """ parts = self.feats_obj.feat_partitions solution = [None for i in parts] norm_sol = [None for i in parts] # twoway_dict = self.feats_obj.two_way_dict ...
def prev_adjacent_block(self, heapItem): # Iterate backwards from heapItem headerIndex for i in range(heapItem.headerIndex-1, 1, -1): # If the heapItem is inuse and is not the same block, then return it if self.heap[i].inuse is True and self.heap[i].name != heapItem.name: ...
This function coalesces adjacent free memory blocks in a heap by checking neighboring blocks. It merges the current block with adjacent free blocks based on their allocation status, updates pointers, and disconnects blocks when both neighbors are free, ensuring contiguous free space for efficient memory management.
def coalesce(self, heapItem): # Get previous and next blocks prevBlock = self.prev_adjacent_block(heapItem) nextBlock = self.next_adjacent_block(heapItem) # If the previous and next blocks are none, then create a dummy HeapItem # that is allocated if prevBlock is None: ...
def open(self, file_name=None, file_content=None): if file_name: wb = xlrd.open_workbook(file_name) self.sheet = wb.sheets()[0] def pre_load(self): pass def is_valid(self): if len(self.cleaned_data)==0: self.convert_json(self.sheet) return len(self.err...
The code's main task is to load and process data by opening a file, performing preprocessing, validating its content, and executing processing steps if valid. If validation fails, it raises an error. The method ensures data integrity through validation before proceeding with processing and post-processing tasks.
def load(self, file_name=None, file_content=None): self.open(file_name,file_content) self.pre_load() if self.is_valid(): self.process() self.post_process() else: raise ValidationError(self.errors)
def click(x,y): # x = x-x/5 #-20% for click # y = y-y/5 # x = int(x) # y = int(y) win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) def check_for_back(): while pyautogui.locateOnScreen('back.png', co...
The code automates sending up to 7 gathering marches in a game. It checks if the screen shows "7outof7.png" (all marches out) to stop, otherwise it sends marches via functions (findCash(), sendGather()), increments a counter, and loops until 7 marches are sent or all are out. It also handles screen checks and delays.
def gathering(): counter = 0 times = 0 if pyautogui.locateOnScreen('Base.png', confidence=0.9, region=(0,0,700,1100)) == None: click(88,1162) print("not on map, switching...") time.sleep(4) #check if already gathering #counter for how often all marches are out is returned ...
def click(x,y): # x = x-x/5 #-20% for click # y = y-y/5 # x = int(x) # y = int(y) win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) def check_for_back(): while pyautogui.locateOnScreen('back.png', co...
The code identifies the type of resource (energy, oil, steel, food, cash) being transferred in a game by locating a specific on-screen image ('mtest.png'), clicking its center, and determining the resource type based on the x-coordinate position. It then prints a descriptive message and returns a numeric code (1-5) cor...
def get_rss_type(): # time.sleep(1) # if pyautogui.locateOnScreen('btest.png', confidence=0.9, region=(0,0,700,140)) != None: # #print("see rss over 1m") # x,y = pyautogui.locateCenterOnScreen('btest.png', confidence=0.9, region=(0,0,700,140)) # click(x,y) # rsstype = 0 # if x <...
def cs_message(): if pyautogui.locateOnScreen('cs_message.png', confidence=0.8, region=(0,0,700,1100)) != None: x, y = pyautogui.locateCenterOnScreen('cs_message.png', confidence=0.7, region=(0,0,700,1100)) time.sleep(1) pyautogui.click(x,y) def check_crash(): if pyautogui.locateOnScreen...
The function `scroll_down()` performs a series of tasks: sends a message (`cs_message()`), checks for crashes (`check_crash()`), logs out if logged in (`log_out_if_logged_in()`), processes historical data (`historical()`), and simulates a mouse drag from (300, 800) to (300, 600) over 0.6 seconds to scroll down the scre...
def scroll_down(): cs_message() check_crash() log_out_if_logged_in() historical() mouse.drag(300, 800, 300, 600, absolute=True, duration=0.6)