dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _check_cache(self) -> Optional[Any]: self._set_cache_info() if os.path.exists(self._cache_path): with open(self._cache_path, "rb") as handle: return pickle.load(handle) return None def _clear_cache_info(self): self._input_text = None self._cache_p...
The code runs a simulation by executing an external binary, optionally using cached results. It configures input parameters, checks for cached data, writes input files, executes the simulation process, loads results, caches them if enabled, and returns a SimulationResult containing execution time and results.
def run(self, full_history: bool = False, expensive_stats: bool = False, use_cache=False) -> SimulationResult: self.input_data.options = ProgramOptions(full_history, expensive_stats, ProgramMode.Simulate) # Check for cached results if use_cache: final_result = self._check_cache() ...
def _check_cache(self) -> Optional[Any]: self._set_cache_info() if os.path.exists(self._cache_path): with open(self._cache_path, "rb") as handle: return pickle.load(handle) return None def _clear_cache_info(self): self._input_text = None self._cache_p...
The function `find_contact_prob` computes contact probability results by either retrieving cached data or executing an external program. It processes input data, runs a subprocess to generate results, converts date formats, and returns a structured `ContactSearchResult`. Caching is utilized to avoid redundant computati...
def find_contact_prob(self, use_cache=False) -> ContactSearchResult: self.input_data.options = ProgramOptions(False, False, ProgramMode.FindContactProb) if use_cache: final_result = self._check_cache() if final_result is not None: final_result: ContactSearchResul...
def delete_sections(config_lines: list[str], sections_to_delete: list[str]) -> list[str]: """Delete sections from the FortiOS config file.""" new_lines = [] section = "" delete_line = False for line in config_lines: if ( line.startswith(CONFIG_LINE_PREFIX) and line[l...
The main task of the code is to clean and sort FortiOS configuration files by reading a source file, removing specified sections and trailing spaces, sorting configurations based on defined sections and subsections, and writing the processed content to a destination file. Verbosity options control logging detail levels...
def main( src_file_path: str = typer.Argument(None, help="Path to the source file"), dst_file_path: str = typer.Option( app_config["destination_path"], "--dst_file_path", "-d", help="Path to the write file", ), verbosity: int = typer.Option( 0, "-v", "--verbose", ...
def sample(self): print('Sampling ......') print_sample_mu = self.mu_x.clone().detach() print_sample_mu = print_sample_mu.sigmoid() print('mu: ', print_sample_mu) print('sigma: ', self.sigma) self.sampler = TruncatedNormal(self.mu_x.sigmoid(), self.sigma, 0.0, 1....
The main task of the code is to perform a search process using a reinforcement learning framework, where parameters (mu, sigma) are iteratively updated via Proximal Policy Optimization (PPO) based on sampled theta values and their associated rewards. The code supports resuming from a previous run by loading saved param...
def search(self): print('Start searching, work dir: ', self.args.output_dir) rounds = [] rewards = [] # save mu as .npy each round for resume save_mu = self.mu_x.clone().view(-1).detach() save_mu = save_mu.sigmoid() save_mu = save_mu.cpu().numpy() ...
def calc_offset_detector(ra, dec, rot, chip): angle_off = offset_dict[chip]['angle'] + float(rot) separation_off = offset_dict[chip]['separation'] chip_coords = calc_offset(ra, dec, angle_off * u.deg, separation_off * u.deg) new_rotation = (rot + offset_dict[chip]['rotation']) % 360 return chip_coor...
This function updates FITS file headers with recalculated right ascension (RA), declination (DEC), and rotation values using detector coordinates, inserts new keywords for updated WCS information, and converts PC matrix parameters to CD matrix format for compatibility with SCAMP, ensuring proper coordinate alignment an...
def update_ra_dec(fits_file): print(fits_file) with fits.open(fits_file, 'update') as f: header = f[0].header if not header.get('COORD_UP', False): ra = header['RA'] dec = header['DEC'] rad = header['RA-D'] decd = header['DEC-D'] #rotat...
def get_k_quote(self): with requests.get(url=KANYE_URL) as response: response.raise_for_status() quote = response.json()["quote"] q_doc = NLP(quote) k_quote = list(q_doc.sents) if len(k_quote) > 2: self.get_k_quote() else: ...
The code initializes a class to prepare data for generating a meme by fetching quotes (k_quote, y_quote) and image dimensions (t_width, t_height), then generates the meme using the collected data and image information (img_data).
def __init__(self): self.k_quote = [] self.y_quote = [] self.t_width = 0 self.t_height = 0 self.img_data = None self.get_k_quote() self.get_y_quote() self.generate_meme()
def validate_voter(name, phone, email, dob, assembly, pin, image): if len(name) < 3 and any(d in name for d in digit): print("Name error.") return False if len(phone) != 10 or not str(phone).isdigit(): print("Phone error.") return False if not '@' in email or not '.' i...
The main task of the code is to add a new voter to a database by validating their details, inserting their information into the 'VOTER' table, storing their image in the 'PHOTO' table, and returning success/failure status. It retrieves assembly ID, generates a voter ID, executes SQL inserts, handles exceptions, and com...
def add_voter(name, phone, email, dob, assembly, pin, image): if not validate_voter(name, phone, email, dob, assembly, pin, image): return False,{} try: conn = get_connection() cursor = conn.cursor() cursor.execute("SELECT AID FROM ASSEMBLY WHERE NAME = %s",(assembly, )) ...
def get_model() -> DigitModel: """ Loads model from weights if they exists, otherwise train model """ if os.path.exists(os.path.join(os.getcwd(), 'model/checkpoint')): model = DigitModel('model/checkpoint') else: model = DigitModel() model.train(epochs=100) return mo...
The code detects a Sudoku grid in an image, classifies its digits using a pre-trained model, solves the puzzle, and overlays the solution on the original image. It loads the image, converts it to grayscale, identifies the grid via inverse perspective transformation, extracts cells, classifies digits, validates/solves t...
def run(path: str): # Digit classifier model model = get_model() # Get image both in RGB and grayscale img = cv2.imread(path, cv2.IMREAD_COLOR) gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Get sudoku grid image along with inverse # perspective transformation sudoku_img, inv_persp...
def get_model() -> DigitModel: """ Loads model from weights if they exists, otherwise train model """ if os.path.exists(os.path.join(os.getcwd(), 'model/checkpoint')): model = DigitModel('model/checkpoint') else: model = DigitModel() model.train(epochs=100) return mo...
This code processes a video to detect and solve Sudoku puzzles in real-time. It reads input video frames, identifies Sudoku grids, classifies digits using a model, solves the puzzles, and overlays solutions on original frames. If enabled, it saves the processed video with solved puzzles. The main task is real-time Sudo...
def run_video(path: str, save=False): model = get_model() cap = cv2.VideoCapture(path) # Keep track of solved grid to not have to # solve each frame solved_grid = None # If saving video, create image list if save: img_list = [] while cap.isOpened(): ret, img = cap.rea...
def open_file(): data_file = open('apartment_data.csv', "a") return data_file def fetch_from_url(url): headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:39.0)'} # driver.get(url) # time.sleep(2) # return driver.page_source.encode("utf-8") # session = HTMLS...
The main task of the code is to scrape property listing data from PropertyFinder's Dubai real estate pages (40 pages) by extracting details from each card, appending property descriptions from individual listing URLs, and writing the aggregated data into a file. It iterates through pages, handles missing card structure...
def main(): data_file = open_file() # add_headers_to_file() for counter in range(1, 41): # dubai link:"https://www.propertyfinder.ae/en/search?c=2&fu=0&l=1&ob=mr&page=1&rp=y" # base_url = f'https://www.propertyfinder.ae/en/search?c=2&fu=0&l=4&ob=mr&page={counter}&rp=y' -- sharjah link ...
def is_win(el): return any((is_full_row(el), is_full_column(el), is_full_diagonal(el))) def difference_number(el_1, el_2): el_1_number = len([x for row in matrix for x in row if x == el_1]) el_2_number = len([x for row in matrix for x in row if x == el_2]) return abs(el_1_number - el_2_number) def is_ne...
This function determines the current game status by checking win conditions for players 'O' and 'X', validating move count differences, and identifying if the game is a draw or still in progress. It returns "Impossible" for conflicting wins, "O wins" or "X wins" for valid victories, "Draw" when no moves remain, or "Gam...
def game_status(): status = "Game not finished" if is_win(O_SIGN) and is_win(X_SIGN) or difference_number(O_SIGN, X_SIGN) >= 2: status = "Impossible" elif is_win(O_SIGN): status = 'O wins' elif is_win(X_SIGN): status = 'X wins' elif not is_next_step(): status = "Draw"...
def print_menu(self): if self.logged_in is False: self.__initial_menu() else: self.__working_menu() def __do_action(self): if self.user_choice == (0, 1): self.do_create_account() elif self.user_choice == (0, 2): self.do_login() elif...
The code defines a method `bank_work_cycle` that runs an infinite loop to repeatedly display a menu, execute user-selected actions, and check for an exit condition. If the exit condition is met, the loop breaks, and a `do_full_exit` method is called to finalize the process. The primary task is to manage a continuous ba...
def bank_work_cycle(self): while True: self.print_menu() self.__do_action() if self.__is_exit(): break self.do_full_exit()
def ask_user_for_options_list(self): input_ = input("Enter custom options list: ") if input_ != '': self.CHOICE_VARIANTS = input_.split(',') print("Okay, let's start") def ask_user_choice(self): self.user_choice = input() while self.user_choice not in self.CHOICE_VARI...
The code's main task is to run a game loop where the user selects options, the computer updates its choice, and actions are executed repeatedly until the user inputs '!exit'. The loop handles user choices, triggers game actions, and updates the computer's response iteratively. Upon exiting, it saves the session results...
def play_game(self): self.ask_user_for_options_list() self.ask_user_choice() self.change_computer_choice() while self.user_choice != '!exit': self.do_action() self.change_computer_choice() self.ask_user_choice() print('Bye!') self.save...
def clear_then_set_qualifiers(self, block): qualifiers = {} for line in block.lines: qualifier = self.QUALIFIER_SYNTAX.get(line.parameter) if qualifier: qualifiers[qualifier] = value self.qualifiers = qualifiers def parse_lookup(self, block): pat...
The main task of this code is to retrieve and group item data from the POE Ninja API based on a given block's specifications. It processes the block's qualifiers, parses lookup data, fetches item details, identifies low-value bases, and organizes items into groups for filter block generation. The function returns struc...
def get_item_groups_for_block(self, block): print(f' $ Looking up price data for: {block.lines[0].block_name} on poe.ninja') # We store things like links, quality, etc. as "qualifiers" for each block. # This way we know what to loop over when considering if an item from a POE Ninja # lo...
def _initialize_state_gaussian(self,obs): ''' # Initializes mean vector and covariance matrix for the states. Each state is inialized to be sort of random gaussian, based on the first training example. Each state_gaussian is initialized to have same covariance which is in fa...
The code trains a Hidden Markov Model (HMM) using the Baum-Welch algorithm for parameter estimation. It handles 2D/3D observation data, initializing state distributions and iteratively updating model parameters via forward-backward probabilities and emission calculations over n_iter rounds to maximize observation likel...
def train(self,obs,n_iter): flag = 2 if(len(obs.shape) == 3): flag = 3 self._initialize_state_gaussian(obs[0]) for i in range(n_iter): print('training round: ',i) for o in obs: self._calculate_emissio...
def get_event_list_raw(username, start: datetime, end: datetime) -> list: events = calendar_db.get_event_list(username, start=None, end=None) req_events = [] for event in events: s_date = get_datetime(event["start_time"]) e_date = get_datetime(event["end_time"]) if e_date >= star...
The code generates a list of free time intervals for a given date across all users, considering their scheduled events. It marks 15-minute time slots as occupied (1) or free (0), then compiles contiguous free slots into time blocks. The output is a list of time intervals where no events are scheduled, converted to huma...
def compare(user_list: list, date: str, tz=pytz.utc) -> list: split_date = date.split("-") date = datetime(int(split_date[0]),int(split_date[1]),int(split_date[2]),0,0,0) date = tz.localize(date) user_event_list = [] for user in user_list: e_list = get_event_list_raw(user,date,date+timede...
def generate_descendant_activity(pt): """ Generates a descendant for a given pt that satisfies the allowed mutations under a selection pressure -----Parameters----------- pt: array-like, float features -----Returns-------------- new_pt: array-like, float features """ global dim, sel, mu, br,...
The function `generate_bag` creates a collection (bag) of example points by recursively generating left and right descendants from an initial point `pt`. It expands each point into new examples using probabilistic branching, appending them to the bag until the specified number of nodes (`num_nodes`) is reached. Each de...
def generate_bag(pt,): """ Generates a bag of examples -------Parameters--------- pt: array-like, float features -------Returns------------ bag: array-like, float """ global sel, mu, br, num_nodes, activity_wt scipy.random.seed() bag = [pt] points = [pt] # generate tree wit...
def parse_blast(blast_output_file, min_alignment_len): df = pd.read_table(blast_output_file, names=["read_id", "ref_id", "read_start", 'read_end', 'ref_start', 'ref_end', 'plus_or_minus', 'aln_len', 'blast_diff', 'read_seq', 'ref_seq']) df['mut_num'] = df['bl...
The code processes BLAST and FASTQ data by parsing alignment results, converting FASTQ reads to a DataFrame, merging them on read IDs, filtering valid alignments, and aggregating statistics. It separates passed/ignored reads, generates summary data for valid alignments, and returns aggregated results along with ignored...
def get_data(blast_output_file, fastq_path, min_alignment_len): blast_data = parse_blast(blast_output_file, min_alignment_len=min_alignment_len) fastqs_data = fastq_to_df(fastq_path) data = blast_data.merge(fastqs_data, on=['read_id']) ignored_reads = data[data.passed == 0] good_data = data[data.pas...
def run_blast(blast_params, output_dir, fastq_path, reference_file): fasta_file = convert_fastq_to_fasta(fastq_file=fastq_path, output_dir=output_dir) blast_output_file = fasta_file + ".blast" bp = blast_params.split(" ") outfmt = "6 qseqid sseqid qstart qend qstrand sstart send sstrand length btop qseq...
The main task of the code is to process sequencing data by aligning reads to a reference using BLAST, filter alignments based on minimum length, generate analysis results (mutations, frequencies), and save structured outputs (TSV files) along with logs. It separates filtered and unfiltered data into distinct directorie...
def main(fastq_path, reference_file, output_dir, blast_params, min_alignment_len): unfiltered_dir = os.path.join(output_dir, 'unfiltered') os.makedirs(unfiltered_dir, exist_ok=True) logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %I:%M:%S %p', level=logging.INFO, ...
def data_dir(dataset): """ data directory corresponding to dataset """ return f'data/didi_{dataset}' def json_file(dataset): """ json file corresponding to dataset """ return f'{PREPROC_DIR}/{dataset}_20200131.ndjson' def display_ink(ddir, ink): """ Draw image, overlay strokes, approximate bbox. """ Prepare...
The function `parse_drawings` processes ndjson and xdot files to extract and analyze drawings. It iterates through datasets, reads JSON lines, and collects the first drawing per unique `label_id` to avoid duplicates. For each selected drawing, it prints strokes and approximates bounding boxes, using `tqdm` for progress...
def parse_drawings(): """ Parse the ndjson and xdot files """ for dataset in DATASETS: ddir = data_dir(dataset) # Collect only the relevant drawings # We pick the first drawing for each label_id drawings = [] ink_set = set() with open(json_file(dataset), 'r') as file: for line in ...
def rmdata(): data_dir = Path(PREPROC_DIR) if data_dir.exists(): logging.info(f"Removing {data_dir} ...") shutil.rmtree(data_dir) def create_dirs(): """ Dir structure for post processed data """ logging.info("Setting up dataset directory structure...") for dataset in DATASETS: ddir = data_dir(data...
The main task of the code is to preprocess the Didi dataset by downloading specific files, organizing them into a structured folder hierarchy, parsing ndjson and xdot files, generating ink-stroked images, extracting approximate bounding boxes, and saving label data. It creates class lists, handles cleanup if enabled, a...
def preprocess_didi(cleanup=False): """ Happens in the following steps: - Download dataset from google cloud storage - In particular, we only download ndjson and the xdot files - Setup folder structure data/{dataset}/{split}/{images,labels} - Output classes.txt for each dataset (set of class hardcoded to s...
def get_token(url): """Get GitHub OAuth token from url or user file.""" token, api_url = parse_url(url) if token is not None: return token, api_url tkn_file = os.path.join(os.path.expanduser("~"), ".git_oauth_token") if not os.path.exists(tkn_file): raise RuntimeError("Github token not speci...
The main task of the code is to check if GitHub repositories require new releases by comparing their latest release tags with the master branch. If commits exist since the last release, it creates a new release for the repo. It specifically handles the 'hysds-framework' repository, generating a new release if any depen...
def main(url, force): """Route request.""" token, api_url = get_token(url) #logging.info("Github token: {}".format(token)) logging.info("Github repo URL: {}".format(mask_token(token, url))) # do a new hysds-framework release new_framework_release = True if force else False # loop over rep...
def join(path: Union[str, Path], join_str: Union[str, List[str]]) -> Union[str, Path]: join_str = join_str if isinstance(join_str, list) else [join_str] if _is_gcs_path(path): base_path: str = path.rstrip("/") # type: ignore for j in join_str: base_path += "/" + j return bas...
The main task of the code is to download a file from a given URL and save it to a specified folder. It checks if the file already exists locally, and if not, downloads it to a temporary directory before copying it to the target folder. The function handles both local and non-local storage scenarios, using `upload_to_ur...
def download_url(url: str, folder: str): r"""Downloads the content of an URL to a specific folder. Args: url (string): The url. folder (string): The folder. log (bool, optional): If :obj:`False`, will not print anything to the console. (default: :obj:`True`) """ from...
def on_launch(): print('on_launch handler reached') def on_intent(intent_request): if not 'intent' in intent_request: get_error_response('intent is not present in request') intent = intent_request['intent'] print('Intent:') print(intent) if not 'name' in intent: return get_error...
The code processes incoming events by checking the request type and routing it to corresponding handlers: on_launch for launch requests, on_intent for intent requests, and on_session_ended for session end requests, with error responses for invalid or missing request structures.
def lambda_handler(event, context): if 'request' in event: if 'type' in event['request']: if event['request']['type'] == "LaunchRequest": return on_launch() # TODO: respond to launch elif event['request']['type'] == "IntentRequest": return on_intent(e...
def initialePopulation(popSize,cityList): population = [] for i in range(0, popSize): population.append(createRoute(cityList)) return population def rankRoutes(cityList): fitnessResults = {} for i in range(0,len(cityList)): fitnessResults[i] = Fitness(cityList[i]).routeFitness() ...
The code implements a genetic algorithm to solve the Traveling Salesman Problem (TSP). It initializes a population of potential routes, iteratively evolves them over specified generations by selecting elites, applying crossover/mutation, and minimizing the path distance. The function returns the best route found after ...
def geneticAlgorithm(cityList, popSize, eliteSize, mutationRate, generations): pop = initialePopulation(popSize, cityList) print("Initial distance: " + str(1 / rankRoutes(pop)[0][1])) for i in range(0, generations): pop = nextGeneration(pop, eliteSize, mutationRate) print("Final distance: " + ...
def initialePopulation(popSize,cityList): population = [] for i in range(0, popSize): population.append(createRoute(cityList)) return population def rankRoutes(cityList): fitnessResults = {} for i in range(0,len(cityList)): fitnessResults[i] = Fitness(cityList[i]).routeFitness() ...
This function implements a genetic algorithm to solve the Traveling Salesman Problem (TSP) by evolving a population of routes over generations. It tracks the best, worst, and mean route distances per generation, visualizes their progress, and returns the optimized route. The algorithm uses selection, crossover, and mut...
def geneticAlgorithmPlot(cityList, popSize, eliteSize, mutationRate, generations): pop = initialePopulation(popSize, cityList) progressBest = [] progressWorst = [] progressMean = [] progressBest.append(1 / rankRoutes(pop)[0][1]) progressWorst.append(1 / rankRoutes(pop)[popSize-1][1]) sum = 0...
def initialePopulation(popSize,cityList): population = [] for i in range(0, popSize): population.append(createRoute(cityList)) return population def rankRoutes(cityList): fitnessResults = {} for i in range(0,len(cityList)): fitnessResults[i] = Fitness(cityList[i]).routeFitness() ...
The main task of the GA_loop function is to execute a Genetic Algorithm (GA) for solving the Traveling Salesman Problem (TSP). It initializes populations, evolves them across generations using selection, crossover, and mutation, tracks the best and worst routes, and visualizes progress. The function manages parameters ...
def GA_loop(cityList,generations,popSize,eliteSize,mutationRate,crossoverRate,chooseselection,choosemutation,graph): ''' Main logic loop for the GA. Creates and manages populations, running variables etc. ''' # first graph=true so else runs and cities in canvas creates # need to...
def initialePopulation(popSize,cityList): population = [] for i in range(0, popSize): population.append(createRoute(cityList)) return population def rankRoutes(cityList): fitnessResults = {} for i in range(0,len(cityList)): fitnessResults[i] = Fitness(cityList[i]).routeFitness() ...
This code implements a genetic algorithm to solve the Traveling Salesman Problem (TSP). It initializes a population of city route permutations, iteratively evolves them through selection, crossover, and mutation over specified generations, and returns the best route found. The algorithm aims to minimize the total dista...
def geneticAlgorithm(cityList, popSize, eliteSize, mutationRate, generations): pop = initialePopulation(popSize, cityList) print("Initial distance: " + str(1 / rankRoutes(pop)[0][1])) for i in range(0, generations): pop = nextGeneration(pop, eliteSize, mutationRate) print("Final distance: " + ...
def initialePopulation(popSize,cityList): population = [] for i in range(0, popSize): population.append(createRoute(cityList)) return population def rankRoutes(cityList): fitnessResults = {} for i in range(0,len(cityList)): fitnessResults[i] = Fitness(cityList[i]).routeFitness() ...
This code implements a genetic algorithm to solve the Traveling Salesman Problem (TSP). It tracks the best, worst, and average route distances across generations, plots their progress, and returns the optimal route. The algorithm initializes a population, iteratively evolves it through selection, crossover, and mutatio...
def geneticAlgorithmPlot(cityList, popSize, eliteSize, mutationRate, generations): pop = initialePopulation(popSize, cityList) progressBest = [] progressWorst = [] progressMean = [] progressBest.append(1 / rankRoutes(pop)[0][1]) progressWorst.append(1 / rankRoutes(pop)[popSize-1][1]) sum = 0...
def GA_loop(cityList,generations,popSize,eliteSize,mutationRate,crossoverRate,chooseselection,choosemutation,graph): ''' Main logic loop for the GA. Creates and manages populations, running variables etc. ''' # first graph=true so else runs and cities in canvas creates # need to...
The main task of the code is to configure and execute a genetic algorithm (GA) for optimization, retrieving user-specified parameters (population size, mutation rate, etc.) and city layout type (random, circle, or 'C'), then running the GA loop with these settings and enabling graph visualization.
def runAlgorithm(event): popSize = int(textbox_pop.get()) eliteSize = int(textbox_elit.get()) mutationRate = float(textbox_mut.get()) generations = int(textbox_generation.get()) crossoverRate = float(textbox_coR.get()) createcity = combo_city.get() chooseselection...
def choose_color(self): color = colorchooser.askcolor() self.color_button.config(bg=color[1]) self.tile_color = color[1] def set_edit_mode(self, edit_mode=False): if edit_mode: state = "normal" button_state = "normal" else: state = "readonly" ...
This code initializes a GUI tile component with editable attributes (ID, name, color, fill, islands) and controls for editing, saving, adding, or removing tiles in a hierarchical structure, integrating with a main GUI interface.
def __init__(self, root, main_gui, parent_tile_id, tile_id=0, name="name", color="#000000", fill=0.5, islands=1, level=0): Frame.__init__(self, root) self.main_gui = main_gui self.tile_id = tile_id self.parent_tile_id = parent_tile_id self.tile_name = name ...
def get_coordinate_tuples(self, searched_id): """Returns list of tuples of coordinates of all tiles on map with searched id""" tuples = [] for row_number, row in enumerate(self._map): for column, id_ in enumerate(row): if id_ == searched_id: ...
The main task of the code is to generate a single tile with non-connecting islands by applying masks to prevent connections between them. It calculates the number of tiles to generate based on the fill percentage, creates isolated islands using the `generate_island` method, trims the generated map, and integrates it in...
def generate_tile(self, raw_map, parent_tile, tile_id, fill, islands=1): """Generates single tile type. Creates non connecting islands one by one and applying mask around them to avoid connections""" number_of_tiles = len(self.get_coordinate_tuples(self._parent_id)) for fill in self.get_...
def colortogreyImage(original_frame: np.ndarray) -> np.ndarray: return cv2.cvtColor(original_frame, cv2.COLOR_BGR2GRAY) def birdseyeView(image_gray: np.ndarray) -> np.ndarray: width, height = image_gray.shape[1], image_gray.shape[0] source = np.float32([[(20, 440), (100, 180), (590, 180), (640, 470)]]) ...
The code processes images in a directory to calculate steering angles for lane detection. It converts images to grayscale, applies transformations, detects lane lines, fits polynomials to lanes, and computes steering angles. It measures total and average processing time, outputting performance metrics like images per s...
def pipeline() -> None: image_directory: str = "determine_dir_opt/calced" image_files: List[str] = os.listdir(image_directory) total_processing_time: float = 0.0 png_files: List[str] = [file for file in image_files if file.endswith('.png')] image_paths_doubled: List[str] = png_files random.shu...
def achilles_age_agg(df): return aggregate_age(achilles_age(df), 'stratum_1', 10, label=True, agg_below=40, sort="asc") def title_row(df, title): df = df.astype(str) trow = pd.DataFrame([[title, *['' for i in range(df.shape[1]-1)]]], columns=df.columns) return pd.concat((trow, df), axis=0, igno...
The code generates demographic summary statistics (age, gender, race, ethnicity) from a DataFrame by aggregating data using helper functions, formatting each as percentage columns with titles, and concatenating them into a single DataFrame with a reset index.
def query(df): age = achilles_age_agg(df) gender = achilles_gender(df) race = achilles_race(df) ethnicity = achilles_ethnicity(df) return pd.concat(( title_row(concat_pct_col(age), 'Age'), title_row(concat_pct_col(gender), 'Gender'), title_row(concat_pct_col(race), 'Race'),...
def submit_scripts(to_run, in_progress, hash_, config): num_sbatch_ops = get_num_ops(hash_, config) while num_sbatch_ops <= config['max_sbatch_ops'] and len(to_run) > 0: run_script = to_run.pop() in_progress.append(run_script) os.popen(f'sbatch {run_script}').read() num_sbatch_op...
The main task of the code is to monitor and update the status of tasks in a grid search. It submits scripts, checks completed tasks by comparing job IDs with system operations, updates finished/in-progress lists, calculates progress percentages relative to total tasks, and prints real-time status. It returns updated in...
def monitor(to_run, in_progress, finished, tot_num, hash_, config): submit_scripts(to_run, in_progress, hash_, config) if len(to_run) == 0 and len(in_progress)==0: config['gridsearch_complete'] = True return in_progress, finished sbatch_ops = get_ops(hash_, config) finished.extend([elt ...
def get_grid(hp): if 'subsets' in hp.keys(): all_grids = [] subsets = hp['subsets'] del hp['subsets'] for sub in subsets: sub_hp = {**hp, **sub} keys, vals = zip(*list(sub_hp.items())) grid = [{k:v for k,v in zip(keys,elt)} for elt in list(itertoo...
The code executes a workflow for running and managing computational experiments. It generates a unique hash from configuration hyperparameters, creates a directory structure, submits jobs via SLURM, collates results, compiles error reports, emails completion notifications, and compresses output files. The process ensur...
def nsg(config): ''' Requires a runfile (e.g. /work/awilf/utils/run_nsg.py) ''' rt = Runtime() hash_ = hashlib.sha1(json.dumps(config['hp'], sort_keys=True).encode('utf-8')).hexdigest()[:config['hash_len']] hash_path = join(config['results_path'], hash_) grid = get_grid(config['hp']) to...
def get_forms(self): statics = None if self.request.POST: statics = {'data': self.request.POST, 'files': self.request.FILES} return {data['prefix']: self.get_form_for(data, statics) for data in self.forms} def is_all_valid(self, forms): ...
This code processes a POST request by validating multiple forms. If all forms are valid, it saves them and returns a success response; otherwise, it returns an invalid response with the forms.
def post(self, request, *args, **kwargs): forms = self.get_forms() if self.is_all_valid(forms): self.objects = self.save_all(forms) return self.forms_valid(forms=forms) return self.forms_invalid(forms=forms)
def check_no_dup(times): """ Remove duplicate events Parameters ---------- times: obspy UTCDateTime event occurrence times """ tset = set() for t in times: if t in tset: print("Duplicate time: %s" % t) tset.add(t) def check_down...
The code downloads seismic data for each earthquake listed in a catalog (source.csv), ensuring no duplicate entries. It creates a directory structure for raw data, iterates through each event, checks if data for the next event is already downloaded, and skips it if so. For each event, it prints progress and triggers a ...
def main(): """ Download data for each earthquake from the catalog (source.csv). """ data_path = '../data/' outputbase = data_path + "raw_data" if not os.path.exists(outputbase): os.makedirs(outputbase) sources = pd.read_csv(data_path + "source.csv") check_no_dup(sources.time) ...
def read_waveform(fn): """ Read seismic data using obspy. Parameters ---------- fn: string File name. Returns ------- st: obspy stream Seismic data. """ st = obspy.read(fn, format="MSEED") return st def select_station_components(st, z...
The function `measure_on_stream` processes seismic waveform data from multiple stations to extract features for earthquakes, using predefined arrival windows. It reads waveform and window files, checks for three components per station, and computes measurements for valid stations. It returns a dictionary of features an...
def measure_on_stream(src, waveform_file, window_file): """ Make features for all stations (three components). Parameters ---------- src: pandas dataframe Earthuake information. waveform_file: string Seismogram file name. window_file: string File name for picked ...
def check_status(self,moves,targets,board,piece): new_moves=[] new_targets=[] for move in moves: is_illegal=self.is_illegal(move,board.copy(),piece) if not is_illegal: new_moves.append(move) for move in targets: is_illegal=self.is_illeg...
This method updates the game state by determining valid moves and targets for a selected piece, checking their status, and enabling visual feedback. If no piece is selected, it alternates turns, disables visual feedback, and checks for checkmate, ensuring proper game flow and UI updates.
def update(self): if self.selected_piece:#cube,piece self.moves,self.targets=self.selected_piece[1].get_moves(self.board.copy(),self.selected_piece[0].id) self.moves,self.targets=self.check_status(self.moves.copy(),self.targets.copy(),self.board.copy(),self.selected_piece) se...
def copy(self,board):#board=[{(move):(cube,piece),...},{...}] copy_board=[{},{}] for i in range(2): copy_dict=board[i].copy() copy_board[i]=copy_dict return copy_board def check_status(self,moves,targets,board,piece): new_moves=[] new_targets=[] fo...
The code updates the game state by determining valid moves and targets for the selected piece or crazy element, applying status checks, enabling/disabling colors based on selection, toggling player turns, and checking for checkmate to manage game progression.
def update(self): if self.selected_piece:#cube,piece self.moves,self.targets=self.selected_piece[1].get_moves(self.copy(self.board),self.selected_piece[0].id) self.moves,self.targets=self.check_status(self.moves.copy(),self.targets.copy(),self.copy(self.board),self.selected_piece) ...
def build_word_frequencies(self, text): for sentence in text: sentence = self.preprocess_sentence(sentence) for word in sentence: if word in self.word_freq: self.word_freq[word] += 1 else: self.word_freq[word] = 1 ...
The code's main task is to process input text by building word frequency counts, creating word-to-index mappings, and encoding sentences into numerical representations for machine learning tasks like NLP. This prepares text data for model training or analysis by converting raw text into structured, quantitative formats...
def build_vocabulary(self, text): self.build_word_frequencies(text) self.build_word_mappings() self.build_encoded_sentences(text)
def _relation_hosts(self, relation) -> dict: """Fetch host names and address of all consumer units for a single relation. Args: relation: An `ops.model.Relation` object for which the host name to address mapping is required. Returns: A dictionary that ma...
This function generates Prometheus static scrape configurations for a given relation by extracting and processing scrape job data and metadata from the relation's application data, then creating labeled job configurations with a standardized naming scheme and host information.
def _static_scrape_config(self, relation) -> list: """Generate the static scrape configuration for a single relation. Args: relation: an `ops.model.Relation` object whose static scrape configuration is required. Returns: A list (possibly empty) of scrape...
def sentences(s): '''helper function for sentence_lengths attribute. Splits the input string 's' by their sentence ending punctuations and returns a list of a length corresponding to the respective length for each sentence within the inputted string''' lengths = [] s = s.replace('?', '.') s = s.replace(...
The code processes a string by counting sentence lengths, quotes, words, word lengths, and stems, updating instance dictionaries. It returns a dictionary of word counts and represented word lengths from the input string.
def add_string(self, s): '''takes a string 's' as input and sorts the "cleaned" version of it into its respective dictionaries--returns a dictionary of the words used and the word- lengths represented in 's''' lengths = sentences(s) for i in range(len(lengths)): if lengths[i] not in ...
def onKeyUp(): ''' On key listener method for the up arrow and w key. Updates the accel state as well as dx and dy. Publishes data to the Vehicle ''' global accel_state, r_x, r_y, ring_1_radius, ring_2_radius, ring_3_radius, curr_ring, theta # the current radius differential rd = 0 ...
The code defines a function `wasd(event)` that listens for keyboard events and triggers specific actions based on the pressed key: 'w' calls `onKeyUp()`, 'a' calls `onKeyLeft()`, 's' calls `onKeyDown()`, 'd' calls `onKeyRight()`, and 'r' calls `reset()`. Its main task is to handle WASD key inputs for controlling moveme...
def wasd(event): ''' On key listeners for wasd keys ''' if (event.char == 'w'): onKeyUp() if (event.char == 'a'): onKeyLeft() if (event.char == 's'): onKeyDown() if (event.char == 'd'): onKeyRight() # reset to original state if (event.char == '...
def background_castor() : # adapted heavily from # https://github.com/CASTOR-telescope/ETC/blob/master/castor_etc/background.py # with additional discussion about renormalizing the zodiacal file from # https://github.com/CASTOR-telescope/ETC/tree/master/castor_etc/data/sky_background ...
The main task of the code is to calculate and add noise components—background, dark current, and read noise—to a dictionary of astronomical filters for multiple telescopes (CASTOR, HST, JWST, Roman, Euclid). It applies scaling factors to normalize noise values across different filter scales and updates the dictionary e...
def determine_noise_components() : dictionary = filters.calculate_psfs() # CASTOR castor_filts = [key for key in dictionary.keys() if 'castor' in key] castor_scales = 0.1*np.ones(5)*u.arcsec/u.pix castor_bkg = background_castor()*u.mag/np.square(u.arcsec) castor_dark = np.array([0.0004...
def get_noise(pretty_print=False) : infile = 'noise/noise_components.txt' if exists(infile) : with open(infile, 'rb') as file : dictionary = pickle.load(file) else : with open(infile, 'wb') as file : dictionary = determine_noise_components() pick...
This function adds realistic noise and point spread function (PSF) convolution to simulated astronomical images from SKIRT output. It calculates telescope-specific parameters, applies background noise, dark current, and read noise, convolves images with Gaussian kernels, and saves noisy images and signal-to-noise ratio...
def add_noise_and_psf(subID, telescope, population='quenched', psf=0.15*u.arcsec, display=False, save=True) : # telescope diameters from # https://www.castormission.org/mission # https://www.jwst.nasa.gov/content/forScientists/ # faqScientists.html#collectingarea # https:/...
def setup_round(self): """Sets up the round. This includes assigning roles and gathering player names.""" # Choose Animal herd_animal = self.random_animal() self.herd_animals.append(herd_animal) self.debug_message(f"The secret animal is {herd_animal}.") # Assign Roles ...
The main task of the code is to manage a game loop that transitions through states like setup, round execution, and resolution. It checks game conditions, displays rules, handles player rounds, calculates scores, and declares a winner when a player reaches the winning score. If no winner is determined, it resets the ga...
def run_game(self): """Starts the game.""" # Check if the game has not been won if self.game_state != "game_end": if self.game_state == "game_start": self.game_message(fetch_prompt("game_rules"), message_type="system") self.game_state = "setup_round" ...
def InitializeMatingPool(self): self.MatingPool.ResetList() while len(self.MatingPool.List) < self.MatingPoolSize: Individual1 = self.Population.GetRandomIndividualWithReplacement() Individual2 = self.Population.GetRandomIndividualWithReplacement() if Individual1.Fitn...
The code executes a genetic algorithm (GA) by iterating through generations to evolve a population toward an optimal solution. It initializes a mating pool, updates the population, checks for convergence, and tracks fitness statistics. The loop terminates when convergence is detected or the maximum generations are reac...
def Run(self): ## print('InitialPopulation.List:\n'+ self.Population.ToString(' ', ' ')) # calculate a statistic self.InitialBestFitness = self.Population.BestFitness() # the actual body of the GA while not self.Finished: self.InitializeMatingPool() ## p...
def log_append(self, text): self.log_update.emit(text) def get_end_cursor_from_page_info(self, page_info): if page_info['has_next_page']: return page_info['end_cursor'] return False def get_parsed_urls_and_names_from_node(self, node): fn_pre = str(node['taken_at_timestamp']) ...
This code crawls Instagram posts via GraphQL queries using a browser driver, handling pagination with 'end_cursor'. It extracts media URLs from JSON responses, logs progress, checks for duplicates, and downloads content to a specified path while respecting a running flag and random delays to avoid rate-limiting.
def download_from_query(self, ins_id, end_cursor, parsed_path, link): while end_cursor: if not self.param['running']: return time.sleep(2 + random.randint(1, 800) / 300) next_query = param["query_format"].format(ins_id=ins_id, end_cursor=end_cursor) self.log_appen...
def load_param(self): r = self.text_scrap_links.toPlainText() if r[len(r) - 1] != '\n': r += '\n' param["ins_model"] = self.string2array(r) param['ignore_downloaded_and_loop'] = self.check_dup_continue.isChecked() #if len(self.line_scrap_ind_link.text()) > 0 and len(self.line_scr...
The main task of the code is to control the running state of a process by checking the 'running' parameter. If 'running' is True, it calls `stalp_running` to stop or pause the process; otherwise, it initiates the process via `start_running`. The function relies on `load_param` to retrieve parameters before making this ...
def click_scrawl(self): self.load_param() if self.param['running']: self.stalp_running() else: self.start_running()
def get_ness_info(self, link): self.log_append('crawling ' + link) driver.get(link) b = self.pq_fy(driver.page_source, 'script[type="text/javascript"]', 'window._sharedData = ') ins_id = b['entry_data']['ProfilePage'][0]['graphql']['user']['id'] parsed_path = param["path"] + self...
This function downloads the first page of Instagram profile media using a provided link. It extracts media URLs, checks for duplicates, and initiates downloads. If an end_cursor is provided, it resumes from that point. Otherwise, it processes the initial page's media edges, collects URLs, retrieves the next cursor, and...
def download_first_page(self, link, end_cursor = False): ins_id, parsed_path, b = self.get_ness_info(link) dl_link = {} if end_cursor: self.download_from_query(ins_id, end_cursor, parsed_path, link) return for i in b['entry_data']['ProfilePage'][0]['graphql'][...
def log_append(self, text): self.log_update.emit(text) def login(self, brawser): usr_name = self.param['usr_name'] pswd = self.param['pswd'] brawser.get('https://www.instagram.com/accounts/login/') time.sleep(1) try: self.log_append("loggging in with usr name ...
The code's main task is to attempt user login using a driver, log success or failure, and proceed with crawling if login is successful. It first checks login status, triggers login if needed, logs a success message upon successful authentication, then initiates data crawling. Early exit occurs if login fails.
def run(self): self.log_append('gogogadget') if not self.param['logged_in']: self.param['logged_in'] = self.login(self.driver) if not self.param['logged_in']: return self.log_append('phew, login successful') self.crawling()
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "path", type=str, help="Path of the file or directory to augment" ) parser.add_argument( "--debug", action="store_true", help=f"Take only {DEBUG_PERCENTAGE}%% of images in each directory", ) ...
The main task of the code is to process either a single file or a directory based on user arguments. It checks if the specified path exists, validates mode compatibility (e.g., excluding debug/balanced modes for single files), and applies augmentation functions (`augment_file` or `augment_directory`) accordingly. The s...
def main(): args = parse_args() if not os.path.exists(args.path): print(f"File not found: {args.path}") sys.exit(1) elif os.path.isfile(args.path): assert not args.debug, "--debug mode is incompatible with single file" assert ( not args.balanced ), "--bala...
def parse_args(): parser = argparse.ArgumentParser(description="Imaging processing") parser.add_argument( "--image", type=str, help="Path to a single image to process" ) parser.add_argument("--src", help="Source directory") parser.add_argument("--dst", help="Destination directory") parse...
The main task of the code is to determine whether the input is a single file or a directory. If it's a file, it processes the image using `handle_file`; if it's a directory, it processes all files in the source directory, applying transformations and saving results to the destination directory via `handle_directory`. T...
def main(): is_file, args = parse_args() if is_file: handle_file(args.image) else: handle_directory(args.src, args.dst, args.transformation)
def get_files(path, filesarr): global preprocess_flag for x in os.listdir(path): if os.path.isfile(os.path.join(path, x)): if(preprocess_flag): preprocess_files(os.path.join(path, x)) filesarr.append(os.path.join(path, x)) return filesarr def train_NB(posfiles...
The main task of the code is to configure preprocessing, training, and testing flags based on user input, then retrieve training files and execute a Naive Bayes model's training and testing processes. It prompts the user to decide on preprocessing, model retraining, and custom testing, updating global flags accordingly...
def main(): global posfiles global negfiles global preprocess_flag global train_flag global test_flag print("Would you like to preprocess your files? (y/n)") inp = input() if(inp == "y"): preprocess_flag = True elif(inp == "n"): preprocess_flag = False else: ...
def _create_web_socket(self, action_result): # Validating if timeout parameter is positive integer if not (str(self._timeout).isdigit() and int(self._timeout) > 0): self.debug_print(SYMANTECCAS_JSON_INVALID_TIMEOUT) self.save_progress(SYMANTECCAS_JSON_INVALID_TIMEOUT) ...
The main task of the code is to detonate a file for analysis by initiating a WebSocket connection, querying the file via REST, waiting for the WebSocket response, and updating the action result with the analysis score and status. It handles connectivity errors, validates responses, and ensures proper status tracking an...
def _detonate_file(self, param): action_result = self.add_action_result(ActionResult(dict(param))) summary_data = action_result.update_summary({}) # Initiating websocket connection ret_val = self._create_web_socket(action_result) # If websocket connection is unsuccessful ...
def reload_node(self, node, version): if not node: return cmd = 'sshpass -p ' + self.options['admin_passwd'] + ' ssh admin@' + node + ' cli -h \\"enable\\" \\"configure terminal\\" \\"reload\\" 2>/dev/null' execute(cmd) time.sleep(120) # rebooting is not so fast wai...
The code performs an in-service upgrade by parallelizing node upgrades using multiprocessing, reloading configurations on master/slave nodes, and initiating failover or UFM startup on the master node via SSH. It coordinates upgrades across multiple nodes, ensures service continuity, and handles post-upgrade tasks like ...
def inservice_upgrade(self, version): arguments = [] n = 0 for node in UFM_APL_NODES: if self.options[node]: arguments.append( (self.options[node], version) ) n += 1 with Pool(processes=n) as pool: result = pool.map(self.inservice_u...
def check_sm(self, node): cmd = 'sshpass -p ' + self.options['admin_passwd'] + ' ssh admin@' + node + ' cli -h \\"enable\\" \\"configure terminal\\" \\"ufm start\\" 2>/dev/null' out = execute(cmd) if 'UFM has started' in out: logging.debug("UFM has started") elif 'Please stop...
The code configures high availability (HA) by checking the master node's status, setting up standalone and master HA nodes, waiting for HA confirmation, and configuring the slave node to ensure redundancy and reliability in the system.
def configure_ha(self): self.check_sm(self.options['master']) self.configure_sm_only_node(self.options['sm_only']) self.configure_ha_master_node(self.options['master']) self.wait_for_ha_ok(self.options['master']) self.configure_ha_slave_node(self.options['slave'])
def get_ufmapl_manufacture_iso(version): ufm_path = UFMAPL_PATH + version + '_*/*' + version + '*.iso' files = glob.glob(ufm_path) if len(files) == 0: print("Could not find iso file for UFM Appliance version " + version) # logging.error("Could not find iso file for UFM Appliance version " + v...
The code remanufactures a node (apl_node) to a specified version by mounting an ISO image, applying network configuration patches, generating PXE boot files, transferring updated images to a server, and rebooting the node. It handles file operations, system commands, and cleanup, ensuring the node boots with the new fi...
def remanufacture_node(self, apl_node): version = self.remanufacture_version if not apl_node or not version: logging.warning("Remanufacturing: node name was not provived - skipping") print("Remanufacturing: node name was not provived - skipping") return print(...
def execute_remotely(cmd): cmd = remote_ssh + ' ' + cmd out = execute(cmd) return out def get_cyberai_proc_pid(): print("Getting cyberai_proc pid") try: cmd = 'ssh root@' + UFM_CYBERAI_MACHINE apl = pexpect.spawn(cmd) apl.expect('password: ') apl.sendline(UFM_CYBERAI_...
The main task of the code is to test the health monitoring system's ability to automatically restart critical Docker containers and processes (e.g., cyberai-web, ufm-telemetry, and cyberai_proc.pyc) after they are forcibly stopped. It stops specified containers and processes, waits 2 minutes, then verifies if they are ...
def check_health_monitoring(): # idea for health monitoring: # kill a process and check that this process is UP again in N seconds # health monitoring process scan dockers and processesses each 2 minutes (configurable) # Health Monitoring checks: # cyberai-web docker # ufm-telemetry docker: ...
def remanufacture(self): logging.info("Remanufacure started on: " + self.options['master'] + ", " + self.options['slave'] + ", " + self.options['sm_only']) n = 0 nodes = [] for node in UFM_APL_NODES: if self.options[node]: nodes.append(self.options[node]) ...
This code upgrades a system component to a specified version. If remanufacture is pending, it triggers remanufacture; otherwise, it performs an in-service upgrade. If configured as a slave node and the version matches HA requirements, it enables high availability. Finally, it verifies UFM status, logs, and REST API fun...
def upgrade(self, version): if not self.remanufacture_done: self.remanufacture_version = version self.remanufacture() self.remanufacture_done = True else: self.inservice_upgrade(version) if self.options['slave'] and version == self.options['ha_aft...
def remove_license_file(path, lic_file): print("Removing license file") logging.debug("Removing license file") cmd = 'rm -f ' + path + '/' + lic_file out = execute_remotely(node, cmd) def clean_log_files(node): print("Cleaning log files") logging.debug("Cleaning log files") for file in log_f...
The function upgrades CyberAI on a specified node by copying and installing a software package, handling license files, and verifying post-upgrade status. It checks if the package exists on the node, copies/untars it if missing, executes the upgrade with options, and ensures the license is correctly installed, logging ...
def upgrade_CyberAI(node, version, option): # 1 found package # 2 check package existence in /tmp # 3 Doesn't exist? # 3a copy package to /tmp # 3b untar package # 4 run install command with needed options logging.info("Upgrading CyberAI on " + node + " to version " + version + " with options " + option) pr...
def handleInput(screen): """ return False if we quit save image on S key """ #Handle Input Events global center, width, height,radius,center,pixelsize for event in pygame.event.get(): if event.type == QUIT: return False elif event.type == KEYDOWN: if e...
The code renders the Mandelbrot set at decreasing pixel resolutions using Pygame, updating the display progressively. It initializes a window, creates a background, and iteratively draws the fractal by calculating color values for each pixel based on Mandelbrot iterations. The loop reduces pixel size each cycle, allowi...
def main(): """this function is called when the program starts. it initializes everything it needs, then runs in a loop until the user quits.""" global pixelsize, screen, background,width,height,center,radius,colors #Initialize Everything pygame.init() width,height = 640,480 screen = p...
def init_board(width: int = BOARD_WIDTH, height: int = BOARD_HEIGHT) -> Board: """ Initializes a new board with empty cells :param width: Board width :param height: Board height :return: Game board with given dimensions """ return [' '] * (width * height) def is_board_full(board: Board) -> ...
The code defines a tic-tac-toe game that initializes a board, alternates turns between players, checks for winning conditions after each move, and declares a winner or draw. It uses global player data, displays the board state, and handles user input to place marks until a win or full board ends the game.
def tictactoe() -> None: """ Starts a tic-tac-toe game """ global PLAYERS current_player = PLAYERS[0] player_won = False board = init_board() while not player_won and not is_board_full(board): display(board) cell = get_player_choice(board, current_player) place_...
def find_flush(hand): suit_dict = {} for card in hand.cards: if card.suit not in suit_dict.keys(): suit_dict[card.suit] = 1 else: suit_dict[card.suit] += 1 for suit in suit_dict: if (suit_dict[suit]) >= 5: return suit return None pass def ...
This function evaluates a poker hand to determine its rank, returning the sorted cards and the hand's name (e.g., 'straight flush', 'four of a kind'). It checks for poker hand types in descending order of strength, using helper functions to identify flushes, straights, value counts, and combinations, then returns the h...
def evaluate_hand(hand): # straight flush fs = find_flush(hand) straight = find_straight(hand, fs) if fs and straight: return straight, 'straight flush' # four of a kind val_counts = count_values(hand) v, n = get_max_count(hand, val_counts) assert n <= 4 ind = get_kind_index(...
def adapt_grid(self): self.minimum = [POSITIVE_INFINITY] * self.nobjs self.maximum = [-POSITIVE_INFINITY] * self.nobjs self.density = [0.0] * (self.divisions ** self.nobjs) for solution in self: for i in range(self.nobjs): self.minimum[i] = min(self.minimum[i...
This code adds a candidate solution to a non-dominated archive while maintaining capacity constraints. It checks if the candidate dominates or is dominated by existing solutions, removes dominated solutions, and manages archive size by either adding the candidate directly if space is available or replacing the densest ...
def add(self, solution): # check if the candidate solution dominates or is dominated flags = [self._dominance.compare(solution, s) for s in self._contents] dominates = [x > 0 for x in flags] nondominated = [x == 0 for x in flags] #dominated by one residence dont let it enter ...
def _check_events(self): '''Check for keyboard and mouse events, and responds to them.''' for event in pygame.event.get(): # Loops through each event. if event.type == pygame.QUIT: # Checks if the player clicks on the close button on the window. pygame.quit() # Uninit...
The main task of the code is to execute the game loop, handling player input, updating game elements (ship, bullets, aliens, asteroids) when the game is active, and rendering the screen continuously until the game ends. It checks for events, updates game objects' positions, and maintains the game state in real-time.
def run_game(self): '''Starts game loop.''' while True: self._check_events() # Check for any keyboard or mouse interactions. # Checks if the game is active and the game_over flag is set to False. if self.stats.game_active and not self.stats.game_over: ...
def initialize_with_zeros(dim): w = np.zeros([dim, 1], dtype="float64") b = 0.0 return w, b def gradient_decent(w, b, X, Y, num_iterations=100, learning_rate=0.009): costs = [] for i in range(num_iterations): grads, cost = propagate(w, b, X, Y) dw = grads["dw"] db = grads["...
The code trains a logistic regression model using gradient descent on training data, evaluates it on test data, calculates training and test accuracy, and returns parameters, costs, and predictions. It initializes weights/bias, iteratively updates them to minimize loss, predicts class labels, and computes accuracy via ...
def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5): w, b = initialize_with_zeros(X_train.shape[0]) params, grads, costs = gradient_decent( w, b, X_train, Y_train, num_iterations, learning_rate) w = params["w"] b = params["b"] Y_prediction_test = predict(w, b...
def translate_MWB_to_REDU_by_logic(MWB_table, path_to_csvs='translation_sheets'): if 'MWB_age' in MWB_table.columns: MWB_table['AgeInYears'] = MWB_table['MWB_age'].apply(convert_to_years) if 'MWB_sex' in MWB_table.columns: MWB_table['BiologicalSex'] = MWB_table['MWB_sex'].map(convert_sex) d...
The main task of the code is to convert Metabolomics Workbench (MWB) data into the REDU format by either retrieving MWB data via API or input JSON, processing it through translation and cleaning steps, handling missing values, and returning a structured DataFrame with specific metadata fields for REDU compatibility.
def MWB_to_REDU_wrapper(mwTab_json=None, MWB_analysis_ID=None, raw_file_name_df=None, Massive_ID='', path_to_csvs='translation_sheets'): if mwTab_json is None and MWB_analysis_ID is None: raise SystemExit("mwTab_json or MWB_analysis_ID has to be provided!") if mwTab_json is not ...
def calc_matrix_P(self, X: np.ndarray): """Calculate matrix P for input matrix X Args: X (np.ndarray): input data points; shape: (N, d) Returns: _type_: _description_ """ entropy=np.log(self.neighbors) n1,n2=X.shape D=np.square(metrics.pa...
This code performs dimensionality reduction by iteratively optimizing a low-rank matrix approximation. It initializes random latent variables Y, computes gradient updates using P (input data) and Q (approximation), and adjusts Y via gradient descent with adaptive learning rate scaling. The algorithm dynamically modifie...
def fit_transform(self, X: np.ndarray): n_samples, n_features = X.shape P = self.calc_matrix_P(X) Y = np.random.randn(n_samples, self.n_components) * 1e-4 Q = self.calc_matrix_Q(Y) dy = self.calc_grad(P, Q, Y) for i in range(self.max_iter): if i == 0: ...
def _safety_heuristic(self, traj): if len(traj) == 0: return 0.0; radar_data = self._radar_data; dynamic_radar_data = self._dynamic_radar_data; safety = 1.0; degree_step = self._radar.get_degree_step(); data_size = self._radar.get_data_size(); radar_range = self._radar.radius; time_offset = 1; safe...
The code plans the robot's next action by scanning obstacles, predicting their motion, and replanning a safe trajectory if necessary. It selects the optimal path from generated candidates, updates the current trajectory, and computes directional speed and heading for the robot's movement, halting if the next target mat...
def select_next_action(self): self._stepNum += 1; # Scan the radar self._dynamic_radar_data = self._radar.scan_dynamic_obstacles(self._gps.location()); self._radar_data = self._radar.scan(self._gps.location()); # Give the current observation to the obstacle motion predictor self.debug_info["future_obstacl...
def _score_clearance(self, traj): if len(traj) == 0: return 0.0; radar_data = self._radar_data; degree_step = self._radar.get_degree_step(); data_size = self._radar.get_data_size(); radar_range = self._radar.radius; safety_buffer = 3; time_offset = 1; cumulative_path_dist = 0 min_radar_distance = ...
The main task of the code is to determine the robot's next action by scanning obstacles, predicting their motion, replanning a trajectory if the current one is unsafe or completed, and steering the robot along the optimal path. It uses radar data, trajectory comparison, and obstacle prediction to ensure safe navigation...
def select_next_action(self): self._stepNum += 1; # Scan the radar self._dynamic_radar_data = self._radar.scan_dynamic_obstacles(self._gps.location()); self._radar_data = self._radar.scan(self._gps.location()); # Give the current observation to the obstacle motion predictor self.debug_info["future_obstacl...
def showOccupation(cells): """ create a dictionary that lists all cell indices per kind of cell occupancy :param cells: dictionary, updated occupation of all cells of the game board :return: dictionary, for each kind of cell occupancy list corresponding cell indices """ cellOccupation = {players...
The function `computersTurn` handles the computer's move in a game by selecting a strategic cell (likely to block or win), updating the game board's state (`fields` dictionary) with the computer's token, and adjusting the list of free cells. It checks for available moves, uses helper functions to determine optimal plac...
def computersTurn(fields, freeCells): """ set computer's input, update dictionary with cell occupation info, draw game board based on the updated occupation dictionary :param fields: dictionary, info about cell occupation :param freeCells: list, cell indices which are not yet occupied by any tok...
def printGray(delim=True): """ convert to gray color :param delim: boolean, if True: vertical delimiter for gameBoard cells """ if delim == True: delimiter = "|" fields = f"\033[0;37m{delimiter}\033[0;0m" return fields else: fields = {} for i in range(9): ...
The code initializes a game board, alternates between player and computer turns to fill cells, and displays the board state after each move until all cells are filled. It uses functions to manage board updates, check available moves, and show results, ensuring gameplay continues while free cells exist.
def main(): # draw initial game board with empty fields, print with corresponding indices in the cells fields = printGray(False) gameBoard(fields) # run game as long as there is still free cells freeCells = limitToFreeFields(fields) # while any(freeCells) in list(range(5)): while len(freeC...
def _handle_explicit_allocation(neutron_network_id, endpoint_id, interface_cidrv4, interface_cidrv6, new_subnets, existing_subnets): if interface_cidrv4: _process_subnet(neutron_network_id, endpoint_id, interface_cidrv4, ...
The main task of the code is to create subnets and a Neutron port based on provided interface details, handling IPv4/IPv6 allocations explicitly or via default pools, and returning the interface response with MAC and IP addresses, while rolling back subnet creation on errors.
def _create_subnets_and_or_port(interface, neutron_network_id, endpoint_id): response_interface = {} existing_subnets = [] created_subnets_response = {'subnets': []} # v4 and v6 Subnets for bulk creation. new_subnets = [] interface_cidrv4 = interface.get('Address', '') interface_cidrv6 = in...
def allowed_file(filename: str) -> bool: return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def get_db(): client = pymongo.MongoClient(application.config['MONGO_URL'], serverSelectionTimeoutMS=10000, connect=False) return client[application.config['MONGO_DB']] def get_exchan...
The code calculates image similarity for a given image using ResNet and VGG16 models, retrieves similar products from a database, converts prices to PHP, aggregates results into a table, and returns them as JSON. It validates input, checks file existence, handles errors, and logs progress.
def api_similarity_calculate(image_name: str) -> Response: with application.app_context(): if not isinstance(image_name, str) or not allowed_file(image_name): return Response(status=400, response="Incorrect image file") if not os.path.isfile(os.path.join(application.config['ORIG_IMAGES'...
def __check_fleet__edges(self): for alien in self.aliens.sprites(): if alien.check_edges(): self.__change__fleet__direction() break def __ship__hit(self): if self.stats.ships_left > 0: self.stats.ships_left -= 1 self.sb.prep_ships() ...
This method updates alien movement, checks for collisions between aliens and the player's ship, and verifies if aliens have reached the screen's bottom. It triggers collision responses and edge/position checks to manage game state and interactions.
def __update__aliens(self): self.__check_fleet__edges() self.aliens.update() if pygame.sprite.spritecollideany(self.ship,self.aliens): self.__ship__hit() self.__check__aliens__bottom()
def __play_music(self): pygame.mixer.music.load("music/1.ogg") pygame.mixer.music.set_volume(1) pygame.mixer.music.play(-1) def __check__events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.sb.write_highest_score() ...
The code runs the game loop by playing music, checking events, updating game elements (ship, bullets, aliens) if the game is active, and rendering the screen continuously.
def run_game(self): self.__play_music() while True: self.__check__events() if self.stats.game_active: self.ship.update() self.__update__bullets() self.__update__aliens() self.__update__screen()
def search_selection(): print("Enter the number associated with an algorithm to select it:\n" + "1. Uniform Cost Search\n" + "2. A* with Misplaced Tile heuristic\n" + "3. A* with Manhattan Distance heuristic") selection = input("Enter number: ") return selecti...
This code implements a general search algorithm for solving a puzzle using A* search with selectable heuristics (no heuristic, misplaced tiles, or Manhattan distance). It tracks nodes expanded, maximum queue size, and terminates if depth exceeds 500. The algorithm explores valid moves, avoids revisiting states, and out...
def general_search(puzzle): already_visited = [] selection = search_selection() if selection == '1': h = 0 elif selection == '2': h = misplaced_tiles(puzzle) elif selection == '3': h = manhattan_distance(puzzle) heuristic = h depth = 0 starting_node = Node(puzzl...
def q_ttt(vector, starting_player = '0', number_of_iteration: int = 1, to_gate: bool = False) -> QuantumCircuit: if not utils.is_valid(vector): raise Exception("Number of O and X are not correct") vec = InputVector(vector, starting_player) qr_input = QuantumRegister(vec.size, name = 'input') qr_...
The code executes a quantum Tic-Tac-Toe game using the input vector, visualizes the quantum circuit, and returns the measurement outcomes (counts) from the simulation. It leverages quantum computing components to process the game state and retrieve statistical results of possible board configurations.
def tic_tac_toe(vector) -> str: try: qc = q_ttt(vector, '1') display(qc) return run_it(qc, False).result().get_counts() except: raise
def print_preamble(): print('///////////////////////////////////////////') print('/// Vimba API Asynchronous Grab Example ///') print('///////////////////////////////////////////\n') def parse_args() -> Tuple[Optional[str], AllocationMode]: args = sys.argv[1:] argc = len(args) allocation_mode =...
The main task of the code is to acquire and process video frames from a specified camera using Vimba's streaming API. It initializes the camera, configures settings, and starts frame acquisition with a custom buffer size (10 frames) and allocation mode. The `frame_handler` processes each frame, and the stream stops whe...
def main(): print_preamble() cam_id, allocation_mode = parse_args() with Vimba.get_instance(): with get_camera(cam_id) as cam: setup_camera(cam) print('Press <enter> to stop Frame acquisition.') try: # Start Streaming with a custom a buffer of 1...
def print_preamble(): print('///////////////////////////////////////') print('/// Vimba API List Features Example ///') print('///////////////////////////////////////\n') def parse_args() -> Optional[str]: args = sys.argv[1:] argc = len(args) for arg in args: if arg in ('/h', '-h'): ...
The main task of the code is to retrieve and print all features of a specified camera using Vimba. It parses command-line arguments to identify the camera, initializes the Vimba instance, accesses the camera by ID, and iterates through its features to display them. This serves as a diagnostic tool for inspecting camera...
def main(): print_preamble() cam_id = parse_args() with Vimba.get_instance(): with get_camera(cam_id) as cam: print('Print all features of camera \'{}\':'.format(cam.get_id())) for feature in cam.get_all_features(): print_feature(feature)
def aggregateMatchScores_pt_fromDesc(dbDesc,qDesc,l,device,refCandidates=None): numDb, numQ = dbDesc.shape[0], qDesc.shape[0] convWeight = torch.eye(l,device=device).unsqueeze(0).unsqueeze(0) if refCandidates is None: shape = [numDb,numQ] else: shape = refCandidates.transpose().shape ...
The function aggregates match scores from either precomputed distance matrices or descriptors. It processes input data using different helper functions based on whether `dMat` is provided and the `dMatProcOneShot` flag, returning a sequence of distance matrices (`dMat_seq`) for matching tasks like image retrieval or fe...
def aggregateMatchScores(dMat,l,device='cuda',refCandidates=None,dbDesc=None,qDesc=None,dMatProcOneShot=False): dMat_seq, matchInds, matchDists = None, None, None if dMat is None: dMat_seq = aggregateMatchScores_pt_fromDesc(dbDesc,qDesc,l,device,refCandidates).detach().cpu().numpy() else: if...
def _post_physics_step_callback(self): """ Callback called before computing terminations, rewards, and observations Default behaviour: Compute ang vel command based on target and heading, compute measured terrain heights and randomly push robots """ resample_buf = (self.episode_lengt...
The code updates the simulation state by refreshing tensors, increments counters, computes physics-related quantities (e.g., base orientation, velocities), calls callbacks for termination checks, reward calculations, and resets. It also handles observation updates, logs training progress, and optionally renders debug v...
def post_physics_step(self): """ check terminations, compute observations and rewards calls self._post_physics_step_callback() for common computations calls self._draw_debug_vis() if needed """ self.gym.refresh_actor_root_state_tensor(self.sim) self.gym.refresh_n...
def date_range(): start_dt = date(2021, 1, 1) # jan 1st end_dt = date(2021, 4, 30) # april 30th for n in range(int((end_dt - start_dt).days)+1): yield start_dt + timedelta(n) def shower_and_bath(): date_range() create_dates() for i in dates: if i.weekday() <= 4: # weekdays...
The main task of the code is to calculate daily water usage by aggregating data from showers, baths, dishes, and laundry. It sums total gallons and hot water gallons per day, structures the data into date-aligned lists/tuples, and prepares the results for database input via an API. The function returns aggregated daily...
def calculate_water_usage(): date_range() shower_and_bath() dishes_and_laundry() #Carter, the syntax used to add all the gallons for each day will be useful when you add the water energy used to the rest of the energy used per day total_gallons = [a + b + c + d for a, b, c, d in zip(shower_gal, ba...
def daterange(): start_dt = date(2021, 1, 1) # jan 1st end_dt = date(2021, 4, 30) # april 30th for n in range(int((end_dt - start_dt).days)+1): yield start_dt + timedelta(n) def shower_and_bath(): daterange() create_dates() gal_per_shower = 25 hot_per_shower = 16.25 gal_pe...
The main task of the code is to calculate daily total water usage (including hot water) by summing data from showers, baths, dishes, and laundry. It combines categorized water usage values with dates, generates daily records, and returns a list of tuples containing date, total gallons, and hot water gallons. Debugging ...
def calculate_water_usage(): daterange() shower_and_bath() dishes_and_laundry() total_gallons = [a + b + c + d for a, b, c, d in zip(shower_gal, bath_gal, dishes_gal, laundry_gal)] total_gallons_daily = [list(e) for e in zip(string_dates, total_gallons)] total_hot = [w + x + y + z for w, x, y,...
def get_2dtraj_through_ns(r02d: mp.matrix, v02d: mp.matrix, k: float, radius: float, t0: float = 0.) -> tuple: infall = get_2dtrajectory(r02d, v02d, k) thetain, r2din, rdotin, thetadotin, tin = enter_ns(r02d, v02d, k, radius) rin = mp.matrix([r2din*mp.cos(thetain), r2din*mp.sin(thetain)]) vin = mp....
This function plots a 2D trajectory through a region (NS) by calculating and visualizing three phases: pre-entry, inside the NS, and post-exit. It uses initial position/velocity, gravitational parameter k, and radius to generate trajectories via linspace and specialized plotting functions. The output includes plots for...
def plot_2dtraj_through_ns(r02d: mp.matrix, v02d: mp.matrix, k: float, radius: float, n_points: int = 10_000) -> None: thetas, *_ = get_2dtraj_through_ns(r02d, v02d, k, radius) thetas_infall = mp.linspace(thetas[0], thetas[1], n_points)[1:] plotin = plot_2dtraj(r02d, v02d, k, n_points, (thetas_infall[0], th...
def get_thetas(r02d: mp.matrix, v02d: mp.matrix, k: float) -> float: Jbar, _, semilatus, eccentricity = get_orbit_params(r02d, v02d, k) theta0 = mp.atan(r02d[1] / r02d[0]) + (1-mp.sign(r02d[0]))/2*mp.pi if r02d[0] else mp.sign(r02d[1])*mp.pi/2 in_or_out = mp.sign(np.dot(r02d, v02d)) is_theta0_gtr = np....
This function computes the 2D trajectory parameters including angular bounds (thetas), radial distance (r), radial velocity (rdot), angular velocity (thetadot), and time (t). It calculates initial angle (theta0), determines minimum/maximum angles (thetamin/thetamax), computes trajectory variables using get_rv2d, calcul...
def get_2dtrajectory(r02d: mp.matrix, v02d: mp.matrix, k: float, t0: float = 0.) -> tuple: theta0 = mp.atan(r02d[1] / r02d[0]) + (1-mp.sign(r02d[0]))/2*mp.pi if r02d[0] else mp.sign(r02d[1])*mp.pi/2 thetamin, thetamax = get_thetas(r02d, v02d, k) r, rdot, thetadot = get_rv2d(r02d, v02d, k) t = get_time(r...
def set_subsample_rate(rate): rate = 0 if rate is None else int(rate) if rate >= 1: global _subsample_rate _subsample_rate = rate; else: logger.debug(f"Invalid subsample_rate {rate} ignored.") logger.debug(f"subsample_rate: {_subsample_rate}") def set_verbosity(flag :bool=False)...
This function consolidates data from all episodes into unified stage data files by concatenating episode-specific files, then optionally cleans up intermediate files. It returns unstamped stage data files, logging settings like subsample rate. If cleanup is enabled, temporary files are removed.
def create_all_stage_data_files(subsample_rate :int=100, cleanup: bool=True, verbosity :bool=False) -> Dict[str,str]: ''' This is the main entry point for create_date_files.py concat the contents all episode stage files into a single set of stage_data_files reports information about the settings u...
def _get_pk_data(self, cosmo): """ Get all cosmology-dependent ingredients to create the different P(k)s needed for the C_ell calculation. For linear bias, this is just the matter power spectrum. """ # Get P(k)s from CCL if self.bz_model == 'Linear': cosmo.com...
The function computes angular power spectra (C_ells) for a cosmological model. It uses a provided CCL cosmology object or creates a default one from input parameters. It retrieves matter power spectra, converts them to C_ells, applies multiplicative bias corrections, and returns the result.
def get_cls_theory(self,CCL_cosmo): if CCL_cosmo is None: cosmo = ccl.Cosmology( Omega_c= self.pars['Omega_c'], Omega_b=self.pars['Omega_b'], h=self.pars['h'], n_s=self.pars['n_s'], sigma8= self.pars['sigma8'...
def _DownloadCertificatesStore(pem_url: str, destination_file: Path): with urlopen(pem_url) as response: pem_file = response.read() logging.info('Got response with status [%d]: %s', response.status, pem_url) if destination_file.parent.exists(): logging.debug('Creating directory and it\'s parents %s', ...
The main task of the code is to convert PEM certificate files (from a URL or local path) into a C/C++ header file. It downloads or reads certificate data, processes it, and generates a header containing certificate digests and content, with options to include full certificate details and control logging verbosity.
def main(): parser = argparse.ArgumentParser( description='This is a tool to transform a crt file ' f'into a C/C++ header: {_GENERATED_FILE}.') parser.add_argument('source_path_or_url', help='File path or URL to PEM storage file. ' 'The supported cert files a...
def __generate_filters(self, search: str = None, genres: str = None, platforms: str = None, ur1: str = None, ur2: str = None, **kwargs) -> dict: filters = {} if search: filters['search'] = search if genres: genres = ','.join(map(str, self.api_fi...
This function retrieves a list of game data from an API, applying filters like search terms, genres, or specific game IDs. It constructs a request URL with pagination, limits, and sorting parameters, then fetches game details including names, covers, ratings, and genres. It enriches the data by replacing cover URLs wit...
def api_get_games_list(self, page: str = '1', game_ids: list = None, genres: bool = False, **kwargs) -> list: """kwargs: search: str = None, genres: str = None, platforms: str = None, user_ratings: tuple = None""" category = 'games/?' additional = { 'f...
def clear(self): """ Reinitialize the network (used during cross validation).""" device = next(self.parameters()).device self.__init__(**self.setting) self.to(device) def fit(self, X_train, y_train, X_test=None, y_test=None, batch_size=20, ...
The main task of the code is to perform k-fold cross-validation on a model by iteratively splitting the data into training and validation sets, training the model on each training split, evaluating it on the corresponding validation split, and collecting the train and test scores for each fold. The results are returned...
def cross_validate(self, X, y, n_splits=4, epochs=100, verbose=False): """ Run cross validation on the model and return the obtained test and train scores. """ kf = KFold(n_splits=n_splits, random_state=1, shuffle=True) tr_scores = [] va_scores = [] result = { ...
def checkEvasion(turn): return True def isUnderCheck(turn): if turn == 0: kpos = kingW.currPos for piece in blackPieces: if (isValidMove((piece.currPos[1], piece.currPos[0]), (kpos[1], kpos[0]), False)): return True elif turn == 1: kpos = kingB.currPos ...
This function determines if the current player is in checkmate by checking if their king has no valid moves to escape check after all possible evasions are ruled out. It copies the board state, checks for evasion possibilities, verifies if the king is under check, and returns True if no legal moves remain, confirming c...
def isCheckMate(turn): boardcopy = BoardState if checkEvasion(turn): return False elif isUnderCheck(turn): if turn == 0: x = generatePossibleMoves((kingW.currPos[1], kingW.currPos[0]), turn) if len(x) == 0: return True else: x = ge...
def get_flights(D, A, Date): DCity = name_to_code(D) ACity = name_to_code(A) url = "https://us.trip.com/m/flights/api/oversea/secondListData/" headers = { "Content-Type": "application/json" } payload = { "Mode": 1, "SearchInfo": { "TripType": "OW", ...
The function queries flight data for specified departure, arrival, and date, processes it to identify transfer routes and times, then calculates and returns a risk score based on these factors and a transfer factor.
def query(departure, arrival, date): flight_data = get_flights(departure, arrival, date) routes, times = get_transfer(flight_data) return {"result:": calculate_risk(routes, times, transfer_factor)}
def update_accor_dropdown_table(dropdown_value): data = slicer(6) df = pd.DataFrame(data) if dropdown_value is not None: filtered_df = df[df['business_unit'] == dropdown_value] data = filtered_df.to_dict("records") return data return data.to_dict("records") def date_range_update(start_d...
The function `update` determines the source of user interaction via `triggered_id` and triggers corresponding updates: it updates a dropdown table if the business unit dropdown is changed, adjusts date range settings if a date picker is used, or refreshes data if the attendance submit button is clicked, returning respe...
def update(value,start_date, end_date,n_click): triggered_id = ctx.triggered_id if triggered_id == 'business-unit-dropdown-dashboard': return update_accor_dropdown_table(value) elif triggered_id == 'my-date-picker-range-dashboard' and start_date is not None: return date_range_update(start_date, e...
def check_position(self, asset, notFound=False): #Check Position (whether its open or not) #IN ticker, wether the asset should be found on not true means it should not #OUT Boolean attempt = 1 while attempt < general_variables.max_attempts_check_position: try: ...
The code executes a trading strategy by analyzing market trends (long/short) and technical indicators (RSI, stochastic) for a given asset. It checks for open positions, confirms trend validity, calculates entry prices, submits limit orders, enters position mode, and exits by placing opposing market orders, ensuring pro...
def run(self): #LOOP until timeout reached (2h) #INITIAL CHECK while True: #POINT A #check the position: check if we have open position with asset if self.check_position(self.asset, True): logging.info('Thre is already and open positio...
def init_vals(self): Bdiag = np.array([np.floor(self.stock_length/self.cuts['cut_length'][i]) for i in self.cuts.index]) Bdim = len(Bdiag) self.b = np.array(self.cuts['num_cuts'],ndmin=2).T # sets the RHS values as column vector self.B = np.diag(Bdiag) # sets the initial basis se...
The main task of the code is to perform optimization using a simplex-like algorithm for a cutting stock problem. It initializes values, iterates to improve the solution until optimality (within epsilon tolerance), checks for unboundedness, and finalizes results. The process updates the UI to indicate optimization statu...
def optimize(self): self.in_window.frames[InputPage].readback_lbl.configure(text='Optimizing!!!') self.in_window.destroy() self.init_vals() # initializes the tableau attributes for optimization while self.benefit - 1 > self.epsilon: #not optimal self.unbounded, self.lv, self...
def _setup_bob(root_path: pathlib.Path) -> CommandListT: """Install Bob into the cmake folder. Todo: - determine if FindBob.cmake should always be overwritten. Might not be expected by users. """ output_folder = root_path / "cmake" logging.debug("Determined cmake folder: %s", output_folder) ...
The function generates a list of commands to prepare a codebase by setting up the root directory and gathering dependencies, based on provided options and environment paths. It includes setup steps and dependencies but does not add toolchain-related commands to the result, though it attempts to gather them.
def generate_commands(options: OptionsMapT, env: EnvMapT) -> CommandListT: """Generate a set of commands to prepare the codebase. Args: options: set of options to take into account. env: a map with relevant locations in the codebase. Returns: A list of commands, each command is a l...