dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def build_ana_popup(self, word, lang, matchingAnalyses=None, translit=None): """ Build a string for a popup with the word and its analyses. """ if matchingAnalyses is None: matchingAnalyses = [] data4template = {'wf': '', 'analyses': []} if 'wf_display' in wo...
This function processes a word or lemma from search results, handling frequency data and generating HTML table rows for display. It retrieves and formats frequency, document count, and sentence count from the input data, then renders either a word or lemma table row template with linguistic details like transliteration...
def process_word_buckets(self, w, nDocuments, nForms, freq, lang, searchType='word', translit=None): """ Process one word taken from response['hits']['hits'] for subcorpus or lemma queries (where frequency data comes separately from the aggregations). """ if '_source' not in w: ...
def retrieve_highlighted_words(self, sentence, numSent, queryWordID=''): """ Explore the inner_hits part of the response to find the offsets of the words that matched the word-level query and offsets of the respective analyses, if any. Search for word offsets recursively, so that...
The main task of the code is to process a sentence from a search result, applying formatting, highlighting, and metadata based on parameters like `getHeader` and `format`. It returns structured data including HTML/CSV-formatted text, document headers, alignment info, images, and RTL language flags, while handling text ...
def process_sentence(self, s, numSent=1, getHeader=False, lang='', langView='', translit=None, format='html'): """ Process one sentence taken from response['hits']['hits']. If getHeader is True, retrieve the metadata from the database. Return dictionary {'header': document header HTML, ...
def process_word_buckets_json(self, response, searchType='word', translit=None, subcorpus=True): """ Process hits from the words index by retrieving an object for each bucket in the agg_group_by_word aggregation. This works for lemmata, as well as for any objects searched in a subcorpus....
The function processes search results from a words index, either delegating to `process_word_buckets_json` for lemma/subcorpus queries or aggregating occurrence, document, and frequency data from Elasticsearch hits. It constructs a structured result with counts and processed word entries, handling edge cases like empty...
def process_word_json(self, response, searchType='word', subcorpus=False, translit=None): """ Process hits from the words index. """ if searchType == 'lemma' or subcorpus: return self.process_word_buckets_json(response, searchType=searchType, ...
def get_pos(word): ''' get the POS of a word. Since the POS could depend on the context ('sale' as verb or noun) this is only an approximation ''' doc = nlp(word) return doc[0].pos_ if doc else None def extract_output_dict(model, tokenizer, verse, k): ''' extract the dictionary of the first k guess ...
The function `modify_verse_with_rhyme` enhances a verse by replacing words with BERT-predicted alternatives, ensuring part-of-speech consistency and rhyme alignment with a song’s structure. It masks each word, generates predictions, filters by POS, and prioritizes rhyming words for the final position using a rhyme mode...
def modify_verse_with_rhyme(BERT_model, rhyme_model, tokenizer, verse, num_extractions, normalized_rhyme_scheme, verse_index, song, num_features): ''' Modifies a verse to maintain or create consistent rhymes with other verses in a song. The function iterates over each word in the verse. For each word, it creat...
def get_report(company, year, period, currency='usd'): # TODO: Currently returns {'region_obj':{'li_num':12.34}} # but should change to v_obj structure (array of {'v*','l','r'}) query = r'sid:HFOD\Reports company="{}" year={} period={} currency={}'.format(company, year, period, currency) series = ...
The code loads and processes a financial report by fetching data, filtering regions, applying user-defined overrides, removing dynamic/non-leaf fields, converting region keys to cells, and performing geospatial calculations to generate a structured report.
def load_report(self): # load it up report = get_report(self.company, self.year, self.period, self.currency) report = {region: line_item for region, line_item in report.items() if region.endswith('_obj')} for o in self.overrides: report[r2f(o['r'])][o['l']] = float(o['v']) ...
def getLabels(labelfile): file = open(labelfile, 'rb') file.read(4) n = int.from_bytes(file.read(4), byteorder='big') # number of entries labelarray = bytearray(file.read()) labelarray = [b for b in labelarray] # convert to ints file.close() return n, labelarray def onehot(i, size): ...
The main task of the code is to prepare training and testing datasets for machine learning. It loads labels from files, converts training labels to one-hot encoding, retrieves image data, and combines features with labels using zip. The function returns two datasets: trainingData (images + one-hot labels) and testingDa...
def prepData(): _, training_labels = getLabels(trainingLabelFile) _, testing_labels = getLabels(testingLabelFile) training_labels_onehot = [] for training_label in training_labels: training_labels_onehot.append(onehot(training_label, 10)) training_features = getImgData(trainingImag...
def startStage_1(): global guy,goblins,platforms,pickups,bg,bgStatic,bgSplit, killGoal, state,walkRight,walkLeft,jumpLeft,jumpRight, points points = 0 state = RUNNING bgSplit = 485 walkRight = [pygame.image.load('MAINFILES/carloB/walkR/R%s.png' % frame) for frame in range(1, 10)] walkLeft = [pyg...
The main task of the code is to manage a game loop with state transitions (START, RUNNING, PAUSED, GAME_OVER, NEXT_STAGE), handle user input, render game elements, and control progression between stages based on kill counts. It initializes fonts, processes events, updates game states, and displays appropriate UI elemen...
def main(): global state, stage, font, kills, textFlash, sFont, keyHeld flag = True font = pygame.font.SysFont('comicsansms', 25,2) pFont = pygame.font.SysFont("timesnewroman", 30,2) sFont = pygame.font.SysFont("impact", 35) sFont1 = pygame.font.SysFont("impact", 25) while flag: pyga...
def determine_hub_speed(v_meas, h_meas, h_hub, alpha): """Determine the windspeed at the hub, from ground data. Parameters ---------- v_meas: float Windspeed measured at the ground h_meas: float Height of at which the windspeed is measured h_hub: float Height of the hub ...
This function calculates the daily revenue and average power output of a wind turbine over 24 hours. It simulates hourly wind speed variations, computes hub height wind speed, determines mechanical power using turbine parameters, accumulates energy with efficiency adjustment, and converts total energy to revenue using ...
def determine_revenue(speeds, h_meas, h_hub, alpha, r, omega, rho, coeffs): # Extract value for this case v_rated = speeds[2] total_energy = 0 for hour in range(0, 24): # Step 1. Predict v_meas v_meas = (1.0 + 0.2 * math.cos(math.tau * (hour - 12) / 24)) * v_rated # Step 2. Calc...
def generate_bitstream(n=NBITS): np.random.seed() return np.random.random_integers(0, 1, n) def bits_to_rx(bits, snr, phi=0, f0=F0, f1=F1, sr=SR, bd=BD): """Modulate a bitstream to a received bytestream.""" tx = fsk_samples(bits, np.pi/8, f0, f1, sr, bd) return add_noise(tx, snr) def rx_to_bits(rx, ...
The code calculates the Bit Error Rate (BER) for a given Signal-to-Noise Ratio (SNR) by simulating bit transmission. It iteratively generates bitstreams, introduces noise based on the SNR, compares received bits to original bits, and counts errors. The loop continues until two errors occur or 1 million bits are process...
def ber_for_snr(snr): """Find the BER at SNR=*snr*. Returns BER.""" nbits = 0 errs = 0 while errs < 2 and nbits < 1024*1024: print(" snr={0:+0.02f} nbits={1}".format(snr, nbits)) tx_bits = generate_bitstream(1024) rx = bits_to_rx(tx_bits, snr) rx_bits = rx_to_bits(rx, ...
def get_hdx_project_details(self, key, value): project_api_url = f"{self.RAW_DATA_API_BASE_URL}/hdx/?{key}={value}" max_retries = 3 for retry in range(max_retries): try: logging.info("Fetching Hdx export details %s:%s", key, value) response = requests....
This function gathers HDX project details by querying either ISO3 codes, HDX IDs, or scheduled exports based on frequency. It aggregates results, processes each export to generate task IDs, and returns these IDs after logging the operation.
def init_call(self, iso3=None, ids=None, fetch_scheduled_exports=None): all_export_details = [] if iso3: for country in iso3: all_export_details.append( self.get_hdx_project_details(key="iso3", value=country.upper()) ) if ids: ...
def setVars(self, signal, signalFreq): self.signal = signal self.signalFreq = signalFreq self.N = len(signal) # time stamps of measurements self.timestamp = np.arange( 0, self.N/self.signalFreq, 1/self.signalFreq) super().__init__() def solve(self, signal): ...
The main task of the code is to process an ECG signal using the Pan-Tompkins algorithm for QRS detection. It initializes parameters, applies signal filtering (integration, band-pass, derivative, and squaring), detects QRS peaks, and returns a structured dictionary containing the processed signals, detected peaks, and s...
def run(self, dataObj, *events): print("doing calculations") # run init again self.setVars(dataObj, self.signalFreq) # run the filters self.timestamp = np.arange(0, len(self.signal)) self.integration_signal, self.band_pass_signal, self.derivative_signal, self.square_signa...
def seed_everything(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = True def get_label_trees(df): cat1_tree_dict = {} ...
The main task of the code is to perform 5-fold cross-validation and ensemble learning for a multi-label classification task using a pre-trained Korean language model (KLUE RoBERTa-large). It loads precomputed probability distributions from distillation models, trains a custom model on stratified folds split by 'cat3' l...
def main(): batch_size = 8 num_workers = 4 max_length = 256 max_epoch = 31 learning_rate = 0.00003 seed=44 ### seed is fixed to 44 ################################################################################################################### ## input output path setting and seed se...
def get_time_taken_seconds(self) -> float: return (self.time_end - self.time_begin).total_seconds() def get_result_hash(self) -> str: return self.__result_hash__().hexdigest() def get_result_count_unique(self) -> int: return len(set(self.get_result_values_as_strings())) def get_url_count_unique(...
This method converts an object's attributes into a structured dictionary, containing metadata like timestamps, configuration, query details, results, and statistics for serialization or reporting.
def as_dict(self) -> Dict[str, Any]: return { "time_begin": self.time_begin.strftime(TIME_FORMAT), "time_end": self.time_end.strftime(TIME_FORMAT), "time_taken_seconds": self.get_time_taken_seconds(), "engine_timeout_reached": self.timeout, "engine_con...
def home(self): """ Print list of commands that user can type """ commands = ['register', 'sign in', 'sign out', 'create product', 'show products', 'select product', 'show cart', 'make order', 'show orders', 'exit'] print('Available commands: \n\t', end='') ...
The code defines a menu-driven interface that continuously displays options (home) and executes corresponding actions (e.g., registration, product management, order processing) based on user input until 'exit' is selected. It handles navigation between functions like sign-in, cart viewing, and order creation, maintaini...
def menu(self): cur_key = 'home' while cur_key != 'exit': self.home() if cur_key == 'home': cur_key = input() if cur_key == 'register': self.register() if cur_key == 'sign in': self.sign_in() if c...
def is_suit_elem(self, elem) -> bool: """ Check if elem attributes correspond to database attributes Parameters ---------- elem The element to be added to the database Returns ------- bool Result of comparing element and database ...
The function updates a database entry with the same `idx` attribute by replacing its note. It first validates the input element's compatibility with database columns and checks if an entry with the given `idx` exists. If valid, it retrieves the existing note, deletes it, and inserts the new note from the provided eleme...
def update(self, elem: compatible_with_db_cols) -> None: """ Update note of object with the same <idx> attribute The function finds entry in database with the same idx attribute, and updates it with ``elem`` """ if not self.is_suit_elem(elem): raise ValueError('The e...
def executingTasks(ex: List[List[str]], rec: bool) -> List[List[str]]: crates: List[List[str]] = CRATES for line in ex: move, from_, to_ = [int(x) for x in line.split() if x.isdigit()] crates = ( moveCratesRec(crates, move, from_ - 1, to_ - 1) if rec else move...
The code processes a file containing crate rearrangement instructions, executes them using two methods (True/False), and prints the resulting top crates for comparison.
def main() -> int: ex = openExample("src/examples/ex05.txt") cratesRec = executingTasks(ex[10:], True) crates = executingTasks(ex[10:], False) printCrates(crates) print( "================================================================================================================" ) ...
def add(base, datum): if not base: return datum return ["["] + base + [","] + datum + ["]"] def update(datum): changed = True while changed: changed = False depth = 0 for idx, char in enumerate(datum): if char == "]": depth -= 1 eli...
The code processes each element in the input data by sequentially applying the `add` and `update` functions to a cumulative list (`base`), then returns the magnitude of the final `base` list. The primary task involves iteratively modifying the list through these operations and computing its magnitude as the final outpu...
def part1(data): base = [] for datum in data: base = add(base, datum) base = update(base) return magnitude(base)
def magnitude(datum): while len(datum) > 1: for i in range(len(datum)): if isdigit(datum[i]) and isdigit(datum[i + 2]): datum = ( datum[: i - 1] + [datum[i] * 3 + datum[i + 2] * 2] + datum[i + 4 :] ) break return datum[0] de...
The function computes the maximum magnitude value obtained by adding every distinct pair of elements in the input list `data`, applying an `update` operation on the sum, and then calculating the magnitude. It iterates through all unique pairs, skips identical elements, and tracks the highest magnitude value encountered...
def part2(data): max_val = 0 for datum in data: for datum2 in data: if datum == datum2: continue val = magnitude(update(add(datum, datum2))) max_val = max(max_val, val) return max_val
def check_database(): """ Check if the table exists, and seed the database if it doesn't """ inspector = Inspector.from_engine(db.engine) tables = inspector.get_table_names() if "mooches_table" not in tables or "definitions" not in tables \ or "failed_nominations" not in tables: ...
The main task of the code is to synchronize a spreadsheet with a database by deleting existing "Mooch" records and adding new entries from the spreadsheet. It checks for non-existent entries in "departures" and "legend" data, collects them into new_records, deletes all current "Mooch" rows, and inserts the new records,...
def update(): """ Scrape the spreadsheet, and if the entry does not already exist then add it """ check_database() new_records = [] for obj in enumerate_departures(): #if not mooch_exists(obj): new_records.append(obj) for obj in enumerate_legend(): if not definiti...
def get_account(index=None, id_=None): """Return account""" # accounts[0] # accounts.add("env") # accounts.load("id") if index: return accounts[index] if id_: return accounts.load(id_) if ( network.show_active() in LOCAL_BLOCKCHAIN_ENVIRONMENTS or network.show...
The function funds a VRF subscription with LINK tokens, ensuring a minimum balance. It creates a subscription and funds it on local networks, or tops up existing subscriptions on live networks if their balance falls below the threshold, returning the subscription ID and details.
def fund_subscription( account=None, vrf_coordinator=None, amount=1000000000000000000, # 1 LINK min_balance=5, force=False, ): """ Transfer LINK token back to minimum balance amount. Use VRFCoordinatorV2Mock to fund subscription for local test. 1 LINK = 1000000000000000000, Re...
def make10000inputs(deltaP): inputList = [] plaintText1 = [] plaintText2 = [] b = 0 for i in range(5000):#TODO change back to 10 000 b = random.randint(131071) plaintText1 = decimalToBinary(b ) if (len(plaintText1) < 16): plaintText1 = np.concatenate((np.array([0]...
The main task of the code is to perform differential cryptanalysis on a block cipher by generating 10,000 plaintext pairs with a specific difference, encrypting them through multiple rounds using a fixed S-box and key schedule, and analyzing ciphertext differences to determine the probability of each subkey in a predef...
def main(): ''' input = [1,0,1,1] sBoxDictionary = {} randomArray = np.arange(16) np.random.shuffle(randomArray) print("sBox mapping:") print(randomArray) for i in range(16): sBoxDictionary[i]= randomArray[i] sbox1 = SBox(randomArray,randomArray) result = sbox1.sbo...
def calculate_cover(ann_list, data_type='coco'): person_per_img = 0 occlusion_per_img = 0 for ann in ann_list: if data_type == 'coco': per_kpt = np.array(ann['keypoints']).reshape(17, 3) else: per_kpt = np.array(ann['keypoints']).reshape(14, 3) all_kpt_num =...
The function calculates the maximum value among three indices—coverage, crowding, and completeness—derived from an annotation list using helper functions. If the coverage index is invalid (-1), it returns -1; otherwise, it returns the highest of the three indices to represent the dominant metric for the given dataset t...
def calculate_total_max_mean(ann_list, data_type='coco'): cover_index = calculate_cover(ann_list, data_type) crowd_index = calculate_crowd(ann_list, data_type) complete_index = calculate_mean_complete(ann_list, data_type) # print(cover_index, crowd_index, complete_index) if cover_index == -1: ...
def calculate_single_cover(ann, data_type='coco'): occlusion_per_img = 0 if data_type == 'coco': per_kpt = np.array(ann['keypoints']).reshape(17, 3) else: per_kpt = np.array(ann['keypoints']).reshape(14, 3) all_kpt_num = np.sum(per_kpt[:, 2] > 0) if all_kpt_num == 0: retur...
This function calculates the maximum value among three indices—coverage, crowding, and completeness—for a single annotation, using the specified data type (default: COCO). It returns the highest index, or -1 if coverage is invalid.
def calculate_single_total_max_mean(single_ann, ann_list, data_type='coco'): cover_index = calculate_single_cover(single_ann, data_type) crowd_index = calculate_single_crowd(single_ann, ann_list, data_type) complete_index = calculate_single_mean_complete(single_ann, data_type) # print(cover_index, crowd...
def unary(self): print("UNARY") if self.check_tokens([Token.PLUS, Token.MINUS]): self.next() self.primary() def check_tokens(self, tts: list): """ Returns true if the current token matches any tokens in the list """; return self.ctok.tt in tts def next(self): """Advances the cu...
The code parses arithmetic expressions involving multiplication and division. It starts by printing "TERM", calls a unary operation method, then repeatedly checks for multiplication/division tokens, advances the tokenizer, and applies unary operations again to handle multi-term expressions.
def term(self): print("TERM") self.unary() while self.check_tokens([Token.MUL, Token.DIV]): self.next() self.unary()
def term(self): print("TERM") self.unary() while self.check_tokens([Token.MUL, Token.DIV]): self.next() self.unary() def check_tokens(self, tts: list): """ Returns true if the current token matches any tokens in the list """; return self.ctok.tt in tts def next(...
This code parses arithmetic expressions with addition and subtraction. It starts by processing a term, then repeatedly checks for '+' or '-' operators. When found, it consumes the operator and processes another term, effectively building the expression by combining terms with additive operators. The loop continues unti...
def expression(self): print("EXPRESSION") self.term() while self.check_tokens([Token.PLUS, Token.MINUS]): self.next() self.term()
def expression(self): print("EXPRESSION") self.term() while self.check_tokens([Token.PLUS, Token.MINUS]): self.next() self.term() def is_comparison_op(self): return self.check_tokens([ Token.GT, Token.GTE, Token.LT, Token.LTE, Token.BEQ, Token.NO...
This code parses a comparison expression by checking for valid comparison operators between expressions. It starts with an expression, verifies the presence of a comparison operator, processes the next expression, and repeats this in a loop to handle chained comparisons. If an expected operator is missing, it aborts wi...
def comparison(self): print("COMPARISON") self.expression() if self.is_comparison_op(): self.next() self.expression() else: self.abort( f"Expected comparison operator at: {self.ctok.val}" ) while self.is_comparison_op(): ...
def check_token(self, tt): """ Return true if the current token matches """; return tt == self.ctok.tt def next(self): """Advances the current token""" self.ctok = self.ptok self.ptok = self.lexer.token def comparison(self): print("COMPARISON") self.expression() ...
This method parses and emits code for various statements in a simple programming language. It handles `print` statements (string or expression), `if`/`while` loops (processing conditions and blocks), `let` variable declarations, and `input` operations. It checks tokens, updates symbol tables, and uses an emitter to gen...
def statement(self): if self.check_token(keywords['print']): self.next() if self.check_token(Token.STRING): self.emitter.emit_line( f'print("{self.ctok.val}")' ) self.next() else: self.emitte...
def readInputFile(fname): with open(fname) as f: lines = f.readline() pixel = list(map(int, lines.split())) lines = f.readline() lines = lines.split() startGoal = [int(i) for i in lines] lines = f.readline() numOfPoly = int(lines) polyList = [[0...
The code implements a menu-driven system to execute various search algorithms (BFS, UCS, IDS, GBFS, A*) on a grid with obstacles, visualized using Python's `turtle` module. It reads input data, draws the grid and polygons, and applies the selected algorithm to find paths between start/goal points. The user can repeat t...
def main(): choice = 0 option = 0 while True: tur = turtle.Turtle() turtle.clearscreen() # turtle.done() print('1. Breadth-first search') print('2. Uniform-cost search') print('3. Iterative deepening searh') print('4. Greedy-best f...
def is_question(user_string): #Checks if the user's string ends in a question mark return user_string[-1] == "?" def get_first_quotes(list_of_quotes): first_quotes = [] for i in list_of_quotes: first_quotes.append(i[0]) return(first_quotes) def respond(list_of_quotes, input_question): list_o...
The code defines a chatbot that processes user questions using different matching strategies based on the version parameter. Version 0 checks exact matches, Version 1 uses similarity thresholds (0.6) to find close matches, and Version 2 identifies the best match (threshold 0.5) by comparing word overlaps between user i...
def chatbot(version): user_input = "" print("Welcome!") user_input = input("Ask me anything. When you're done, just type \'bye\'\n - ").lower() if version == 0: while user_input != "bye": if is_question(user_input): if user_input in get_first_quotes(get_quotes()): ...
def fitness(self, chromosome): n = len(chromosome) horizontal_conflicts = ( sum([chromosome.count(queen) - 1 for queen in chromosome]) / 2 ) left_diagonal = [0] * 2 * n right_diagonal = [0] * 2 * n for i in range(n): left_diagonal[i + chromosome...
The code implements a genetic algorithm to solve the N-Queens problem. It iteratively evolves a population of chromosomes (potential solutions) until one achieves the maximum fitness (no conflicting queens). For N=2 or 3, it immediately reports no solution. Otherwise, it generates new populations via genetic operations...
def solve(self): if self.n == 2 or self.n == 3: print(f"No solution possible for {self.n} queens.") return # saat nilai fitness dari kromosom tiap populasi tidak sama dengan max fitness while not self.max_fitness in [ self.fitness(chromosome) for chromosome i...
def get_rows_proposition(self, board, queen): rows = [] for row in range(self.n): if self.is_correct(board, row, queen): rows.append(row) return rows def get_unassigned_from_constraint(self, board, queen): result = [] for row in range(self.n): ...
This code implements a backtracking algorithm with forward checking to solve the N-Queens problem. It attempts to place queens column by column, checks for conflicts using constraints, and recursively explores valid placements. If a placement leads to a dead end (domain wipe-out), it backtracks. The solution terminates...
def solve(self, board, queen): if self.n == 2 or self.n == 3: print(f"No Solution possible for {self.n} queens.") return if self.n == queen: self.status = True return True rows_proposition = self.get_rows_proposition(board, queen) for ro...
def read_schema(schema_name, version): schema_urls = { "deployments": f"https://raw.githubusercontent.com/tdwg/camtrap-dp/{version}/deployments-table-schema.json", "media": f"https://raw.githubusercontent.com/tdwg/camtrap-dp/{version}/media-table-schema.json", "observations": f"https://raw.g...
The code defines a command-line interface using argparse, supporting subcommands like 'schema', 'datapackage', 'deployments', 'media', 'observations', and 'all'. Each subcommand requires specific arguments (e.g., path, version) and triggers corresponding functions (e.g., read_schema, create_datapackage). The 'all' comm...
def main(): parser = argparse.ArgumentParser() subparser = parser.add_subparsers(dest="command") schema = subparser.add_parser("schema") datapackage = subparser.add_parser("datapackage") deployments = subparser.add_parser("deployments") media = subparser.add_parser("media") observations...
def add_event_deployments(resource: dict): location = get_location(resource.get('deploymentID')) event = models.Event( event_id = resource.get('deploymentID'), parent_event_id = None, dataset_id = 'ningaloo', location_id = location.location_id, protocol_id = None, ...
The code processes three resources ('deployments', 'media', 'media-observations') from a package. For each row in these resources, it converts the row to a dictionary and passes it to corresponding functions (`add_event_deployments`, `add_event_media`, `add_event_media_observation`) to generate event-related data, prin...
def manage_event(package): # deployments = package.get_resource('deployments') # pprint(deployments.read_rows()) # print(type(deployments)) # pprint(deployments.header) with package.get_resource('deployments') as resource: for row in resource.row_stream: # print(f'Row: {row}')...
def add_digital_entity(resource: dict): digital_entity = models.DigitalEntity( digital_entity_id = f"digent_{resource.get('mediaID')}", digital_entity_type = 'MOVING_IMAGE', access_uri = resource.get('filePath'), web_statement = None, format = resource.get('fileMediatype'), ...
The code processes media and media-observations resources from a package. It converts each row to a dictionary, creates digital entities from media data, and generates organism/identification records from media-observations, printing results. The main task is to transform structured data into digital entities and assoc...
def manage_entity(package): with package.get_resource('media') as resource: for row in resource.row_stream: media_dict = row.to_dict(json=False) digital_entity_media = add_digital_entity(resource=media_dict) print(f"digital_entity_media: {digital_entity_media}") ...
def manage_location(package): with package.get_resource('deployments') as resource: for row in resource.row_stream: deployment = row.to_dict(json=False) add_location(resource=deployment) add_georeference(resource=deployment) def manage_event(package): # deployments...
The main task of the code is to process a data package containing CSV files, truncate a database, and populate it with structured data by managing locations, events, entities, assertions, and taxon identifications. Finally, it executes an export process to generate output files, ensuring data is correctly imported and ...
def main(): # package = Package('output/datapackage.json') package = Package('output/dp/*.csv') # pprint(package.extract()) database.truncate_db() manage_location(package) manage_event(package) manage_entity(package) manage_assertion(package) manage_taxon_identification(package) ...
def ics_next_event(ics_data: str, now: arrow, timezone: str) -> Optional[ics.Event]: curr = None diff = None cal = ics.Calendar(ics_data) event = None for event in cal.events: # Set correct timezone event.begin = event.begin.replace(tzinfo=timezone) if event.begin.datetime ...
The function retrieves the next upcoming event from a calendar, adjusts for timezone, checks if it's today (or allowed to show future days), formats the time as "human-readable" or "HH:mm", and returns an `Event` object with name, formatted time, and an alert flag indicating if the event is approaching.
def upcoming_event() -> Optional[Event]: """Get the next event closest in time""" config: Config = caep.load(Config, "ICAL Status", "icalstatus", "config", "status") now = arrow.now().replace(tzinfo=config.timezone) next = ics_next_event( get_data(config.calendar_url, config.no_verify, config....
def demo_on(self): self.clock = pygame.time.Clock() self.demo_screen = pygame.display.set_mode((self.demo_size, self.demo_size)) def reset(self, seed=None): if seed is not None: self.rng = np.random.default_rng(seed) # agent start at the center self.agent_position = ...
This code demonstrates a random policy in a simulated environment using Pygame. It runs for a specified number of steps (default: 1000), rendering each state, taking random actions (0-4), and handling user interrupts to exit gracefully.
def demo_random_policy(self, demo_step=1000): self.demo_on() self.reset(seed=random.randint(0, 10000)) for _ in range(demo_step): # Handle events (so that you can quit the pygame window and it won't freeze) for event in pygame.event.get(): if event.type ...
def isPlayable(self, play_card, table_card): def equalCheck(card1, card2): if card1 == card2: return True else: return False tc_color = table_card.getColor() tc_usage = table_card.getUsage() tc_number = table_card.getNumber() ...
This function automatically selects and plays a playable card from the player's deck. If no playable cards exist, it buys a new card and checks playability again. It returns whether the next player needs to take an action after playing a card, ensuring continuous game progression by handling both existing and newly acq...
def autoPlay(self, player, table_card): cards = player.getCards() player_name = player.getName() next_player_action = False # player.showCards() for index, card in enumerate(cards): played = False if self.isPlayable(card, table_card): pla...
def deckAssemble(self): # reads json with open('assets/deck.json','r') as file: cards = load(file) for card in cards: self.deck.append( Card(card['color'], card['number'], card['usage'] ) ...
The code initializes a card game by assembling a deck, drawing cards, and starting the game. The `init` method sets up the game state by calling `deckAssemble` to create the deck, `drawCards` to distribute cards, and `start` to initiate gameplay. This structure prepares the game for player interaction and execution.
def init(self): self.deckAssemble() self.drawCards() self.start()
def print_judge_summary(judges: list[JudgeAvailability]) -> str: """Outputs the number of available judges for each round E.g.: Round 1: 10 Round 2: 8 ... """ output = "Judges available per round:" for round_name in ROUND_ORDER: num_judges = len( [judge for judge in ...
The main task of the code is to generate a judge schedule based on a maximum time per stage constraint. It retrieves judge data, prints a summary, creates a schedule with the specified time limit, displays the formatted schedule, and exports it to a CSV file alongside judge details.
def main(max_time_per_stage): judges = get_judge_data() print(print_judge_summary(judges)) schedule = create_schedule(judges, max_time_per_stage=max_time_per_stage) print(pretty_print_schedule(schedule)) write_schedule_to_csv(schedule, judges, "schedule.csv")
def get_ec2_client(): try: client = get_session().client('ec2') except Exception as e: print(f"Failed with error '{e}'") print("To specify Virginia region, do 'export AWS_DEFAULT_REGION=us-east-1'") sys.exit() return client def is_good_response(response): """Helper method to check if boto3 call ...
The function retrieves a dictionary of named VPCs from AWS, using tags to assign names. It ensures uniqueness by asserting no duplicate names and skips unnamed VPCs. The result maps each valid name to its corresponding VPC object, logging warnings for duplicates if detected.
def get_vpc_dict(): """Returns dictionary of named VPCs {name: vpc} Assert fails if there's more than one VPC with same name.""" client = get_ec2_client() response = client.describe_vpcs() assert is_good_response(response) result = OrderedDict() ec2 = get_ec2_resource() for vpc_response in response['...
def get_efs_client(): while True: try: return get_session().client('efs') except Exception as e: # can get following # botocore.exceptions.DataNotFoundError: Unable to load data for: endpoints util.log(f"get_session().client('efs') failed with {e}, retrying") time.sleep(2) def ca...
The main task of the code is to retrieve a dictionary mapping EFS names to their corresponding EFS IDs by querying AWS EFS resources. It uses the EFS client to list all file systems, fetches their tags to identify names, filters out unnamed systems, and constructs an ordered dictionary with unique name-to-ID mappings. ...
def get_efs_dict(): """Returns dictionary of {efs_name: efs_id}""" # there's no EC2 resource for EFS objects, so return EFS_ID instead # https://stackoverflow.com/questions/47870342/no-ec2-resource-for-efs-objects efs_client = get_efs_client() response = call_with_retries(efs_client.describe_file_systems, ...
def get_ec2_client(): try: client = get_session().client('ec2') except Exception as e: print(f"Failed with error '{e}'") print("To specify Virginia region, do 'export AWS_DEFAULT_REGION=us-east-1'") sys.exit() return client def is_good_response(response): """Helper method to check if boto3 call ...
This function retrieves all named EC2 security groups from AWS, maps each to its name as a dictionary key, and returns the ordered dictionary. It skips unnamed groups, logs warnings for duplicates, and enforces uniqueness if configured. The result uses security group IDs as values for named entries.
def get_security_group_dict(): """Returns dictionary of named security groups {name: securitygroup}.""" client = get_ec2_client() response = client.describe_security_groups() assert is_good_response(response) result = OrderedDict() ec2 = get_ec2_resource() for security_group_response in response['Securi...
def get_username(): assert 'USER' in os.environ, "why isn't USER defined?" return os.environ['USER'] def validate_aws_name(name): """Validate resource name using AWS name restrictions from # http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-restrictions""" assert len(name) <= 127 # disall...
The main task of the code is to generate a valid AWS keypair name by combining a prefix with the current username, ensuring the username contains no hyphens, adheres to AWS naming rules, and stays under 30 characters to avoid AWS limits.
def get_keypair_name(): """Returns current keypair name.""" username = get_username() assert '-' not in username, "username must not contain -, change $USER" validate_aws_name(username) assert len(username) < 30 # to avoid exceeding AWS 127 char limit return get_prefix() + '-' + username
def get_ec2_resource(): try: client = get_session().resource('ec2') except Exception as e: print(f"Failed with error '{e}'") print("To specify Virginia region, do 'export AWS_DEFAULT_REGION=us-east-1'") sys.exit() return client def get_prefix(): """Global prefix to identify ncluster created reso...
The function `lookup_instance` searches for an existing AWS EC2 instance by name, filtering instances based on state and ensuring they match the current environment's prefix and username. It verifies the instance's type and image name if specified, raising errors for mismatches. It returns the first matching instance o...
def lookup_instance(name: str, instance_type: str = '', image_name: str = '', states: tuple = ('running', 'stopped', 'initializing')): """Looks up AWS instance for given instance name, like simple.worker. If no instance found in current AWS environment, returns None. """ ec2 = get_ec2_resour...
def get_efs_client(): while True: try: return get_session().client('efs') except Exception as e: # can get following # botocore.exceptions.DataNotFoundError: Unable to load data for: endpoints util.log(f"get_session().client('efs') failed with {e}, retrying") time.sleep(2) def is...
The main task of the code is to create an Amazon EFS file system with a specified name, handle retries if the file system already exists, extract the created file system's ID using a unique token, tag it with the provided name, and verify its visibility in a local dictionary before returning the corresponding entry.
def create_efs(name): efs_client = get_efs_client() token = str(int(time.time() * 1e6)) # epoch usec response = efs_client.create_file_system(CreationToken=token, PerformanceMode='generalPurpose') assert is_good_response(response) start_time = time.time() while T...
def get_keypair_name(): """Returns current keypair name.""" username = get_username() assert '-' not in username, "username must not contain -, change $USER" validate_aws_name(username) assert len(username) < 30 # to avoid exceeding AWS 127 char limit return get_prefix() + '-' + username def get_account_n...
The function generates a file path for a PEM keypair by combining the keypair name, account number, and region into a formatted string, returning the full path under the PRIVATE_KEY_LOCATION directory.
def get_keypair_fn(): """Location of .pem file for current keypair""" keypair_name = get_keypair_name() account = get_account_number() region = get_region() fn = f'{PRIVATE_KEY_LOCATION}/{keypair_name}-{account}-{region}.pem' return fn
def _sample_beam(self, fc_feats, att_feats, att_masks=None, opt={}, batch_index = None): beam_size = opt.get('beam_size', 10) group_size = opt.get('group_size', 1) sample_n = opt.get('sample_n', 10) batch_index[:] = sample_n # when sample_n == beam_size then each beam is a sample...
This code generates sequences (e.g., captions) using sampling methods like greedy or beam search, handling batch processing, constraints (e.g., trigram blocking, bad ending removal), and temperature scaling. It iteratively predicts next words based on log probabilities, applies decoding constraints, and returns generat...
def _sample(self, fc_feats, att_feats, att_masks=None, batch_index=None, opt={}): sample_method = opt.get('sample_method', 'greedy') beam_size = opt.get('beam_size', 1) temperature = opt.get('temperature', 1.0) sample_n = int(opt.get('sample_n', 1)) group_size = opt.get('group_s...
def prelimSolve(data): # set hasNakedSingles to true to keep the solve process going until marked false. hasNakedSingles = True while hasNakedSingles: edited = False for i in range(9): for j in range(9): log("value = ", data[i][j]) # if a index loc...
The main task of the code is to solve a puzzle (e.g., Sudoku) using backtracking by recursively attempting values in empty cells. It processes the dataset, identifies the first empty cell, and iteratively fills it with possible values, recursively solving the modified dataset. If a valid solution is found, it returns i...
def guessSolve(data): newDataSet = prelimSolve(data) # done and failed if newDataSet == None: return None firstEmptyCellInfo = findFirstEmptyCell(newDataSet) # done and successful if firstEmptyCellInfo == None: return newDataSet # happens if not done for value in firs...
def take_input (puzzle): # creates soduku in 2d array log("puzzle", puzzle) sudokuData=[[],[],[],[],[],[],[],[],[]] i=0 while (i<=8): j=0 while(j<=8): sudokuData[i].append(puzzle[f'{i}-{j}']) j+=1 i+=1 log("organized sudokuData", sudokuData) re...
The function `solve_one` processes input data by first obtaining and logging the dataset, then applying a preliminary solution (`prelimSolve`) to transform it. It prints each element of the transformed dataset (indices 0–8) for inspection before returning the modified dataset. The core tasks involve data transformation...
def solve_one(data): dataSet = take_input(data) log(dataSet, "dataSet") newDataSet = prelimSolve(dataSet) print("newDataSet") print(newDataSet[0]) print(newDataSet[1]) print(newDataSet[2]) print(newDataSet[3]) print(newDataSet[4]) print(newDataSet[5]) print(newDataSet[6]) ...
def ave_of_segmentation (dict_segment,args=None): """_summary_ Args: dict_segment (_type_): _description_ args (_type_, optional): _description_. Defaults to None. Returns: _type_: _description_ """ imlist = list ( dict_segment.keys() ) N = len(imlist)*1.0 # float arr=np.zeros(dic...
The function computes and saves averaged segmentation images from a group of data, applying parameters like smoothing, thresholding, and pixel cutting. It constructs a filename prefix based on arguments, then either averages segmentations directly or averages images first before segmenting. Outputs are saved as PNGs, w...
def average_over_data (group_name, segmentation_of_group, args, suffix_to_add=""): """_summary_ Args: group_name (_type_): _description_ suffix_to_add (_type_): when compare group1-NIH vs group1-Peter, group_name=Group1 in both sets, so we need @suffix_to_add segmentation_of_group (_type_): _des...
def item(name: str = None, item_template: Item_Template = None): if name: item_template = local_session.query(Item_Template).filter(Item_Template.name == name).first() if not item_template: print("no template") return item_type = item_template.item_type kwargs = item_templa...
The function creates an Area instance by either using a provided Area_Template or querying the database for a template with the given name. It copies the template's attributes, initializes an Area object, and populates it with inventory items, containers, and rooms derived from the template. The resulting Area is retur...
def area(name: str = None, area_template: Area_Template = None): global npcs if name: area_template = local_session.query(Area_Template).filter(Area_Template.name == name).first() if not area_template: print("no template") return kwargs = area_template.__dict__.copy() k...
def check_versions(self): self.cefstream.get_logger().info("CEF Python {ver}".format(ver=cef.__version__)) self.cefstream.get_logger().info("Python {ver} {arch}".format(ver=platform.python_version(), arch=platform.architecture()[0])) assert cef.__version__ >= "55.3", "CEF Python v55.3+ required ...
The code initializes a CEF-based browser with windowless rendering, sets a frame rate of 55 FPS, creates a browser window for "https://google.com/", and starts the message loop to handle events. It ensures version compatibility and logs initialization status.
def launch(self): self.check_versions() self.cefstream.get_logger().info('Initializing CEF') settings = { "windowless_rendering_enabled": True } cef.Initialize(settings=settings) self.set_fps(55) self.create_browser(identifier='dzikoysk.net', url='ht...
def connect(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((SERVER_IP, SERVER_PORT)) return s def login(conn): while (True): username = input("Please enter username: \n") password = input("Please enter password: \n") build_and_send_message(conn, chatlib.PROTOCOL_CLIENT["login_msg"], use...
The main task of the code is to manage a trivia game interface, allowing users to play questions, check scores, view high scores, and monitor logged-in users via a command menu. It maintains a database connection, processes user inputs, and executes corresponding functions like `play_question`, `get_score`, and `get_hi...
def main(): conn = connect() login(conn) while (True): print("""p Play a trivia question s Get my score h Get high score l Get logged users q Quit""") cmd = input("Write a command \n") if (cmd == "s"): get_score(conn) elif (cmd == "h"): get_highscore(conn) e...
def startup(): update_viewport(None, 400, 400) glClearColor(0.5, 0.5, 0.5, 1.0) def render(time): glClear(GL_COLOR_BUFFER_BIT) dywan(-100.0, -80.0, 200.0, 7.0) glFlush() def shutdown(): pass
This code initializes a GLFW window for OpenGL rendering, sets up a rendering loop with vsync, and manages the OpenGL context lifecycle. It creates a 400x400 window, registers a viewport update callback, and repeatedly calls a render function using the current time. The loop continues until the window is closed, then r...
def main(): if not glfwInit(): sys.exit(-1) window = glfwCreateWindow(400, 400, __file__, None, None) if not window: glfwTerminate() sys.exit(-1) glfwMakeContextCurrent(window) glfwSetFramebufferSizeCallback(window, update_viewport) glfwSwapInterval(1) startup() ...
def create_site_instance(self): try: target_exe = "chromedriver.exe" driver_path = glob.glob(os.path.join(os.getcwd() + '\\lib', '**', target_exe), recursive=True)[0] chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--no-sandbox") ...
This function repeatedly attempts to log in to a portal by creating a site instance, killing existing Chrome processes, and checking the login URL. It uses a counter to limit retry attempts, raising an exception if login fails after reaching the maximum allowed attempts. The loop continues until successful login or err...
def re_login_if_not_logged_in(self): counter = Counter(max_count=self.max_count) Utils.kill_all_chrome_processes() while True: try: self.create_site_instance() self.login() if self.driver.current_url == self.portal_config.portal_home_ur...
def re_login_if_not_logged_in(self): counter = Counter(max_count=self.max_count) Utils.kill_all_chrome_processes() while True: try: self.create_site_instance() self.login() if self.driver.current_url == self.portal_config.portal_home_ur...
The main task of the code is to retrieve a student's name, attendance records, and timetable data by first ensuring login status, then compiling these details into a list for return.
def get_attendance_with_timetable(self): try: self.re_login_if_not_logged_in() student_name = self.get_student_name() attendance_tracker = self.get_attendance(student_name) timetable = self.get_timetable() return [student_name, attendance_tracker, time...
def mirror_board(self): mirrored = [0, 0] mask = pow(2, 6) - 1 for i in range(2): mirrored[i] |= (self.board[i] & mask) << 42 mirrored[i] |= (self.board[i] & (mask << 7)) << 28 mirrored[i] |= (self.board[i] & (mask << 14)) << 14 mirrored[i] |= self...
This code implements the negamax algorithm with alpha-beta pruning and transposition table to determine the optimal move in a Connect Four game. It evaluates board states recursively, prioritizes winning moves, uses heuristics for depth-zero evaluations, and stores results in a table to avoid redundant calculations.
def search(self, depth, alpha=-math.inf, beta=math.inf, tt=None): # negamax search algorithm with alpha-beta pruning tuple_board = tuple(self.board) # this ensures the table is cleared each run if tt is None: tt = {} # check if position has been found if tupl...
def hamiltonian_path_helper(raw_obs): r_obs = torch.zeros(raw_obs.shape) r_obs[BODY][0, 1] = 1 r_obs[HEAD][0, 1] = 1 r_obs[FOOD][0, 0] = 1 path = np.array(longest_path_helper(r_obs)) path = np.append(path, np.array([[0,1],[0,2]])).reshape(-1, 2) return path def get_dist(x): return hamilt...
The code implements an optimized Hamiltonian path search for a snake game, determining the best movement direction. It uses a precomputed Hamiltonian path (`path_h`) and a grid mapping to evaluate potential moves. The function checks valid directions, calculates distances for the snake's head, tail, and food, and selec...
def optimised_hamiltonian_path_search(raw_obs): ''' Optimised hamiltonian path search on raw observation (takes shortcuts) ''' global path, hamiltonian_grid, path_h if path_h is None: path_h = hamiltonian_path_helper(raw_obs) max_size = len(path_h) if hamiltonian_grid is N...
def sortScale(scale): return sorted(list(set(scale))) def transpose(scale, interval): return [add(s, interval) for s in scale] def getModeNumber(scale, scaleGroupRepresentative): curr_mode = 0 for i in range(0, 12): cp = sortScale(transpose(scaleGroupRepresentative, -i)) if cp == scale: return cur...
This code identifies a musical scale from a pitch class list by transposing it through 12 possible positions, checking for matches against predefined scales. If a match is found (with a root note '0'), it returns the scale's name, details, transpose value, and mode number. If no match is found, it returns an error mess...
def getScaleFromPCList(pclist): for i in range(0, 12): cp = sortScale(transpose(pclist, i)) if 0 in cp: for c in scales.items(): if cp == c[1]["Notes"]: m = getModeNumber(pclist, cp) return {"Name": c[0], "Details": c[1], "Transpose": i, "Mode": m} return({"Name": "No match...
def write_model_metadata(self, model): """ Write out the model metadata. Args: model (dict) A dictionary containing the metadata of the model used. """ # Open the file self._open_file() # Create a group for the model metadata ...
The function writes common datasets and attributes for a Synthesizer grid, including axis arrays, spectra grids, wavelength data, and model metadata. It handles unit conversions, applies default descriptions, manages alternative axis names via soft links, and validates inputs. The goal is to standardize grid structure ...
def write_grid_common( self, axes, wavelength, spectra, alt_axes=(), descriptions={}, model={}, ): """ Write out the common parts of a Synthesizer grid. This writer method writes all datasets and attributes that Synthesizer exp...
def read_files(*files): f = [] for i in files: r = open(i, 'r').read().split('\n')[:-1] r = [(j.split(',')[0], j.split(',')[1]) for j in r] f.append(r) return f def to_bits(inp, len): return bin(int(inp, 16))[2:].zfill(len) def six_to_five(k6): k6 = [bin(i)[2:].zfill(6) if i ...
The function identifies the correct value of `tk[2]` in a cryptographic key by analyzing decrypted blocks. It performs XOR operations on hex values, converts results to bits, and tests 64 potential key values. For each candidate key, it decrypts data, compares bit results with a reference value, and counts successful m...
def find_S3_r6_subbits(): outp = read_files('filtered_out_c1.txt')[0] d = {} dx = '40080000' tk = [i for i in k6] for out in outp: fx = xor(bytes.fromhex(out[0][:8]), bytes.fromhex(out[1][:8])).hex() dfx = xor(bytes.fromhex(dx), bytes.fromhex(fx)).hex() dfx = to_bits(dfx, 32)...
def read_files(*files): f = [] for i in files: r = open(i, 'r').read().split('\n')[:-1] r = [(j.split(',')[0], j.split(',')[1]) for j in r] f.append(r) return f def six_to_five(k6): k6 = [bin(i)[2:].zfill(6) if i != '$' else '$$$$$$' for i in k6] k6 = ''.join(k6) k5 = ['$...
The code performs a cryptanalytic attack to determine a likely key candidate by analyzing differences in decrypted blocks. It processes encrypted outputs, decrypts them with a key `k6`, and uses intermediate values (`_si1`, `_si2`, `_sox`) to test possible key bits through s-box transformations. By iterating over speci...
def break_r5(): global kf kf = 1 d = {} outp = read_files('filtered_out_c1.txt')[0] k5 = six_to_five(k6) for out in outp: b60 = decrypt_block(out[0], k6) b61 = decrypt_block(out[1], k6) _si1, _si2, _sox = till_s_in_out(b60, b61, '40080000') sk = [] for i i...
def permute(k, arr, n): permutation = "" for i in range(0, n): permutation = permutation + k[arr[i] - 1] return permutation def to_bits(inp, len): return bin(int(inp, 16))[2:].zfill(len) def find_round_key(out, ex, selected_boxes): for i in range(len(out)): _s1, _s2, _so = till_s_in_...
This function performs differential cryptanalysis on a block cipher by analyzing input differences (dx, cx), applying permutations and substitutions to derive a candidate round key. It identifies zero-value chunks in transformed data, computes an approximate key via XOR operations, and selects the most frequent key fro...
def break_r6(out_tup, dx, cx): global key_dict, partial_key t = permute(to_bits(dx, 32), exp, 48) arr = [t[i:i+6] for i in range(0,48,6)] arr2 = ['0000' if i=='000000' else '1111' for i in arr] sel_box = [i for i in range(len(arr)) if arr[i]=='000000'] Dx = int(permute(''.join(arr2), per, 32), 2...
def get_cip(inp, io): io.sendline(mod_inp(inp)) io.recvuntil('It reads ...\r\n\t\t') out = io.recvuntil('\r\n\r\n\r\nPress').decode()[:-11] io.recvuntil('> ') io.sendline('c') return out def dec(inp): out = "" for i in inp: out += hex(ord(i)-ord('f'))[2:] return out def revp(...
This code retrieves a password from input 'io', decrypts it, splits the result into two 16-byte parts, processes each part with the 'revp' function using 'iip' as an argument, and returns the processed pairs as a tuple (a, b).
def get_pass(io): out = get_cip('password', io) out = dec(out) a, b = revp(out[:16], iip), revp(out[16:], iip) return a,b
def read_files(*files): f = [] for i in files: r = open(i, 'r').read().split('\n')[:-1] r = [(j.split(',')[0], j.split(',')[1]) for j in r] f.append(r) return f def break_r6(out_tup, dx, cx): global key_dict, partial_key t = permute(to_bits(dx, 32), exp, 48) arr = [t[i:i+...
The function performs cryptanalysis by reading ciphertexts from two files, applying the `break_r6` method with specific hex keys to each, and then uses the resulting partial key to retrieve a 42-byte output via `obtain_42b`.
def start_cryptanalyis(): _o = read_files('outputs_c1.txt')[0] break_r6(_o, '40080000', '04000000') _o = read_files('outputs_c2.txt')[0] break_r6(_o, '00200008', '00000400') return obtain_42b(*partial_key)
def _set_round(self, selenium_object): """ Scrap data about the score from selenium object ('head')""" try : self.round = selenium_object.find_element_by_tag_name('th').text except common.exceptions.NoSuchElementException: self.round = None def reset(self): """ Re...
This function scrapes ATP tournament data from a webpage, extracting match scores, player information, and last-meeting details via API calls. It processes singles and doubles matches, saves results into databases, and logs errors. The code uses Selenium for web scraping, handles test mode breaks, and ensures data is s...
def scores_tournament_data(self, test=False): """ Extract general information about tournament of a particular year from ATP """ driver = webdriver.Chrome(config.PATH) driver.get(self.url) self._driver = driver table = self._driver.find_element_by_class_name('day-...
def create_grid_condition(i,condition): row_num = root.grid_size()[1] check_button_array[i] = IntVar() condition_string = stringify_condition(condition) check_button = Checkbutton(root, text=condition_string, variable=check_button_array[i]) #, command=lambda key=i: Readstatus(key)) check_button.gr...
The main task of the code is to create a GUI interface for processing resumes. It allows users to input a resume file path, add custom conditions, and execute a parser to save results to an Excel file. The interface includes dynamic condition fields, a "Run parser" button, and updates the layout using global variables ...
def main1(): global row_count global conditions_array #global check_button_array howto_label = Label( root, text="enter path of resumes below then press button") howto_label.grid(row=row_count, sticky=W, padx=10, pady=10) row_count+=1 path_input = Text(root, height=1, width=49) pat...
def draw_circle(x=0, y=0, number=1): cs = map.CS scale = to_scale(cs) x, y = x * 2 + window.width/6.5, y * 2.1 circle = [image("assets/hitcircle.png"), image("assets/hitcircle-full.png"), image("assets/hitcircleoverlay.png")] i = 0 for c in circle: c = sprite...
The code's main task is to render a game screen by clearing the window, updating the title with map metadata, drawing boundaries, and iterating through hit objects (circles, sliders, spinners) to render them with a combo counter that resets at 100, followed by cursor rendering.
def on_draw(): window.clear() window.set_caption(map.artist + " - " + map.title + " [" + map.diffName + "]") boundaries.draw() combo = 1 for o in map.hitObjects: if combo == 100: combo = 1 if isinstance(o, objects.Circle): draw_circle(o.x, o.y, combo) ...
def _apply_transitions(self, state): def _perform_transition(citizens: List[Citizen], transition_matrix): new_infections = 0 new_recoveries = 0 new_deaths = 0 for c in citizens: new_infection_state = get_transition_for_element(c.infection_state,...
This code simulates a process over a specified number of days (default 30), updating the system state daily through transitions, location assignments, and infection processing. It records daily statistics, prints them, and accumulates results for return. The core task involves modeling dynamic state changes and trackin...
def run(self, total_days=30): for d in range(0, total_days): self.day_stats = DayStats() self.state = self._apply_transitions(self.state) self.state = self._assign_new_locations(self.state) self.state = self._process_infections_at_locations(self.state) ...
def kmeans(data, k): n = len(data) centroids = initialCentroids(data, k) # kmeans++ prevClusters = None clusters = [] iteration = 0 while (iteration < config['MAX_KMEANS_ITERATIONS']) and (clusters != prevClusters): prevClusters = clusters[:] clusters = [] for clust...
The main task of the code is to cluster aligned biological sequences using k-means clustering, evaluate cluster quality with silhouette values, and save the results as a new FASTA file with detailed cluster information. It processes sequence data, determines optimal cluster numbers, organizes clusters by size, and reco...
def findClusters(fileName, omitFirst = True, minK = config['MIN_K'], maxK = config['MAX_K']): writelog('Clustering aligned sequences in ' + fileName + '...', VERBOSE) aln = AlignIO.read(fileName, 'fasta') # Bio.Align.MultipleSeqAlignment object if len(aln) <= 2: writelog(' Skipping - too ...
def getHitsForDiagram(): writelog(' Reading hits for diagrams ...', VERBOSE) dir = Path(SPECIMEN_RESULTS_DIR) subdirs = [d for d in dir.iterdir()] files = [d / XML_DIR / (d.name + '_hits.xml') for d in subdirs] files.sort() allVirusHits = {} allSpecimens = [] for file in files: ...
The main task of the code is to generate diagrams by processing virus hits data, filtering viruses based on hit thresholds, determining their families, and rendering each virus's diagram with specified parameters, including whether to separate populations and other visualization flags.
def drawAll(separatePops = False): writelog('Creating diagrams ...', VERBOSE) allVirusHits, allSpecimens = getHitsForDiagram() fams = readFamFile() for acc in allVirusHits: hitCount = sum(hit.isPrimary() for specimen in allVirusHits[acc] for hit in allVirusHits[acc][specimen].getHits()) ...
def processCmdLine(): for arg in sys.argv[1:]: if arg[:2] != '--': usage() return False parts = arg[2:].split('=') try: left = parts[0].strip() right = parts[1].strip() except: usage() return False if lef...
The main task of the code is to process command-line arguments, manage the results directory by checking its existence and prompting user confirmation if verbose, create the directory if needed, log start time and configuration, execute processes (either parallel or sequential based on MP flag), consolidate results, an...
def main(): if not processCmdLine(): exit(1) global VERBOSE if VERBOSE: if Path(RESULTS_DIR).exists(): answer = ' ' while answer not in 'yYnN': answer = input('Results directory ' + RESULTS_DIR + ' exists. OK to write (y/n)? ') ...
def __resetBoard(self): self.solved_board = [[0 for i in range(9)] for j in range(9)] self.board = [[0 for i in range(9)] for j in range(9)] def generate(self, i, j): number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] if(j > 8): j = 0 i += 1 if i > 8: ...
The code generates a Sudoku board by removing cells from a solved board while ensuring the puzzle remains uniquely solvable. It adjusts the number of removed cells based on the input level, checks for solution uniqueness using backtracking, and stores the modified board as the playable puzzle and a copy as the answer.
def generate_board(self, level = 1): self.__resetBoard() self.generate(0, 0) print(self.solved_board) remove_cell = 32 if(level == 1): remove_cell = random.randint(32, 38) elif(level == 2): remove_cell = random.randint(40, 46) eli...
def _is_finished(self, y, depth): # modify the signature of the method if needed if (depth >= self.max_depth or self.n_class_labels == 1 or self.n_samples < self.min_samples_split or self._is_homogenous_enough(y)): return True return Fa...
This function recursively constructs a decision tree by selecting the best split based on random features, creating child nodes, and stopping when conditions are met. It checks stopping criteria, determines the most common label for leaves, selects optimal splits, and recursively builds left/right subtrees. The node st...
def _build_tree(self, X, y, depth=0): self.n_samples, self.n_features = X.shape self.n_class_labels = len(np.unique(y)) # stopping criteria if self._is_finished(y, depth): u, counts = np.unique(y, return_counts=True) most_common_Label = u[np.argmax(counts)] ...
def perturb_adj(adj, n_perturbations, type='add'): modified_adj = adj.tolil() type = type.lower() assert type in ['add', 'remove', 'flip'] if type == 'flip': # sample edges to flip edges = random_sample_edges(adj, n_perturbations, exclude=set()) for n1, n2 in edges: ...
The main task is to evaluate a graph neural network (GNN) model's performance on a perturbed graph dataset. The code loads a dataset (Cora/CiteSeer), configures GPU settings, modifies the adjacency matrix with adversarial perturbations, updates the graph structure, loads a pre-trained model, and tests its accuracy on t...
def main(): if not torch.cuda.is_available(): logging.info('no gpu device available') sys.exit(1) # np.random.seed(test_args.seed) torch.cuda.set_device(test_args.gpu) cudnn.benchmark = True torch.manual_seed(test_args.seed) cudnn.enabled = True torch.cuda.manual_seed(test_a...
def attack(adj, n_perturbations=622, dim=32, window_size=5, attack_type="remove", min_span_tree=False, n_candidates=None, seed=None, **kwargs): assert attack_type in ["remove", "add", "add_by_remove"], \ "attack_type can only be `remove` or `add`" if attack_type == "remove": if min_...
The code evaluates a graph neural network model on a modified graph dataset. It loads a dataset (Cora/CiteSeer), preprocesses data, modifies the adjacency matrix with an attack, loads a pre-trained model, and tests its performance on the altered graph. The main task is assessing model robustness against adversarial att...
def main(): if not torch.cuda.is_available(): logging.info('no gpu device available') sys.exit(1) # np.random.seed(test_args.seed) torch.cuda.set_device(test_args.gpu) cudnn.benchmark = True torch.manual_seed(test_args.seed) cudnn.enabled = True torch.cuda.manual_seed(test_a...
def pack_one(t, pattern): return pack([t], pattern) def exists(v): return v is not None def entropy(prob): return (-prob * log(prob)).sum(dim=-1) def unpack_one(t, ps, pattern): return unpack(t, ps, pattern)[0]
The main task of the code is to quantize input features into codebook representations using a threshold-based method, compute entropy and commitment losses during training, and return the quantized tensor, indices, and loss breakdown. It handles both image/video inputs and standard tensors, applies straight-through est...
def forward( self, x, inv_temperature = 100., return_loss_breakdown = False, mask = None, ): """ einstein notation b - batch n - sequence (or flattened spatial dimensions) d - feature dimension, which is also log2(codebook size) ...
def writeToLastUpdateCache(self, key, learnCode, nativeCode): CACHEMAX = 35 cachecode = self.generateCodeForLastUpdateCache(learnCode, nativeCode, True) data = memcache.get(cachecode) if data is None: data = [] position = 0 found = False ...
The code processes HTTP request parameters to add a word and its attributes to a system. It escapes input values, handles caching flags, and uses a WordCore instance to perform the addition. If successful, it updates the cache (if enabled) and returns the result; otherwise, it reports errors. The function ensures data ...
def methodAddWord(self): strl = cgi.escape(self.request.get('l')) strlc = cgi.escape(self.request.get('lc')) strn = cgi.escape(self.request.get('n')) strnc = cgi.escape(self.request.get('nc')) strlp = cgi.escape(self.request.get('lp')) strld = cgi.escape(self.request.get(...
def ResortLearnAndNativeCode(self, word1Code, word2Code, word1, word2): #w1c, w2c = [word1Code, word2Code].sort() alist = [word1Code, word2Code] alist.sort(); w1c = alist[0] w2c = alist[1] if w1c != word1Code: #switch w =...
This function adds multiple word pairs (with associated details like pronunciation, description, and specifications) to a database, handling language codes and splitting input words by "|". It validates language codes, processes word combinations, and returns success status along with generated keys for added/updated e...
def addWord(self, word1a, word2a, word1Code, word2Code, pronouc1, desc1, spec1, pronouc2, desc2, spec2): w1c, w2c, word1, word2 = self.ResortLearnAndNativeCode(word1Code, word2Code, word1a, word2a) w1l = self.getLangIdFromCode(w1c) if not w1l: return False,...
def methodAddWord(self): strl = cgi.escape(self.request.get('l')) strlc = cgi.escape(self.request.get('lc')) strn = cgi.escape(self.request.get('n')) strnc = cgi.escape(self.request.get('nc')) strlp = cgi.escape(self.request.get('lp')) strld = cgi.escape(self.request.get(...
This code handles HTTP GET requests by routing them to specific methods based on the 'm' parameter. It retrieves and escapes the 'm' value from the request, then executes corresponding actions like adding/deleting words, translation, displaying words, voting, or fetching language lists. If 'm' is invalid or unspecified...
def get(self): method = cgi.escape(self.request.get('m')) if method == 'add': self.methodAddWord() if method == 'del': self.methodWordDelete() elif method == 'trans': self.methodTrans() elif method == 'show': ...
def _percentage(self, decimal): """ Converts a decimal to a whole number string""" decimal = round(decimal) return "{}%".format(decimal) def overall_average(self): course_ids = self._return_course_info().org_units() course_grades = [] for course_no in course_ids: ...
The main task of the code is to generate a structured JSON response containing overall grade statistics and detailed course grades. It calculates percentages for overall averages, remaining scores, and promotion thresholds, then aggregates course-specific grade data into a list. The result is a JSON string combining bo...
def grades_all(self): grades_json = { "Overall": { "Average": self._percentage(self.overall_average()), "Remaining": self._percentage(self.overall_remaining()), "Promotion": self._percentage(65) }, "CourseData": None } ...
def set_goal(self): self.goal = self.np_random.uniform(low=0., high=self.range_cnt, size=(8,)) # print('self.goal = ', self.goal) self.goal[0] = 0 self.goal = np.append(self.goal, self.range_cnt) res = self.env_reset_client(self.goal, self.__name) if res.success: ...
The main task of the code is to reset the environment's state by setting a new goal configuration, converting quaternions to axis-angle representations, initializing robot joint positions, checking collisions, and constructing a state vector that includes the goal difference, collision data, joint angles, and limits fo...
def reset(self): # if self.done: self.goal = np.array(self.set_goal()) self.goal[3:6], self.goal[6] = trans.quaternions.quat2axangle(self.goal[3:7]) self.goal[6] /= pi self.old, self.joint_pos[:12], self.joint_pos[12:24], self.joint_pos[24:27],self.joint_angle, self.limit = self....
def set_old(self): self.start = self.np_random.uniform(low=0., high=self.range_cnt, size=(8,)) rpy = self.np_random.uniform(low=-1*self.rpy_range, high=self.rpy_range, size=(4,)) # if self.start[0]>0.5: # if self.start[0]>0.75: # self.start[2] /= -3 # else...
The code resets the environment state by initializing joint positions, checking for collisions recursively until collision-free, constructing a state vector with position differences, quaternions, link distances, joint angles, and other metrics, then returning the state for the next episode.
def reset(self): self.old, self.joint_pos[:15], self.joint_pos[15:30], self.joint_angle, self.limit, self.goal_quat, self.quat_inv = self.set_old() linkPosM, linkPosS = self.collision_init() alarm, Link_dis = self.cc.checkCollision(linkPosM, linkPosS) alarm_cnt = 0 for i in alarm...
def set_goal(self): self.goal = self.np_random.uniform(low=0., high=self.range_cnt, size=(8,)) # print('self.goal = ', self.goal) self.goal[0] = 0 self.goal[3] = self.range_cnt/2 self.goal = np.append(self.goal, self.range_cnt) res = self.env_reset_client(self.goal, self....
The code resets the environment by setting a new goal, initializing positions, checking for collisions, and reconstructing the state vector if no collisions occur. It recursively resets if collisions are detected, then combines position differences, link distances, joint angles, limits, and goal distance into the state...
def reset(self): # if self.done: self.goal = self.set_goal() self.old, self.joint_pos[:12], self.joint_pos[12:24], self.joint_pos[24:27],self.joint_angle, self.limit = self.set_old() linkPosM, linkPosS = self.collision_init(self.old[:3]) alarm, Link_dis = self.cc.checkCollision(l...
def create_graph(self): nodes = self.nodes_entry.get().split(',') # Get nodes input and split by comma edges = self.edges_entry.get().split(',') # Get edges input and split by comma for node in nodes: # Iterate over nodes self.graph[node.strip()] = {} # Add node to graph diction...
The code implements Iterative Deepening Depth-First Search (IDDFS) to find a path from a start node to a goal node in a graph. It creates the graph, retrieves user-input start/goal nodes, executes the IDDFS algorithm, and displays the resulting path.
def iterative_deepening_dfs(self): # Iterative Deepening Depth-First Search (IDDFS) algorithm self.create_graph() # Call function to create graph start_node = self.start_node_entry.get() # Get start node from input goal_node = self.goal_node_entry.get() # Get goal node from input ...
def get_numbers(questions, question_counter): numbers = questions.get(question_counter) # one pair of numbers return numbers def generate_hint(first_number, second_number): if second_number == 1: # when multiply with 1, then have single number return f"Hint : {first_number}" else: # w...
The main task of the code is to present a series of multiplication questions to the user, display hints, collect answers via Enter key presses, and manage interface states. It generates questions using `get_numbers`, updates UI elements like labels and entry fields, binds input handling, waits for user responses, and d...
def play_one_round(): global enter_pressed global question_counter global questions enter_pressed = tk.BooleanVar() for _ in range(MAX_QUESTIONS): numbers = get_numbers(questions, question_counter) first_number = numbers[0] second_number = numbers[1] question = f"{fi...
def generate_quest(current_level): """ Generates two lists of 5 numbers for a given level. Parameters: - current_level, difficulty Returns: A dictionary containing five pairs of two numbers. """ first_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] first_numbers = shuffle(first_numbers) ...
The function `start_level()` initializes a new game level by generating questions, recording the start time, updating UI elements (label text, button state, answer entry), and positioning the question frame, then triggers the first round of gameplay with `play_one_round()`.)
def start_level(): global questions global start_time questions = generate_quest(current_level) # generat quest start_time = time.time() # keep start time apps.frame3.level_label.config(text=update_label_text()) apps.frame3.start_button.config(text="Play") apps.frame3.start_button['state']...
def get_all_stats(match): all_stats = {} players = get_players(match) all_stats['Winners'] = get_stats_for_players(players[0:5]) all_stats['Losers'] = get_stats_for_players(players[5:10]) return all_stats def get_metadata(match): parent_tag = match.parent.parent.find( 'table', class_='c...
The function `get_match_stats` extracts and formats match statistics by retrieving metadata (map, date, duration), counting friends, calculating scores, and aggregating player stats. It processes data, updates the stats dictionary, and returns the compiled match information for analysis or display.
def get_match_stats(match): stats = {} all_players_stats = get_all_stats(match) [map_, date, _, duration] = get_metadata(match) stats['Map'] = map_.partition('Competitive ')[2] stats['Date'] = format_date(date) stats['Duration'] = duration.partition('Match Duration: ')[2] stats['Friends'] = ...
def parseEnum(groups): # Determine name name = None if groups[0] and groups[0].startswith("typedef"): name = groups[3].strip() if not name: name = groups[1].strip() if not name: return None # Split enumeration values rawValues = safeSplit(groups[2], ',') # Inspect...
This function parses a struct definition from input groups, extracting members, handling bindings (constructors, methods, getters), nested structs/enums, and descriptions. It constructs an Entity object with the struct's name, namespace, description, and parsed members, appending related entities to the provided list.
def parseStruct(entities, groups, desc, namespace = []): category = "struct" # Determine name name = None if groups[0] and groups[0].startswith("typedef"): name = groups[-2].strip() if not name: name = groups[1].strip() if not name: return None childNamespace = namesp...
def guessNumberType(value): value = value.lower() if "lf" in value: return "double" elif "f" in value and not "x" in value: return "float" elif "." in value or ("e" in value and not "x" in value): return "double" elif "ull" in value: return "unsigned long long" el...
The code parses a header string to extract entities like defines, constants, enums, typedefs, handles, structs, and functions. It uses regex to identify each entity type, extracts their attributes, and creates corresponding `Entity` objects with types, names, and descriptions. The function iteratively processes the hea...
def parseHeader(header): entities = [] desc = None header = reOddBackslashesNL.sub(r"\1", header) while header: # Define if (match := reDefine.search(header)): name = match.group(1).strip() type = guessNumberType(match.group(2)) if type and name: ...
def intro(inp): return "I am Chat Bot to assist you buying a product"+"</span><br><br><span>"+"Which product are you interested in?" def ask_price(inp): global category category=inp return "Do you have any max price preferences ?" def price_asked(max_price): global state, category, search_space, avg...
The code manages a state machine for a chatbot, transitioning through predefined conversation stages (intro, price inquiry, price confirmation, and continuation) based on a global state variable. It returns specific responses depending on the current state and user input, ensuring a structured interaction flow.
def get_bot_response(): inp = request.args.get('msg') global state if(state==-1): state=0 return intro(inp) elif(state==0): state=1 return ask_price(inp) elif(state==1): state=2 return price_asked(inp) elif(state==2): return continue_conv...
def render_cluster_config(replicas: int): environment = Environment(loader=FileSystemLoader("deploy/templates")) template = environment.get_template("erl-cluster.yaml.jinja2") with open('deploy/erl-cluster.yaml', 'w') as out_file: content = template.render( replicas=replicas, ) ...
The main task of the code is to parse command-line arguments for running Mnesia benchmarks in a Kubernetes cluster. It configures benchmark parameters (e.g., workload types, node counts, values), adjusts cluster settings via `render_cluster_config`, and executes benchmarks multiple times using `run(args)`, logging resu...
def main(): parser = argparse.ArgumentParser( prog='benchmark', description='Run mnesia benchmark inside k8s cluster', epilog='epilog' ) parser.add_argument('-l', '--log', help='log file name', default='log.txt', type=str) parser.add_argument('-b', '--ben...
def _export_tables(self: typing.Any) -> None: """Exports all tables to CSV files in the environment's bucket.""" logger.info("Exporting tables...") for table, columns, _ in tables: columns_expression = ", ".join(columns) select_query = f"SELECT {columns_expression} from {...
The code exports a database to CSV files in the environment's bucket by checking the environment, granting permissions, exporting tables, revoking permissions, copying files if DRS is enabled, post-processing data, exporting DAGs/plugins, removing temporary configurations, saving encryption keys, and notifying users of...
def export_database(self: typing.Any) -> None: """Exports the database to CSV files in the environment's bucket.""" self._check_environment() self._grant_permissions() self._export_tables() self._revoke_permissions() self._copy_csv_files_to_cp_if_drs_is_enabled() ...
def _parse_members(self): ms = self._org_model["members"]["schema"] md = self._org_model["members"]["data"] cols = [a.rstrip().lstrip() for a in ms.split(",")] for row in md: rv = [a.rstrip().lstrip() for a in row.split(",")] dict_entry = {cols[i]: rv[i] for i in ...
The main task of the code is to generate a graph structure by parsing and processing members, teams, and organizational models through three internal methods: _parse_members(), _parse_teams(), and _parse_org_models(). This function likely constructs a relational or hierarchical graph representation of entities within a...
def _gen_graph(self): self._parse_members() self._parse_teams() self._parse_org_models()
def create_confluence_wiki(wiki_page): """ Creates a Confluence page from the given Redmine Wiki page. Parameters: wiki_page (obj): Redmine Wiki page to migrate. Returns: Confluence page (obj), if successful. Otherwise, it returns -1. """ # Create a page in Confluence. new_ti...
This function migrates Redmine Wiki pages to Confluence by recursively importing pages and their children, creating Confluence pages from Redmine content, updating Redmine pages with Confluence links if requested, and ensuring each page is imported only once. It returns 0 upon successful completion of all imports.
def import_confluence_wiki(wiki_page_title): """ Imports Redmine Wiki page in Confluence. Parameters: wiki_page_title (str): Title of the Redmine Wiki page to migrate. Returns: Function calls itself until all the pages are imported and returns 0, if successful. """ wiki_page = se...
def get_issue_work_type(redmine_issue): """ Get the issue and work type for the given Redmine issue. Parameters: redmine_issue (obj): Redmine issue (Resource object). Returns: issue_type (str): Issue type. redmine_work_type (str): Work Type. """ # Retrieve all the tags ...
The main task of the code is to create a Jira issue by mapping data from a Redmine issue, including custom fields, issue types, descriptions, and relationships. It handles specific configurations for different issue types (e.g., ESCSTORY, EPIC, SPIKE), updates fields like priority, assignees, status, time tracking, and...
def create_jira_issue(redmine_issue): """ Create a new Jira issue from the given Redmine issue. Parameters: redmine_issue (obj): Redmine issue (Resource object). Returns: Returns a newly created Jira issue (Resource object). """ issue_type, redmine_work_type = get_issue_work_type...
def quadrant_0_90_180(self): for pad in self.pads: pos = pad.GetPosition() net = pad.GetNetCode() if pos.y > self.y0: if pos.x > self.x0: # bottom-right 225 x = pos.x + self.pitchx/2 y = pos.y + self....
The code determines a PCB routing pattern based on alignment type ('Quadrant', 'Diagonal', 'X-pattern') and angle. It selects specific methods for standard angles (0°, 90°, etc.) or default methods for other angles, then triggers a PCB refresh to apply changes.
def fanout(self): if self.alignment == 'Quadrant': if self.degrees in [0.0 , 90.0, 180.0, -90.0]: self.quadrant_0_90_180() elif self.degrees in [45.0 , 135.0, -135.0, -45.0]: self.quadrant_45_135() else: self.quadrant_other_angl...
def stretch_time(self): """ Determine if it is possible to reach distance d in the time t. If not calculate a new minimum t. STEP 1 Stretch time without accounting for v_max. This expands the parallelogram defined in the check_range() docstring. The area represe...
This function calculates a time-velocity profile to achieve a target distance `d` between velocities `v1` and `v2` using acceleration `a` and maximum velocity `v_max`. It adjusts the time `tv2` if necessary, computes intermediate time/velocity values (t1, tm, t2, vm), and validates that the resulting distance falls wit...
def get_profile(self): """ determine what profile can achieve d in tv2 between v1 and v2 with a and v_max. Stretch tv2 if necessary. The results are stored in the following properties which describe the profile to take: t1, tm, t2, vm, tv2 (tv2 is an input property but m...
def population_fitness(population): """Evaluate the fitness of a complete population""" list_with_fitness = [] for members in range(len(population)): list_with_fitness.append( individual_fitness(get_chromosome(population, members))) return list_with_fitness def sort_a_list(a_list): ...
The code generates a new population from an input population using a genetic algorithm approach. It calculates individual fitness, sorts candidates, cleans data, splits into subsets, selects individuals, shuffles them for diversity, and creates a new generation through population renewal. The process emphasizes selecti...
def generate(input_population): """Generate a new population from the one inputed""" population_with_fitness = population_fitness(input_population) sorted_list = sort_a_list(population_with_fitness) cleaned_list = clean_list(sorted_list) cutted_list = numpy.array_split(cleaned_list, 4) selecti...