dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def __init__(self): going = True while going: amount = input("How many players? (2-4) ") if amount.isdigit(): amount = int(amount) if amount in range(2, 5): going = False else: self.error("Incorrect ...
The main task of the code is to prompt the user to continue or end the game. If the user chooses "Yes," it restarts the game by reinitializing the object; if "No," it ends the game. For invalid inputs, it displays an error message and recursively re-prompts the user for a valid response.
def next_set(self): response = input("Would you like to continue playing? (Yes or No): ") if response.lower()[0] == "y": self.__init__() elif response.lower()[0] == "n": self.end_game() else: self.error("Unexpected response, please try again", self.lin...
def generate_tasks(k): queue = [] for i in range(k): location = [random.randint(0, 100), random.randint(0, 100)] task = Task(distance(location, base_location) + random.randint(-30, 30), location) queue.append(task) return queue def run1(R,queue): print("\n\nAuction Test for Dutch...
The main task of the code is to compare the performance of four auction-based task allocation algorithms (Dutch, SSI, SSI with Hillclimbing, and Comb) in a multi-robot system. It runs 100 iterations, collecting metrics such as task allocation counts, travel distance, execution time, and computational overhead for each ...
def bar_graph_test(R): count = 0 array = [0, 0, 0] array_comb = [0, 0, 0] array2 = [0, 0, 0] time_arr = [] time_arr2 = [] time_arr3= [] iteration_number=[] time_avg = 0 time_avg2 = 0 time_avg3 = 0 time_arr4 = [] array_dutch = [0, 0, 0] time_avg4 = 0 dutch_dist...
def _make_frozen_graph( behavior_name: str, graph: tf.Graph, sess: tf.Session ) -> tf.GraphDef: with graph.as_default(): target_nodes = ",".join(_process_graph(behavior_name, graph)) graph_def = graph.as_graph_def() output_graph_def = graph_util.convert_variables_to_constants( ...
The function exports a TensorFlow policy model into `.nn` (Barracuda) and/or `.onnx` formats for Unity embedding. It freezes the input TensorFlow graph, saves it as a `.pb` file, and converts it to `.nn` if enabled. If ONNX export is allowed, it attempts to convert the frozen graph to `.onnx`, handling errors by loggin...
def export_policy_model( model_path: str, output_filepath: str, behavior_name: str, graph: tf.Graph, sess: tf.Session, ) -> None: """ Exports a TF graph for a Policy to .nn and/or .onnx format for Unity embedding. :param output_filepath: file path to output the model (without file suffi...
def cellLitId(i, j, k): return (i * size + j) * size + k def rowAuxRowLitId(i, j, k): return cellAuxColLitId(size - 1, size - 1, sqrtSize) + (i * size + j) * nofAuxVars + k def rowAuxColLitId(i, j, k): return rowAuxRowLitId(i, j, k) + sqrtSize
This function generates logical clauses to enforce Sudoku-like constraints on a row: "At Least One" (ALO) ensures each number appears at least once in the row, while "At Most One" (AMO) prevents duplicates using auxiliary variables. It constructs clauses for rows, columns, and subgrids to ensure valid placements, linki...
def rowConstraint(i): clauses = [] ################################### # ALO clauses for k in range(1, size + 1): atLeastOne = [] for j in range(size): litId = cellLitId(i, j, k) atLeastOne.append(litId) clauses.append(atLeastOne) ################################### #################...
def cellLitId(i, j, k): return (i * size + j) * size + k def colAuxRowLitId(i, j, k): return rowAuxColLitId(size - 1, size - 1, sqrtSize) + (i * size + j) * nofAuxVars + k def colAuxColLitId(i, j, k): return colAuxRowLitId(i, j, k) + sqrtSize
The function generates clauses to enforce constraints on a column in a grid-based puzzle (like Sudoku). It creates "At Least One" clauses to ensure each group has all required values and "At Most One" clauses to prevent duplicates in subgrid rows/columns. Auxiliary variables link cell assignments to subgrid constraints...
def colConstraint(j): clauses = [] ################################### # ALO clauses for k in range(1, size + 1): atLeastOne = [] for i in range(size): litId = cellLitId(i, j, k) atLeastOne.append(litId) clauses.append(atLeastOne) ################################### #################...
def parse(): parser = argparse.ArgumentParser(description = 'Train neural network') parser.add_argument('--data_directory', default="flowers", help = 'data directory is required!') parser.add_argument('--save_dir', help = 'directory needed to save a neural network') parser.add_argument('--arch', help = ...
The main task of the code is to initialize a pre-trained VGG16 image classifier model, configure it for a specified dataset, and prepare it for training or evaluation. It loads the model, processes command-line arguments, sets up the device (CPU/GPU), applies data transformations, adjusts the model structure, and moves...
def main(): model = models.vgg16(pretrained = True) model.name = "vgg16" print("Image classifier is being created!") global args args = parse() device = torch.device("cuda" if torch.cuda.is_available() else "cpu") train_dir = args.data_directory + '/train' train_data = train_tr...
def welcome_menu(self, error=False): error_text = 'Invalid Selection\n' if error else '' message = '{}\nWelcome To Chekkit\n\n1.Verify Product\n2.Exit'.format(error_text) return self.process_response(message=message, response_type=RESPONSE, client_state=VERIFY_PRODUCT_MENU) def verify_product_me...
This method determines the appropriate response based on the request type and stage. If the response type is INITIATION, it returns a welcome menu. For RESPONSE type, it routes to specific handlers like product verification, complaints, or location input depending on the stage.
def process_request(self): if self.response_type == INITIATION: return self.welcome_menu() elif self.response_type == RESPONSE: if self.stage == VERIFY_PRODUCT_MENU: return self.verify_product_menu() elif self.stage == VERIFY_PRODUCT: ...
def getPlayedHands(cards): # Break the hand in the individual hands bottomCards = sorted(cards[:5], key=lambda card: card[0], reverse=True) middleCards = sorted(cards[5:10], key=lambda card: card[0], reverse=True) topCards = sorted(cards[10:], key=lambda card: card[0], reverse=True) # Score the thr...
The function calculates scores for two players based on their card hands. It checks hand validity, compares layers (bottom, middle, top) to determine point advantages, applies bonuses for winning all layers, and computes total points by combining layer results with individual hand values. Invalid hands yield penalties,...
def getPoints2Players(player1Cards, player2Cards): # Get the played hands for both players p1Hands = getPlayedHands(player1Cards) p2Hands = getPlayedHands(player2Cards) # Check if the hands are valid p1ValidHands = areValidHands(p1Hands) p2ValidHands = areValidHands(p2Hands) # Check higher...
def compareItems(a, b): global count count += 1 # increment return a < b def mergeSort(arr, l, r): if l < r: m = l + (r - l) // 2 mergeSort(arr, l, m) mergeSort(arr, m + 1, r) merge(arr, l, m, r) def genJacobsthal(n): return (2 ** n - (-1) ** n) // 3 def binarySearch...
The code implements a hybrid sorting algorithm combining insertion sort and merge sort. It first sorts adjacent pairs, creates Pair objects, sorts them via merge sort, then merges pend elements into the main chain using Jacobsthal numbers and binary search for efficient insertion.
def mergeInsertionSort(arr): # sort pairs in-place for i in range(0, len(arr) - 1, 2): if compareItems(arr[i + 1], arr[i]): # swap if necessary arr[i], arr[i + 1] = arr[i + 1], arr[i] # create Pair objects pairs = [] for i in range(0, len(arr) - 1, 2): pairs.append(Pair(...
def compareItems(a, b): global count count += 1 # increment return a < b def mergeSort(arr, l, r): if l < r: m = l + (r - l) // 2 mergeSort(arr, l, m) mergeSort(arr, m + 1, r) merge(arr, l, m, r) def genJacobsthal(n): return (2 ** n - (-1) ** n) // 3 def binarySearch...
The main task of the code is to sort an array using a hybrid approach combining insertion sort for adjacent pairs, merge sort for pair-based ordering, and Jacobsthal-guided insertion of remaining elements. It first sorts pairs in-place, creates and sorts pairs by their large values, then inserts smaller values into the...
def mergeInsertionSort(arr): # sort pairs in-place for i in range(0, len(arr) - 1, 2): if compareItems(arr[i + 1], arr[i]): # swap if necessary arr[i], arr[i + 1] = arr[i + 1], arr[i] # create Pair objects pairs = [] for i in range(0, len(arr) - 1, 2): pairs.append(Pair(...
def run_releases(self, releases: List[str], from_environment: str, target_environment: str) -> List[ReleaseConfig]: """ Runs a list of releases associated to a specific deployment and environment. If it can't find the release it assumes its not available for that environment...
The main task of the code is to sequentially execute deployments to rebuild an environment. It checks each deployment's status, runs incomplete ones by processing releases, waits for their completion, marks them as done, saves progress, and logs completion. Finally, it performs cleanup after all deployments are process...
def run_deployments(self): """ Rebuilds the environment by running group of deployments. Once a deployment has been completed its state is saved and the next deployment is run. """ for deployment in self.deployments: if not deployment.complete: ...
def calcCorrectness(data): for index, row in data.iterrows(): RT = calculate_RT(row) # This function needs to be defined based on textual accuracy criteria RIT = calculate_RIT(row) # Already defined to assess image-text consistency and color detection # Calculate the overall Correctness Score for each ...
The code calculates three quality scores (correctness, completeness, compliance) for each entry in the input dataset using separate functions. It combines these into a DataFrame, sums them to generate a total score per entry, and returns a new DataFrame containing these total scores. The total score is the direct sum o...
def main(data): # csv_file_path = 'product_dataset(1).csv' # data = pd.read_csv(csv_file_path, delimiter=',') correctness_scores = calcCorrectness(data) completeness_scores = calcCompleteness(data) compliance_scores = calcCompliance(data) scores = pd.DataFrame({'Correctness Score': correctness_...
def pet_asleep(pet): print(sleep, f'\n{pet["name"]} is sleeping. You will need to wake {pet["name"]} up first.') def press_enter(): input('\nPress enter to continue.') def walking(pet): pet['weight'] -= 0.5 for x in range(3): print('\nWalking...') time.sleep(1) pet['xp'] += pet['...
The code simulates taking a pet for a walk, handling bathroom needs, and granting XP. It checks if the pet is asleep, then either lets the pet rest or proceeds with the walk. If the pet needs to pee/poop, it processes this, awards XP, and continues. Otherwise, it collects loot and lets the user decide to keep walking o...
def walk(pet): if pet['sleep']: pet_asleep() press_enter() else: print(f'\nTaking {pet["name"]} for a walk.') press_enter() if pet['pee'] or pet['poop']: walking(pet) print(f'\n{pet["name"]} is stopping to use the bathroom.') ...
def _advance(self): self.current += 1 return self.source[self.current - 1] def _add_token(self, ttype, literal=None): self.tokens.append(Token( ttype, self.source[self.start:self.current], literal, self.line )) def _match(self, expected_cha...
This method scans and tokenizes individual characters into their corresponding token types, handling symbols, operators, comments, strings, numbers, and identifiers. It processes each character, adds appropriate tokens, skips whitespace, increments line counts for newlines, and reports errors for unexpected characters....
def _scan_token(self): c = self._advance() if c == '(': self._add_token(TokenType.LEFT_PAREN) elif c == ')': self._add_token(TokenType.RIGHT_PAREN) elif c == '{': self._add_token(TokenType.LEFT_BRACE) elif c == '}': self._add_token...
def __filter_current_page(page, record): page = str(page) cleaned_data = {'activity': []} url = 'https://scistarter.org/api/stream-page?page='+page+'&key=5255cf33e739e9ecc20b9b260cb68567fbc81f6b1bfb4808ba2c39548501f0a1523e2e97d79563645cba40a09894bfdb277779d1145a596f237ebdc166afcf50' content = __getPage(...
The main task of the code is to update records by filtering and processing activity data from multiple pages. It extracts relevant clicks from a stream, updates data if activity exists, iterates through pages to fetch and process data, and finally saves historical records to a pickle file and a CSV matrix while updatin...
def update_records(): global page global record print('filter current page') cleaned = __filter_current_page(page, record) cut_unrelevant_clicks() extract_clicks() # from click stream if len(cleaned['activity']) != 0: _update_data(cleaned) while True: page = int(page) +...
def welcome_message(): print( "Welcome to the \"Hoped Programm\" where you can begin to earn money in juste a few days ! All you need to do" " is recruit other persons.") def begin_menu(): print("1. Register") print("2. Login") print("3. Quit") choice = input("Your choice : ") wh...
The main task of the code is to manage a user session loop, starting with a welcome message, then repeatedly checking for a valid token. If the token is empty, it displays a beginning menu. Once a token is obtained, it fetches an invitation code and current balance, then presents a logged-in menu. The loop persists ind...
def main_loop(): welcome_message() while True: global token while token == "": begin_menu() global invitation_code invitation_code = get_invite_code() global current_balance current_balance = get_current_balance() logged_menu()
def is_expired(self, ref, type, subtype, extra, delay) -> bool: try: store = Store.objects.get(ref=ref, type=type, subtype=subtype, extra=extra) return store.is_expired(delay) except Store.DoesNotExist: return True def get_or_create_language(self, code='en', name='Eng...
The main task of the code is to retrieve and store word-related data (pronunciations, audios, definitions, examples, relations) from the Wordnik API for a given word. It checks for data expiration, fetches fresh data if needed, stores it in a data lake, updates the word reference object, and handles API limits or error...
def get_word_by_wordnik(self, source, target, word, word_ref): error_pronunciations, pronunciations = True, None error_audios, audios = True, None error_definitions, definitions = True, None error_examples, examples = True, None error_relations, relations = True, None i...
def apply(self, test: Test, inputs: dict[int, Input]) -> str: """ Apply to the test the inputs. Args: test (Test): the test to mutate inputs (list[Input]): the inputs to mutate Returns: str: the mutated test content """ ...
The main task of the code is to perform a single round of mutation on a fuzzed test by checking if it's interesting and safe without mutation, then applying strategies to mutate inputs, reducing the test, and returning the first successful mutation that produces an interesting and ASAN-safe result.
def _single_mutation(self, fuzzed_test: FuzzedTest): """ Perform a single round of mutation on a file. """ # check without mutation if the test is interesting try: no_mut = self.compiler.compile_test((fuzzed_test.test, self.apply(fuzzed_test.test, fuzzed_test...
def apply_Pinv(params, c): ''' Apply the precondition matrix to the left/right hand side :param params: class params initialized in diffusion_brain_net.py :param c: current concentration c(x, t) :return: left/right hand side of discretized PDE. ''' N = params.N dt = params.dt c = c.reshape((N,N,N)...
The function solves a diffusion PDE using anisotropic coefficients derived from tissue types (white/grey matter), applying conjugate gradient (CG) at each time step to simulate diffusion in a 3D brain mesh. It initializes concentration values for a specified ROI, enforces non-negativity and threshold constraints, accum...
def solve_forward_cg(params, roi_id, subj_name): ''' Solve the diffusion PDE utilizing all functions mentioned above. :param params: class params initialized in diffusion_brain_net.py :param roi_id: id of region of interest :return: class params with PDE solution referred as params.c1 ''' T = params.T ...
def apply_Pinv(params, c): ''' Apply the precondition matrix to the left/right hand side :param params: class params initialized in BrainDiffusion_cpu.py :param c: current concentration c(x, t) :return: left/right hand side of discretized PDE. ''' N = params.N dt = params.dt c = c.res...
The function solves a time-dependent anisotropic diffusion PDE using the conjugate gradient (CG) method, computing diffusion coefficients from tissue-specific parameters, initializing concentration values, and iteratively solving the PDE over time steps. It accumulates the solution, applies a Gaussian filter, and store...
def solve_forward_cg(params, roi_id, subj_name): ''' Solve the diffusion PDE utilizing all functions mentioned above. :param params: class params initialized in BrainDiffusion_cpu.py :param roi_id: id of region of interest :return: class params with PDE solution referred as params.c1 ''' T = ...
def X_mask(params, roi_id): Xmask = cp.zeros(params.wm.shape) Xmask[params.labels == roi_id] = 1 Xmask = gaussian_filter(Xmask, params.gm_sigma) # Xmask = weierstrass_smoother(Xmask, params.N, params.sm_sigma) params.Xmask = Xmask.copy() return params def applyA_lhs(params, c): #div = cp.fft....
The code solves a linear system using the conjugate gradient method (CG) for a specific region of interest (ROI) in a 3D image. It initializes parameters, applies masking, computes a smoothed initial guess, sets up a linear operator, and solves the system to obtain a reconstructed image (c). The result is smoothed and ...
def solve_forward_cg(params, roi_id): N = params.N wm = params.wm_ref.copy() gm = params.gm_ref.copy() params.k_gm_wm = 0.0001 params.T_par = params.T_par * params.kappa * cupy.expand_dims(wm + params.k_gm_wm * gm, axis=(3, 4)) params.T_orth = params.T_orth * params.kappa * cupy.expand_dims(wm + param...
def get_transaction(address, chain="eth"): return web3_client(chain).eth.get_transaction(HexBytes(address)) def web3_client(chain="eth", provider="http"): if provider and provider == "websocket": return Web3(Web3.WebsocketProvider(CHAIN_WEBSOCKET_ENDPOINTS[chain])) return Web3(Web3.HTTPProvider(CHAI...
The code decodes a blockchain transaction's function call and parameters. It retrieves transaction data, identifies the target contract, and uses the contract's ABI to decode the input data, returning the function object and arguments. If decoding fails, it logs the error and re-raises the exception.
def decode_contract_transaction(transaction_address, chain="eth"): transaction = web3_client(chain).eth.get_transaction(HexBytes(transaction_address)) contract_address = transaction.get('to') print(f"decoding transaction. hash: {transaction_address} | contract: {contract_address}") contract = get_cont...
def web3_client(chain="eth", provider="http"): if provider and provider == "websocket": return Web3(Web3.WebsocketProvider(CHAIN_WEBSOCKET_ENDPOINTS[chain])) return Web3(Web3.HTTPProvider(CHAIN_ENDPOINTS[chain])) def checksum_address(address, chain="eth"): return web3_client(chain).toChecksumAddress...
The code retrieves blockchain events (e.g., 'Transfer') from a specified contract within a block range, applying filters like token ID, topics, and chain. It constructs an event filter using the contract's ABI, queries logs via `eth_getLogs`, and returns parsed event data as a list.
def get_events(contract_address, event_name='Transfer', token_id=None, start_block=0, end_block="latest", chain="eth", topics=None): codec = web3_client(chain).codec contract_address = checksum_address(contract_address) contract = get_contract(contract_address) event_abi = find_matching_e...
def web3_client(chain="eth", provider="http"): if provider and provider == "websocket": return Web3(Web3.WebsocketProvider(CHAIN_WEBSOCKET_ENDPOINTS[chain])) return Web3(Web3.HTTPProvider(CHAIN_ENDPOINTS[chain])) def checksum_address(address, chain="eth"): return web3_client(chain).toChecksumAddress...
The function extracts and decodes specific event data from a transaction receipt using a given contract address and event name. It processes each log in the receipt, attempts to decode it with the contract's ABI and specified event, and collects valid events into a list. Exceptions during decoding are caught, allowing ...
def get_receipt_events(transaction_receipt, contract_address, event_name='Transfer', chain="eth"): codec = web3_client(chain).codec contract_address = checksum_address(contract_address) contract = get_contract(contract_address) event_abi = find_matching_event_abi(contract.abi, event_name) logs = tr...
def homie_publish_area(self): self.homie_publish_property( node_id="area", property_id="areaid", datatype="string", value=self.area_id, ) self.homie_publish_property( node_id="area", property_id="areaname", datat...
The main task of the code is to publish multiple data components (area, API, status) via the `homie_publish_*` methods and record the current timestamp. The function sequentially calls `homie_publish_area()`, `homie_publish_api()`, and `homie_publish_status()`, while `self.homie_publish_all_time` captures the execution...
def homie_publish_all(self, init=False): self.homie_publish_area() self.homie_publish_api() # self.homie_publish_events() self.homie_publish_status() self.homie_publish_all_time = datetime.now(timezone(TIMEZONE))
def homie_init_device(self): topic = "{}/{}/{}".format(HOMIE_BASE_TOPIC, HOMIE_DEVICE_ID, "$homie") self.homie_publish(topic, HOMIE_DEVICE_VERSION) topic = "{}/{}/{}".format(HOMIE_BASE_TOPIC, HOMIE_DEVICE_ID, "$name") self.homie_publish(topic, HOMIE_DEVICE_NAME) self.homie_publis...
The code initializes a Homie device by configuring its device, area, API, and status components. It marks the device as "ready," records the initialization timestamp, and disables further initialization.
def homie_init(self): # device to init self.homie_init_device() self.homie_init_area() self.homie_init_api() self.homie_init_status() # self.homie_init_events() # device ready self.homie_publish_device_state("ready") self.homie_init_time = datetim...
def homie_init(self): # device to init self.homie_init_device() self.homie_init_area() self.homie_init_api() self.homie_init_status() # self.homie_init_events() # device ready self.homie_publish_device_state("ready") self.homie_init_time = datetim...
The main task of the code is to periodically check time-based conditions and trigger actions such as initializing Homie, updating loadshedding status, retrieving API data, and publishing updates. It runs an infinite loop with 5-second intervals, executing specific methods when predefined timestamps are exceeded, ensuri...
def main_loop(self): """Wait for and then process messages.""" while True: sleep(5) now = datetime.now(timezone(TIMEZONE)) if self.do_homie_init or now > self.homie_init_time + timedelta(seconds=HOMIE_INIT_SECONDS): self.homie_init() elif n...
def run_gsea_human_analysis(gsea_all_gene_set_json_bundle_path): print('Running GSEA human analysis') with open(gsea_all_gene_set_json_bundle_path, "r") as f: data = json.load(f) keys = list(data.keys()) genes = {} for k in keys: genes[k] = data[k]['geneSymbols'] genes = list(g...
The main task of the code is to execute Gene Set Enrichment Analysis (GSEA) on human data using a specified JSON file, convert the raw results into a structured DataFrame, and export the processed results to an Excel spreadsheet for further analysis or reporting.
def main(): gsea_json_path = "assets/msigdb.v2023.1.Hs.json" results = run_gsea_human_analysis(gsea_json_path) parsed_results_df = raw_results_to_df(results, start=0, end=None) dump_results_to_excel(results, excel_name="results.xlsx", start=0, end=None)
def _create_binary_chromosomes_map(self, gene_group_size=None): if self.experiment_chromosomes is None: self.generate_reduced_chromosomes(self.get_genes_names()) genome_main = utils.create_chromosomes_dict(self.experiment_chromosomes) binary_map = [] symbols = self.get_genes...
This function identifies statistically enriched genomic intervals by calculating IMHG scores and p-values for each chromosome. It processes binary chromosome maps, filters significant intervals based on a threshold, and saves results if specified. The task involves statistical analysis of gene group distributions to de...
def find_enriched_intervals(self, gene_group_size, verbose=True, ignore_errors=True, save_to_file=True, include_group_size_in_chromosome=True): if verbose: print("Using {} genes".format(gene_group_size)) enriched_intervals = ExperimentResults(self.experiment_...
def check_for_images(using_windows): """ Copies over the images folder if any of the images are not found """ image_names = [ 'images/new_preset.png', 'images/save_preset.png', 'images/delete_preset.png', 'images/up_arrow.png', 'images/down_arrow.png', 'images/cancel.png', 'images/add.png', 'im...
The code creates a GUI for a backup tool, allowing users to manage presets, select backup locations, run backups, and adjust settings. It loads presets, displays folders, handles user interactions for adding/removing backups, and executes backup operations with options for file deletion handling. The interface includes...
def show_gui(using_windows): """ Shows the main GUI """ main.presets = saving.load_presets() preset_keys = [] for key in main.presets: preset_keys.append(str(key)) BAR_MAX = 1 gui.theme('DarkGrey') gui.theme_button_color('#7A7A7A') h1_font = ("Arial Bold", 12) h2_font = ("...
def run_file(argument1): os.system(f"start {argument1}") text(f"$>>started {argument1}", 'none') def start_selenium(argument1): global line print('reached new thread') try: text("$>>Threading started", 'none') threading.Thread(target=selenium(argument1)).start() ...
The code defines a function `sort_commands()` that processes user commands by checking the value of the `command` variable and executing corresponding actions. It handles commands like "file", "slm", "help", "c", "s", and "sl", each triggering specific functions (e.g., `run_file()`, `start_selenium()`, `chrome()`). It ...
def sort_commands(): global line print(f"\n-----------COMMAND----------:\n{command}\n----------------------") if command == "file": print("sorted") run_file(argument1) elif command == "slm": start_selenium(argument1) elif command == "help": help() elif com...
def month_day_today(): return datetime.date.today().strftime('%B %-d') def read_last_good_month_day(client, bucket_name): try: response = client.get_object(Bucket=bucket_name, Key=BUCKET_KEY) return response['Body'].read().decode('utf-8') except client.exceptions.NoSuchKey as e: retu...
The function checks if today is a "good day" (via `has_mocha_chip_today()`). If so and if no prior notification exists for the current month/day in an S3 bucket, it sends an SNS message to the specified topic, logs the action, and updates the S3 bucket with the current date. Otherwise, it returns False. The task combin...
def notify_if_good_month_day(topic_arn, bucket_name, message='mocha chip! <3'): month_day = month_day_today() session = boto3.Session() s3 = session.client('s3') LOGGER.info('reading last good day from {}'.format(bucket_name)) if read_last_good_month_day(s3, bucket_name) != month_day: if h...
def make_blank(self, image: Image) -> Image: white = (255, 255, 255) draw = ImageDraw.Draw(image) draw.rectangle( [(0, 0), image.size], fill=white ) return image def get_situations_keys(self, size: str) -> dict: resources = Data.get_situations() ...
The main task of the code is to add a specified number of cards to an image based on given size and orientation parameters. It rotates the image if the orientation doesn't match the size's default, clears the image, then overlays cards using predefined resources, cycling through them as needed. The result is an image w...
def add_cards(self, image: Image, size: str, orientation: str) -> Image: if (self.size_to_orientation_map[size] != orientation): image = self.rotate_image_90(image) image = self.make_blank(image) cards_count = self.size_to_cards_number_map[size] resources_keys = self.get_sit...
def make_blank(self, image: Image) -> Image: white = (255, 255, 255) draw = ImageDraw.Draw(image) draw.rectangle( [(0, 0), image.size], fill=white ) return image def get_technologies_keys(self, size: str) -> dict: resources = Data.get_technologies(...
This function adds a specified number of cards to an image, adjusting orientation if necessary. It prepares a blank canvas, then iterates to add cards using technology keys, cycling through them if needed.
def add_cards(self, image: Image, size: str, orientation: str) -> Image: if (self.size_to_orientation_map[size] != orientation): image = self.rotate_image_90(image) image = self.make_blank(image) cards_count = self.size_to_cards_number_map[size] resources_keys = self.get_tec...
def get_relations_keys(self) -> list: return list(Data.get_relations().keys()) def add_card_to_image(self, image: Image, size: str, index: int, relation_key: str) -> Image: x, y = self.card_manager.get_coordinates_a8(index) image = self.insert_card(image, x, y, relation_key, index) retur...
The main task of the code is to add cards to an image based on specified size and orientation, adjusting the image rotation, generating a card layout with repeated relations keys, and then appending recipient cards in reversed order while applying 180-degree rotation. It manages card placement, orientation alignment, a...
def add_cards(self, image: Image, size: str, orientation: str) -> Image: if (self.card_manager.size_to_orientation_map[size] != orientation): image = self.card_manager.rotate_image_90(image) image = self.card_manager.make_blank(image) cards_count = self.card_manager.size_to_cards_nu...
def _collate_scalar(batch, field): "Collate scalars by concatting." if field == 'abstract_id': return torch.tensor([int(x[field]) for x in batch]) else: return torch.tensor([x[field] for x in batch]) def _pad_tokenized(self, tokenized): """ Pad the tokeniz...
The code's main task is to collate a batch of data into padded tensors for model input. It aggregates scalar values, pads tokenized text and fields like 'abstract_sent_idx' and 'rationale', and ensures consistent keys across the batch. The result is a structured dictionary containing claim/abstract IDs, tokenized text,...
def __call__(self, batch): # it is called when an instance of SciFactCollator is invoked as a function. # # Create an instance of SciFactCollator: collator = SciFactCollator() "Collate all the data together into padded batch tensors." # NOTE(dwadden) Set missing values to 0 for `abstract...
def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def generate_keys(p, q): # Calculate n ...
The code implements RSA encryption by taking two prime numbers to generate public and private keys, encrypting a user-input message with the public key, and decrypting it with the private key. It validates prime inputs, demonstrates key generation, encryption, and decryption processes.
def main(): p = int(input("Enter first prime number (p): ")) q = int(input("Enter second prime number (q): ")) if not is_prime(p) or not is_prime(q): print("Both numbers must be prime.") return public_key, private_key = generate_keys(p, q) print("Public Key (e, n):", public_key) ...
def state_to_features(last_action, game_state: dict) -> np.array: # This is the dict before the game begins and after it ends if game_state is None: return None feat = [] x,y = game_state['self'][3] grid = [(x+1,y),(x-1,y),(x,y+1),(x,y-1),(x+2,y),(x-2,y),(x,y+2),(x,y-2)] bomb_pos = [i[0]...
The code implements an agent's decision-making in a game, using a model to select actions based on the game state. It tracks position history to detect loops, checks for traps, and uses an epsilon-greedy strategy for exploration. Valid actions are filtered, and Q-values from the model determine the optimal move. Specia...
def act(self, game_state: dict) -> str: if game_state['step'] == 1: self.coordinate_history = deque([], 20) #print(self.coordinate_history) self.last_action = None self.cur_action = None self.bomb_dropped = [] #print(self.bomb_dropped) self.loop = False self.t...
def get_project(project_name): return project.find_one({"name": project_name}) def copy_log(task_name, log_path, timestamp): if os.path.exists(log_path): if not os.path.exists(f"./logs/{task_name}"): os.makedirs(f"./logs/{task_name}") shutil.copy(log_path, f"./logs/{task_name}/{times...
The main task of the code is to execute a specified project's script using its virtual environment, log execution details, determine success/failure status, record execution history, trigger dependent tasks, and return the subprocess result. It retrieves project configuration, runs the script with provided arguments, t...
def run_project(task_name, json_args): if project_info := get_project(task_name): venv_python = project_info["python_path"] args = [venv_python, project_info["exec_path"], str(json_args)] start_time = datetime.datetime.now(tz=pytz.timezone("America/Sao_Paulo")) execution = subprocess...
def log_in (self,postvars): if(bytes('username', encoding='utf8')in postvars ): username = postvars[bytes('username', encoding='utf8')] password = postvars[bytes('password', encoding='utf8')] password = password[0] username = username[0].decode("utf-8") ...
This code handles POST requests by checking a global lock status. If not locked, it parses incoming form data, logs in the user, verifies a code, generates a new code, and sends a response. If locked, it redirects to a "logged_out.html" page.
def do_POST(self): global is_locked if not is_locked: length = int(self.headers['content-length']) postvars = parse_qs(self.rfile.read(length), keep_blank_values=1) self.log_in(postvars) self.check_verif...
def newtonMethod_multivariate(xn, h=0.0125): steps = 0 while True: steps += 1 xn_previous = xn xn = xn + gaussianElimination(jacobian(xn), negativeFArrow(xn)) print("\nStep number: ", steps, ", x = ", xn, end=" ") if np.linalg.norm(xn - xn_previous, np.inf) < 5e-6 or st...
The code applies Newton's method to solve a system of nonlinear equations defined by functions f, g, and m. It starts with an initial guess x0 and step size h, iteratively refining the solution until convergence. The function prints the number of steps taken, the final solution vector x, and the evaluated results of f(...
def pm2(x0, h=0.0125): x, steps = newtonMethod_multivariate(x0, h) print("\n\nNumber of steps: ", steps) print("x =", x) print("fx = ", f(x[0], x[1], x[2])) print("gx = ", g(x[0], x[1], x[2])) print("mx = ", m(x[0], x[1], x[2]))
def get(qq): """ Do an http GET call from a local Jazz server. See https://kaalam.github.io/jazz_reference/api_ref_intro.html """ return http.get(LOCAL_SERVER_URL + qq) def ls(self, path): a = get('//deque/etl_stack/~last=//file&%s;' % path) assert a.status_code == 200 a = get('//deque/etl_stack/~plast.text') ...
The main task of the code is to compile GitHub repositories into a structured dataset, storing them in an LMDB database. It checks for required folders, compiles each repository, writes dataset blocks, and optionally deletes source code. If "github_repos" is missing, it alerts the user and halts. The process ensures da...
def compile(self, keep_repositories = False): """ This is the compiler. See https://kaalam.github.io/jazz_reference/reference_docker_tangle_server.html """ get('//deque/etl_stack.new') if 'github_repos' not in self.ls('/home/jazz/jazz_dbg_mdb/')['key']: print('The "github_repos" folder does not exist in t...
def clean_key(key): return str(key).upper().strip() def get_request(request, year='2022'): request = str(request) if request[0] != "/": request += "/" if year is None: answer = requests.get(api_url_base, headers=header) # Raise error and pass over the function if the data is n...
The function imports events related to a specific district and year by cleaning the district key, fetching event data via a request, and processing each event with `import_event` for the given year.
def import_district(key, year='2022'): key = clean_key(key) if year is None or year == "": year = '2022' request = "/events?districtCode=" + key try: request = get_request(request, year) except NoGoodResponseError: return events = request['Events'] for event in event...
def clean_key(key): return str(key).upper().strip() def get_request(request, year='2022'): request = str(request) if request[0] != "/": request += "/" if year is None: answer = requests.get(api_url_base, headers=header) # Raise error and pass over the function if the data is n...
The function imports event schedules from an API, handling errors, ensuring the event exists in the database, and processing each match by importing its data. It constructs a request URL based on the event key, year, and playoff status, then iterates through returned matches to import them.
def import_schedule(event_key, year="2022", playoffs=False): event_key = clean_key(event_key) if year is None or year == "": year = '2022' request = "/schedule/" + event_key + "?tournamentLevel=" + ("Playoff" if playoffs else "Qualification") try: request = get_request(request, year) ...
def normalize_text(text): """Returns a normalized version of the specified string. You can add default parameters as you like (they should have default values!) You should explain your decisions in the header of the function. Args: text (str): the text to normalize Returns: ...
The code performs spell checking by generating and scoring potential corrections for each token in the input text using a language model and a noisy channel model. It prioritizes known words, applies edit-distance-based corrections, and returns the most probable fix. If no corrections are found, it retains the original...
def spell_check(self, text, alpha, normalize=False): """ Returns the most probable fix for the specified text. Use a simple noisy channel model if the number of tokens in the specified text is smaller than the length (n) of the language model. Args: text (str...
def process_ispindel_report_for_service(self, report: IspindelReport, service: Destination) -> IspindelReport: if service: if service == Destination.GRAINFATHER: report.name = report.name + ",SG" elif service == Destination.BREWFATHER: report.name = report...
This code processes incoming MQTT messages by identifying their topic, parsing payloads into structured reports (iSpindel or Irelay), applying service-specific transformations, and publishing the processed data to a web service. It handles multiple channels for iSpindel devices and relay reports, ensuring relevant data...
def on_message_received(self, client, userdata, message): print(f"Message received on topic: {message.topic}") for channel in range(1, MAX_ISPINDEL_CHANNELS + 1): topic = TOPIC_FORMAT_ISPINDEL_REPORT.format(channel) if message.topic == topic: logging.debug(f"Proce...
def quick_k_means(foreground, background, k=KMEANS_COMPONENTS): fg_mu, bg_mu = foreground[np.random.choice(foreground.shape[0], k), :], background[np.random.choice(background.shape[0], k), :] avg_centroid_change = float('Inf') while avg_centroid_change > Kmeans_thresh: fg_dist = cdist(foreground, fg_mu, metric='...
The code implements the GrabCut algorithm for image segmentation. It initializes a segmentation map based on a user-provided bounding box, separates foreground and background regions, and iteratively refines the segmentation using Gaussian Mixture Models (GMMs). The algorithm updates the foreground and background model...
def grabcut(img, box): seg_map = np.zeros((img.shape[0], img.shape[1])) seg_map[int(box['y_min']) - 1:int(box['y_max']) + 1, int(box['x_min']) - 1:int(box['x_max']) + 1] = 1 bg, fg = img[seg_map == 0], img[seg_map == 1] fg_ass, bg_ass = quick_k_means(fg, bg) change = 1 i = 0 oldshape = fg.shape[0] while (c...
def canny(img, low_threshold, high_threshold): return cv2.Canny(img, low_threshold, high_threshold) def region_of_interest(img, vertices): mask = np.zeros_like(img) if len(img.shape) > 2: # this is where the image contains more than one channel like an RGB picture channel_count = img.sha...
The main task of the code is to process an input image to detect and trace lane lines using edge detection, Hough transform, and region masking. It converts the image to grayscale, applies Gaussian blur, detects edges, isolates the region of interest (ROI), identifies lane lines via Hough transform, separates left/righ...
def pipeline(image): # we will first start with converting the image to gray scale which makes it easier to apply hough transform on # then applying a gaussianBlur filter to reduce the noise in the image grayscaled= cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gaussianBlur = cv2.GaussianBlur(grayscaled, (5, 5), 0)...
def get_expr(self, as_latex=None, with_name=True): """ Gets expression (equation) of this variable Parameters ---------- as_latex : bool wether to make this latex ready or more readable for console. Default is defined by options with_name : bool w...
The main task of the code is to display equations, Gaussian error, maximum error, and value strings as LaTeX-formatted text in a matplotlib plot. It constructs a formatted string with these elements, applies LaTeX rendering, positions the text at (0, 0.1), disables the coordinate axis, and renders the plot with the spe...
def show(self, font_size=12): """ Shows screen with all equations and values Parameters ------- font_size : int font size of everything """ text = "" text += "$" + self.get_expr(as_latex=True) + "$\n" text += "$" + self.get_gauss_error...
def get_value_str(self, error_mode=None, as_latex=None, no_rounding=None, scientific=True): """ Get value or values of this instance formatted Returns ------- error_mode : ErrorMode See `ErrorMode` as_latex : bool See `error_analysis.options.as_la...
This code generates a formatted string representation of an object, combining its name, value, expression, and error terms (Gaussian and max) based on specified flags. It prioritizes `print_all` to enable all outputs, uses LaTeX formatting when enabled, and appends newline characters to separate different components. T...
def to_str(self, print_values=False, print_expr=False, print_gauss_error=False, print_max_error=False, print_all=False, as_latex=options.as_latex): """ .. warning:: Unfinished. Do not use! """ ret_str = "" if print_values == False and print_expr == False and print_...
def record(self, frame_num, boundaries=(7,10)): # frame_num = constsant + frame_num if self.use_random_keyframes: self.frame = self.frame + random.uniform(boundaries[0], boundaries[1]) else: self.frame = self.frame + 8 bpy.ops.pose.select_all(action='SELECT') ...
The code's main task is to process motion data over a specified time duration by recording frames, assigning labels based on the subject's position (e.g., Standing, Walking, Sitting), and saving coordinate data with labels. If the subject is in "Sitting_in_front_of_a_table" or "Standing" positions for at least 3 second...
def wait(self,time): for line in range(0,time): # self.frame = self.frame + random.uniform(6, 5) # frame = 10 self.record(self.frame) if "Standing" == self.position: label = 1.0 elif "walk" in self.position.lower(): label = 2.0 ...
def validate_shipping_details(**args): """Shipping Details Validator""" if not args.get('type_of_shipment'): print("hdwaa") return { 'type_of_shipment': "type_of_shipment is required", } if args.get("type_of_shipment") == "By courier": if not args.get('courier_nam...
The main task of the code is to validate input parameters for adding an entry by checking required fields (recieving_details, shipping_details, customer_details, items_list, comments, created_by) and their data types. It returns specific error messages for missing fields or invalid types, or True if all validations pas...
def validate_add_entry(**args): """Add Entry Validation""" if not args.get("recieving_details") or not args.get('shipping_details') or not args.get('customer_details') or not args.get('items_list') or not args.get('comments') or not args.get('created_by'): return { "recieving_details": "Reci...
def upload_file_csv(file_link): ''' Returns dataframe of a csv file with the input as the file's path''' #print(" Displaying nlot Snipet of Data") return pd.read_csv(file_link) def merger(base_data, merger_data, merg_on_feat, how= None): '''Joins two dataframe together and returns result. See 'merge' ...
The function processes training data by loading, merging, cleaning, encoding features, and binning variables, then trains an XGBoost model on the prepared dataset. It saves the trained model for test data prediction and returns the model.
def combined_proc_modelling(train_features_link, train_target_link): ''' Function automates loading, cleaning, prepocessing of train data, then the training of entire train data on xgb model and returns trained model which is saved for test data prediction Parameters: train_feature_link(st...
def advance(self): self.linesLeft -= 1 if (self.hasMoreCommands()): self.currentLine += 1 self.currentCommand = self.lines[self.currentLine] def hasMoreCommands(self): return self.linesLeft > 0 def commandType(self): if '/' in self.currentCommand: inde...
This method parses Hack assembly code into a structured list. It processes each command type (A, L, or C), extracting symbols or components (dest, comp, jump) and appending them to a list. The loop advances through commands, handling labels and instructions, then closes the file and returns the parsed list of command p...
def parseMain(self): parsedCode = [] self.advance() while self.hasMoreCommands(): if self.commandType() == 'A_COMMAND': parsedCode.append(self.symbol()) elif self.commandType() == 'L_COMMAND': parsedCode.append('(' + self.symbol()) ...
def activate_unit(self, selected_tile): self.active_movement_tile = selected_tile; #Display movement options tile_radius = selected_tile.occupying_unit.movespeed; self.display_movement_area(tile_radius); """ x_center = selected_tile.x_pos; y_center = selected_tile...
This code handles player clicks for unit movement and combat. It checks if a selected tile is valid for movement (within range and unoccupied), activates units, initiates attacks on valid targets, and manages state transitions between movement and combat modes, printing feedback for each action.
def handle_click(self, selected_tile): if self.active_movement_tile == None: if selected_tile.occupied: if selected_tile.occupying_unit.awaiting_orders == False: print("That unit has already moved, but that's ok for now"); self.activate_unit(select...
def get_directory_by_dir_id(self, dir_id): """ Get directory by dir id """ try: dir_ = self.db['directories'].find_one({ '_id': ObjectId(dir_id) }) if dir_: return dir_ else: return None ...
This function recursively copies a directory and its contents to a new parent directory. It retrieves the source directory, updates its parent and user IDs, creates a new directory, then iterates through sub-items. For each sub-directory, it recursively calls itself; for files, it triggers a file copy. The task ensures...
def copy_helper_dir(self, content_id, new_parent_id): temp_dir = self.get_directory_by_dir_id(content_id) temp_dir['parent_dir_id'] = new_parent_id temp_dir['user_id'] = temp_dir['owner_id'] new_con = self.create_new_directory(**temp_dir) sub_con = self.list_content_by_dir_id( ...
def okmessage(title, mess): tkinter.messagebox.showinfo(title, mess) def infi_redo_1(x): okmessage ("Step 1", x) okmessage ("Step 2", "Start counting down in 10s") app = ExampleApp() win.focus_set() def infi_next(fin): win.destroy() y="Prepare to close your other fingers as much as you can" ...
The code defines a function `infi()` that guides a user through a multi-step process, displaying instructions via `okmessage()` and creating a GUI window (`Toplevel`) with buttons for 'Redo', 'Next', and 'Cancel'. It initializes a global window (`win`) for step 3, prompts user interaction, and links button actions to o...
def infi(): x="Prepare to point your other fingers horizontal to floor" okmessage ("Step 1", x) okmessage ("Step 2", "Start counting down in 10s") app = ExampleApp() global win win = Toplevel() win.title('Step 3') message = "Please select the following options" Label(win, text=messag...
def get_keys(old_dict, selected_keys): return {key: old_dict[key] for key in selected_keys} def deploy_all_functions(project_id, allow_private, datasets, cloud_storage_directory, specific=False): """ Procedure to deploy all functions to BigQuery :param project_id: :param allow_private: :param da...
The code deploys functions to BigQuery by iterating through projects, retrieving configuration details, and executing deployment. It then processes generated documentation into structured data, creating two markdown files: one for general use and another tailored for GPT. The script handles exceptions and concludes wit...
def run(): # Deploy functions to BigQuery try: selected = [] specific = False if selected: projects_selected = get_keys(projects, selected) else: projects_selected = projects for project in projects_selected: project = projects[project...
def findAvailable(self, piece): '''Returns a list of lists of available moves and the pieces that need to be flipped for that move. If no moves are available, return False.''' available = [] #list that contains lists of available moves and their #respective pieces that ...
This function implements the Minimax algorithm with alpha-beta pruning to evaluate the best move for a player in a board game (likely Reversi/Othello). It recursively explores available moves, alternates turns between 'white' (maximizing) and 'black' (minimizing), updates board states, and calculates scores. Alpha-beta...
def minimax(self, depth, whose_turn, alpha, beta): '''Minimax algorithm with alpha beta pruning.''' availableMoves = self.findAvailable(whose_turn) #difficulty level if (not availableMoves or depth > 5): return self.boardScore() if whose_turn == 'white': ...
def findAvailable(self, piece): '''Returns a list of lists of available moves and the pieces that need to be flipped for that move. If no moves are available, return False.''' available = [] #list that contains lists of available moves and their #respective pieces that ...
The code evaluates the best move for a given piece using a minimax algorithm with alpha-beta pruning. It temporarily applies each available move, checks if the opponent has valid moves, updates point values, and calculates the board's value. The best move is selected based on maximizing/minimizing the evaluated value, ...
def bestMove(self, piece): '''Returns the index of the best available move. Evaluated using a minimax algorithm.''' if piece == 'white': #maximising bestValue = -inf otherPiece = 'black' else: #minimising bestValue = inf ...
def C_from_T(T): return T[0:3, 0:3] def r_from_T(T): return T[0:3, 3] def log_SO3(C): assert (len(C.shape) == 2 and C.shape[0] == 3 and C.shape[1] == 3) phi_norm = np.arccos(np.clip((np.trace(C) - 1) / 2, -1.0, 1.0)) assert (phi_norm >= 0 and np.sin(phi_norm) >= 0) if phi_norm < np.pi / 2 and...
The code computes the logarithm of an SE(3) transformation matrix $ T $, decomposing it into a rotation matrix $ C $ and translation vector $ r $. It converts $ C $ to a rotation vector $ \phi $ using $ \log_{SO(3)} $, adjusts $ r $ via the left Jacobian inverse of $ \phi $, and concatenates the results into a 6D vecto...
def log_SE3(T): C = C_from_T(T) r = r_from_T(T) phi = log_SO3(C) rou = left_jacobi_SO3_inv(phi).dot(r) return np.concatenate([rou, phi])
def handle_401(self): print("The user is not logged in") self.send_response(401) self.end_headers() def end_headers(self): # self.send_header("Access-Control-Allow-Origin", "*") # or null, will change when actually hosted self.send_header("Access-Control-Allow-Origin", s...
This function retrieves truck details and metadata by ID if the user is authenticated. It checks for user authentication, fetches truck data from the database, combines it with metadata, and returns a JSON response. If the truck isn't found or authentication fails, it triggers appropriate error handlers.
def handle_find_truck(self, id): if "userId" not in self.session_data: self.handle_401() return trucks_db = TrucksDB() truck = trucks_db.get_truck(id) if truck: truck_meta = trucks_db.get_truck_meta(truck["name"]) all_data = {"mytruck": tru...
def handle_401(self): print("The user is not logged in") self.send_response(401) self.end_headers() def end_headers(self): # self.send_header("Access-Control-Allow-Origin", "*") # or null, will change when actually hosted self.send_header("Access-Control-Allow-Origin", s...
This function handles creating a new truck entry by validating user authentication, parsing form data, checking required fields, and storing the truck details in the database with the authenticated user's ID.
def handle_create_truck(self): if "userId" not in self.session_data: self.handle_401() return length = self.headers['Content-Length'] request_body = self.rfile.read(int(length)).decode("utf-8") if request_body: parsed_body = parse_qs(request_body) ...
def handle_401(self): print("The user is not logged in") self.send_response(401) self.end_headers() def end_headers(self): # self.send_header("Access-Control-Allow-Origin", "*") # or null, will change when actually hosted self.send_header("Access-Control-Allow-Origin", s...
The main task of the code is to allow authenticated users to edit their truck's details by validating input data, checking ownership, and updating the database if all required fields (name, type, rating, review, location) are provided. It enforces user authentication, ownership verification, and data integrity before p...
def handle_edit_truck(self, id): if "userId" not in self.session_data: self.handle_401() return trucks_db = TrucksDB() found = trucks_db.get_truck(id) if found["user_id"] != self.session_data["userId"]: self.handle_401() return len...
def handle_401(self): print("The user is not logged in") self.send_response(401) self.end_headers() def end_headers(self): # self.send_header("Access-Control-Allow-Origin", "*") # or null, will change when actually hosted self.send_header("Access-Control-Allow-Origin", s...
This function deletes a truck from the database if the authenticated user owns it. It first checks if the session contains a user ID, retrieves the truck by ID, verifies ownership by comparing user IDs, and deletes the truck if authorized. If unauthorized or the truck isn't found, it returns 401 or 404 errors respectiv...
def handle_delete_truck(self, id): if "userId" not in self.session_data: self.handle_401() return trucks_db = TrucksDB() found = trucks_db.get_truck(id) if found["user_id"] != self.session_data["userId"]: self.handle_401() return i...
def load_session(self): # CALLED AT THE TOP OF ALL DO FUNCTIONS # Cookie should not be changing when sending new request from same client # Clear cookie and check get new one # Restart server and check if got new one # Try to tamper with cookie, see if get new one self.lo...
This code handles HTTP GET requests by parsing URL paths to retrieve data from 'trucks' or 'users' collections. It extracts parameters like member_id and user_id, then delegates to specific methods to fetch individual items, user-specific data, or entire collections, with fallback for invalid routes.
def do_GET(self): self.load_session() parts = self.path.split("/") collection = parts[1] member_id = None user_id = None if "?user=" in collection: user_id = collection.split("=")[1] collection = collection.split("?")[0] if len(parts) > 2: ...
def load_session(self): # CALLED AT THE TOP OF ALL DO FUNCTIONS # Cookie should not be changing when sending new request from same client # Clear cookie and check get new one # Restart server and check if got new one # Try to tamper with cookie, see if get new one self.lo...
This code handles HTTP PUT requests to update a specific truck in the "trucks" collection by its ID. It splits the request path to extract the collection name and member ID, then calls handle_edit_truck() if valid. Otherwise, it returns a 404 Not Found response for invalid collections or missing IDs.
def do_PUT(self): self.load_session() parts = self.path.split("/") collection = parts[1] member_id = None if len(parts) > 2: member_id = parts[2] if collection == "trucks": if member_id: # Update specific member self...
def load_session(self): # CALLED AT THE TOP OF ALL DO FUNCTIONS # Cookie should not be changing when sending new request from same client # Clear cookie and check get new one # Restart server and check if got new one # Try to tamper with cookie, see if get new one self.lo...
This code handles DELETE requests by checking the URL path to identify the 'trucks' collection and a member ID. If both are present, it deletes the specified truck; otherwise, it returns a 404 Not Found error. The function uses `handle_delete_truck` for deletion and relies on session loading and error-handling methods.
def do_DELETE(self): self.load_session() parts = self.path.split("/") collection = parts[1] member_id = None if len(parts) > 2: member_id = parts[2] if collection == "trucks": if member_id: # Delete specific member s...
def load_session(self): # CALLED AT THE TOP OF ALL DO FUNCTIONS # Cookie should not be changing when sending new request from same client # Clear cookie and check get new one # Restart server and check if got new one # Try to tamper with cookie, see if get new one self.lo...
This code handles POST requests by routing them to specific methods based on the URL path. It loads the session, checks the request path, and calls corresponding handlers for creating trucks, users, sessions, or logging out. If the path is unrecognized, it triggers a not-found response.
def do_POST(self): self.load_session() if self.path == "/trucks": self.handle_create_truck() elif self.path == "/users": self.handle_create_user() elif self.path == "/sessions": self.handle_create_session() elif self.path == "/logout": ...
def get_equipment_latest_age(self, serialNumber): dt = self.get_equipment_latest_upload_dt(serialNumber) if dt is None: return None return datetime.now(timezone.utc) - dt def get_equipment_latlong(self, serialNumber): lat = self.get_equipment_attribute(serialNumber, "Location", "Latitude...
The code iterates through a dictionary of equipment items, printing each serial number and associated details like upload age, location, engine status, hours, fuel level, fuel consumed, and odometer. It uses helper methods to retrieve specific data for each equipment entry, providing a summary of their current status a...
def print_all_equipment(self): for serial in self.equipment: print(serial) # print(self.equipment[serial]) print("Latest Upload Age: ", self.get_equipment_latest_age(serial)) print("LatLong: ", self.get_equipment_latlong(serial)) print("Engine Running:...
def create_doover_client(self): self.cli = pd.doover_iface( agent_id=self.kwargs['agent_id'], access_token=self.kwargs['access_token'], endpoint=self.kwargs['api_endpoint'], ) def add_to_log(self, msg): if not hasattr(self, '_log'): self._log = "" ...
The main task of the code is to initialize communication channels, log system information, retrieve machine details, and process messages based on a specified type (DEPLOY, DOWNLINK, UPLINK, FETCH). It handles errors by logging exceptions and ensures execution tracking through timestamps and activity logs.
def execute(self): start_time = time.time() self.create_doover_client() self.uplink_recv_channel = pd.channel( api_client=self.cli.api_client, agent_id=self.kwargs['agent_id'], channel_name='uplink_recv', ) self.notifications_channel = pd.c...
def _mkdirp(path): """ Creates a directory at the given path if it doesn't already exist. """ if not os.path.exists(path): run("mkdir -p {}".format(path)) def _find_files_with_extension(path, extension): """ In Python 3.5 and above, glob supports recursive patterns such as '**/*.swif...
The code compiles the XCTest framework using Swift, generating both a static library (`libXCTest.a`) and a shared library (`libXCTest.so`). It configures build paths, compiles source files with options for debug/optimization, links against Foundation, Swift, and other dependencies, and installs the built artifacts if s...
def build(args): """ Build XCTest and place the built products in the given 'build_dir'. If 'test' is specified, also executes the 'test' subcommand. """ swiftc = os.path.abspath(args.swiftc) build_dir = os.path.abspath(args.build_dir) static_lib_build_dir = Gener...
def progressPets(self,tokens): #days = datetime.date.today()-datetime.datetime.strptime(self.lastResolve, '%Y-%m-%d').date() progress = self.factor(tokens) for pet_entry in self.pet_objects: pet_entry.age+=progress self.tokens = 0 self.check_death_oldAge() def save_pe...
The function calculates the number of days since the game's last session, adjusts for specific time conditions (e.g., play after midnight), updates the player's "zeal" activity log by adding zeros for missed days, progresses pets accordingly, and checks if neglect (low zeal) causes pets to die. It also updates the last...
def progress_down_days(self): '''on init - progress the days the game was not played ''' #days = datetime.date.today()#-datetime.datetime.strptime(self.lastResolve, '%Y-%m-%d').date() self.util.debug("\t\t\tGame progress_down_days(): start") try: days_str = datetime.date.to...
def check_excecution_date(self): # check that not today date and check for case where resolve is done after midnight to 4 oclock # in the midnight to 4 case change the lastResolve date to day before # case days == 2 and it is between 0 and 4 hours -> allowed and day counts as previous day ...
The code manages daily token and reputation updates. It checks execution frequency, updates tokens based on daily stats, adjusts pet reputation if recent zeal scores are high, maintains a 15-day zeal history, and saves progress.
def resolveDay(self): # to only excecute once per day: [resolve,date_lastResolve]=self.check_excecution_date() self.util.debug(str([resolve,date_lastResolve])) if resolve: # check if last resolve is more than one day in the past: self.progress_down_days() ...
def get_record_config(resource_id: str) -> MetadataRecordConfig: logging.info(f"Loading record for resource: {resource_id}") try: record_path = get_record_path(resource_id=resource_id) logging.debug(f"Record location matched to '{record_path}'") except LookupError as e: logging.error...
The function deposits resource artefacts by processing distribution options from a record configuration, creating a resource directory, updating artefacts via `deposit_resource_artefact`, and compiling deposit details into a dictionary. It validates configurations, logs progress, and returns artefact deposit data inclu...
def deposit_resource_artefacts(resource_id: str) -> dict: record_config = get_record_config(resource_id=resource_id) validate_record_config(record_config=record_config) deposit_data_ = {"artefacts": []} logging.info("processing constraints to apply to artefacts") constraint = record_config.config[...
def ping(self, start_response): """Route: GET /ping.""" return ok({"reply": "pong"}, start_response) def new_session(self, environ, start_response): """Route: POST /newSession.""" sid = self.sessions.new_session() return ok({"sid": sid}, start_response) def del_session(self, en...
This code handles HTTP requests by routing them to specific methods based on the URL path and HTTP method. It logs each request, checks the route and method, and delegates to corresponding functions like ping, new_session, del_session, or eval_chunk. If no match is found, it returns an unknown handler response.
def __call__(self, environ, start_response): logger = getLogger(LOGGER_NAME) route = environ["PATH_INFO"] method = environ["REQUEST_METHOD"].upper() logger.info(f"Processing request: {method} {route}") if route == APP_ROUTE_PING and method == HTTP_METHOD_GET: return...
def create_parser(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="Gem5 to McPAT parser") parser.add_argument( '--config', '-c', type=str, required=True, metavar='PATH', help="Input config.json from Gem5 output.") ...
The main task of the code is to process command-line arguments, read statistical, configuration, and McPAT template files, prepare an output template, and generate the final McPAT output. It involves parsing inputs, configuring settings, and producing structured output files, likely for performance analysis or simulati...
def main(): global args parser = create_parser() args = parser.parse_args() readStatsFile(args.stats) readConfigFile(args.config) readMcpatFile(args.template) prepareTemplate(args.output) dumpMcpatOut(args.output)
def readStatsFile(statsFile): global stats stats = {} F = open(statsFile) ignores = re.compile(r'^---|^$') statLine = re.compile( r'([a-zA-Z0-9_\.:-]+)\s+([-+]?[0-9]+\.[0-9]+|[-+]?[0-9]+|nan|inf)') count = 0 for line in F: # ignore empty lines and lines starting with "---" ...
The code processes input files (stats, config, template) by reading statistics, configuration, and McPAT template data, prepares an output structure, and generates the final output using McPAT. It orchestrates data parsing, configuration setup, and output generation for performance analysis.
def parse_data(stats, config, template, output): readStatsFile(stats) readConfigFile(config) readMcpatFile(template) prepareTemplate(output) dumpMcpatOut(output)
def set_EmployeeID(self): conn = sqlite3.connect("OS_Employee.db") #Connect to database of choice. cur = conn.cursor() #Shorthand. with conn: while True: #Loops until break. print("\nEmployeeID length must be 4 digits long.") EmployeeID = remove_all(i...
The main task of the code is to create an Employee object by initializing and setting its attributes—EmployeeID, FirstName, LastName, Email, and Password—using corresponding setter methods to populate the object's properties with required data.
def create_Employee(self): self.set_EmployeeID() self.set_FirstName() self.set_LastName() self.set_Email() self.set_Password()
def remove_special_characters(text): regex = r'[^a-zA-Z0-9\s]' text = re.sub(regex, '', text) return text def pos_tagging(text): pos_tag = nltk.pos_tag(text.split()) pos_tagged_noun_verb = [] for word, tag in pos_tag: if tag == "NN" or tag == "NNP" or tag == "NNS" or tag == "VB" or tag =...
This function calculates a sentence's importance score by summing TF-IDF values of its processed words. It removes special characters/digits, performs POS tagging, filters out stopwords, lemmatizes words, and accumulates scores via word_tfidf. The result reflects the sentence's relevance based on term frequency-inverse...
def sentence_importance(sentence, dict_freq, sentences): sentence_score = 0 sentence = remove_special_characters(str(sentence)) sentence = re.sub(r'\d+', '', sentence) pos_tagged_sentence = [] # no_of_sentences = len(sentences) pos_tagged_sentence = pos_tagging(sentence) for word in pos_tagg...
def remove_special_characters(text): regex = r'[^a-zA-Z0-9\s]' text = re.sub(regex, '', text) return text def lemmatize_words(words): lemmatized_words = [] for word in words: lemmatized_words.append(wordlemmatizer.lemmatize(word)) return lemmatized_words def freq(words): words = [wor...
This function generates a summary from a text file by tokenizing, cleaning, and weighting sentences based on word frequencies. It selects top sentences according to a specified percentage, constructs a summary, and evaluates it against a reference summary using Rouge scores. Key steps include text preprocessing, import...
def tfidf_func(file_in=open('Data/the-cactus.txt', 'r'), percent_in=50, idlSummary=open('Data/res.txt').read()): text = file_in.read() tokenized_sentence = sent_tokenize(text) text = remove_special_characters(str(text)) text = re.sub(r'\d+', '', text) tokenized_words_with_stopwords = word_tokenize(t...
def get_grouped_names(game_id, all_groups): join_expr = get_inner_join_expression("players", "games_and_players", "players.player_id=games_and_players.player_id") groups = [] total_names = 0 for group in all_groups: names = select("player_name", join_expr, f"game_id={game_id} AND group_id={group...
The code generates a sequence of names by randomly selecting elements from groups sorted by size, ensuring each group's elements are evenly distributed in the output. It adjusts indices to maintain group order after removals, using a bubble sort and dynamic index handling to avoid conflicts during selection.
def get_group_series(game_id, all_groups): groups, total_names = get_grouped_names(game_id, all_groups) bubble_sort_by_size(groups) output = [] ignore_index = -1 while(len(output) < total_names): print(output) print(groups) selected_index = random.randint(0, get_index_high(gr...
def get_groupless_series(game_id): join_expr = get_inner_join_expression("players", "games_and_players", "players.player_id=games_and_players.player_id") names = select("player_name", join_expr, f"game_id={game_id}") names = randomise_order(names) return [name[0] for name in names] def get_group_series(...
The function `draw(game_id)` retrieves a list of names associated with a game, either from groups or without groups, then pairs each name with the next one in a circular manner using `set_picked_name`, and finally marks the game as drawn with `mark_drawn(game_id)`.)
def draw(game_id): names = [] from_expr = get_inner_join_expression("groups", "games_and_groups", "groups.group_id=games_and_groups.group_id") all_groups = select("groups.group_id", from_expr, f"game_id={game_id}") if len(all_groups) == 0: names = get_gr...
def size(node): # calculates the size of the cluster generated from the subtree of this node # # this could be made much more efficient if it was tail-recursive and stopped # when either it visited the entire tree OR the min_size was hit # for now just visit the whole tree to get size if node.no...
The function `extract_clusters` extracts a specified number of clusters from a tree structure, ensuring each cluster meets a minimum size requirement. It starts with the root node and iteratively splits non-leaf nodes into their children, adding them to the cluster list if they meet the size threshold. Nodes below the ...
def extract_clusters(root, num_clusters, min_size): clusters = [root] while len(clusters) < num_clusters: expandable = [n for n in clusters if n.node_type != 'LEAF'] if not expandable: break node = expandable[0] s = size(node) sl = size(node.data[0]) s...
def modify_state_file(case, state_path): with open(state_path, "r") as json_file: state = json.load(json_file) if "render_mode" in case: state["1"]["model"]["renderMode"] = case["render_mode"] if "prim_view_width" in case: state["1"]["ui"]["primViewWidth"] = case["prim_view_width"]...
The main task of the code is to configure and launch a USD viewer application by copying a pre-defined state configuration file, writing an execution script to a temporary file, handling OS-specific window management (maximizing, permissions), launching the process, verifying the application window exists, and performi...
def open_tool(script_path, execution_script, engine, case=None, is_first_opening=False): global process # copy baseline state.json of usdview with necessary settings state_file_location = os.path.join(os.path.expanduser("~"), ".usdview") state_file_name = "state.json" target_file_location = os.pat...
def getSystemAppend(self, systemElement: ET.Element, systemSettings: list[str]): defaultStartPower = systemSettings[0] defaultMaxPower = systemSettings[1] systemStart = systemElement.get('start') systemMax = systemElement.get('max') systemPower = int(systemElement.get('power')) ...
The function generates a list of system strings from a blueprint, processing each system's configuration. It checks for system presence, handles artillery by appending weapon names, and resolves conflicts like medbay overriding clonebay. Each entry includes display names, power levels, and special tags, formatted into ...
def getSystemsList(self) -> list[str]: systemList = self.blueprint.find('systemList') systemsList = [] for (systemName, systemSettings) in self.systems.items(): systemElements = systemList.findall(systemName) if len(systemElements) == 0: # system not on ship ...
def sum(self): return sum([self.states[(i, j)][3] for i in range(self.m) for j in range(self.n)]) def iteraltion(self, directions, times): while times > 0: s1 = self.sum() for i in range(self.m): for j in range(self.n): if self.isTerminal(i, j...
The code performs policy iteration in a reinforcement learning algorithm, iterating until the policy converges based on a convergence threshold. It calculates the number of iterations required, adjusts a counter 't' using internal iteration methods, and displays the result. The loop breaks when the change in the summed...
def policy_iteration(self): t = 0 while True: s1 = self.sum() t += MAX_ITERATION - self.iteraltion(None, MAX_ITERATION) t += 1 - self.iteraltion(range(4), 1) s2 = self.sum() if s2 - s1 < self.CONVERGE_VALUE: break pr...
def getConcept(formalcontextName,dictionnaire): expression = '(\d+) \[.*\{Concept\_'+formalcontextName+'\_(\d+).*' for line in content: res = re.search(expression,line) if res: conceptId = res.group(1) conceptName = 'Concept_'+formalcontextName+'_'+res.group(2) lst=line.split('|') lstExtension...
The main task of the code is to extract and write rules from a formal context of stations using concept relationships. It processes concepts, their attributes, and hierarchical links (successors/predecessors), then iterates through introductory concepts to generate rules connecting them to successor concepts. These rul...
def extractRules(content,formalContextStationsName): getConcept(formalContextStationsName,dictConceptStations) getSuccessorsPredecessors(dictConceptStations) getIntroductorsConcept(dictConceptStations) getIdSourceIdTarget(dictConceptStations) print("introductor concepts stations number : "+str(len(introductorsCon...
def section_cells_update(self): """ A helper function that executes logical operations based on which section of the piece we are in. :return: None """ if self.section_manager.current_section == 3: self.section_three() elif self.section_manager.current_section...
The main task of the code is to manage section transitions in a timed sequence, updating GUI elements like section names, instructions, and status texts. It handles initial setup by retrieving timing data and triggering self-updates, then progresses through subsequent sections by advancing the section manager, updating...
def update_section(self): """ Logic for updating the section. If this is the first section on boot, will get appropriate time elapsed, get the appropriate score cells, and call itself until the end of piece protocol. In further sections The next section is loaded, the necessary cells are...
def _split_args_line(line): """Split out the --params option value from the input line arguments. Args: line (str): The line arguments passed to the cell magic. Returns: Tuple[str, str] """ lexer = lap.Lexer(line) scanner = lap.Parser(lexer) tree = scanner.input_line() ...
This function processes a SQL query with parameters, validates and parses the --params option, replaces placeholders in the query with parameter values, executes the query against Athena, and returns or stores the result as a DataFrame in the current namespace.
def _cell_magic(line, cell): # This arg parsing code is copied from the google.cloud.bigquery.magic # The built-in parser does not recognize Python structures such as dicts, thus # we extract the "--params" option and inteprpret it separately. try: params_option_value, rest_of_args = _split_arg...
def has_comparandum(present): if not present.comparandum(): raise ValueError(f"{present}.comparandum() cannot be an empty string.") def _run_comparison( self, present: Comparable, all: List[Comparable] ) -> Dict[Comparable, float]: res = {} for other in all: s...
The main task of the code is to compare a given item (`present`) against a list of other items (`others`), compute similarity scores using a private method, filter scores exceeding a threshold, and return the indices of the most similar items as a list.
def compare( self, present: Comparable, others: List[Comparable] ) -> List[Comparable]: self.has_comparandum(present) scores = pd.Series(self._run_comparison(present, others)) most_similar = self._bigger_than_cutoff(scores) return most_similar.index.tolist()
def __list_input_files(self): files = os.listdir(self.settings['input_files_dir']) return [file for file in files if os.path.splitext(file)[1].lower() == '.txt'] def __load_file_refs(self, all_files): refs = {} for file_name in all_files: ref_file_name = os.path.join(self.set...
The code generates a comprehensive report by processing input files for each vendor, aggregating vendor-specific results into a global report, and exporting them to HTML and Excel formats. It checks for processed files, creates vendor reports using their specific logic, and compiles all data into structured outputs for...
def report(self): print("Creating report data...") all_files = self.__list_input_files() file_refs = self.__load_file_refs(all_files) global_report = {} for vendor_name in self.settings['vendors'].keys(): vendor = VENDORS[vendor_name](self.settings['vendors'][vendor_n...
def run_count_reads(target, output, bed_file, genome_sizes, use_fast_count): if target.endswith(".bam"): count_bam(target, bed_file, output, genome_sizes=genome_sizes, use_fast_count=use_fast_count) elif target.endswith(".tagAlign.gz") or target.endswith(".tagAlign.bgz"): count_tagalign(target, ...
This function computes and integrates coverage metrics for a specific genomic feature into a DataFrame. It generates or loads BEDGraph coverage data, merges it with the input DataFrame, calculates read counts, RPM, and optionally RPKM values, and returns the updated DataFrame with these metrics.
def count_single_feature_for_bed(df, bed_file, genome_sizes, feature_bam, feature, directory, filebase, skip_rpkm_quantile, force, use_fast_count): orig_shape = df.shape[0] feature_name = feature + "." + os.path.basename(feature_bam) feature_outfile = os.path.join(directory, "{}.{}.CountReads.bedgraph".form...
def read_bed(filename, extra_colnames=bed_extra_colnames, chr=None, sort=False, skip_chr_sorting=True): skip = 1 if ("track" in open(filename, "r").readline()) else 0 names = ["chr", "start", "end"] + extra_colnames result = pd.read_table(filename, names=names, header=None, skiprows=skip, comment='#') r...
The function processes enhancer data by reading candidate peaks, counting genomic features, assigning gene classes, applying normalization, calculating activity scores, and saving results to files. It handles cell-type annotations, optional qnorm normalization, and outputs detailed enhancer information in BED and tab-s...
def load_enhancers(outdir=".", genome_sizes="", features={}, genes=None, force=False, candidate_peaks="", skip_rpkm_quantile=False, cellType=None, tss_slop_for_class_as...
def setup_device(): return "cuda" if torch.cuda.is_available() else "cpu" def setup_model(model_path): tokenizer = LlamaTokenizer.from_pretrained(model_path) model = LlamaForCausalLM.from_pretrained( model_path, load_in_8bit=True, torch_dtype=torch.float16, device_map="auto" ) tokenizer.pad_...
The code fine-tunes a pre-trained language model using LoRA (Low-Rank Adaptation) for sentiment analysis on the Alpaca Tweets dataset. It loads the model and tokenizer, prepares training/validation data, configures PEFT settings, initializes a trainer, compiles the model, and trains it. After training, the optimized mo...
def main(): DEVICE = setup_device() model, tokenizer = setup_model(Configuration.MODEL_PATH) train_data, val_data = prepare_datasets(data_path="/content/drive/MyDrive/repo/LLM-Sentimental-Analysis/data/alpaca-tweets-sentiment-dataset.csv", tokenizer=tokenizer) model = setup_peft_model(model) train...
def reconnect(self): if self.device_name in TangoAttribute.devices and TangoAttribute.devices[self.device_name] is not self.device_proxy: self.logger.debug('Device proxy changed for %s' % self.full_name) if time.time() - self.time > self.reconnect_timeout: self.connect() ...
This method reads an attribute value synchronously or asynchronously based on parameters, handles connection retries, timeouts, and errors, logs warnings for timeouts, disconnects on repeated failures, and returns the read value.
def read(self, force=None, sync=None): if force is None: force = self.force_read if sync is None: sync = self.sync_read try: self.reconnect() self.test_connection() if force or sync: self.read_sync(force) els...
def reconnect(self): if self.device_name in TangoAttribute.devices and TangoAttribute.devices[self.device_name] is not self.device_proxy: self.logger.debug('Device proxy changed for %s' % self.full_name) if time.time() - self.time > self.reconnect_timeout: self.connect() ...
This code writes a value to an attribute, handling connection management, synchronization/asynchronous writes, and error recovery. It reconnects if needed, validates the connection, processes the value, and uses synchronous or asynchronous writes based on the 'sync' flag. It logs warnings for timeouts, disconnects on r...
def write(self, value, sync=None): if self.readonly: return if sync is None: sync = self.sync_write try: self.reconnect() self.test_connection() wvalue = self.write_value(value) if sync: self.write_sync(wvalu...
def response(self, activations, replay=False): # for i in range(self.layers): response = activations for neuron in self.neurons: response[neuron] = self.neurons[neuron].response(activations) # line below can be compressed? activations[self.neurons[neuron].neur...
This function implements error-driven neurogenesis by adding new neurons to correct high output errors. When error exceeds a threshold, it removes output neurons, creates a new neuron, and connects it to output layers with weights proportional to the error. It also handles replay scenarios by visualizing neurons and ad...
def error_driven_neuro_genesis(self, activations, output_error, correct_class): if np.max(np.abs(output_error)) > self.error_threshold: if self.replaying: # self.response(self.convert_vis_to_activations('out{}'.format(correct_class)), replay=True) self.response(self.c...
def next(): username = current_user.username # print(con.execute("SELECT * FROM label").fetchall()) # q_str = text(f"""SELECT summary_uuid FROM generated_summaries WHERE NOT EXISTS ( # SELECT * FROM label WHERE generated_summaries.summary_uuid = label.summary_uuid AN...
The function `save_annotation` processes form submissions to save user annotations (factual/non-factual labels) along with summary, article, and system data into a database. It determines label type based on checkbox inputs, constructs a database record, and inserts it using an SQL query. Depending on the button clicke...
def save_annotation(): # print('Annotated by ' , current_user.username) # relevancy_score = int(request.form['likert_relevance']) num_sentences = int(request.form['submit_var']) uid = str(request.form['summ_uuid']) # print('NUM SENTENCES', num_sentences) checked_values = [] for i in range(...
def next(): username = current_user.username # print(con.execute("SELECT * FROM label").fetchall()) # q_str = text(f"""SELECT summary_uuid FROM generated_summaries WHERE NOT EXISTS ( # SELECT * FROM label WHERE generated_summaries.summary_uuid = label.summary_uuid AN...
The function `save_annotation` processes user annotations by capturing form data (user ID, summary details, error labels) and saving them to a database table (`error_label`) when the "submit" button is pressed. It handles navigation ("next", "clear") or backtracking based on button values, ensuring structured data stor...
def save_annotation(): user_id = str(request.form['username']) summ_id = str(request.form['summ_id']) summary_uuid = str(request.form['summ_uuid']) system_id = str(request.form['system_id']) button_val = str(request.form['button']) if button_val == 'next': inaccuracy_severity_previ...