dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def delta(self): return (Option(self.call, self.S + self.diff, self.K, self.t, self.R, self.sigma).price() - self.price()) / self.diff def gamma(self): return (Option(self.call, self.S + self.diff, self.K, self.t, self.R, self.sigma).delta() - self.delta()) / self.diff de...
The method 'greeks' returns a dictionary containing the calculated values of Delta, Gamma, Theta, Vega, and Rho—financial metrics assessing options pricing sensitivity. It aggregates individual Greek measures into a structured format for consolidated access.
def greeks(self): return {"Delta": self.delta(), "Gamma": self.gamma(), "Theta": self.theta(), "Vega": self.vega(), "Rho": self.rho()}
def account_jiffies(samples, cpu=None): """ Returns the ratio of the jiffies with attribution corrections. """ if not isinstance(samples, pd.DataFrame): tasks = compute_task_jiffies(samples.process) cpu = compute_cpu_jiffies(samples.cpu) else: tasks = samples activity = (tasks /...
The code computes energy-related metrics ('footprints') from input data by processing components like 'jiffies', 'nvml', and 'rapl' with specialized accounting functions, aggregating results into a dictionary for virtualization analysis.
def compute_footprint(data): """ Produces energy virtualizations from a data set. """ activity = account_jiffies(data) footprints = {} footprints['activity'] = activity if len(data.nvml) > 0: footprints['nvml'] = account_nvml(data.nvml) if len(data.rapl) > 0: footprints['rapl'] ...
def flash_x310(): os.system(f"./utils/flash_usrp.sh") def run_gnb(self, type): if type != 'relay': local_ip = self.main_ip local_dev = MAIN_DEV set_route(MAIN_DEV) else: local_ip = self.iab_ip local_dev = IAB_DEV f1_cmd_args = self....
The code's main task is to execute device-specific operations based on the `self.type` value, with optional flashing via `flash_x310()` if enabled. It calls `run_gnb()` or `run_ue()` for different device types (donor, cu, du, relay, ue), exiting with an error if the type is unrecognized.
def run(self): if self.args.flash: flash_x310() time.sleep(5) if self.type == 'donor': self.run_gnb(type='donor') elif self.type == 'cu': self.run_gnb(type='cu') elif self.type == 'du': self.run_gnb(type='du') elif self....
def onOpen(self): self.videofile = filedialog.askopenfilename(initialdir="./", title="Select a file") if self.videofile: self.showMessage("open file {0:s}".format(self.videofile)) self.loadImage(self.videofile) def onReset(self): # override to implement this self...
The main task of the code is to bind button click events to corresponding handler methods (onOpen, onReset, onPlay, onApply) and link the window resize event Configure to the onResize method, enabling interactive functionality for a GUI application.
def bindBtnEvents(self): self.btnOpen['command'] = lambda : self.onOpen() self.btnReset['command'] = lambda : self.onReset() self.btnPlay['command'] = lambda : self.onPlay() self.btnApply['command'] = lambda : self.onApply() self.root.bind("<Configure>", self.onResize)
def bytes_from_int(x: int) -> bytes: return x.to_bytes(32, byteorder="big") def x(P: Point) -> int: assert not is_infinite(P) return P[0] def has_even_y(P: Point) -> bool: return y(P) & 1 == 0
This function converts a point's x-coordinate to bytes, with optional compression. If compressed, it prefixes the x-coordinate with 0x02 (even y) or 0x03 (odd y). Otherwise, it returns only the x-coordinate bytes.
def bytes_from_point(P: Point, compressed: bool = False) -> bytes: x_coord = bytes_from_int(x(P)) if compressed: if has_even_y(P): return b'\x02' + x_coord else: return b'\x03' + x_coord return x_coord
def lift_x(b: bytes) -> Optional[Point]: if len(b) == 32: x = int_from_bytes(b) even = True else: x = int_from_bytes(b[1:]) even = (b[0] == 2) if x >= p: return None y_sq = (pow(x, 3, p) + 7) % p y = pow(y_sq, (p + 1) // 4, p) if pow(y, 2, p) != y_sq: ...
The code aggregates nonces from multiple signers into a list of elliptic curve points. Each signer's nonces are extracted from the input bytes, converted to points using `lift_x`, and summed via `point_add`. If all nonces for a signer sum to the infinite point (indicating potential dishonesty), it replaces the result w...
def aggregate_nonces(nonces_to_aggregate: List[bytes]) -> List[Point]: # Every nu nonces are a set corresponding to one signer aggregated_nonces = [] for j in range(nu): R_j = None for combined_nonce in nonces_to_aggregate: nonce_component = combined_nonce[33*j : 33*(j + 1)] ...
def int_from_bytes(b: bytes) -> int: return int.from_bytes(b, byteorder="big") def point_mul(P: Optional[Point], n: int) -> Optional[Point]: R = None for i in range(256): if (n >> i) & 1: R = point_add(R, P) P = point_add(P, P) return R def bytes_from_point(P: Point, compress...
The function generates a public key from a secret key using elliptic curve point multiplication. It converts the input secret key bytes to an integer, validates its range, multiplies the generator point G by the secret key to derive the public key point P, and returns P as compressed or uncompressed bytes.
def pubkey_gen(seckey: bytes, compressed: bool = False) -> bytes: d0 = int_from_bytes(seckey) if not (1 <= d0 <= n - 1): raise ValueError('The secret key must be an integer in the range 1..n-1.') P = point_mul(G, d0) assert P is not None return bytes_from_point(P, compressed)
def point_mul(P: Optional[Point], n: int) -> Optional[Point]: R = None for i in range(256): if (n >> i) & 1: R = point_add(R, P) P = point_add(P, P) return R def has_even_y(P: Point) -> bool: return y(P) & 1 == 0 def bytes_from_int(x: int) -> bytes: return x.to_bytes(32, ...
The main task of the code is to generate a cryptographic secret key (as bytes) that, when multiplied by an elliptic curve generator point $ G $, produces a public key with an even $ y $-coordinate if `force_even_y` is True. It ensures this by adjusting the secret integer if necessary and converting it to bytes for outp...
def seckey_gen(force_even_y: bool = True) -> bytes: # choose random integer below the order of the curve seckey_int = secrets.randbelow(n) # Check that this int gives a public key with even y P = point_mul(G, seckey_int) if force_even_y and not has_even_y(P): seckey_int = n - seckey_int ...
def key_agg_coeff(key_set: List[bytes], public_key: bytes) -> int: # Sort the set of keys in lexicographical order sorted_keys = sorted(key_set) # If this is the second unique key in the list, we optimise by using coefficient 1 if is_second_unique_key(sorted_keys, public_key): return 1 # Com...
The function aggregates a list of public keys into a single cryptographic point by multiplying each key with a computed coefficient, summing the results. It also identifies the coefficient of a specified 'own_key' if present, ensuring valid key formatting and non-infinite results.
def aggregate_public_keys(public_key_list: List[bytes], own_key: Optional[bytes]) -> Tuple[Point, int]: aggregate_key = None own_coeff = 0 for key_bytes in public_key_list: # a_i is an integer coefficient a_i = key_agg_coeff(public_key_list, key_bytes) # If this key is the one specif...
def point_mul(P: Optional[Point], n: int) -> Optional[Point]: R = None for i in range(256): if (n >> i) & 1: R = point_add(R, P) P = point_add(P, P) return R def point_add(P1: Optional[Point], P2: Optional[Point]) -> Optional[Point]: if P1 is None: return P2 if P2...
The code computes a cumulative point addition of nonce points multiplied by exponentially increasing powers of 'b' modulo 'n', resulting in a non-identity point R.
def compute_R(nonces: List[Point], b: int) -> Point: R = None for j in range(nu): R_j = point_mul(nonces[j], (b**j) % n) R = point_add(R, R_j) assert not is_infinite(R) return R
def point_mul(P: Optional[Point], n: int) -> Optional[Point]: R = None for i in range(256): if (n >> i) & 1: R = point_add(R, P) P = point_add(P, P) return R def lift_x(b: bytes) -> Optional[Point]: if len(b) == 32: x = int_from_bytes(b) even = True else: ...
The function verifies a cryptographic signature by checking if the computed point 'left' (s*G) equals the sum of 'R' and 'c*aggregate_key', where 'c' is a challenge hash derived from the message, R, and aggregate key. This confirms the signature's validity in a Schnorr-like scheme.
def verify_sig(aggregate_key_bytes: bytes, msg: bytes, R_bytes: bytes, s: int) -> bool: left = point_mul(G, s) R = lift_x(R_bytes) aggregate_key = lift_x(aggregate_key_bytes) c = chall_hash(aggregate_key_bytes, R_bytes, msg) right = point_add(R, point_mul(aggregate_key, c)) return left == right
def display_game_state(self, m_or_b): start_time = time.time() tabs = '\t\t' self.log(f""" {tabs}Scores: {tabs} 1: {self.states[m_or_b].scores[1]} | 2: {self.states[m_or_b].scores[2]} {tabs} {tabs}Board: {tabs} {self.beautify_board(m_or_b)} ...
This function enables manual gameplay by taking player inputs, validating moves, updating the game state, and checking for win conditions. It displays the board, reserved pieces, and valid moves, alternates turns between two players, and declares a winner when the game ends.
def play_manual_game(self): self.display_game_state('main') current_player = 1 while True: input_action = input(f"Take an action for player {current_player}: ") if "PRINT" in input_action.upper(): if "BOARD" in input_action.upper(): ...
def display_game_state(self, m_or_b): start_time = time.time() tabs = '\t\t' self.log(f""" {tabs}Scores: {tabs} 1: {self.states[m_or_b].scores[1]} | 2: {self.states[m_or_b].scores[2]} {tabs} {tabs}Board: {tabs} {self.beautify_board(m_or_b)} ...
This code simulates a turn-based game where two players take random valid actions until one wins. It alternates between players, checks for valid moves, executes random choices, updates the game state, and declares the winner when the game ends. The function returns the total number of turns taken.
def play_random_game(self): m_to_b = 'main' turn = 1 current_player = 1 while True: print(f"TURN {turn}") self.display_game_state(m_to_b) valid_moves = self.getValidMoves(None, current_player, m_to_b) if np.sum(valid_moves) > 1: ...
def heapInsert(self,heap,item,vertices): """ Functionality of the function is to insert the item into the heap Time complexity:O(logv) for worst case and O(1) for best case where the item is the largest one in the heap Space complexity:O(v) for the list vertices Error handle:None...
The function `quickestSafePath` computes the shortest path from a source to a target node in a graph, avoiding nodes with cameras and edges with tolls, using Dijkstra's algorithm with a min-heap. It returns the path and total time if a valid route exists, otherwise `[[], -1]`. The algorithm ensures safety constraints, ...
def quickestSafePath(self,source,target): """ Functionality of the function is to find the shortest from the source to the target that doesn't contain any cameras or tolls Time complexity:O(ElogV) since dijkstra using min heap will use O(ElogV) time Space complexity: O(E+V) same ...
def built_tries_num(data,spots): """ This function is to build the prefix trie Time Complexity:Best:O(T). It needs to proceed all the IDs and last names Worst:O(T). It needs to proceed all the IDs and last names Space Complexity:Best:O(T). The indexes of all IDs and last names ne...
This function retrieves records from a file matching given ID and last name prefixes using trie structures for efficient prefix searches, returning their original indexes while handling empty files and data formatting constraints.
def query(filename,id_prefix,last_name_prefix): """ This function is to find all the record matched the id prefix and last name prefix Time Complexity:Best:O(NM) for reading the file. O(T) for generating the trie.O(k+l) for query which has no match record Worst:O(NM) for reading the file...
def transferToNum(char): """ This function is to convert a letter to a num using ASCII Time Complexity:Best:O(1) Worst:O(1) Space Complexity:Best:O(1) Worst:O(1) Error Handle:None :Precondition: the parameter must be a valid char in the ASCII :param ch...
The function `reverseSubstrings` identifies all substrings in a given file's content that have their reverse also present in the string, along with their starting and ending indexes. It processes the input string, constructs a suffix trie for efficient reverse substring lookup, and returns a list of such substrings and...
def reverseSubstrings(filename): """ This function is to find all the substrings and indexes that have a reverse one in the string Time Complexity:Best: O(k) for no reverse substrings in the string Worst:O(k^2+p) for the string is repeating one letter.i.e: all of them are inverse of each...
def n_reg(self, hexid): offset = hexid - 0xA00001 if offset < 0 or offset > 915399: return None digit1 = math.floor(offset / 101711)+1 reg = f'N{digit1}' offset %= 101711 if offset <= 600: return reg + self.n_letters(offset) offset -= 601 dig...
The main task of the code is to convert a hexadecimal ID to an integer, check if it is NaN, and sequentially query multiple registration methods (`n_reg`, `ja_reg`, `hl_reg`, `numeric_reg`, `stride_reg`) to find a matching region or category. If none match, it returns `None`.
def lookup(self, hexid): hexid = int(hexid,16) if math.isnan(hexid): return None reg = self.n_reg(hexid) if reg: return reg reg = self.ja_reg(hexid) if reg: return reg reg = self.hl_reg(hexid) if reg: ret...
def deduct_blinds(self): for i, player in enumerate(self.players): if self.blinds[i] > 0: player.evaluate_action('r' + str(self.blinds[i]), 0, self.pot) # set the highest bet to the highest blind self.highest_bet = max(self.blinds) def play_step(self): las...
The code simulates a poker game round by deducting blinds, dealing cards (flop, turn, river), executing betting rounds, evaluating winners, distributing winnings, and resetting the game. It handles card dealing, betting phases, pot management, and transitions between rounds. The function recursively continues play if n...
def play_poker(self): #TODO: abstract this further (playing flop, playing river etc) #TODO: change play_step() function name to betting_round() # deduct the blinds from the (correct) players, and add them to the pot self.deduct_blinds() # play pre-flop self.play...
def _print(self): for i, f in enumerate(self.get_files()): print('{:3d}. {:30s}'.format(i + 1, f)) print('{:3d}. {:30s}'.format(0, 'exit')) def _get_absolute_path(self, file): return join(self.directory, file) def get_files(self): return [f for f in listdir(self.directory) if...
The function presents a menu by printing separators and options, prompts the user for input, exits if the input is 0, and returns the absolute path of the selected file from a list retrieved by `self.get_files()`.
def select(self, text): print('___________________________________________') self._print() print('___________________________________________') number = int(input(text)) if number == 0: exit() return self._get_absolute_path(self.get_files()[number - 1])
def get_token(self): r = requests.post(f"{base_url}/oauth2/token", params=credentials) access_token = r.json().get("access_token") self.access_token = re.sub(r'(!)', r'\\!',access_token) return self.access_token def get_job_id(self): s = self.get_job() soup = BeautifulSou...
The code's main task is to extract data from Salesforce by authenticating, initiating a job, processing batches, waiting for completion, retrieving results, verifying data integrity, and closing the job, ultimately returning the extracted data.
def get(self): ''' function to extract data from salesforce query ''' self.get_token() self.job_id = self.get_job_id() batch_id = self.get_batch(self.job_id) batches = self.get_batch_info(self.job_id) batches_new = self._wait_for_batch_completion(batches) ...
def get_nonempty_user_input(self, prompt: str): question = questionary.text(prompt).ask() while question == "": print("ERROR : Input cannot be empty") question = questionary.text(prompt).ask() return question def get_first_suggestions(self, question: str): ''' ...
The code's main task is to generate and display top 10 question suggestions based on user input, allowing users to view answers to suggestions or proceed to write their question. It handles two stages: first suggestions from the question title, then refined suggestions combining title and body text, with interactive pr...
def start(self): ''' Prints the top 10 question suggestions, based on the user's command line entry. :param self: Instance of the BasicCLI object ''' if self.__matcher is None: raise RuntimeError("Matcher has not been set.") while True: #...
def _get_word_class_embeddings(self, log_lines): docs = list(self.nlp_parse.pipe(log_lines)) word_classses = [" ".join([t.pos_ for t in doc]) for doc in docs] # print(word_classses) return word_classses def _get_word_class_embeddings_dep(self, log_lines): docs = list(self.nlp_par...
The main task of the code is to process batches of log lines by cleaning and tokenizing them, generating embeddings, predicting suitable tokens, and producing structured results with confidence scores and suggestions. It uses regex to sanitize input, creates test data loaders, runs predictions, and compiles outcomes in...
def predict_batch(self, log_lines: List[str]): tokenized = [] regex = re.compile('[^a-zA-Z ]') self.log_lines = self._get_word_class_embeddings(log_lines) log_lines_dep = self._get_word_class_embeddings_dep(log_lines) for lm in log_lines_dep: self._predict_top_N_su...
def chromeSetting(url: str) -> WebDriver: # user_agent = UserAgent() options = webdriver.ChromeOptions() prefs = {"profile.managed_default_content_settings.images": 2} options.add_experimental_option("prefs", prefs) # options.add_argument(f"user-agent={user_agent}") options.add_argument("--disa...
The function automates web scraping by initializing a Chrome driver, navigating to a search page, adjusting zoom, extracting data from the first result, and returning it as a dictionary.
def parseFirst(url: str, search_name: str) -> dict: chromeDriver = chromeSetting(url=url) goToSearch(search_name=search_name, driver=chromeDriver) zoomPage(1) data = [] getData(chromeDriver, data, parse_all=False) # jd = json.dumps(data, ensure_ascii=False) closeDriver(chromeDriver) re...
def chromeSetting(url: str) -> WebDriver: # user_agent = UserAgent() options = webdriver.ChromeOptions() prefs = {"profile.managed_default_content_settings.images": 2} options.add_experimental_option("prefs", prefs) # options.add_argument(f"user-agent={user_agent}") options.add_argument("--disa...
The main task of the code is to scrape data from a website by initiating a Chrome browser session, navigating to a search page with a specified query, adjusting page zoom, iterating through multiple pages to collect data, and returning the structured results in a dictionary with the search term as the key.
def parseAll(url: str, search_name: str) -> dict: chromeDriver = chromeSetting(url=url) goToSearch(search_name=search_name, driver=chromeDriver) zoomPage(7) data = [] goToNextPages(chromeDriver, data) # jd = json.dumps(data, ensure_ascii=False) closeDriver(chromeDriver) return {f"{sear...
def to_df(self): if self.data is None: print('Data is not loaded!') return None return pd.DataFrame(self.to_dict()) def find_answer_sentence(self, context, answer_start): answer_sentence_list = [context[answer_start]] i, j = answer_start - 1, answer_start + 1 ...
The code preprocesses data by converting the object to a DataFrame, extracting answer sentences from context using `find_answer_sentence`, and applying text preprocessing to specified columns (`context_answer`, `question`, `answer`). It then retains only these processed columns in the DataFrame and returns it.
def preprocess(self): df = self.to_df() df['context_answer'] = df.apply(lambda row: self.find_answer_sentence(row.context, row.answer_start), axis = 1) keys = ['context_answer', 'question', 'answer'] for key in keys: df[key] = self.text_preprocess(df[key]) self.df...
def lb_parsing(self): df = pd.read_excel(self.path, header=[2]) new = df["Specifications"].str.split(",", expand=True)[0][:2] df["Processor"] = str(new[0]) + "," + str(new[1]) df["RAM"] = df["Specifications"].str.split(",", expand=True)[2] df["HDD"] = df["Specifications"].str.sp...
The code initializes a class to parse Excel files, mapping column headers to standardized names and device types. It identifies the file type from the filename prefix (LB/CT/other) and calls corresponding parsing methods (lb_parsing, ct_parsing, tes_parsing) to process data into a structured DataFrame, handling variati...
def __init__(self, path, donor=None): self.final_df: pd.DataFrame = None self.path: str = path self.donor: str = donor self.excel_file = path.split("/") self.index: dict = {"Quantity": ["Qty", "Quantity"], "Reference": ["Book No.", "PATNumber", "Refer...
def get_list_enemies(game_state): return game_state.enemy_spaceships + game_state.asteroids def sort_by_priority(enemies_list): a_list = list(enemies_list) a_list.sort(key=lambda x: x.rect.left) return a_list def near_dangerous_object_upside(self, list_enemies_sorted): if len(list_enemie...
The main task of the code is to determine the next safe move for an AI agent in a game by evaluating potential dangers from enemies, adjusting movement directions (up/down) based on proximity to obstacles, and prioritizing moves from a stack or generating new ones if necessary. It processes enemy positions, identifies ...
def get_next_move_ia(self, game_state): list_enemies = self.get_list_enemies(game_state) list_enemies_sorted = self.sort_by_priority(list_enemies) list_danger = [] coord_impact = [] if len(self.move_stack) != 0: next_move = self.move_stack[0] self.move_sta...
def normpath(path): return os.path.normpath(os.path.join(relative_to, path)) def write_group(notes, i, groups, class_that_sent_to_group, f): g_name = notes[i].step.group g_num, g_count = groups.get(g_name, (len(groups) + 1, 0)) g_count += 1 f.write('\ngroup %d00: %s\n' % (g_num, g_name)) start_n...
This code generates PlantUML files for each flow in the input dictionary, writing sequence diagrams that visualize call flows. It creates files named "[flow_name]_flow.puml" in the specified path, replacing existing files. The code processes each note in the flow, handling grouped steps and automatic numbering, while w...
def generate(flows, path): for name, notes in flows.items(): fname = os.path.join(normpath(path), '%s_flow.puml' % name) if os.path.exists(fname): os.remove(fname) outer_stepnum = 1 with open(fname, 'wt') as f: f.write('@startuml\n\ntitle Calls in the "%s" Flo...
def _print(a): print(ast.dump(a, indent=4)) def _next(typ: collections.abc.Iterator | collections.abc.Generator) -> type: if get_origin(typ) is collections.abc.Iterator: return get_args(typ)[0] elif get_origin(typ) is collections.abc.Generator: raise NotImplementedError("Didn't do generators...
The function `get_type` infers the type of a Python AST node based on its structure and context within a given scope. It recursively processes nodes like `Expr`, `Constant`, `List`, `Tuple`, and comprehensions, resolving types for literals, collections, and assignments. It updates the scope with variable types during a...
def get_type(node: ast.expr | ast.stmt | ast.AST, state: Scope) -> Optional[type]: """ :param node: :param _state: :return: `None` if statement. """ # _locals was a parameter # if _locals is None: # _locals = {} # # state = global_state | _locals _print(node) if isi...
def _next(typ: collections.abc.Iterator | collections.abc.Generator) -> type: if get_origin(typ) is collections.abc.Iterator: return get_args(typ)[0] elif get_origin(typ) is collections.abc.Generator: raise NotImplementedError("Didn't do generators yet") def resolve_generic_func(cls: type, func_...
This function assigns type information to variables in a scope based on AST nodes. It handles `ast.Name` by mapping variable names to types, `ast.Tuple` by iterating over elements with resolved types (handling unions and generics), and `ast.Starred` by treating the value as a list type. The goal is to propagate type an...
def helper(target: ast.Tuple | ast.Name | ast.Starred, _state: Scope, value: type) -> None: if isinstance(target, ast.Name): _state[-1][target.id] = value elif isinstance(target, ast.Tuple): if get_origin(value) is Union: ...
def read_images(filename, n_max_images=None): images = [] with open(filename, 'rb') as f: _ = f.read(4) # magic number from mnist n_images = bytes_to_int(f.read(4)) if n_max_images: n_images = n_max_images n_rows = bytes_to_int(f.read(4)) n_columns = bytes_...
The main task of the code is to load training and test image data along with their labels, extract features from the images, and perform k-NN classification with k=3. It also includes debug prints to check the dimensions of image data before and after feature extraction.
def main(): X_train = read_images(TRAIN_DATA_FILENAME, 200) # print(len(X_train)) # print(len(X_train[0])) # print(len(X_train[0][0])) y_train = read_labels(TRAIN_LABELS_FILENAME) X_test = read_images(TEST_DATA_FILENAME, 200) y_test = read_labels(TEST_LABELS_FILENAME) print(len(X_train[...
def LocalRivers(upperleft,lowerright,world,ElevationInterp): local_rivers = [rv for rv in world.RiverLocs if (rv[0]<lowerright[0] and rv[0]>upperleft[0] and rv[1]<lowerright[1] and rv[1]>upperleft[1])] rivsphi = [rv[0] for rv in local_rivers] rivthet = [rv[1] for rv in local_rivers] rivers = [] una...
This function generates detailed geographical data for a specified region on a globe by interpolating elevation, identifying landmasses, extracting river networks, political boundaries, and cities from global datasets, then returning these elements along with interpolated grids and elevation data for further analysis o...
def ZoomInRegion(upperleft,lowerright,world,demographics,res = 500): Phi = world.GlobeGrid[0][0] Theta = world.GlobeGrid[1].T[0] ElevationInterp = interp2d(Phi,Theta,world.Elevation, kind = 'quintic') phi = np.linspace(upperleft[0],lowerright[0],res) theta = np.linspace(upperleft[1],lowerright[1],re...
def Desire(self,world): ResourceDesire =(world.Renewables + world.NonRenewables)/np.max(world.Renewables+ world.NonRenewables) TempDistSummer = np.array([dt - world.Temps[1] for dt in self.PreferredTemp])**2 TempDistWinter = np.array([dt - world.Temps[0] for dt in self.PreferredTemp])**2 ...
This code simulates population and resource dynamics using ODE integration. It updates population distributions, renewable/non-renewable resources, tracks historical data, and recalculates political structures and conflicts. The function returns new renewable and non-renewable resource states after time-step dt.
def ChangePop(self,world,dt = 0.1): grwall = ode(self.ChangeFun) grwall.set_initial_value(np.concatenate([self.Populations.flatten(),world.Renewables.flatten(),world.NonRenewables.flatten()]),0) desires = self.Desire(world) mvParams = [[des.flatten(),world.neighborkey] for des in desires...
def ZoomInRegion(upperleft,lowerright,world,demographics,res = 500): Phi = world.GlobeGrid[0][0] Theta = world.GlobeGrid[1].T[0] ElevationInterp = interp2d(Phi,Theta,world.Elevation, kind = 'quintic') phi = np.linspace(upperleft[0],lowerright[0],res) theta = np.linspace(upperleft[1],lowerright[1],re...
This code initializes a region-based object by extracting geographic data (elevation, land, rivers, countries) and demographic information from a global world dataset. It sets up interpolated grids for population and elevation, calculates region dimensions, compiles demographic statistics, initializes country and city ...
def __init__(self,upperleft,lowerright,world,demographics,res = 500): Local,LocalLand,local_rivers,LocalCountry,cities,P,T,ElevationInterp = ZoomInRegion(upperleft,lowerright,world,demographics,res=res) self.Phi = P self.Theta = T self.Elevation = Local self.Land = LocalLand ...
def etch(self, number=20, stochastic=True): """Etch a glass for a number of steps. Arguments: number: int, number of time steps stochastic: boolean, roll the dice for reaction? Returns: None Populates: self.etchingg self.latt...
The main task of the code is to perform an etching process for a specified number of time steps and generate multiple visualizations (graphs) of the results using methods like `gaze()`, `peer()`, `quantify()`, `qualify()`, and `recite()`. The function uses default chemical species if none are provided and returns nothi...
def study(self, number=100, species=None): """Perform an etch and graph results. Arguments: number: int, number of time steps Returns: None """ # set default species species = species or self.chemicals # etch self.etch(number) ...
def _acquire(self, path): """Load in a yaml file. Arguments: path: str, filepath Returns: dict """ # open yaml file with open(path, 'r') as pointer: # and read contents information = yaml.safe_load(pointer) retu...
The main task of the code is to populate an object with reaction data by reading a YAML file containing species, reactions, bonds, and forces. It calculates bond and repulsion energies for species, computes reaction rates using energy differences, and creates Reaction instances. If the YAML file is missing, it generate...
def _populate(self): """Populate with reactions. Arguments: None Returns: None Populates: self """ # make folder self._make(self.folder) # populate text and yam self.text = '{}/{}.txt'.format(self.folder, se...
def quiver(self, vertical, horizontal, initial=None, extent=20, tag=''): """Draw a quiver plot based on a two dimensional projection. Arguments: vertical: list of floats, vertical axis horizontal: list of floats, horizontal axis initial: list of floats, initial coord...
The code generates quiver, stream, and divergence plots for 2D vector fields using given axes data, initial coordinates, and extent, with optional tagging for file naming. It combines these visualizations to analyze vector field behavior.
def swirl(self, vertical, horizontal, initial=None, extent=20, tag=''): """Draw a quiver and stream plot based on a two dimensional projection. Arguments: vertical: list of floats, vertical axis horizontal: list of floats, horizontal axis initial: list of floats, ini...
def _randomize(self, number=1000, initial=None, extent=20): """Create a set of ranom points within the designated extent. Arguments: number: number of points initial: dict of species, quantities extent: int, extent of sample space around initials Returns: ...
The code generates a PCA-based visualization (plate) by sampling random points in chemical reaction space, converting them to reaction rates, decomposing via PCA, selecting top vectors for horizontal/vertical axes, and plotting them with specified parameters for analysis.
def plate(self, number=1000, modes=(0, 1), top=3, places=2, initial=None, extent=20, tag=''): """Create a plate from the most interesting slice through the phase space. Arguments: number: number of random points modes: tuple of ints, the pca modes to use top: int, nu...
def get_function(line): type_and_name, raw_params = line.split('(') raw_params = raw_params[:-1] return_type, func_name = type_and_name.split(' ') params = {} param_strings = raw_params.split(',') if param_strings != ['']: for param in param_strings: param_type, param_n...
This function parses a Dart file to generate FFI bindings, extracting functions and classes with metadata. It processes lines to identify classes, their methods, and initializers, then outputs Dart code with FFI declarations and class implementations for the specified library.
def generate_dart_ffi_stuff(fname): out = "" lines = list(map( lambda line: line.strip(), get_lines(fname) )) funcs = [] classes = {} # {"class_name": {"methods": [Function(), Function()], "initializer": Function() or None}} current_class_name = "" current_metadata = "" ...
def generate_decl(name): return f"// ----- {name.upper()} -----\n\n" def enums(): dart = "" c = "" for f in get_all_files_with_extension(C_CODE_DIR, "enum"): name_without_extension = path.splitext(f)[0] dart += generate_dart_enum(name_without_extension) c += generate_c_enum(name_...
This code generates Dart and C language files for enum declarations and FFI bindings. It combines generated enum declarations, implementations, and FFI code from multiple source files, then writes the resulting C header and Dart code to disk for use in cross-language interoperability.
def main(): dart_file = f"import 'dart:ffi';\nimport 'package:ffi/ffi.dart';\nimport 'getLibrary.dart';\n\nconst LIB_DIR = '{LIB_DIR}';\n\n" c_header = "#ifndef C_CODEGEN_H\n#define C_CODEGEN_H\n\n" enums_decl = generate_decl("enums") dart_file += enums_decl c_header += enums_decl dart_en...
def retrieve_message(chat_id: int, message_id: int) -> types.Message | Any: # this should only be called by celery tasks try: return bot.get_messages(chat_id, message_id) except ConnectionError as e: logging.critical("BOT IS NOT STARTED YET: %s", e) bot.start() return bot.get...
This function handles YouTube video downloads using yt-dlp, managing errors like file size limits. It retrieves a message, attempts a download, and if the file is too large, notifies the user with a premium subscription prompt. On other errors, it sends the specific error message. Logging is used to track task start/en...
def ytdl_download_task(chat_id: int, message_id: int, url: str): logging.info("YouTube celery tasks started for %s", url) bot_msg = retrieve_message(chat_id, message_id) try: ytdl_normal_download(bot, bot_msg, url) except FileTooBig as e: # if you can go there, that means you have premiu...
def get_unique_clink(original_url: str, user_id: int): payment = Payment() settings = payment.get_user_settings(user_id) clink = channel.extract_canonical_link(original_url) try: # different user may have different resolution settings unique = "{}?p={}{}".format(clink, *settings[1:]) ...
The function `ytdl_download_entrance` manages video downloads via YouTube-DLP, prioritizing cached files from Redis. If no cache exists, it selects download mode (normal or Celery-based) and initiates the process. It handles errors like file size limits by notifying users and offering premium access options, while logg...
def ytdl_download_entrance(client: Client, bot_msg: types.Message, url: str, mode=None): # in Local node and forward mode, we pass client from main # in celery mode, we need to use our own client called bot payment = Payment() redis = Redis() chat_id = bot_msg.chat.id unique = get_unique_clink(u...
def getSuggestionsForStage(progress): """ Get all projects which are published in a resource-type event """ project_list = [] resource_events = [e.id for e in Event.query.filter_by( lock_resources=True).all()] for eid in resource_events: projects = Project.query.filter_by( ev...
This function allows an active user to create a new project for a specific event. It validates user permissions, checks event restrictions, generates a project form with category options, handles template data, and creates/saves the project with appropriate progress status. On successful submission, it redirects to the...
def project_new(event_id): if not isUserActive(current_user): flash( "Your account needs to be activated - " + " please contact an organizer.", 'warning' ) return redirect(url_for('public.event', event_id=event_id)) form = None event = Event.query.filter_by(id...
def Nc(epsilon_0, k, epsilon_c2, sigma_cd, n, y_b, y_t, b, h, tol_k): if abs(k * h) < tol_k: N_c = sigmac(epsilon_0, epsilon_c2, sigma_cd, n) * b * h else: epsilon_b = epsilon_0 + y_b * k epsilon_t = epsilon_0 + y_t * k N_c = b * DI0(epsilon_t, epsilon_b, epsilon_c2, sigma_cd, n)...
This function plots the interaction diagram of axial force (N_r) and moment (M_r) resistance for a structural section. It calculates resistances using concrete (Nc, Mc) and steel (Ns, Ms) contributions across interpolated parameter ranges, then overlays results from iterative calculations. The plot visualizes the relat...
def plot_N_r_M_r(epsilon_c2, epsilon_cu, sigma_cd, n, b, f_yd, epsilon_yd, h, y_t, y_b, y_s, phi, nb, tol_k, epsilon_0_it, kappa_it): c = epsilon_c2 u = epsilon_cu A = [0, c] B = [u / h, u * y_t / h] C = [(u + 10) / (y_t - min(y_s)), u - y_t * ((u + 10) / (y_t - min(y_s)))] D = [0, -10] E = ...
def Nc(epsilon_0, k, epsilon_c2, sigma_cd, n, y_b, y_t, b, h, tol_k): if abs(k * h) < tol_k: N_c = sigmac(epsilon_0, epsilon_c2, sigma_cd, n) * b * h else: epsilon_b = epsilon_0 + y_b * k epsilon_t = epsilon_0 + y_t * k N_c = b * DI0(epsilon_t, epsilon_b, epsilon_c2, sigma_cd, n)...
This function computes the axial force (N_r) and moment (M_r) capacity of a structural element by iterating over strain (epsilon_0) and curvature (kappa) values. It combines concrete (Nc, Mc) and steel (Ns, Ms) contributions using helper functions, generating capacity curves for design analysis.
def N_r_M_r(epsilon_c2, epsilon_cu, sigma_cd, n, b, f_yd, epsilon_yd, h, y_t, y_b, y_s, phi, nb, tol_k): c = epsilon_c2 u = epsilon_cu A = [0, c] B = [u / h, u * y_t / h] C = [(u + 10) / (y_t - min(y_s)), u - y_t * ((u + 10) / (y_t - min(y_s)))] D = [0, -10] E = [(u + 10) / (y_b - max(y_s)),...
def Dc(epsilon, epsilon_c2, sigma_cd, n): if epsilon < 0: D_c = 0 elif 0 <= epsilon <= epsilon_c2: D_c = sigma_cd * n * (1 - epsilon / epsilon_c2)**(n - 1) / epsilon_c2 else: D_c = 0 return D_c def DJm(epsilon_t, epsilon_b, epsilon_0, epsilon_c2, sigma_cd, n, m): return Jm(ep...
This function computes a 2x2 Jacobian matrix $ J_c $ based on material and geometric parameters. It uses different formulas depending on whether $ |k \cdot h| $ is below a tolerance. If true, it applies simplified expressions with $ Dc() $; otherwise, it calculates derivatives of $ DJm() $, $ DI0() $, and $ DI1() $ to ...
def Jc(epsilon_t, epsilon_b, epsilon_0, epsilon_c2, sigma_cd, n, b, k, h, tol_k): J_c = np.zeros((2, 2)) if abs(k * h) < tol_k: J_c[0, 0] = -Dc(epsilon_0, epsilon_c2, sigma_cd, n) * b * h J_c[0, 1] = 0 J_c[1, 0] = 0 J_c[1, 1] = -Dc(epsilon_0, epsilon_c2, sigma_cd, n) * b * h**3 /...
def Ns(y_s, nb, phi, f_yd, epsilon_yd, epsilon_0, k): A_si = [np.pi * phi**2 * nbi / 4 for nbi in nb] epsilon_s = epsilon_0 + y_s * k N_si = np.zeros_like(y_s) for i in range(len(y_s)): N_si[i] = A_si[i] * sigmas(epsilon_s[i], f_yd, epsilon_yd) return np.sum(N_si) def Ms(y_s, nb, phi, f_yd, ...
The code implements the Newton-Raphson method to solve for strain parameters (ε₀, k) that satisfy applied axial force (N_d) and moment (M_d) in a reinforced concrete section. It iteratively computes internal forces (N_r, M_r) from concrete and steel contributions, evaluates residuals (f_ad), and updates parameters usin...
def Verificacao(fck, gamma_c, sigma_cd, gamma_conc, f_yk, gamma_s, E_s, f_yd, epsilon_yd, gamma_aco, c, b, h, d, nc, nb, phi, y_s, N_d, M_d, epsilon_c2, epsilon_cu, x_lim, n, tol_J, tol_k, tol_f, i, it_max, y_t, y_b, epsilon_0, k, epsilon_0_it, k_it, epsilon_t, epsilon_b): ## Newton-Raphson method # Calculate N...
def deal_hand(n): """ Returns a random hand containing n lowercase letters. ceil(n/3) letters in the hand should be VOWELS (note, ceil(n/3) means the smallest integer not less than n/3). Hands are represented as dictionaries. The keys are letters and the values are the number of times the p...
The function `play_game` allows a user to play a series of hands in a word game, accumulating total scores. It prompts for the number of hands, lets the user substitute a letter once per game, and offers a one-time replay option for any hand to retain the better score. The total score across all hands is calculated and...
def play_game(word_list): """ Allow the user to play a series of hands * Asks the user to input a total number of hands * Accumulates the score for each hand into a total score for the entire series * For each hand, before playing, ask the user if they want to substitute one letter f...
def nextMove(a, cell): min_deg_idx = -1 c = 0 min_deg = (N + 1) nx = 0 ny = 0 # Try all N adjacent of (*x, *y) starting # from a random adjacent. Find the adjacent # with minimum degree. start = random.randint(0, 1000) % N for count in range(0, N): i = (start + count) % N nx = cell.x + cx[i] ny = cell....
The code determines if a closed knight's tour exists on an N×N chessboard starting from position (3,2), using Warnsdorff's heuristic to select moves. It marks the path, checks if the final position neighbors the start to complete the loop, and returns `True` if successful, otherwise `False`. (100 words)
def findClosedTour(): # Filling up the chessboard matrix with -1's a = [-1] * N * N # initial position sx = 3 sy = 2 # Current points are same as initial points cell = Cell(sx, sy) a[cell.y * N + cell.x] = 1 # Mark first move. # Keep picking next points using Warnsdorff's heuristic ret = None for i in ra...
def _init_cols_rows_squares(self): for i in range(self._BOARD_SIZE): self._squares.append(Square(i)) self._rows.append(Row(i)) self._cols.append(Column(i)) for i in range(self._BOARD_SIZE): for j in range(self._BOARD_SIZE): square_num = in...
The main task of the code is to generate a valid Sudoku board by initializing columns, rows, and squares, filling the diagonal cells, iteratively attempting to complete the board, resetting and retrying if unsuccessful, and finally erasing parts of the board to create a solvable puzzle.
def _create_board(self): self._init_cols_rows_squares() self._fill_diagonal() while not self._fill_remaining(): self._clear_board() self._fill_diagonal() self._erase_part_of_the_board()
def get_valid_num_in_range(prompt, lowerRange, upperRange, errorMessage): while True: try: value = int(input(prompt)) except ValueError: print("Sorry, I didn't understand that.") continue if value < lowerRange or value > upperRange: print(erro...
The main task of the code is to present a menu-driven calculator interface, allowing users to select from four calculation categories (simple, geometry, linear equations, advanced math). It displays options, validates input range, and directs users to corresponding functions based on their choice, ensuring a structured...
def main(): print("Welcome to Chloe's Calculator! Here you'll be able to chose from a variety of calculations ranging from simple to advanced.") print("Below is a list of the types of calculations you can make.") counter = 1 for i in calcOptions: print("(" + str(counter) + ") " + i) coun...
def introduction(): startingMoney = 0 playerInfo.name = input("Welcome to the game of roulette! What is your name? ") print("Hello " + playerInfo.name + """, in this game of roulette, you're allowed to bet on up to 36 of the numbers and also you're able to bet on the colour or parity of the roll. Goodluck...
The main task of the code is to execute a game loop where the player selects bet types, simulates a ball roll, checks winnings, and decides to continue playing. The loop repeats until the player chooses to stop, with each iteration handling game mechanics and user interaction through function calls like betTypespecific...
def main(): introduction() while (playAgain == True): betTypespecification() ballRoll() playerWinningsCheck() playMore()
def available_actions(board): """ returns a set of the possible actions to be made on a board """ actions = set() for i in range(WIDTH): # index the cul and then return how many zeros there are, and the put +1 to the action cul = board[:, i] row = cul[cul == 0].size - 1 ...
The function identifies a winning move for the specified player by iterating through available actions, simulating each move on the board, and returning the first action that results in the player winning.
def check_for_win(board, player): """ before depth in search, first check if you can win through is board """ for action in available_actions(board): if winner(update_board(board, action)) == player: return action
def game_is_over(board): """ return true if game is over """ if winner(board) is not None or available_actions(board) == set(): return True else: return False def utility(board, com_player): """ returns the value of each ending state, win, lose and tie """ if winner(b...
The code implements the Minimax algorithm with Alpha-Beta pruning to determine the optimal move for a computer player in a two-player game. It evaluates board states recursively, prioritizing winning moves, and uses depth-limited search with heuristic value estimation when depth is exhausted. The algorithm alternates b...
def minimax(board, depth, is_player, alpha, beta, com_player): """ the AI taking place """ if game_is_over(board): return utility(board, com_player), None elif depth == 0: return value_estimate(board, com_player), None # is it our players turn? if is_player: # set th...
def clearModels(self): for model in self.modelList: model.detachNode() self.modelList.clear() def setSize(self, shape): if shape == self.shape: return self.shape = to_xy_shape(shape) self.base.buffer.setSize(self.shape[0], self.shape[1]) lens = Ort...
The code renders a 3D model by clearing existing objects, setting the buffer size, adding lighting (and optionally filters), rendering facial landmarks with accessories from the mesh data, and returning the final rendered result.
def render(self, shape, mesh, accesory_name): # Clear existing nodes. self.clearModels() # Reset buffer size. self.setSize(shape) # Try adding lights and filters if they don't exist. if not self.hasLight: self.addLight() self.hasLight = True ...
def update_pos(self): tempPos = self.get_info(["Position"]) self.lead_screw_position = tempPos[0][0] # Get parameters for finger deflections depending on which finger set is being used # Estimate finger deflection from quadratic finger stiffness curve-fitting self.finger_deflect...
The code manages a gripper's operational states (Opening, Holding, Closing, Idle) by updating sensor data, applying PI control for force regulation, detecting object contact, and sending serial commands to a Teensy board. It transitions between states based on position/force thresholds, maintains force stability, handl...
def gripper_loop(self): if self.status == 'Opening': # Update current position self.update_pos() if abs(self.lead_screw_position-self.positionsetpoint) < self.positionthreshold: self.status = 'Idle' func = self.functions_dictionary['Loose'] ...
def transform_matrix(m): for i, row in enumerate(m): row_sum = sum(row) if row_sum == 0: m[i][i] = 1 else: for j, col in enumerate(row): m[i][j] = frac(col,row_sum) def getSubmatrix(m,row,col): new_m = [] for i in row: new_row = [] ...
The code solves a Markov chain problem to compute the probabilities of ending in terminal states from non-terminal states. It separates terminal and non-terminal states, constructs submatrices Q (non-terminal transitions) and R (transitions to terminal states), calculates the inverse of (I - Q), multiplies it with R, a...
def solution(m): terminal_states, non_terminal_states = [[],[]] for index, row in enumerate(m): if sum(row) == 0: terminal_states.append(index) else: non_terminal_states.append(index) if len(terminal_states) == 1: return [1, 1] # 1) Transforming matri...
def is_close(self): "Should return whether the target has been reached" return bool(self.distance() <= self._threshold) def is_done(self): return self.is_close() or self._steps >= self._episode_length def check_collision(self): """Return whether collision has occurred""" return F...
This function calculates a sparse reward for an agent based on its state: it returns a success reward (plus collision penalty) if close to a goal, a failure reward (plus penalty) if the task is done, or a step failure reward (plus penalty) otherwise, using collision detection to apply penalties when applicable.
def const_sparse_reward(self): close = self.is_close() done = self.is_done() punishment = self._collision_reward if self.check_collision() else 0 if close: return self._success_reward + punishment elif done: return self._failure_reward + punishment ...
def is_done(self): return self.is_close() or self._steps >= self._episode_length def is_close(self): "Should return whether the target has been reached" return bool(self.distance() <= self._threshold) def check_collision(self): """Return whether collision has occurred""" return F...
The function calculates a sparse reward for an agent based on task completion status, proximity to a goal, and collisions. It returns a success reward minus path cost (if close), a failure reward (if done), or a step failure reward, each adjusted by a collision penalty.
def joint_sparse_reward(self): done = self.is_done() close = self.is_close() punishment = self._collision_reward if self.check_collision() else 0 if close: return self._success_reward - self.path_cost() + punishment elif done: return self._failure_reward ...
def update_history(self): self._rewards.append(self._reward_fn()) def move(self, action): """Performs the action logic""" pass def is_done(self): return self.is_close() or self._steps >= self._episode_length def info(self): return {} def save_history(self, **kwargs): self...
This function executes a single step in an environment by updating the step count, applying the given action, checking termination, calculating reward, and logging results if the episode is done. It returns the new state, reward, termination status, and additional information.
def step(self, action): """Performs the step logic""" self._steps += 1 self.update_history() self.move(action) done = self.is_done() reward = self._reward_fn() info = self.info() if done: self.update_history() if done and self._log_f...
def play_reset_actions(self): for v in self._reset_actions: self.move(v) def get_joint_values(self): return np.array([self._robot.get_joint_positions()[j] for j in self._joints]) def empty_move(self): self.move(np.zeros((len(self._joints),))) def get_state(self): if self._dyn...
The code resets the environment by clearing previous actions, sampling new reset actions, executing them, recording joint positions, performing an empty move, and returning the current state. This initializes the system to a predefined configuration for subsequent operations.
def reset(self): super().reset() self._reset_actions.clear() for _ in range(self._nreset_actions): self._reset_actions.append(self._reset_action_space.sample()) self.play_reset_actions() self._reset_joint_positions = self.get_joint_values() self.empty_move()...
def getMovieEntity(bot, movieName): movie = 'movie' + movieName.lower().replace(' ', '') for m in bot.likes.movies: if m.name == movie: return m, True for m in bot.dislikes.movies: if m.name == movie: return m, False entity = onto.movies(movie, realName=movieName...
The function `respond` manages user interactions about movies and characters, handling tasks like retrieving plot details, updating entity information, and responding to queries about preferences. It checks context flags (e.g., `plot`, `tell`, `whichMovie`, `know`, `like`, `hate`) to determine the user's intent. If the...
def respond(bot, entity=None, isMovie=None, res=None): # global lastQ # lastQ = 0 # last question is do global initialBotSentence if contexts['plot']: # user want to know more plot contexts['lastOperation'] = 'plot' # last operation contexts['plot'] = False movie = True if con...
def gaussianelimination(self, verbose=False): if self.RREF: return detailed = "" smaller = min(self.rows(), self.cols()) for step in range(smaller): if verbose: detailed += f"Step: {step}\n{str(self)}\n" #need a non-zero valu...
The code solves a system of linear equations by first performing Gaussian elimination to reach reduced row-echelon form (RREF). It checks for inconsistency (all-zero rows) and returns "inconsistent" if found. For consistent systems, it returns solutions either as specific values (for square matrices) or in terms of fre...
def solution(self, fract=True): if self.b is not None: if not self.RREF: self.gaussianelimination() #if any row is all 0's, the system is inconsistent for k in self: if not any(k): return "The system is inco...
def preprocess(img): """Threshold an image using grayscale and global threshold Parameters ---------- img : Image The image to be grayscaled and thresholded Output ------ threshold : Image The thresholded image of the input image """ grayscaled = cv2.cvtColor(img,c...
The code processes an image to detect and visualize contours using the Marching Squares algorithm on a denoised thresholded image. It filters closed contours with an area exceeding 100 pixels, overlays them on the denoised image, plots specified center points, and saves the result as a PNG file with a numbered filename...
def drawContour(img_num, path, center_list): img = cv2.imread(path) threshold = preprocess(img) sk_img = image_denoise(img) sk_thre = image_denoise(threshold) contours = path_Marching_Squares(sk_thre, 0.45) fig, ax = plt.subplots(figsize=(10,10)) plt.gray() ax.imshow(sk_img) for co...
def build_heap(self, arr): length = self.heap_size(arr) for i in range(int(length/2), -1, -1): self.heapify(arr, length, i) def heap_size(self, arr): return len(arr) def heapify(self, arr, boundary, i): larger = i left = self.left(i) right = self.right(i) # the idea to work opposite of the smaller v...
The main task of the code is to sort the input array in ascending order using a min-heap. It builds a min-heap, then iteratively swaps the root (smallest element) with the last unsorted element, reduces the heap size, and restores the heap property. This process repeats until the array is fully sorted.
def minheap_kthSmallest(self, arr): self.build_heap(arr) for i in range(self.heap_size(arr)-1, -1, -1): # swap values arr[0], arr[i] = arr[i], arr[0] self.heapify(arr, i, 0) return arr
def print_blogs(): # print the availble blogs for key, blog in blogs.items(): # same as (key:blog_name,value:Blog,(blog_name,Blog)) """for both the key(blog_name),value("blog_object)""" # print("I am printing to the console,but i will be patched in the system test") # key:blogName and ...
The main task of the code is to provide a menu-driven interface for users to manage blogs by allowing them to create blogs, view available blogs, read blog content, create posts, and exit the system, with options handled in a loop until the user selects "q" to quit.
def menu(): """this menu is UI that will allow the users to create blogs,""" # show the user avaible blogs # let the user make a choice # do something with that choice # eventually exit the blog content system print_blogs() selection = input(MENU_PROMPT) while selection != "q": ...
def order_unique(self): r=self.load_file() order=[] for i in r: for item in i: if item not in order: order.append(item) return order def get_frequent(self,itemsets,prev_discarded): transac =self.load_file() num_trans=len(tra...
This code generates the L1 frequent itemsets using the Apriori algorithm. It initializes candidate itemsets of size 1, calculates their support counts via `get_frequent`, filters frequent items, and returns the resulting L1 set along with support counts. The method prints the L1 results in a table format before returni...
def L1(self): C={} L={} itemset_size=1 C.update({itemset_size:[[i] for i in self.order_unique()]}) Discarded={itemset_size:[]} supp_count_L={} f,sup,new_discarded=self.get_frequent(C[itemset_size],Discarded) Discarded.update({itemset_size:new_discarded}) ...
def L1(self): C={} L={} itemset_size=1 C.update({itemset_size:[[i] for i in self.order_unique()]}) Discarded={itemset_size:[]} supp_count_L={} f,sup,new_discarded=self.get_frequent(C[itemset_size],Discarded) Discarded.update({itemset_size:new_discarded}) ...
This code implements the Apriori algorithm for association rule mining. It iteratively generates candidate itemsets (C), identifies frequent itemsets (L) based on support thresholds, and derives association rules using confidence and lift metrics. The process continues until no new frequent itemsets are found, outputti...
def CkLkAr(self): itemset_size=1 C={} CI={} L={} new_discarded=[] supp_count_L={} k=itemset_size+1 temp=self.L1() transac =self.load_file() num_trans=len(transac) L.update({itemset_size:temp}) CI.update({itemset_size:[[i] fo...
def eligible_digit(row, col, world, visited): return within_bounds(row, col, world) and not visited[(row, col)] and world[row][col].isdigit() def search_west(row, col, world, visited=defaultdict(bool)): num = "" j = col - 1 while eligible_digit(row, j, world, visited): num = world[row][j] + num ...
The code calculates the sum of values from adjacent cells in all eight directions (NW, N, NE, W, SW, S, SE, E) around a given cell in a grid. It checks if adjacent cells are eligible (via `eligible_digit`) and adds their values (from `search_west`/`search_east` functions) to a cumulative score. If ineligible, it separa...
def search(row, col, world, visited): adjacent_part_score = 0 # NW, N, NE if eligible_digit(row - 1, col, world, visited): adjacent_part_score += int(search_west(row - 1, col, world, visited) + world[row - 1][col] + search_east(row - 1, col, world, visited)) else: part_w = search_we...
def within_bounds(row, col, world): width = len(world[0]) height = len(world) return row < width and row >= 0 and col >= 0 and col < height def search_west(row, col, world, visited=defaultdict(bool)): num = "" j = col - 1 while eligible_digit(row, j, world, visited): num = world[row][j]...
The function identifies adjacent numeric parts in a grid relative to a given cell, collects valid numbers from surrounding directions, and returns the product of the first two found parts. If fewer than two parts are found, it returns 0.
def search_gears(row, col, world): adjacent_parts = [] # NW, N, NE if within_bounds(row - 1, col, world) and world[row - 1][col].isdigit(): adjacent_parts.append(int(search_west(row - 1, col, world) + world[row - 1][col] + search_east(row - 1, col, world))) else: part_w = search_west(row...
def get_train_data(): url = './data.csv' df = pd.read_csv(url) km = df["km"].to_list() price = df["price"].to_list() x_train = np.array(km) y_train = np.array(price) return x_train, y_train def data_standardization(data): mean = mean_(data) standard = get_stddev(data) res = (data...
The code performs linear regression using gradient descent to predict housing prices based on mileage. It standardizes input data, iteratively updates weights and bias, tracks cost history, and visualizes training progress with cost vs. iterations and prediction vs. actual values. An animation of the optimization proce...
def linear_regression(): x_train, y_train = get_train_data() learning_rate = 0.01 iterate = 10000 b, w = 0,0 x_norm = data_standardization(x_train) J_history = [] p_history = [] for _ in range(0, iterate): tmp0, tmp1 = b, w b -= learning_rate * get_bias(tmp0, tmp1, x_nor...
def get_train_data(): url = './data.csv' df = pd.read_csv(url) km = df["km"].to_list() price = df["price"].to_list() x_train = np.array(km) y_train = np.array(price) return x_train, y_train def data_standardization(data): mean = mean_(data) standard = get_stddev(data) res = (data...
This code performs linear regression using gradient descent. It standardizes training data, iteratively updates parameters (theta0, theta1) via gradient descent, and unnormalizes the final coefficients to return the model's intercept and slope.
def linear_regression(): x_train, y_train = get_train_data() learning_rate = 0.001 iterate = 100000 theta0, theta1 = 0,0 x_norm = data_standardization(x_train) for _ in range(0, iterate): tmp0, tmp1 = theta0, theta1 theta0 -= learning_rate * get_bias(tmp0, tmp1, x_norm, y_train)...
def get_versions(file: str): versions: list[str] = read_json(file) new_ver: list[tuple[int, int]] = [] for ver in versions: try: new_ver.append(parse_version(ver)) except ValueError: pass new_ver.sort() return new_ver def get_db_from_update(root: str, platform...
This function processes package versions by prehashing different package types (0-6) for a given platform. It retrieves version info, decrypts database files, and writes decrypted databases to specified directories. For package type 0, it uses decrypted DBs; for type 4, it extracts to a microdl folder. The task involve...
def prehash_packages(root: str, platform: str): path = f"{root}/{platform}/package" info = get_versions(f"{path}/info.json") for version in info: dbfiles = get_db_from_update(root, platform, version) # Prehash print("Prehasing package for version", *version) verstr = version_...
def update_http_client( parse: urllib.parse.ParseResult, handle: http.client.HTTPSConnection | http.client.HTTPConnection | None ): if ( handle is None or handle.host != parse.hostname or handle.port != get_port_by_parseresult(parse) or (isinstance(handle, http.client.HTTPSConnec...
The main task of the code is to download a file from a given URL, handling HTTP redirects (301-308) recursively up to 5 times. It uses an HTTP client to send a GET request, checks the response status code, and either follows redirects or returns the file content as bytes. If redirects exceed the limit or the status cod...
def download_file_notry(url: str, /, *, redircount: int = 0) -> bytes: global _dl_http_client parse = urllib.parse.urlparse(url) _dl_http_client = update_http_client(parse, _dl_http_client) _dl_http_client.request("GET", get_paths_from_parseresult(parse)) response = _dl_http_client.getresponse() ...
def read_json(file: str): with open(file, "r", encoding="UTF-8", newline="") as f: return json.load(f) def version_str(ver: tuple[int, int]): return "%d.%d" % ver def build_new_update_info(root: str, platform: str): path = f"{root}/{platform}/update" versions: list[tuple[int, int]] = [] # Sc...
The main task of the code is to check the generation version of an archive directory, update its metadata and prehash packages for specified platforms if the version is outdated, and ensure consistency with a predefined generation version. It parses input arguments, validates the archive root, reads/writes version data...
def main(): parser = argparse.ArgumentParser() parser.add_argument("archive_root", type=path_validate) args = parser.parse_args() root: str = args.archive_root # Load generation version genfile = f"{root}/generation.json" if os.path.isfile(genfile): gendata: dict[Literal["major", "m...
def download_file(url: str, /): retry = 0 while True: try: return download_file_notry(url) except Exception as e: retry = retry + 1 if isinstance(e, CloneDownloadError) or retry >= 25: raise e from None def verify_hash(data: bytes, checksums: D...
The function processes software update files by loading version-specific download links from an 'update.pickle' file, downloading and verifying each update archive, organizing them into version directories, generating metadata files, updating a version list, and cleaning up temporary files.
def continue_update(path: str): update_pickle = path + "/update.pickle" if not os.path.exists(update_pickle): return with open(update_pickle, "rb") as f: update_info: UpdateInfo = pickle.load(f) if int(time.time()) >= update_info.expire: raise RuntimeError(f"Links expired...
def download_file(url: str, /): retry = 0 while True: try: return download_file_notry(url) except Exception as e: retry = retry + 1 if isinstance(e, CloneDownloadError) or retry >= 25: raise e from None def verify_hash(data: bytes, checksums: D...
This function resumes batch downloading of package files by loading a pickle file containing update information, verifying expiration, organizing downloads into version-specific directories, downloading missing files with checksum validation, and generating info.json files to track downloaded packages. It removes the t...
def continue_batch_download(path: str, package_type: int): update_pickle = f"{path}/package_{package_type}.pickle" if not os.path.exists(update_pickle): return with open(update_pickle, "rb") as f: package_info: PackageInfo = pickle.load(f) if int(time.time()) >= package_info.expire: ...
def _handle_device_registration_response(self, payload: Device_Input): if payload.status == ActiveMessageStatus.SUCCESS.name: self._device_registration_flag = True else: self._device_registration_flag = False print("LIGHT-DEVICE Registered! - Registration status is avail...
This method processes MQTT topics related to device management by checking the topic name against predefined formats. It triggers actions like handling device registration responses, sending device status, or processing update requests based on the topic. If the topic is unsupported, it logs an error message.
def _handle_topic(self, topic_name, payload): if topic_name == ActiveTopics.SET_DEVICE_REGISTRATION_STATUS_TOPIC_NAME.value.format(self._device_id): self._handle_device_registration_response(Device_Input.from_json(payload)) elif topic_name == ActiveTopics.GET_DEVICE_STATUS_TOPIC_NAME.value.f...
def _handle_device_registration_response(self, payload: Device_Input): if payload.status == ActiveMessageStatus.SUCCESS.name: self._device_registration_flag = True else: self._device_registration_flag = False print("AC-DEVICE Registered! - Registration status is availabl...
This method processes MQTT topics related to device management by routing incoming messages to specific handlers based on the topic name. It checks if the topic matches predefined formats for device registration status, status requests, or update requests, then triggers corresponding actions like handling registration ...
def _handle_topic(self, topic_name, payload): if topic_name == ActiveTopics.SET_DEVICE_REGISTRATION_STATUS_TOPIC_NAME.value.format(self._device_id): self._handle_device_registration_response(Device_Input.from_json(payload)) elif topic_name == ActiveTopics.GET_DEVICE_STATUS_TOPIC_NAME.value.f...
def get_displacements(self) -> np.ndarray: """ Returns atomic displacement as a flattened numpy array. Returns: - A numpy array containing the atomic displacements. """ self._is_ground_match_to_excited_state() ground_state_positions = utils.get_positions(self.gr...
The code calculates configuration coordinates for all vibrational modes by combining displacement vectors, eigenvectors, and the square root of the mass matrix. It iterates over each mode, computes coordinates using a helper method, and returns a list of these coordinates for all 3N modes (N = number of atoms). The TOD...
def get_configuration_coordinates(self) -> list[float]: """ Calculates configuration coordinates for all vibrational modes. Returns: - list[float]: a list of configuration coordinates corresponding all modes. """ number_of_modes = 3 * utils.get_number_atoms(self.ground_s...
def get_displacements(self) -> np.ndarray: """ Returns atomic displacement as a flattened numpy array. Returns: - A numpy array containing the atomic displacements. """ self._is_ground_match_to_excited_state() ground_state_positions = utils.get_positions(self.gr...
The main task of the code is to compute partial Huang-Rhys factors for all vibrational modes of a material, applying the acoustic rule by setting the first three acoustic modes to zero. It calculates factors using displacement vectors, mass matrices, and eigenvectors, then returns the resulting list of values.
def get_partial_huang_rhys_factor(self) -> list[float]: """ Calculates partial Huang-Rhys factors for all vibrational modes. Returns: - list[float]: a list of partial Huang-Rhys factors for each mode, with the acoustic modes set to zero by the acoustic rule. """ ...
def clear_screen(background=None): global _canvas_x, _canvas_y _canvas.delete('all') draw_background() _canvas_x, _canvas_y = 0, _canvas_ys letters = text((75, 20), color='black', contents="Letters:", size=20) wordsHeader = text((75, 200), color='black', contents="Possible words:", size=20) def ...
The code displays the alphabet letters in three rows on a screen, positioning each letter at specific coordinates with colors from a dictionary. The first 10 letters (A-J) appear at the top, the next 10 (K-T) in the middle, and the last 6 (U-Z) at the bottom, each spaced 50 units apart horizontally. The function clears...
def displayLetters(): clear_screen() alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] i = 300 for letter in alphabet[:10]: text((i, 10), color=letterDict[letter], contents=letter, size=30) ...
def startingWords(): global allWords allWords = newGame() def clear_screen(background=None): global _canvas_x, _canvas_y _canvas.delete('all') draw_background() _canvas_x, _canvas_y = 0, _canvas_ys letters = text((75, 20), color='black', contents="Letters:", size=20) wordsHeader = text((...
The main task of the code is to initialize a game or process by displaying starting instructions, clearing the screen, and creating a letter dictionary for subsequent operations, likely preparing the environment for user interaction or game mechanics.
def startOver(): startingWords() clear_screen() createLetterDict()
def plot_state_lines(bokeh_figure, state_list=None, colors=None, us_states_dat=None): """Plots US state borders and allows color coding by state, for example to represent different emissions goals. :param bokeh.plotting.figure.Figure bokeh_figure: bokeh figure to plot on. :param list state_list: li...
The main task of the code is to generate an interactive SVG map of Texas's power grid using Bokeh, visualizing geographical boundaries, AC power flow lines, and generation data (as pie charts). It allows optional map background tiles, customizes plot elements, and exports the result as "fig3.svg".
def plot_texas_powerflow(pf=None, branch=None, pie_data=None, background_map=False, text_data=None, colors = None): # Initialize figure bokeh_figure = figure( tools="pan,wheel_zoom,reset,save", x_axis_location=None, y_axis_location=None, plot_width=800, plot_height=800, ...
def put_charts(web3): put_markdown("## Charts") put_html(charts.get_block_miners(web3)).style("width: 60vw; height: 40rem") put_markdown( "###### This graph shows the miners who mined the most blocks from a sample of 1,000 blocks." ) put_markdown("---") def put_blocks(web3): put_markdown...
The code creates a vertical navigation bar using PyWebIO's grid layout, displaying "PyWebIO Ether Demo" as the title and three clickable sections: "Charts", "Blocks", and "Transactions". Each section triggers a corresponding function (put_charts, put_blocks, put_transactions) with the web3 parameter when clicked, enabl...
def put_navbar(web3): put_grid( [ [ put_markdown("### PyWebIO Ether Demo"), put_markdown("#### Charts").onclick(lambda: put_charts(web3)), put_markdown("#### Blocks").onclick(lambda: put_blocks(web3)), put_markdown("#### Transaction...
def writeToOutput(self, string): self.output.write(" " * self.indents + string) def indent(self): self.indents += 1 def advance(self): # advance the tokenizer. self.tokenizer.advance() # check if the tokenizer's and CE's current line is different. if self.tokenizer.curr...
The main task of the code is to compile a class variable declaration, handling either 'static' or 'field' variables. It processes the variable type, identifier(s), and updates the symbol table with the kind (STATIC/FIELD) and type. It also tracks the number of fields when 'field' is used, updates the symbol table for e...
def compileClassVarDec(self): self.writeToOutput("<classVarDec>\n") self.indent() # eat either static or field if not self.skip_advance: self.advance() self.skip_advance = True ifField = False numFields = 0 if self.tokenizer.current_token ==...
def writeToOutput(self, string): self.output.write(" " * self.indents + string) def indent(self): self.indents += 1 def advance(self): # advance the tokenizer. self.tokenizer.advance() # check if the tokenizer's and CE's current line is different. if self.tokenizer.curr...
The code compiles a list of parameters by parsing their types and identifiers, adding them to the symbol table, and generating XML output. It handles multiple parameters separated by commas, ensuring each is correctly defined with its type and name, then structures the output within `<parameterList>` tags.
def compileParameterList(self): self.writeToOutput("<parameterList>\n") self.indent() self.advance() self.skip_advance = True if (self.tokenizer.current_token in ["int", "char", "boolean"] or self.tokenizer.tokenType() == TokenType.IDENTIFIER): # comp...
def writeToOutput(self, string): self.output.write(" " * self.indents + string) def indent(self): self.indents += 1 def eat(self, token): # advance the current character if second argument is true. if not self.skip_advance: self.advance() else: self.skip_...
The code compiles a variable declaration by parsing 'var', a type, and one or more identifiers separated by commas. It updates the symbol table with each local variable's name and type, then returns the count of declared variables. The function outputs XML tags for the declaration structure and handles token advancemen...
def compileVarDec(self): self.writeToOutput("<varDec>\n") self.indent() """ <varDec> <keyword> var </keyword> <identifier> SquareGame </identifier> <identifier> game </identifier> <symbol> ; </symbol> </varDec> :return:...
def take_step(self): tree = self.tree maxn = self.max_nodes sig = self.sig # sorting the parent choices gives agreement for the same random seed. # otherwise small differences can cause a difference in the parent which causes big differences later on par_choices...
The code's main task is to evolve a population by iteratively taking steps, culling nodes, and tracking the mean fitness and number of active walkers over each iteration until reaching the maximum node limit. It initializes lists to record these metrics, executes evolution steps, prunes the population, and appends upda...
def run_evo(self): self.mean_s_traj = [] # mean fitness of population over evolution self.num_active_traj = [] # number of active walkers over evolution while self.epoch<self.max_nodes-1: self.take_step() self.cull_nodes() self.mean_s_traj.append(self.get_mean...
def take_step(self): tree = self.tree par = np.random.choice([n for n in tree.nodes if self.active[n]]) mu_par = self.labels[par][0] # should the conditioning be that new fitness is greater than mean fitness? random_part = sample_truncated(self.rho_func*self.coeff_list,...
This function simulates an evolutionary process over a specified number of steps, tracking population fitness metrics, active walker counts, and derived values. It initializes trajectory lists, iteratively executes evolution steps (take_step, cull_nodes), records mean fitness of active nodes, active population size, an...
def run_evo(self,num_steps): self.s_dist_traj = [] # mean fitness of population over evolution self.num_active_traj = [] # number of active walkers over evolution self.ds_traj = [] # fitness gains self.mu_traj = [] for i in range(num_steps): self.take_step() ...
def take_step(self): tree = self.tree maxn = self.max_nodes # don't want to exceed maximum size assert len(tree)<maxn sig = self.sig par = np.random.choice([n for n in tree.nodes if self.active[n]]) # print([n for n in tree.nodes if self.active[n...
The code evolves a population by iteratively taking steps, culling nodes, and tracking the mean fitness of the population and the number of active walkers over each generation until the tree reaches its maximum node limit.
def run_evo(self): self.mean_s_traj = [] # mean fitness of population over evolution self.num_active_traj = [] # number of active walkers over evolution while len(self.tree)<self.max_nodes: self.take_step() self.cull_nodes() self.mean_s_traj.append(self.get_me...
def take_step(self): tree = self.tree par = np.random.choice([n for n in tree.nodes if self.active[n]]) mu_par = self.labels[par][0] rho_func = np.sqrt((1-self.rho_list**2)/2) random_part = sample_truncated(rho_func*self.coeff_list,-np.dot(mu_par,self.coeff_list...
The main task of the code is to simulate an evolutionary process over a specified number of steps. It tracks the population's mean fitness and active walker count at each step by repeatedly calling `take_step()` to evolve the population, `cull_nodes()` to prune inactive elements, and appending metrics to `mean_s_traj` ...
def run_evo(self,num_steps): self.mean_s_traj = [] # mean fitness of population over evolution self.num_active_traj = [] # number of active walkers over evolution for i in range(num_steps): self.take_step() self.cull_nodes() self.mean_s_traj.append(self.get_me...
def create_destination_dirs(destination_dir, number_splits): for i in range(number_splits): os.makedirs(os.path.join(destination_dir, destination_sub_dirs[i], 'images')) os.makedirs(os.path.join(destination_dir, destination_sub_dirs[i], 'labels')) def split_file_list(file_list, sizes): length = ...
The function shuffles and splits image-label pairs from an origin directory into specified proportions (sizes), then moves them to subdirectories in a destination directory. It ensures sizes sum to 100%, supports 1-3 splits, handles file extensions, and optionally preserves original files. Image and label files are sep...
def shuffle_split_files( sizes: list, origin_dir: str, destination_dir: str, extensions: Union[str, list, None] = 'jpg', keep_original: bool = True): assert sum(sizes) == 1, 'sizes must add up to 1 (100%)' assert 1 <= len(sizes) <= 3, 'length of sizes must be between 1 an...
def __create_output_file(self): if not self.overwrite_existent and os.path.isfile(self.output_path): raise FileExistsError('Output file already exist, please change output path or set overwrite_existent to ' 'True if you want to over write the old file') re...
The main task of the code is to generate an output file by iterating through image paths and their associated annotations from a reader instance. It writes each image's annotations as lines in the file and triggers an exit handler afterward. The method creates the output file, processes label data from the reader, and ...
def write_annotations(self) -> None: """ loop through all image paths provided by the reader instance and write all annotations to the output file. :return: """ self.file = self.__create_output_file() for (image_path, objects) in self.reader.next_labels(): s...
def create_dirs(self, dataset_types: List[YoloV5DatasetType]): for dataset_type in dataset_types: os.mkdir(os.path.join(self.output_dir, dataset_type.value)) os.mkdir(os.path.join(self.output_dir, dataset_type.value, 'images')) os.mkdir(os.path.join(self.output_dir, dataset_t...
The main task of the code is to process an input file by splitting its lines into dataset types (e.g., train/val/test), create directories based on specified sizes, and write annotations for each dataset type into corresponding directories. It organizes data into structured folders for machine learning workflows.
def __call__(self): self.create_dirs(list(self.sizes.keys())) with io.open(self.input_file, 'r') as input_file: lines = self.split_lines(input_file.readlines()) for dataset_type, lines_part in lines.items(): self.write_dataset_type_annotations(dataset_type, lines_...
def detrend_prices(self, dfAP): dfDetrend = pd.DataFrame(np.zeros_like(dfAP.values), index = dfAP.index, columns = dfAP.columns) for column in dfAP.columns: dfDetrend[column] = detrendPrice.detrendPrice( dfAP.loc[:, column] ).value...
The function backtests a rotational momentum strategy on ETF portfolios using price/adjusted price dataframes. It calculates returns, determines entry/exit signals, applies laddering/trailing stops, and computes performance metrics (CAGR, Sharpe Ratio, volatility). It returns equity curves and optional metrics, with op...
def backtest(self, dfP, dfAP, laddering = False, show_trailing = True, return_metrics = False, trailing_stop=False, plotting = False, print_metrics = False): """ Backtests an individual portfolio/set of ETFs according to the rotational momentum strategy. Parameters ---------- ...
def make_delaunay(f_w, f_h, theList): # Make a rectangle. rect = (0, 0, f_w, f_h) # Create an instance of Subdiv2D. subdiv = cv2.Subdiv2D(rect) # Make a points list and a searchable dictionary. theList = theList points = [(int(x[0]),int(x[1])) for x in theList] dictionary = {x[0]:x[1] for x in list(zip(poin...
The code generates a morphed image by aligning keypoint-based Delaunay triangulations of two input images, blending corresponding triangles using morph_triangle, and overlaying white lines to visualize the triangulation structure. The result is displayed and returned as a morphed image with preserved shape and color in...
def generate_morphed_image(img1, img2): points1 = keypoints(img1) # print(points, len(points)) listd1 = make_delaunay(img1.shape[1], img1.shape[0], points1) # print(listd) drawLines(img1, points1, listd1) points2 = keypoints(img2) # print(points, len(points)) listd2 = make_delaunay(img2.shape[1], img1.shape[0...
def create_bounding_box(current_pos: LatLong, AREA=30_000 * math.sin(math.pi / 4)): """ Given a LatLong pair, return the bounding box of size area from the position. Returns: (pos - area, pos + area), (pos + area, pos - area) to represent the top left, and top right """ new_br = LatLong( *tr...
The main task of the code is to retrieve and visualize flights near a user's location. It creates a bounding box around the user's position, fetches flights within that area, loads their data, generates flight observations, and produces a map visualization. The function returns both the processed flight observations an...
def get_flights_near_user(current_pos: LatLong): users_bounding_box = create_bounding_box(current_pos) flights_near_user = get_flights_in_box(users_bounding_box) flights_near_user = load_flight_data(flights_near_user) observations = create_flight_observations( flights_near_user, (current_pos.l...
def recvint(self): try: return int(self.request.recv(10)) except: return 0 def addsec(self): if len(self.data) > MAXNUM: self.request.sendall(b"[Error] too many secrets\n") raise LicenseRequired name = os.urandom(4).hex() self.data[...
This code implements a server handling interactions for a custom secure tar file service, allowing users to add secrets, upload/download ctar files, read secrets, and add flags. It uses a temporary directory, processes menu-driven commands, and cleans up resources before closing the connection.
def handle(self): #if not self.proof_of_work(): # return self.data = {} self.dir = tempfile.mkdtemp() os.chdir(self.dir) signal.alarm(120) self.request.sendall(b"*** Welcome to ctar service ***\nUpload and archive your secrets with our super fancy homemade secu...
def speedChange(self, speedChange): if(self.speed + speedChange < 0): if(self.speed + speedChange * self.deceleration < self.minspeed): self.speed = self.minspeed else: self.speed += speedChange * self.deceleration else: if((self.speed ...
The function `inputChange` adjusts an animal's (wolf or sheep) speed and rotation randomly. If the animal is a wolf, it retrieves and debug-prints vision data (detecting sheep, wolves, or walls) along with position/rotation. If a sheep, it updates its position. Debug mode enables detailed output of sensory inputs and s...
def inputChange(self): #a = NeuralNetwork() #a.funca() if(self.animal == 1): self.speedChange((random.randrange(-10, 10)/10.0)) self.rotationChange(random.randrange(-3600, 3600)/10.0) vision = getWolfVision(self.index) if(debug): ...