dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def setup(self): ''' Performs initial set up of a new hand. ''' # Update dealer, collect blinds / antes self.dealer = (self.dealer + 1) % len(self.players) # Clear player hands, community cards and pot self.table = [] self.pot = [] # Shuffle ca...
The code simulates running a specified number of games, each involving setup, gameplay, and player status tracking. It prints game summaries, detects busted players (chips ≤ 0), prompts user input to continue, and removes busted players from the player list. The loop repeats for the given count, ensuring sequential gam...
def run(self, count): ''' Run the specified number of games. ''' for i in range(count): print('\n------ GAME NO. %d ------' % (i + 1)) self.setup() self.playHand() print('\n-------QUICK SUMMARY-------') self.getPlayerSummary(...
def chatbot_qna(): flag=True print('\n') print("BOT: I am your Virtual assistant. I will try to answer your questions on Accidents Data! \n \t If you want to exit any time, just type Bye!") while(flag==True): print('\n') user_response = input("You: ") user_response=user_respo...
The main task of the code is to run a chatbot that presents users with a menu of options for question-answering, accident level analysis, potential accident level analysis, and historical data insights. It processes user input, routes requests to corresponding functions, and allows exiting via "Bye", "Exit", or "Quit"....
def chatbot_main(): mainflag=True flag = False while(mainflag==True): if flag == False: print('') print("BOT: Please Select appropriate option: \n \t \n \t 1 --> For Question and Answers \n \t 2 --> For finding the Accident level for your p...
def _create_headers(self): for el in self._model['elements']: if el['xmi:type'] == 'uml:Artifact': if not 'stereotype' in el: print(f"WARNING: artifact {el['name']} has no stereotype, ignoring") elif el['stereotype'] == 'header': ...
The main task of the code is to orchestrate post-processing steps by creating headers, organizing function groups, categorizing data types, arranging variables, and managing macro constants, likely to structure or optimize code/data within a system.
def post_process(self): self._create_headers() self._arrange_function_groups() self._arrange_types() self._arrange_variables() self._arrange_macro_constants()
def format_tags(df): tags = [] tag_lists = [] for subjects in df.subjects: if type(subjects) is str: s = subjects.split(",") else: if type(subjects) is list: s = subjects else: s = [] s = [t.lstrip().rstrip() for t ...
The code preprocesses a dataset for classification by filtering rows based on health-related tags, renaming columns, converting categorical labels to numerical values, cleaning text data using lemmatization, and preparing training features (X_train) and labels (y_train) for evaluation.
def main(): # Importing the dataset data_file_path = "train.tsv" df = pd.read_csv(data_file_path, sep='\t', encoding = "ISO-8859-1") df, df_tags = format_tags(df) mask = df['tags'].apply(lambda x: health(x)) df = df[mask] # text_col contains the column name of where claims are found #...
def get_max_preds(batch_heatmaps): ''' get predictions from score maps heatmaps: numpy.ndarray([batch_size, num_joints, height, width]) ''' assert isinstance(batch_heatmaps, np.ndarray), \ 'batch_heatmaps should be numpy.ndarray' assert batch_heatmaps.ndim == 4, 'batch_images should be 4...
This function processes heatmaps to refine predicted keypoint coordinates by applying Gaussian blur, logarithmic transformation, and Taylor expansion, then optionally transforms coordinates back to the original image space using given center and scale parameters.
def get_final_preds(hm, center, scale, transform_back=True, test_blur_kernel=3): coords, maxvals = get_max_preds(hm) heatmap_height = hm.shape[2] heatmap_width = hm.shape[3] # post-processing hm = gaussian_blur(hm, test_blur_kernel) hm = np.maximum(hm, 1e-10) hm = np.log(hm) for n in ra...
def get_person_detection_boxes(model, img, threshold=0.5): pred = model(img) pred_classes = [COCO_INSTANCE_CATEGORY_NAMES[i] for i in list(pred[0]['labels'].cpu().numpy())] # Get the Prediction Score pred_boxes = [[(i[0], i[1]), (i[2], i[3])] for i in list(pred[0]['box...
The main task of the code is to detect people in an image using a pre-trained Faster R-CNN model, estimate their pose using a TransPose model, and return two images with drawn poses: one on a black background and the original image with poses, along with detected bounding boxes.
def get_pose_pair(pil_img): device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') box_model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True) image_bgr=np.array(pil_img) box_model.to(device) box_model.eval() model = torch.hub.load('yangsenius/T...
def predict_class(self, sentence): bow = self.bag_of_words(sentence) res = self.model.predict(np.array([bow]))[0] ERROR_THRESHOLD = 0.25 results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD] results.sort(key=lambda x: x[1], reverse=True) return_li...
The main task of the code is to determine the appropriate response to a given sentence by classifying its intent. If neural prediction is enabled, it uses `predict_class` to identify the intent, retrieves the corresponding response and confidence probability, and returns them. If neural prediction is disabled, it bypas...
def get_response(self, sentence, ignore_neural=False): if not ignore_neural: ints = self.predict_class(sentence) tag, res, probability = self.get_result(ints, self.intents) return tag, res, probability else: tag, result = self.get_result_without_neural(sen...
def wr_line(f, str, num=1): f.write('\t'*num) f.write(str) f.write('\n') def insert_spouse_pair(f, pair): wr_line(f, f'{pair} [shape=point]', num=2) def insert_person(f, person): shape = " [shape=box]" gender_color = "" if person.sex == 'M': gender_color = " [color=blue]" elif p...
The code generates a structured output by iterating through generations, inserting nodes for individuals and spouse pairs into groups with "rank=same" for alignment, then applying ordering within each generation.
def insert_generation(f, people, generations): for i in range(len(generations)): wr_line(f, "{") wr_line(f, "rank=same", num=2) for person in generations[i]: if isinstance(person, tuple): insert_spouse_pair(f, person[0]) else: insert...
def insert_generation(f, people, generations): for i in range(len(generations)): wr_line(f, "{") wr_line(f, "rank=same", num=2) for person in generations[i]: if isinstance(person, tuple): insert_spouse_pair(f, person[0]) else: insert...
This function generates a family tree graph from hierarchical data, writes it to a DOT file with specified formatting, and converts it to a PNG image using Graphviz. It structures generations, defines parent-child relationships, and applies orthogonal or standard layouts based on the 'ortho' flag.
def get_family_tree(root, display=False): people, generations = get_family_data(root, display) filename = "output/" + root.replace(' ', '_').lower() + ".dot" with open(filename, "w") as f: f.write('digraph {\n') f.write('\tedge [dir = none];\n\n') if ortho: f.w...
def make_dataset(config, train, train_transform=None, test_transform=None): """ Split image paths into training and validation sets, creates the dataset objects for both training and validation """ try: CustomTensorDataset = getattr(datasets, config.dataset) except: raise NotImpleme...
The main task of the code is to set up a machine learning training pipeline by creating datasets and data loaders, initializing a model, optimizer, and loss function, and printing configuration details, sample statistics, and verifying model compatibility with input/output shapes. It returns the model, criterion, optim...
def set_up_train(config, train_transform=None, valid_transform=None): # Get data and make datasets trainds, validds = make_dataset(config=config, train=True, train_transform=train_transform, test_transform=valid_transform) # Make data loaders train_loader = make_dataloader(trainds, config.batch_size, c...
def _prepare_level_events( self, level_events: List[Dict[str, Any]], ): """ Prepare level events for creating STAN input :param level_events: level_events input to self.fit """ self.level_events = [] n_active_level_events = 0 for level_i in le...
The function prepares event data by determining which level and trend events should be learned, predicted, or deactivated based on historical data. It processes input events, identifies active events, validates their presence, and logs configurations. Events before history are deactivated, while those after are predict...
def _prepare_event_data( self, level_events: List[Dict[str, Any]], trend_events: List[Dict[str, Any]] ): """ Parse events, setting which should be learned, predicted and deactivated. This is all based on how much history there is. E.g. - if an event comes bef...
def _prepare_data(self, data: pd.Series): """ Prepare data and perform input checks :param data: data input to fit method ... :returns: prepared data """ logger.debug("Raw input data: %s", data) # Ensure actuals data is a pd.Series of floats utils...
The `fit` method trains a Bayesian time series model (JudgyProphet) to forecast data, incorporating specified level/trend events and adaptive changepoints. It uses Stan for probabilistic inference, optimizing parameters like base trends, seasonality (via Fourier terms), and event impacts (level shifts, trend gradients)...
def fit( self, data: pd.Series, level_events: List[Dict[str, Any]], trend_events: List[Dict[str, Any]], unspecified_changepoints: Union[int, Iterable] = 0, seasonal_period: Optional[int] = None, seasonal_type: str = "add", event_start_cutoff: int = 4, ...
def read_file(self, path): # open the file for reading with open(path, 'r') as file: # read the first line first_line = file.readline() # number of blocks in the file n = 5 * 5 elements = first_line.split()[:n] # convert to ints int_e...
The main task of the code is to generate a map matrix by randomly placing pre-defined map chunks from files into a grid. It iterates over a grid of size (n/5 x m/5), selects random chunks, and places them at positions (i*5, j*5). A specific "exit" chunk is placed at intervals where (i+1) % 5 == 0 and (j+1) % 3 == 0. Af...
def make_map(self): for i in range(0, self.n // 5, 1): for j in range(0, self.m // 5, 1): # generate a random number to select a map chunk random_integer = random.randint(1, NUM_OF_MAPS) if (i + 1) % 5 == 0 and (j + 1) % 3 == 0: ...
def set_time_ranges(self): self.hour_from = (self.hour_from - 1) self.hour_from = ((self.hour_from - 0) + 0) % (23 - 0 + 1) # ensure the number is with 24 hour range self.hour_to = (self.hour_to - 1) ''' this formula is for `wrapping` or a `circular range` ''' self.hour_to = ((s...
The code initializes an object with attributes for storing observations, files, and data, sets an ID, defines time ranges based on start and end hours, and populates these attributes using methods like `set_time_ranges`, `set_files`, `set_data`, and `set_observations` to configure and load relevant information.
def __init__(self, sid: str, start_hour: int = 0, end_hour: int = 23): self.observations = [] self.files = [] self.data = [] self.id = sid self.hour_from = start_hour self.hour_to = end_hour self.set_time_ranges() self.set_files() self.set_dat...
def get_part_of_lung(ct, segmentation, lung_label): lung_seg_part = (segmentation == lung_label) * 255 lung_seg_part = lung_seg_part.astype(np.uint8) contours, hierarchy = cv.findContours(image=lung_seg_part, mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_NONE) x_min, y_min, x_max, y_max = get_bbox_from_con...
This function adds a simulated cancer lesion to a specified lung region in a CT scan. It extracts a lung segment, checks its size, generates a cancer mask if sufficient, and overlays it onto the CT image within the lung's bounding box. If the lung segment is too small, the original CT is returned.
def add_cancer_to_ct(ct, lung_mask, lung_segment_id): ct_part, part_mask, part_bbox = get_part_of_lung( ct=ct, segmentation=lung_mask, lung_label=lung_segment_id ) body_mask = get_body_part(ct=ct, segmentation=lung_mask) cancer_h, cancer_w = ct_part.shape if (cancer_h > 10)...
def get_part_of_lung(ct, segmentation, lung_label): lung_seg_part = (segmentation == lung_label) * 255 lung_seg_part = lung_seg_part.astype(np.uint8) contours, hierarchy = cv.findContours(image=lung_seg_part, mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_NONE) x_min, y_min, x_max, y_max = get_bbox_from_con...
The function `add_covid_to_ct` inserts a synthetic COVID-19 lesion into a specific lung segment of a CT scan. It extracts the lung region using a mask and segment ID, checks if the region is sufficiently large (>10x10 pixels), generates a COVID-19 pattern using graph-based data (`G`), and overlays it onto the original ...
def add_covid_to_ct(ct, lung_mask, lung_segment_id, G): ct_part, part_mask, part_bbox = get_part_of_lung( ct=ct, segmentation=lung_mask, lung_label=lung_segment_id ) covid_h, covid_w = ct_part.shape if (covid_h > 10) and (covid_w > 10): covid = get_covid( G=G...
def get_covid_images(dicoms): return np.concatenate([ds.pixel_array[None] for ds in dicoms]) def add_cancer_to_ct(ct, lung_mask, lung_segment_id): ct_part, part_mask, part_bbox = get_part_of_lung( ct=ct, segmentation=lung_mask, lung_label=lung_segment_id ) body_mask = get_body_p...
The main task of the code is to add simulated metastasis to CT scans within DICOM files by applying lung segmentation masks, modifying pixel data for specified lung regions, and optionally generating disease contours. It returns the updated DICOMs with metastasis and contour data if auto-markup is enabled.
def add_metastasis_to_dicoms(dicoms: List[FileDataset], lung_part_list: List[int], auto_markup: bool): cts = get_covid_images(dicoms) model = lungmask.get_model('unet', 'LTRCLobes') segs = lungmask.apply(cts, model) new_dicoms = [] if auto_markup: dicom_contours = [] else: dico...
def get_covid_images(dicoms): return np.concatenate([ds.pixel_array[None] for ds in dicoms]) def add_covid_to_ct(ct, lung_mask, lung_segment_id, G): ct_part, part_mask, part_bbox = get_part_of_lung( ct=ct, segmentation=lung_mask, lung_label=lung_segment_id ) covid_h, covid_w = c...
The code modifies DICOM images by synthetically adding COVID-19 to specified lung regions using a lung segmentation model and a neural network, returning updated DICOMs and optional disease contours. It processes each image, applies segmentation, injects COVID-like lesions via a pre-trained generator, and preserves ori...
def add_covid_to_dicoms(dicoms: List[FileDataset], lung_part_list: List[int], auto_markup: bool): cts = get_covid_images(dicoms) model = lungmask.get_model('unet', 'LTRCLobes') segs = lungmask.apply(cts, model) new_dicoms = [] if auto_markup: dicom_contours = [] else: dicom_con...
def parse_ps_clk(self, config): self.ps_in_freq_mhz = get_num_in_range( config, "ps_in_freq_mhz", None, float, platform["ps_in_freq_mhz"]["min"], platform["ps_in_freq_mhz"]["max"] ) print(f"PS input clk frequency: {self.ps_in_freq_mhz} MHz") def parse_cpu_clk...
This code initializes clock configurations for a Zynq system by parsing PS and CPU clocks, generating an IO PLL, and conditionally configuring DDR clocks based on the 'ddr.enabled' flag. It sets up hardware-specific clock parameters for a FPGA design, handling both DDR-enabled and non-DDR scenarios.
def __init__(self, config, part, ddr): self.parse_ps_clk(config) print("Generating Zynq clocks:") self.parse_cpu_clk(config, part) self.gen_io_pll(config, part) if ddr.enabled: self.ddr_enabled = True self.parse_ddr_clk(ddr, part) else: ...
def readData(input_file): with open(input_file, 'r') as f: line = f.readline().split() N = int(line[0]) M = int(line[1]) K = int(line[2]) csp = dict() for i in range(N): csp[i] = [] domain[i] = [i for i in range(K)] ...
The main task of the code is to benchmark and compare the performance of two depth-first search (DFS) algorithms—plain and improved—on multiple instances of a constraint satisfaction problem (CSP). It records execution time and state counts for each run, generating 20 problem instances (initial + 19 regenerated) and st...
def multiple_test(input_file, output_file, mode_flag): global num_states import os import time #import numpy as np # Keep track of all the times and states all_times = [] all_states = [] N, M, K, csp = readData(input_file) start = time.time() if mode_flag == 0: ...
def readData(inpu_file): with open(input_file, 'r') as f: line = f.readline().split() N = int(line[0]) M = int(line[1]) K = int(line[2]) csp = dict() for i in range(N): csp[i] = [] domain[i] = [i for i in range(K)] ...
The main task of the code is to evaluate the performance of the min_conflicts algorithm on Constraint Satisfaction Problems (CSPs). It runs the algorithm up to 500 times per problem, recording solution times and state counts. After solving an initial problem, it generates 19 new CSPs with the same parameters, repeating...
def multiple_test(input_file, output_file): global num_states import os import time # import numpy as np # Keep track of all the times and states all_times = [] all_states = [] N, M, K, csp = readData(input_file) start = time.time() for i in range(500): re...
def get_all_price_histories( ipc: market.ItemPriceCache, items: Iterable[world.ItemType] ) -> ItemPriceHistoryDict: return {it: ipc.get_price_history(it) for it in items} def get_all_items(formulas: List[world.Formula]) -> Set[world.ItemType]: r: Set[world.ItemType] = set() for f in formulas: r....
The code processes historical item price data to calculate and rank profit ratios for various formulas over specific dates. It initializes services, retrieves price histories, folds formulas, computes profit ratios for each date, and sorts results by profitability, ultimately printing ranked outcomes.
def history(): logging.basicConfig(level=logging.INFO) serv = services.Services() w = world.World(serv.reference_db) ipc = market.ItemPriceCache(serv.store_db, serv.api) formulas = [w.find_formula(w.find_item_type(id)) for id in REACTIONS] prices = get_all_price_histories(ipc, get_all_items(for...
def _is_fresh(self, d: datetime.datetime) -> bool: return datetime.datetime.now() - d <= datetime.timedelta( hours=random.uniform(3, 3) ) def get_market_data(api: SwaggerClient, type_id: int) -> ItemPriceWithDetails: low_price = 0.0 high_price = math.inf daily_trade_volume = 0.0 ...
The code retrieves item price data from a database, returning cached values if they are recent. If not, it fetches updated pricing data via an API, stores it in the database, and returns the new price information.
def find_item_price(self, item_type: world.ItemType) -> ItemPrice: ip = dataclass_from_row( ItemPrice, self.conn.execute( "SELECT " " type_id, last_refreshed, daily_trade_volume, " " low_price, high_price " "FROM eveMarket...
def _is_fresh(self, d: datetime.datetime) -> bool: return datetime.datetime.now() - d <= datetime.timedelta( hours=random.uniform(3, 3) ) def parse_history(data: List[Dict[str, Any]]) -> List[HistoricalItemPrice]: return [dataclass_from_row(HistoricalItemPrice, d) for d in data] def get_...
This function retrieves historical price data for a given item type from a database. If the cached data is up-to-date, it returns parsed history directly. Otherwise, it fetches fresh market data via an API, updates the cache, and returns the parsed history.
def get_price_history( self, item_type: world.ItemType ) -> List[HistoricalItemPrice]: row = self.conn.execute( "SELECT last_refreshed, history " "FROM eveMarket WHERE type_id = ?", (item_type.id,), ).fetchone() if row and self._is_fresh(datetime.d...
def setChange(direction): global set1,set2,set3,set4,set5 changed = False set = int(currSet['text']) exec("global set" + str(set) + "\nset" + str(set) + " = [[] for times in range(len(players)+2)]") eval("set" + str(set))[0].append(homeScore['text']) eval("set" + str(set))[0].append(awayScore['t...
The main task of the code is to save volleyball match statistics and player performance data into a text file. It calculates set wins, side-out percentages, serve holds, and player metrics, formats them with team names, timestamps, and detailed tables, then writes the structured data to a user-specified file using a GU...
def save(): setChange("none") file = tkinter.filedialog.asksaveasfile(mode='w',defaultextension='.txt') if file != None: homeSets = sum([1 for test in range(1,6) if eval("set" + str(test))[0][0] > eval("set" + str(test))[0][1]]) awaySets = sum([1 for test in range(1,6) if eval("set" + str(te...
def _detect_game_phase(self,board): nr_friendly_pieces = 0 nr_friendly_pawns = 0 nr_friendly_kings = 0 for i in range(8): for j in range(8): occupant = board.location(i, j).occupant if(occupant is not None): if(occupant.col...
This function performs a step in a game or simulation by detecting the current game phase (if needed), generating a move and choice using the `_evo` method, and applying the action to the board via `_action`. It ensures phase-specific logic is handled before executing the move, advancing the game state accordingly.
def _evo_step(self,board): if (self.phase != 2 and self.phases == 3) or (self.phase != 1 and self.phases == 2): detect_game_phase = self._detect_game_phase(board) move, choice, _ = self._evo(board) self._action(move, choice, board) return
def _encode_status(self) -> None: self.df['status'] = np.where(self.df['status'] == "OPEN", 1, 0) def _encode_route_type(self) -> None: self.df['route_type'] = np.where(self.df['route_type'] == 'ARRIVAL', 1, 0) def _apply_feature_engineering(self) -> None: self.df['distance'] = self.df['waypoint...
The function preprocesses training data by encoding categorical variables (status, route type), applying feature engineering, extracting date-related features, and dropping irrelevant columns. If 'waypoints' is True, it also removes waypoint-specific features. The processed DataFrame is returned after these transformat...
def preprocess_train(self, waypoints: bool = False) -> pd.DataFrame: self._encode_status() self._encode_route_type() # self._one_hot_encode_airports() self._apply_feature_engineering() self._extract_info_from_date() self._drop_irrelevant_features([...
def _encode_route_type(self) -> None: self.df['route_type'] = np.where(self.df['route_type'] == 'ARRIVAL', 1, 0) def _apply_feature_engineering(self) -> None: self.df['distance'] = self.df['waypoints'].apply(lambda x: self.distance_fromlist(eval(x))) self.df['no_of_waypoints'] = self.df['waypoin...
The main task of the code is to preprocess test data by encoding route types, applying feature engineering, extracting date-related information, and dropping irrelevant features like waypoints, timestamps, and route IDs. The processed DataFrame is returned, ready for modeling. Commented-out sections suggest optional st...
def preprocess_test(self) -> pd.DataFrame: self._encode_route_type() # self._one_hot_encode_airports() self._apply_feature_engineering() self._extract_info_from_date() self._drop_irrelevant_features(['waypoints', 'timestamp', 'route_id', 'timestamp_date']) ...
def _encode_route_type(self) -> None: self.df['route_type'] = np.where(self.df['route_type'] == 'ARRIVAL', 1, 0) def _apply_feature_engineering(self) -> None: self.df['distance'] = self.df['waypoints'].apply(lambda x: self.distance_fromlist(eval(x))) self.df['no_of_waypoints'] = self.df['waypoin...
The main task of the code is to preprocess a dataset by merging it with route definition data, encoding route types, applying feature engineering, extracting date-related information, dropping irrelevant columns, and returning the first row of the processed DataFrame as a transposed DataFrame.
def preprocess_sample(self) -> pd.DataFrame: file_path = Path(__file__).resolve() file_path = file_path.parents[1] / 'data' / 'statuses' / 'route_definitions.csv' self.df = pd.merge(self.df, pd.read_csv(file_path), on='route_id') self._encode_route_type() self._apply_feature_engi...
def _encode_route_type(self) -> None: self.df['route_type'] = np.where(self.df['route_type'] == 'ARRIVAL', 1, 0) def _apply_feature_engineering(self) -> None: self.df['distance'] = self.df['waypoints'].apply(lambda x: self.distance_fromlist(eval(x))) self.df['no_of_waypoints'] = self.df['waypoin...
The main task of the code is to preprocess a dataset by merging it with 'route_definitions.csv', encoding route types, applying feature engineering, extracting date-related information, and returning the first row of the processed DataFrame as a transposed DataFrame.
def preprocess_sample_dont_drop_col(self): file_path = Path(__file__).resolve() file_path = file_path.parents[1] / 'data' / 'statuses' / 'route_definitions.csv' self.df = pd.merge(self.df, pd.read_csv(file_path)) self._encode_route_type() self._apply_feature_engineering() ...
def full_reconcile(self): logging.info("Beginning full reconcile") job_list = self.batch_v1_api.list_namespaced_job( namespace=self.target_namespace ) resource_version = job_list.metadata.resource_version current_jobs = job_list.items job_dict = {} for...
The code initializes a Watcher to monitor Kubernetes resources and Redis events. It connects to Redis, configures Kubernetes API access (with SSL bypass), sets up API clients, performs initial reconciliation, and starts threads for Redis listening, periodic reconciliation, and continuous job monitoring. The main task i...
def __init__(self, config: aconfig.Config): """Function to initialize the Watcher.""" self.config = config logging.info("Attempting connection to Redis") self.db_client = RedisHelper(self.config) self.tuning_image = self.config.trainer_config.tuning_image self.target_na...
def get_team_stats(df_team, year, team_name): return df_team[ (df_team["year"] == year) & (df_team["team_name"] == team_name) ] def resolve_team_name(team_name): # Apply hard-coded corrections to team names team_name_dict = { "Colorado-Colorado Springs": "Colorado", "Colorado Col...
This function processes game data and team statistics to create a structured DataFrame. It iterates through each game, retrieves team stats for both teams in the game, checks for valid data, and compiles indices, team stats, and win outcomes. If data is missing, it optionally prints the issue. Finally, it constructs an...
def get_team_stats_df(df_team, game_df, should_print=False): indeces_w_stats = [] t1_stats_list = [] t2_stats_list = [] t1_wins_list = [] for index, row in game_df.iterrows(): year = row["year"] team_1 = row["team_1_name"] team_2 = row["team_2_name"] team_1_score = ro...
def is_power_of_two(num): return (((num & (num - 1)) == 0) and num != 0) or num == 2 def get_team_stats(df_team, year, team_name): return df_team[ (df_team["year"] == year) & (df_team["team_name"] == team_name) ] def resolve_team_name(team_name): # Apply hard-coded corrections to team names ...
The function generates matchup statistics for a tournament by pairing teams, retrieving their stats and seeds, and creating a DataFrame. It checks if the team count is a power of two, processes each pair, and constructs stats using post-season-specific logic if enabled.
def get_matchups_stats(df_team, teams, post_season, year): i = 0 t1_stats = [] t2_stats = [] t1_seeds = [] t2_seeds = [] if not is_power_of_two(len(teams)): print("ERROR: invalid number of team names") return False while i < len(teams): t1_name, t1_seed = teams[i] ...
def generate_t(n, data_type, length): if data_type == 'unbalanced': out = list() for i in range(n): pool = np.linspace(0.01, 1, 100, endpoint=True) out_i = np.random.choice(pool, 50, replace=False) out_i.sort() out.append(out_i) elif data_type == '...
The function `repeated_exp` performs multiple iterations of an experiment involving data generation, kernel matrix computation, precision operator calculation, and ROC AUC evaluation. It generates synthetic data, computes coordinates and kernels, evaluates precision, and appends the AUC metric for each iteration to a l...
def repeated_exp(times, n, dim, y, t_type, d_type, k_type): out = list() for i in tqdm(range(times)): a, t = generate_t(n, t_type, 50) b = gen_sample(a, 50, d_type, dim, t, k_type) c = cal_coor(b[0], a, t_type, t, k_type) dim = b[0][0].shape[1] d = kernel_x_mat(b[0], c,...
def user_input(self, event): """ Handles user input for the game :param event: pygame event object """ if event.type == pygame.MOUSEBUTTONDOWN: x, y = pygame.mouse.get_pos() uniq_piece = self.postion_piece(x, y) if uniq_piece is not None: ...
The game_loop method manages the main game loop by handling Pygame events, updating the display, processing user input, checking for a winner, playing victory music, and maintaining a 60 FPS frame rate. If a winner is detected, it displays the result, plays music, waits 7 seconds, then exits the loop and terminates Pyg...
def game_loop(self): """ The program's main game loop launches and manages game events. Until the game is ended, the loop keeps going. It looks for pygame events, such as the exit event. To handle user input, it invokes the user_input method. To update the game display, the draw ...
def permutationMatrix(n): """ Return a permutation matrix which, when multiplied on the right of a list in the standard ordering, produces a list in the gray code ordering. This works by making a list in the standard ordering ([0, 1, ..., n]), and then uses bitshifts to put these numbers i...
The function `genNQubitTransform` decomposes a given unitary matrix $ U $ into a sequence of $ k $-controlled single-qubit gates using a method from Rieffel and Polak's book. It converts $ U $ into Gray code ordering, iteratively applies controlled transformations $ C_m $ to reduce $ U $ to the identity matrix, and con...
def genNQubitTransform(U, n_qubits, t): """ Return pyQuil Program which implements the n-qubit tranformation represented by the unitary matrix `U` (in standard ordering). This algorithm is based on the one presented by Rieffel and Polak in their book, "Quantum Computing: A Gentle Introduction"....
def get_grid_pos(self, pose): pos_x, pos_y, pos_z = pose.position.x, pose.position.y, pose.position.z grid_x = self.map_width - int((pos_x - self.occupancy_map.info.origin.position.x) / self.occupancy_map.info.resolution) grid_y = int((pos_y - self.occupancy_map.info.origin.position.y) / self.oc...
The main task of the code is to perform real-time path planning and visualization for a robot using ROS. It continuously checks for map data, robot pose, and goal positions, drawing them on an image. When a path is completed, it controls the robot's movement toward the goal, publishes the path, and stops the robot upon...
def main_process(self): self.path_planning = False while not rospy.is_shutdown(): if self.map_set: self.draw_img = cv2.merge((copy.deepcopy(self.img), copy.deepcopy(self.img), copy.deepcopy(self.img))) if rospy.has_param('path_id'): grid_x,...
def loadData(): train = np.loadtxt("train_cancer.csv", delimiter=",") test = np.loadtxt("test_cancer_pub.csv", delimiter=",") X_train = train[:, 0:-1] y_train = train[:, -1] X_test = test return X_train, y_train[:, np.newaxis], X_test def trainLogistic(X,y, max_iters=max_iters, step_size=step_size): ...
The code trains logistic regression models on a dataset, comparing performance with and without a bias term. It loads data, trains models, evaluates accuracy, and performs k-fold cross-validation. It also prepares test predictions and saves results to a CSV for submission. Key tasks include model training, bias compari...
def main(): # Load the training data logging.info("Loading data") X_train, y_train, X_test = loadData() logging.info("\n---------------------------------------------------------------------------\n") # Fit a logistic regression model on train and plot its losses logging.info("Training logistic regression ...
def get_nearest_neighbors(example_set, query, k): dists = [] for i in range(len(example_set)): # get distances dist = np.linalg.norm(example_set[i] - query) dists.append(tuple((dist,i))) # add tuple (distance, index) dists.sort() # sort by distance x,dists = map(list, zip(*dists)) # filter out indexe...
The main task of the code is to implement and evaluate a k-Nearest Neighbors (k-NN) classifier. It includes testing the algorithm's correctness with sanity checks, performing 4-fold cross-validation to select the optimal k-value, and using the best k to predict test data for a Kaggle submission. The code also validates...
def main(): ############################################################# # These first bits are just to help you develop your code # and have expected ouputs given. All asserts should pass. ############################################################ # I made up some random 3-dimensional data and ...
def sort_features_by_mutual_information(self) -> np.ndarray: ''' Sorts the features by mutual information with the target variable. ''' mutual_informations = [] transform = lambda x: 1 if x == True else 0 for i in range(len(self.features[1])): transformed_num...
The main task of the code is to initialize a decision tree model by sorting features based on mutual information, selecting the root node, and constructing the tree structure using the provided features and target array. It prepares the dataset, identifies the optimal split feature, and builds the tree hierarchy for cl...
def __init__(self, features: np.ndarray, target: np.ndarray): self.features = features self.target = target self.sorted_nodes_by_I = self.sort_features_by_mutual_information() self.leafs = self.get_leafs() self.root = (str(FeatureType(self.sorted_nodes_by_I[0][0])).split('.')[1],...
def get_shapes(self): visible_facet_indices = self.get_visible_facets() group_facets = self.group_by_coplanar_facets(visible_facet_indices) adjacency = face_adjacency(self.mesh.faces) shapes = [] for coplanar_facets in group_facets: shapes_on_coplanar_facet = [] ...
The function extracts lines and arcs from an STL file by analyzing coplanar shapes. It groups points, checks consecutive line angles and length differences using thresholds, classifying segments as arcs (if angles and lengths are similar) or lines. Arcs are collected as grouped points, while lines are stored separately...
def get_lines_and_arcs(self, angle_threshold: float = 0.1): """ Extract lines and arcs from an STL file \n If the line angle between two lines is close to 0 and the line length is close to the previous line length, it is considered an arc. \n Note: This is not a robust al...
def clean_data_frame(df): df = df.applymap(normalize_string) df_boolean_mask = df.applymap(lambda x: MIN_LEN <= len(x.split()) <= MAX_LEN) df_boolean_mask = df_boolean_mask.iloc[:,0] & df_boolean_mask.iloc[:,1] # Remove too short and too long sentences return df[df_boolean_mask] def create_val_and_t...
The code prepares training, validation, and test datasets for a machine learning task, handling both supervised and unsupervised scenarios. It reads input data, cleans it, appends unsupervised data if specified, and saves processed files. The main tasks include dataset creation, corruption handling, and splitting into ...
def main(opts): """Main logic""" # E2E specific files e2e_train_dataset = "trainset.csv" e2e_new_train_dataset = "new_trainset.csv" e2e_valid_dataset = "devset.csv" e2e_new_valid_dataset = "new_devset.csv" #e2e_test_dataset = "testset_w_refs.csv" e2e_new_test_dataset="new_testset.csv" ...
def predict_u(self, user, movie): ''' Uses user - user filtering to find predicted rating ''' ium = self.utilmat.ium um = self.utilmat.um bx = self.utilmat.bx bi = self.utilmat.bi mu = self.utilmat.mu if um.get(user) == None: if ium.get...
This function calculates RMSE and MAE for three prediction models (u, i, b) using a utility matrix. It iterates over all user-movie ratings, computes squared errors for RMSE and absolute errors for MAE, averages them across all entries, and returns six metrics: RMSE/MAE for each model.
def calc_loss(self, utilmat): ''' Computes RMSE loss for the data given in utilmat ''' um = utilmat.um rmse_u = 0 rmse_i = 0 rmse_b = 0 mae_u = 0 mae_i = 0 mae_b = 0 cnt = 0 for user in um: for movie in um[user]:...
def show_score(): score1_string = "Player 1 Total Wins: {}" score2_string = "Player 2 Total Wins: {}" clear_screen() print("Current Score:") print(score1_string.format(score[0])) print(score2_string.format(score[1])) print("\n" * 4) def input_play(): valid_bool = False while valid_bo...
The code facilitates a two-player game where each player selects a move (via input_play()) while the other looks away. It displays scores before and after moves, then determines the winner using determine_winner() with both players' choices.
def play_game(): show_score() print("Player 1! Input your choice! Player 2! Look away now!") player1_play = input_play() show_score() print("Player 2! Input your choice! Player 1! Look away now!") player2_play = input_play() determine_winner(player1_play, player2_play)
def _update_screen(self): # redraw the screen during each pass through the loop. self.screen.fill(self.settings.bg_colour) self._draw_floors() self.hero.blitme() self._draw_fires() self._draw_yakuza() for bullet in self.bullets.sprites(): bullet.draw_b...
This function handles a 'super jump' mechanic by moving the hero upward if activated, updating the screen, reducing health on floor collision, and transitioning to falling states. It also updates the hero's position and checks for fire collisions.
def _super_jump(self): flying_speed = 3 if self.hero.super_jump: self.hero.y -= flying_speed self.hero.rect.y = self.hero.y self._update_screen() if self.floor_collisions: self.sb.health -= 1 self._falling2() else: ...
def _super_jump(self): flying_speed = 3 if self.hero.super_jump: self.hero.y -= flying_speed self.hero.rect.y = self.hero.y self._update_screen() if self.floor_collisions: self.sb.health -= 1 self._falling2() else: ...
The main task of the code is to handle a hero's actions during a game update: it triggers super and regular jumps, checks for fire-related collisions, updates the hero's state, and verifies if the level should end. This method orchestrates movement, collision detection, and level progression logic for the hero characte...
def _update_hero(self): self._super_jump() self._hero_jump() self._check_hero_fire_collisions() self.hero.update() self._end_level()
def _check_events(self): """Watch for keyboard and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame...
The code starts the game's main loop, continuously checking for events, updating active game elements (hero, fire, yakuza, bullets), and rendering the screen. It runs while the game is active, handling gameplay logic and level progression until the game ends.
def run_game(self): """Start the main loop for the game""" while True: self._check_events() if self.game_stats.game_active: self._update_hero() self._update_fire() self._update_yakuza() self._update_bullets() ...
def __verbose_print(self, *args, **kwargs) -> None: ''' Print if verbose is enabled ''' if self.__verbose: print(*args, **kwargs) def __ensure_cf(self, retry: int = 0) -> None: ''' Ensure that the Cloudflare cookies is still valid\n Parameters: ...
The code initializes a browser for interacting with OpenAI's chat interface. It sets up a virtual display on headless servers, configures Chrome with window size/proxy, launches the browser, restores session cookies, validates Cloudflare cookies, opens the chat page, and removes introductory elements/alerts to prepare ...
def __init_browser(self) -> None: ''' Initialize the browser ''' # Detect if running on a headless server if self.__is_headless: try: self.display = Display() except FileNotFoundError as e: if 'No such file or directory: \'X...
def format(self): #initiate and format drive file and save instance self.driveInst = drive.Drive(self.driveName) self.driveInst.format() #create a volume instance and write the intial bitmap volData = volume.Volume(self.driveName) volData.intialBitmapFormat() sel...
This function processes a command line input by parsing arguments, identifying the command, and executing corresponding actions like formatting drives, reconnecting, listing files, creating directories, appending data, or quitting. It handles errors and ensures proper command structure, with special handling for quoted...
def processCommandLine(self,line): print(line) #split line into arguments firstQuote = int(str(line).find('"')) cmdline = line #if there is data (3rd param) remove it to get command if firstQuote != -1 : cmdline = line[:firstQuote] #get command an...
def conv_bn_relu(in_channels, out_channels, kernel_size, stride, padding, groups, dilation=1): if padding is None: padding = kernel_size // 2 result = conv_bn(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, ...
This code initializes a neural network block with depthwise convolutions, large kernel reparameterization, and dropout. It sets up projection layers (pw1, pw2), a large kernel convolution (ReparamLargeKernelConv), ReLU activation, batch normalization, and stochastic depth. The block processes input features through the...
def __init__(self, in_channels, dw_channels, block_lk_size, small_kernel, drop_path): super().__init__() self.pw1 = conv_bn_relu(in_channels, dw_channels, 1, 1, 0, groups=1) self.pw2 = conv_bn(dw_channels, in_channels, 1, 1, 0, groups=1) self.large_kernel = ReparamLargeKernelConv(in_chan...
def urlparse(cls, url): """ Split S3 URL into bucket, key, filename """ _url = deepcopy(url) if url[0:5] == 'https': _url = cls.https_to_s3(url) if _url[0:5] != 's3://': raise Exception('Invalid S3 url %s' % _url) url_obj = _url.replace('s3://', '').split...
The function retrieves the latest inventory manifest file from an S3 bucket by checking the current and previous day's directories. It constructs date-specific paths, searches for 'manifest.json' files, and returns the JSON content of the most recent valid manifest, or None if none is found.
def latest_inventory_manifest(self, url): """ Get latest inventory manifest file """ parts = self.urlparse(url) # get latest manifest file today = datetime.now() manifest_url = None for dt in [today, today - timedelta(1)]: _key = op.join(parts['key'], dt.strft...
def latest_inventory_manifest(self, url): """ Get latest inventory manifest file """ parts = self.urlparse(url) # get latest manifest file today = datetime.now() manifest_url = None for dt in [today, today - timedelta(1)]: _key = op.join(parts['key'], dt.strft...
This function generates a list of objects from a cloud storage bucket's inventory files. It retrieves the latest inventory manifest, extracts file schema keys, iterates through inventory files, and yields results from each file using the schema. The generator filters files by suffix (if specified) and processes them in...
def latest_inventory(self, url, **kwargs): """ Return generator function for objects in Bucket with suffix (all files if suffix=None) """ manifest = self.latest_inventory_manifest(url) # read through latest manifest looking for matches if manifest: # get file schema ...
def get_grid( max_leaf_gap=__DEFAULT_MAX_LEAF_GAP, grid_resolution=__DEFAULT_GRID_RESOLUTION, leaf_pair_widths=__DEFAULT_LEAF_PAIR_WIDTHS, ): """Get the MU Density grid for plotting purposes. Examples -------- See `pymedphys.mudensity.calculate`_. """ leaf_pair_widths = np.array(le...
The function `calc_mu_density` calculates the spatial distribution of monitor units (MU) density across a grid defined by jaw and MLC (multi-leaf collimator) movements. It processes input arrays of MU values, MLC positions, and jaw positions for each control point, accounting for grid resolution, leaf gap constraints, ...
def calc_mu_density( mu, mlc, jaw, grid_resolution=None, max_leaf_gap=None, leaf_pair_widths=None, min_step_per_pixel=None, ): """Determine the MU Density. Both jaw and mlc positions are defined in bipolar format for each control point. A negative value indicates travel over the...
def forward( model: torch.nn.Module, batch: typing.Dict[str, torch.Tensor], calc_acc=False, ) -> typing.Tuple[torch.Tensor, typing.Dict[str, float]]: """ Forward pass for the model. :param model: A encoder-decoder pytorch model. :param batch: A batch of data. This is a dictionar...
The function trains a PyTorch encoder-decoder model using gradient accumulation, logging, evaluation, and checkpointing. It iterates over a training dataloader, computes loss, performs backpropagation with the accelerator, and updates the optimizer/scheduler. After gradient accumulation steps, it logs metrics, evaluate...
def train( model: torch.nn.Module, train_dataloader: torch.utils.data.DataLoader, test_dataloader: torch.utils.data.DataLoader, accelerator: accelerate.Accelerator, lr_scheduler: torch.optim.lr_scheduler.LRScheduler, optimizer: torch.optim.Optimizer, logger: loggi...
def onCancel(self): self.clearItem() def clearItem(self): self.var_edit_name.set('') self.var_edit_qty.set('') self.enableEdit(False) self.error_text.config(text='') self.mode = ProductFrame.MODE_NONE def reportUpdate(self): if self.notify_update: self...
This method deletes a selected item from a treeview by calling ProductItem.Delete with specific values. If successful (rows_affected > 0), it clears the item, triggers a report update, and refreshes the treeview. If deletion fails (no rows affected), it displays an error indicating either the item's absence or backgrou...
def onDetele(self): self.onCancel() selected = self.treeview.focus() if selected: item = self.treeview.item(selected) vals = item['values'] rows_affected = ProductItem.Delete(vals[0], vals[3]) if rows_affected > 0: self.clearItem() ...
def query_initial_regions(self): print("Region of interst guess is (leave blank to accept guesses) :") print("From %5.2f (min)" % self.model.time_data[self.model.region_start_index]) print("To %5.2f (min)" % self.model.time_data[self.model.region_end_index]) start = self.handle_input("Ti...
The main task of the code is to execute a sequence of methods that query different regions and interpolations, likely for data analysis or modeling purposes, by calling `query_initial_regions()`, `query_interpolations()`, `query_linear_region()`, and `query_tg_region()` in order.
def run_model(self): self.query_initial_regions() self.query_interpolations() self.query_linear_region() self.query_tg_region()
def get_all_template_ids(self, library_id): url = f"https://{self.hostname}/api/content/library/item?library_id={library_id}" headers = {'vmware-api-session-id': self.session} data = self.api_call(url, method='get', headers=headers, verify=self.validate_certs) templates = [] if d...
The code's main task is to remove unpublished templates from a specified library. It retrieves all template IDs, checks each template's publication status, and deletes those marked as unpublished. This function ensures only published templates remain in the library by iterating through entries and applying deletion bas...
def remove_unpublished_templates(self, library_id): templates = self.get_all_template_ids(library_id) for template_id, _, _, template_notes in templates: if self.check_template_published(template_notes) == 'False': self.delete_template_from_library(template_id, library_id)
def get_all_template_ids(self, library_id): url = f"https://{self.hostname}/api/content/library/item?library_id={library_id}" headers = {'vmware-api-session-id': self.session} data = self.api_call(url, method='get', headers=headers, verify=self.validate_certs) templates = [] if d...
This function copies published templates from a source library to a destination library, ensuring each template is only copied once by checking for duplicates in the destination library.
def copy_templates_to_library(self, source_library_id, destination_library_id): source_templates = self.get_all_template_ids(source_library_id) destination_templates = self.get_all_template_ids(destination_library_id) if source_templates: for template_id, os_version, template_name, ...
def get_vm_id(self): url = f"https://{self.hostname}/rest/vcenter/vm?filter.names={self.vm_name}" headers = {'vmware-api-session-id': self.session['value']} data = self.api_call(url, headers=headers, verify=self.validate_certs) return data['value'][0]['vm'] if data else None def get_lib_...
This function adds a virtual machine to a VMware vCenter content library by making an API call with authentication, specifying the VM source and target library, then handling cleanup and template publishing. It retrieves VM/library IDs, constructs a POST request, checks for success, and removes excess templates if need...
def add_vm_to_content_library(self): vm_id = self.get_vm_id() lib_id = self.get_lib_id() url = f"https://{self.hostname}/rest/com/vmware/vcenter/ovf/library-item" headers = { 'vmware-api-session-id': self.session['value'], 'Content-Type': 'application/json' ...
def get_source_library_id(self): url = f"https://{self.hostname}/api/content/library?action=find" headers = {'vmware-api-session-id': self.session} params = {'name': self.source_library, 'type': 'LOCAL'} data = self.api_call(url, method='post', headers=headers, json=params, verify=self.v...
The main task of the code is to copy templates from a source content library to a destination library. It first verifies both libraries exist, then removes unpublished templates from the destination, copies templates from the source to the destination, and deletes excess templates in the destination. The process conclu...
def main(self): """Main entry point of the module.""" source_library_id = self.get_source_library_id() source_library_state = self.check_content_library_state(source_library_id) destination_library_id = self.get_destination_library_id() destination_library_state = self.check_con...
def check_content_library_state(self): lib_id = self.get_lib_id() return 'present' if lib_id else 'absent' def get_lib_id(self): url = f"https://{self.hostname}/api/content/library?action=find" headers = {'vmware-api-session-id': self.session} params = {'name': self.content_libra...
The main task of the code is to update notes in templates within a content library. It first verifies the library's existence, retrieves its ID, identifies templates requiring updates, and iterates through them to modify their notes using their respective IDs, ensuring data is passed as a JSON string.
def process_state(self): if self.check_content_library_state() == 'absent': self.module.fail_json(msg=f"Content Library '{self.content_library}' does not exist.") # Get library id lib_id = self.get_lib_id() # Get all templates to update templates_to_update = self.upda...
def check_content_library_state(self): lib_id = self.get_lib_id() return 'present' if lib_id else 'absent' def check_vm_state(self): lib_id = self.get_vm_id() return 'present' if lib_id else 'absent' def add_vm_to_content_library(self): vm_id = self.get_vm_id() lib_id = s...
The main task of the code is to validate the existence of a content library and a virtual machine (VM) source. If either is missing, it raises an error using `fail_json` with specific messages. If both exist, it proceeds to add the VM to the content library via the `add_vm_to_content_library()` method. The code ensures...
def process_state(self): if self.check_content_library_state() == 'absent': self.module.fail_json(msg=f"Content Library '{self.content_library}' does not exist.") if self.check_vm_state() == 'absent': self.module.fail_json(msg=f"Virtual Machine Source '{self.vm_name}' does not ex...
def get_img_contour_thresh(img): img = cv2.flip(img, 1) imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) dst = cv2.calcBackProject([imgHSV], [0, 1], hist, [0, 180, 0, 256], 1) disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(10,10)) cv2.filter2D(dst,-1,disc,dst) blur = cv2.GaussianBlur(dst, (11,11), 0) blur = cv...
This code implements a gesture-controlled calculator using a webcam. It detects hand gestures to input numbers/operators, evaluates expressions, and provides real-time visual/audio feedback. It manages states for entering first/second numbers, operators, and clearing, with voice feedback toggling and result display.
def calculator_mode(cam): global is_voice_on flag = {"first": False, "operator": False, "second": False, "clear": False} count_same_frames = 0 first, operator, second = "", "", "" pred_text = "" calc_text = "" info = "Enter first number" Thread(target=say_text, args=(info,)).start() count_clear_frames = 0 whi...
def change_pass_admin_frame(self): change_pass_admin_frame = Frame(self.user_frame, bg="white", highlightcolor="black", highlightthickness=2) change_pass_admin_frame.place(x=10, y=320, height=300, width=500) change_pass_label = Label(change_pass_admin_frame, text="ADMIN CHANGE PASSWORD", ...
The code initializes a user management GUI with features to add, edit, delete users, and search user data. It sets up input fields, buttons, and a table to display user details, using Tkinter widgets and image icons for interactions.
def __init__(self, frame): self.user_frame = frame self.admin_old_pass = StringVar() self.admin_new_pass = StringVar() self.admin_re_ent_pass = StringVar() self.rows = [] self.cash_username = StringVar() self.cash_pass = StringVar() self.cash_re_ent_pas...
def __get_link(self): soup = self.__fetch_soup() element = soup.find(self.element, href=re.compile(f'{self.pattern}.{self.ext}')) if not element: print(f'{self.name} with .{self.ext} extension not found!') else: url = element.get("href") self.link = se...
The main task of the code is to generate a link by selecting and executing a specific private method based on the value of `self.type`. It acts as a dispatcher, routing to different link-generation strategies like fetching from GitHub, adding versions, or creating direct links, while handling invalid types with an erro...
def generate_link(self): if self.type == 1: self.__get_link() elif self.type == 2: self.__make_link_with_version() elif self.type == 3: self.__get_link_from_github() elif self.type == 4: self.__direct_link() elif self.type == 5: ...
def __get_link(self): self.link = self.__get_link_base() if self.link: match = re.search(f'{self.pattern}.{self.ext}', self.link) self.version = match.group(1) if match else 'Unknown' def __make_link_with_version(self): soup = self.__fetch_soup() element = soup.fi...
The main task of the code is to generate a link by routing to different private methods based on the `self.type` value. Depending on the type (1–7), it calls methods like `__get_link`, `__make_link_with_version`, or `__redirect_link` to handle specific link-generation logic. If the type is invalid, it prints an error m...
def generate_link(self): if self.type == 1: self.__get_link() elif self.type == 2: self.__make_link_with_version() elif self.type == 3: self.__get_link_from_github() elif self.type == 4: self.__direct_link() elif self.type == 5: ...
def deleteOldSamples(self, fig): t_start = self.realtimeWindow_start - self.realtimeWindow if t_start < 0: t_start = 0 for f in range(len(self.figsInfo)): if f != fig: continue if self.figsInfo[f] is None: continue f...
The main task of the code is to update real-time plots by refreshing data in subplots, adjusting axes limits dynamically based on new data ranges, and ensuring visualizations remain synchronized with the latest input values while managing multi-threaded execution control.
def updatePlotData(self): if self.threadEvent.isSet(): return fig_num = 0 t_start = self.realtimeWindow_start - self.realtimeWindow if t_start < 0: t_start = 0 xlim = [t_start, self.realtimeWindow_start + self.realtimeInterval + 1.0] for f in range...
def get_mlm_command(args, arg_dict): # Define the default hyperparameters in a dictionary # Try avoiding arguments which are already defaults in the code # Default hyperparameters default_hyperparams = { 'warmup_steps': '10000', 'learning_rate': '1e-4', 'save_steps': '-1', 'max_seq_length': 512...
This function constructs and executes commands for specified NLP tasks (e.g., MLM, XNLI, NER) based on input arguments. It validates required parameters like output directory and model path, generates task-specific commands using helper functions, and runs them sequentially via os.system() or prints them if run_command...
def construct_and_run(args): # Create a dictionary of all the arguments that need to be passed to the script arg_dict = {} if args.other_args: for arg in args.other_args: if '=' in arg: # Arguments with values split_args = arg.split('=') ar...
def read_fasta(inFile): fin = open(inFile, 'r') seqs = {} seq = '' seqId = '' begin = True for l in fin.readlines(): l = l.strip() if len(l) == 0: continue if l.startswith(">"): if not begin: seqs[seqId] = seq seq = ''...
The code processes a DNA sequence from a FASTA file, generates all possible protein sequences from both the original and reverse-complement strands, and writes unique proteins to an output file.
def res (self, inFile, outFile): print ('Run solution for dataset: %s' % inFile) fin = open(inFile, 'r') fout = open(outFile, 'w') fasta = read_fasta(inFile) seq = list(fasta.values())[0] rcpSeq = self.reverseComplement(seq) ...
def solve(instructions, n, src, target, helper): """Solve the Ha Noi Tower problem""" if n == 1: instructions.append([src, target, helper]) return solve(instructions, n - 1, src, helper, target) instructions.append([src, target, helper]) solve(instructions, n - 1, helper, target, sr...
This code simulates the Tower of Hanoi puzzle using Pygame, visualizing step-by-step disk movements between pillars. It initializes game components, generates disks, and executes pre-calculated instructions to move disks from the source to target pillar via a helper, counting total steps. The loop handles rendering, us...
def main(): """Main function""" instructions = [] pillars = [SRC, TARGET, HELPER] solve(instructions, NUMBER_OF_DISKS, SRC.number, TARGET.number, HELPER.number) total_steps = 0 entered = False pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock...
def check_token(self, user): d = datetime.now(tz=pytz.timezone(self.timezone)).replace(tzinfo=None) e = datetime.strptime(user['expire'], '%Y-%m-%d %H:%M:%S.%f') try: if self._debug == 1: print("Datetime now: " + str(d)) print("Expires: " + str(...
The code fetches energy data from a device via an API by constructing a request URL with user credentials and device details, then returns the retrieved data if successful or an error code otherwise.
def get_energy_now(self, user): self.check_token(user) device = user['devices'][user['device']] req_url = self.build_request_url('queryDeviceDataOneDayPaging', self.salt(), user['secret'], user['token'], device[4], user['plantid'], device[3], device[2]) ...
def check_token(self, user): d = datetime.now(tz=pytz.timezone(self.timezone)).replace(tzinfo=None) e = datetime.strptime(user['expire'], '%Y-%m-%d %H:%M:%S.%f') try: if self._debug == 1: print("Datetime now: " + str(d)) print("Expires: " + str(...
This function checks if a device is invalid by querying an API. It constructs a request URL with user/device parameters, sends a GET request, and evaluates the response's error code. If the error code is non-zero (indicating an issue), it returns True (invalid); otherwise, False (valid).
def invalid_device(self, user, device): self.check_token(user) req_url = self.build_request_url('queryDeviceDataOneDayPaging', self.salt(), user['secret'], user['token'], device['devcode'].strip, user['plantid'], device['p...
def check_token(self, user): d = datetime.now(tz=pytz.timezone(self.timezone)).replace(tzinfo=None) e = datetime.strptime(user['expire'], '%Y-%m-%d %H:%M:%S.%f') try: if self._debug == 1: print("Datetime now: " + str(d)) print("Expires: " + str(...
The code fetches paginated device data for a specified day, handling token validation, error codes, and data structuring. It iterates through 6 pages, constructs API requests, processes JSON responses, and aggregates field values into a dictionary with titles as keys. On error code 12, it returns results after timing; ...
def get_data(self, user, day): to_return = dict() self.check_token(user) stime = time.time() for page in range(6): print(page) self.check_token(user) device = user['devices'][user['device']] req_url = self.build_request_url('queryDeviceData...
def check_token(self, user): d = datetime.now(tz=pytz.timezone(self.timezone)).replace(tzinfo=None) e = datetime.strptime(user['expire'], '%Y-%m-%d %H:%M:%S.%f') try: if self._debug == 1: print("Datetime now: " + str(d)) print("Expires: " + str(...
The code fetches current energy data for a plant by authenticating the user, constructing an API request with a salt and credentials, and returning the response data if successful or an error code otherwise.
def get_energy_summary(self, user): self.check_token(user) req_url = self.build_request_url('queryPlantCurrentData', self.salt(), user['secret'], user['token'], plant_id=user['plantid']) r = requests.get(req_url).json() if r['err'] == 0: # print(r['dat']) return r...
def CTGS_New_1(CTGS_New_Tmp2): CTGS_New_1_Tmp = Question.query.filter(Question.question.ilike( f'%{CTGS_New_Tmp2}%')).all() return CTGS_New_1_Tmp def CTGS_New_2(CTGS_New_Tmp3): CTGS_New_2_Tmp = len(CTGS_New_Tmp3) if ( CTGS_New_2_Tmp == 0): abort(404) def orderP(g...
The function handles two main tasks: (1) If a 'searchTerm' is provided, it processes the term to retrieve and return relevant questions along with total counts. (2) If no 'searchTerm' is present, it creates a new question from input data, inserts it into the database, and returns details of the created question and upd...
def CTGS_New(): CTGS_New_Tmp1 = request.get_json() ter = 'searchTerm' if (CTGS_New_Tmp1.get(ter)): CTGS_New_Tmp2 = CTGS_New_Tmp1.get(ter) CTGS_New_Tmp3 = CTGS_New_1(CTGS_New_Tmp2) CTGS_New_2(CTGS_New_Tmp3) CTGS_New_que = orderP(request, C...
def CTGS_q_3(): CTGS_q_3_x = len(CTGS_q_2()) if ( CTGS_q_3_x == 0): abort(404) def CTGS_q_2(): CTGS_q_2_x = Question.query.all() CTGS_q_2_y = orderP(request, CTGS_q_2_x) return CTGS_q_2_y def CTGS_q_1(): CTGS_q_1_x = Question.query.all() CTGS_q_1_y = l...
The main task of the code is to compile and return a structured JSON response containing success status, a list of questions, total question count, and categories by calling auxiliary functions. It first invokes CTGS_q_3(), then aggregates data from CTGS_q_2(), CTGS_q_1(), and CTGS_q_4() to construct the response using...
def CTGS_q(): CTGS_q_3() return jsonify({'success': True,'questions': CTGS_q_2(),'total_questions': CTGS_q_1(),'categories': CTGS_q_4()})
def _create_model(layers_widths): all_inputs, encoded_features = _prepare_inputs() last_layer = tf.keras.layers.Concatenate()(encoded_features) for width in layers_widths: last_layer = tf.keras.layers.Dense(int(width), activation=tf.keras.activations.relu)(last_layer) output = tf.keras.layers.D...
The code initializes a machine learning model, advances a time series, trains it with a batch, and sets up a prediction function. It creates a TensorFlow model, defines a prediction method for single inputs, and registers this predictor with a dispatcher to handle jobs by converting job data into model inputs and retur...
def init(self, ts, dispatcher, workers): self.model = _create_model(self.layers_widths) self._advance_ts(ts) self._train_batch() @tf.function def predict_single(input): return self.model(input, training=False)[0] def predictor(job): x = np.array(...
def _put_here(self, key: KTYPE, val: VTYPE) -> Self: cls = self.__class__ # maybe this could be a class method??? i = self._gte_index(key) # the key is already present! if i < len(self.keys) and self.keys[i] == key: if self.vals[i] == val: return self # we can return our old self if there is no change...
This method inserts a key-value pair into a tree structure. If the tree is empty, it directly places the value. Otherwise, it recursively inserts the value based on the key's height and the tree's current height, maintaining the tree's structure.
def put(self, key: KTYPE, val: VTYPE) -> Self: if self.subtrees == (None,): # special case for empty tree return self._put_here(key, val) return self._put_recursive(key, val, self.key_height(key), self.height())
def train_target(env): """"if ist is the first time, the :A_visibilitymatrix should be opened. elese: the other one named: updatedvisibilitymatrixforpositioning""" with open('Input_data/' + env) as csv_file: csv_visibility_matrix = csv.reader(csv_file, delimiter=',') visibility_matrix = [] ...
This code evaluates dialogue systems by analyzing communication efficiency across different initial information combinations in CSV datasets. It processes each CSV file, extracts training data, and calculates entropy-based and random robustness metrics for visible objects. Results are stored in JSON files, comparing co...
def dialogue_evaluation(): for root, dirs, files in os.walk("Input_data"): for file in files: if file.endswith(".csv"): train, target, feature_cols = train_target(file) communication_count = {} communication_count_random = {} commun...
def explode_string(string): characters = [] for character in string: characters.append(character) return characters def question_1(original_array): iteration_data = check_seats(original_array) while True: if (iteration_data == check_seats(iteration_data)).all(): break ...
(The code reads input data from "day11.txt", processes each line with `explode_string`, converts the data into a NumPy array, and then solves two problems (`question_1` and `question_2`) using this array. The main task involves parsing input data and performing computations for two distinct problems, likely related to ...
def main(): inp = [] with open("Inputs/day11.txt", "r") as file: for line in file: inp.append(explode_string(line.rstrip())) data = np.array(inp) question_1(data) question_2(data)
def parse_arguments(): """Arguments of the DeviceAnalyzer script. Returns -------- args : argparse Setted arguments of the script. """ parser = argparse.ArgumentParser( description="""Analyze of captured network flow in database. Database is created by CreateScript. Filled ...
The main task of the code is to process command-line arguments, determine whether to analyze JSON data or an SQLite database, execute corresponding analysis functions for devices/networks, and ensure proper resource cleanup by closing the database connection. It prioritizes JSON analysis if specified, otherwise connect...
def main(): """Main function call one of three function by arguments where it is set. """ args = parse_arguments() if args.printJSON != "": if args.print == False and args.file == "": print( "Need define output method (print to command line or file [-p], [-f])" ...
def wrap_str(_str): return "[" + _str + "]" def get_position(req_id, symbol): if not check_api_enable(enable_get_position): return None print(req_id, wrap_str(inspect.stack()[0][3])) positions = client.futures_account()['positions'] target = None for position in positions: if po...
This code processes trading signals from a webhook, validates passphrases, and executes trade orders (BUY/SELL) with dynamic position sizing, leverage, stop-loss, and take-profit parameters. It checks existing positions, closes them if needed, cancels open orders, and sends Telegram notifications. The logic handles ent...
def webhook(request): body_unicode = request.body.decode('utf-8') close_position_delay = 2 create_order_delay = 2 precision = 2 percentage = 0.95 # percentage = 0.1 # preserve prev position exists less than preserve_prev_position_second = 30 req_id = wrap_str(str(uuid.uuid1()).split(...
def GetDRprofile(size,feature_list,pdb_file): if size == 50: # pdb_file = sys.argv[1] DR_profile = Get_list_distanceDistrbution(feature_list) return DR_profile,feature_list if size == 30: # pdb_file = sys.argv[1] feature_list = Get_feature_points(pdb_file, mode = 30) ...
The function `SK` generates a similarity kernel (SK) between two proteins by processing their structural features. It computes DR profiles from PDB files using specified features, converts them to iDR profiles, averages them (with K-dependent parameters), and combines them via `SK_prepare`. Different K values (30, 50, ...
def SK(K,pdb_file1,pdb_file2,feature_list_1,feature_list_2): if K == 30: DR_profile1 = GetDRprofile(30,feature_list_1,pdb_file1)[0] iDR_profile1 = ByDRprofileGetiDRprofile(DR_profile1,90) iDR_profile1 = averageList(length = 4, list = iDR_profile1) DR_profile2 = GetDRprofile...
def initialization_parameters(): parser = argparse.ArgumentParser() parser.add_argument('-pdb1', type=str, required=True, help='input file, it is a pdb file.') parser.add_argument('-pdb2', type=str, required=True, help='input file, it is a pdb file.') par...
The code compares two protein structures by calculating their SRMS (Structural RMS) score. It extracts feature points from each PDB file, computes the score, and prints the result. A score above 0.8 indicates high structural similarity. The function returns the base names of the input files and their SRMS score. Your r...
def main(): args = initialization_parameters() pdb_file1 = args.pdb1 pdb_file2 = args.pdb2 preName1 = pdb_file1.split('/')[-1].split('.')[0] preName2 = pdb_file2.split('/')[-1].split('.')[0] feature_list_1 = Get_feature_points(pdb_file1, mode = 50) feature_list_2 = Get_feature_points(p...
def reconnect(self): print("reconecting") try: serialInst.close() time.sleep(2) self.ArduinoState = False for entry in self.settings.list: entry.isActive = False self.connect() except Exception as e: print(e)...
The code continuously monitors and updates the serial port settings, reconnects if changed, reads serial data, and periodically checks active windows every second when the Arduino is active, ensuring real-time data handling and state management.
def inputLoop(self): lastTime = time.time() while True: time.sleep(0.01) if not self.port is self.settings.port: self.port = self.settings.port self.reconnect() self.readSerial() if time.time() - lastTime > 1: ...
def typing(text, color, inline=False, speed=0): """ Simulate typing effect for displaying text. Args: text (str): The text to be displayed. color (str): The color of the text. inline (bool, optional): Whether to display the text inline without a new line. Defaults to False. ...
The code's main task is to initiate a game by selecting a category and a random word from that category, then prompting the user to guess the word. It displays a welcome message, retrieves the category and word, and passes them to the 'guess' function for gameplay.
def play(user_name): """ Start the game and handle the gameplay. Args: user_name (str): The name of the user. Returns: None """ typing(( f"You choosed to play. Good luck {user_name}!" ), "yellow", False, SLOW) category, str_category = category_picker() ...
def cprint(text, color): """ Print colored text using ANSI escape codes for background colors. Args: text (str): The text to be printed. color (str): The background color to be used. Supported colors are 'black', 'red', 'green', 'yellow', 'blue', 'magenta', ...
The main task of the code is to display a menu with options for a user to choose from, handle their input, and execute corresponding actions like viewing game rules, starting the game, or exiting. It validates input to ensure it's a number between 1-3, provides feedback for invalid choices, and includes an exit confirm...
def menu(user_name): """ Display the menu options and handle user input. Args: user_name (str): The name of the user. Returns: None """ while True: cprint(menu_text, "cyan") # Giving space to input print("\n") choose = input(typing(( ...
def cprint(text, color): """ Print colored text using ANSI escape codes for background colors. Args: text (str): The text to be printed. color (str): The background color to be used. Supported colors are 'black', 'red', 'green', 'yellow', 'blue', 'magenta', ...
The main task of the code is to execute the HANGMAN game's initialization process by displaying the logo and welcome message, collecting the user's name and age, and presenting the game menu to start the gameplay.
def main(): """ Executes the main logic of the HANGMAN game. This function displays the game's logo, welcomes the user to the HANGMAN game,prompts the user to enter their name, retrieves the user's age, and displays the game menu. """ cprint(logo, "magenta") typing("Welcome to HANGMA...
def ffs(x): if x == 0: return None return (x & ~x).bit_length()() - 1 def bucket_head_remove(buckets): buckets[min(buckets.keys())].queue.popleft() def bucket_insert(flow, g): return def compute_group_state(g): s = ER if g.s <= V else EB x = ffs_from(set[ER], g.id) s = s + IB if x !=...
This function dequeues a packet from a flow in a group, updates scheduling parameters (s/f values), manages group states (IDLE/active), adjusts eligibility tracking (ER/IB bits), and ensures proper flow bucket reinsertion and group unblocking for ongoing processing. It returns the dequeued packet while maintaining sche...
def packet_deque(): global V if set[ER] == 0: return g = groups[ffs(set[ER])] flow = bucket_head_remove(g.buckets) packet = flow.queue.popleft() flow.s = flow.f if len(flow.queue) != 0: p = flow.queue[0] flow.f = flow.s + p.length / flow.weight bucket_insert(...
def gen_key(q): key = random.randint(1, q) while gcd(q, key) != 1: key = random.randint(1, q) return key def power(a, b, c): x = 1 y = a while b > 0: if b % 2 != 0: x = (x * y) % c y = (y * y) % c b = int(b / 2) return x % c def get_string_from_...
This code sets up a server using sockets to perform a Diffie-Hellman key exchange with a client. It generates a prime number (q), a random base (g), and computes a public key (h) using a private key. The server sends these values to the client, receives encrypted messages and a parameter (p), then decrypts the message ...
def main(): host = socket.gethostname() port = 5000 server_socket = socket.socket() server_socket.bind((host, port)) server_socket.listen(2) print("Server is listening") conn, address = server_socket.accept() print("Connection from: " + str(address)) q = int(input("Enter the value o...
def web_wipe(): """Removes the photo data from the website front-end. Note this does not delete the photo_frame JSON save, only images currently in the website. """ #Deleting id_table.json try: remove(str(p_table.absolute())) except FileNotFoundError: print('id_table.js does n...
The main task of the code is to update local website front-end files with data derived from a photo_frame object, including generating ID tables, location data dumps, JavaScript files, and JSON structures to reflect the frame's information.
def web_drop(frame): """Takes a photo_frame object and updates the local website front-end files accordingly. """ web_wipe() im_id = get_id(frame) id_tbl_dump(frame, im_id) toloc_js_dump(frame) latlon_data = get_latlon_data(frame,im_id) lat_lon_dump(latlon_data) id_co_dump(fra...
def log(self, message: str): """Log a message""" if self._verbose: print(message) def run_code( self, code: str, data_frame: pd.DataFrame, use_error_correction_framework: bool = True, ) -> str: """ A method to execute the python code genera...
The code's main task is to make DataFrames conversational by using an LLM to generate and execute Python code based on user prompts. It handles multiple DataFrames, anonymizes data, caches results, and applies error correction. The function returns answers, optionally in conversational format, while processing middlewa...
def run( self, data_frame: pd.DataFrame, prompt: str, is_conversational_answer: bool = None, show_code: bool = False, anonymize_df: bool = True, use_error_correction_framework: bool = True, ) -> Union[str, pd.DataFrame]: """ Run the PandasAI to...
def start_UDP(senderPort:int)->socket.socket: """ Create a UDP socket and bind it to the specified port Args: senderPort (int): port number of the sender Returns: socket.socket: UDP socket """ clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Create a UDP socket...
The main task of the code is to initiate and manage a UDP-based transaction by sending a payload file in dynamically adjusted data chunks. It reads the payload, establishes a UDP connection, negotiates a transaction ID, and transmits data while adapting chunk sizes based on processing times and timeouts. The code logs ...
def startTransaction(receiverIP, receiverPort, senderID,senderPort, payloadName): """ Start a new transaction Args: - receiverIP (str): IP address of the receiver - receiverPort (int): port number of the receiver - senderID (str): unique ID of the sender - senderPort (int): ...
def initialize_session(): ''' Initializes a new session by creating a new log file and prompting the user to enter the path to the ecosystems directory. Rteturns a dictionary containing the ecosystem name, the mapping of ecosystem titles to TOML file paths, and the snapshot of the repos already in oss direc...
The main task of the code is to orchestrate the processing of ecosystems, projects, and collections by either converting TOML files to JSON or generating YAML collection files based on user input. It initializes a session, queries user decisions, processes project data, and creates a collection YAML file with specified...
def main(version=SCHEMA_VERSION): ''' Main function that orchestrates the processing of ecosystems, projects, and collections. ''' # Initialize a new session session = initialize_session() ecosystem_name = session['ecosystem_name'] # Determine whether to process the collection or generate ...
def get_slug(): while True: print("Enter a slug or 'q' to quit:") slug = input().strip() if slug == "": print("Slug cannot be blank. Please enter again.") continue elif slug == "q": return None else: return slug def get...
The main task of the code is to repeatedly process slugs by either updating existing YAML files (if the corresponding path exists) or generating new YAML files (if the path does not exist), continuing until no more slugs are available or an error occurs. It handles batch updates/creations of project data in YAML format...
def batch_add_or_update(): while True: slug = get_slug() if slug is None: break path = get_path(slug) if os.path.exists(path): success = update_yaml_file(slug) if success: print(f"Project with slug '{slug}' updated successfully.") ...
def get_artifact(entry=None): if entry is None: print("Enter an artifact followed by a type:") entry = input() if not entry or ',' not in entry: return None artifact, artifact_type = entry.split(",")[0:2] if 'github' in artifact_type: artifact = "https://github.co...
The code processes a CSV file to update or create YAML configurations based on artifact data, filtering by workflow type. It groups artifacts by 'slug', skips GitHub entries, and prompts user confirmation for each update. If the target path exists, it updates the YAML; otherwise, it would generate a new one (though thi...
def bulk_update(csv_path, workflow_type): updates = {} with open(csv_path, 'r') as stream: csv_data = csv.DictReader(stream) for row in csv_data: slug = row['slug'] if slug == '': continue if row['workflow'] != workflow_type: c...
def get_sorted_uncollapsed_tiles(): return [x for x in get_tiles_sorted_by_entropy() if len(tile_at_pos(x)) >= 2] def tile_at_pos(pos): return grid[pos[0]][pos[1]] def propogate(pos): # Tiles to be propogated stack = [pos] while len(stack) > 0: tile = stack.pop() neighbors ...
The function `iterate()` performs one iteration of the Wave Function Collapse (WFC) algorithm. It selects a low-entropy, uncollapsed tile at random, assigns it a random valid state, and collapses it into the grid. It then recursively propagates this collapse to neighboring tiles to enforce consistency. If propagation f...
def iterate(): global iter_count iter_count += 1 print(f"\nBeginning WFC Iteration #{iter_count}.\n") # Step 1: Collapse random uncollapsed tile tiles = get_sorted_uncollapsed_tiles() # Tiles with the lowest possible states, but they must be uncollapsed low_entropy_tiles = [x for x in tiles...
def _evict_items(self): while len(self.key_index) >= self.max_items: self._evict_item() def _delete_item(self, item): # Remove from priority index self.priority_index[item.priority].remove((item.access_time, item)) if len(self.priority_index[item.priority]) == 0: del self.priority_index[item.priority] ...
This method inserts or updates a key-value pair in a priority-based cache. It evicts items if the cache is full, updates existing entries by removing and re-adding them, and stores the item in key-indexed, priority-indexed, and expiry-indexed structures for efficient retrieval and management.
def set(self, key, value, priority=1, expiry=sys.maxsize): if len(self) >= self.max_items: self._evict_items() if key in self.key_index: existing_item = self.key_index[key] self._delete_item(existing_item) self.set(key, value, priority=priority, expiry=expiry) return item = Item(key, value, prior...
def _base(self): return self.BASE_PROMPT.format( tools_str = self._make_tools_str(self.tools), final_goal = self.final_goal, current_tasks = self.current_tasks, final_result = self.final_result, stored_info=self.stored_info ) def load_json(self...
This method processes a completed task's result by updating the system's state, using an LLM to determine next steps. It checks if the goal is achieved, updates stored information, final results, and remaining tasks, and persists changes if enabled. It returns True when the goal is met.
def refine(self, task_name: str, task_result: str): """ Use this after a task has been completed. This will update the current_tasks, final_result, stored_info, and completed_tasks - saving if persist is set. Uses base prompt plus `self.REFINE_PROMPT`. Returns True if goal has been met. :param ...
def _base(self): return self.BASE_PROMPT.format( tools_str = self._make_tools_str(self.tools), final_goal = self.final_goal, current_tasks = self.current_tasks, final_result = self.final_result, stored_info=self.stored_info ) def load_json(self...
This function checks if a goal is completed by querying a language model (LLM) with a prompt. It updates final results, adds new tasks, and triggers completion logic if the LLM confirms the goal is done. If completed, it logs the result, calls a completion handler, resets tasks, and returns True. Otherwise, it returns ...
def ensure_goal_complete(self): prompt = self._base() + self.ENSURE_COMPLETE_PROMPT resp = self.llm(prompt) res = self.load_json(resp) if (final_result := res.get('final_result')): if self.verbose: self.output_func(f'[system] new final result: {final_result}'...