dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def grab_times(loc): """Grab all timings from directories starting with *prefix* Returns ------- list of timings """ timings = [] for d in glob.glob('{}_*'.format(os.path.join(loc, _get_prefix(loc)))): try: times = parse_all_timefiles(d) cpuinfo = parse_cpui...
The function `get_times(loc)` retrieves timing data from a specified location, processes it to extract pressures and corresponding time values, converts time values to integers, and returns the sorted results. It uses `grab_times(loc)` to fetch raw data, extracts pressures via `get_pressure()`, converts time strings to...
def get_times(loc): """Grab all timing results from *loc* Returns: pressures, times """ times = grab_times(loc) pressures = [get_pressure(t[0]) for t in times] times = [map(int, t[1]) for t in times] return sort_times(pressures, times)
def find_file_pairs(directory): filtered_patterns = ['cluster_marker_genes.h5ad', 'secondary_analysis.h5ad'] unfiltered_patterns = ['out.h5ad', 'expr.h5ad'] filtered_file = find_files(directory, filtered_patterns) unfiltered_file = find_files(directory, unfiltered_patterns) return filtered_file, unf...
The main task of the code is to process multiple directories by annotating paired files, mapping gene IDs, precomputing dataset percentages in parallel, and concatenating all annotated data into a unified `anndata` object. Metadata and percentage results are stored in the output file `concatenated_annotated_data.h5ad` ...
def main(token: str, directories: List[Path]): token = None if token == "None" else token # Load files file_pairs = [find_file_pairs(directory) for directory in directories] filtered_files = [fp[0] for fp in file_pairs] annotation_metadata = get_annotation_metadata(filtered_files) #This can be ...
def ProcessConns(conns, devices): devs = [{"id": d.id, "type": d.type, "theta": d.theta, "phi": d.phi, "n": d.n, "input_type": d.input_type, "x": d.x, "y": d.y, "inputs": [], "outputs": [], "step": -1, "modes": [], "project_key": d.project_key} for d in devices] for c in conns: con = json.l...
The function retrieves devices and connections from a database for a given project, processes them to validate circuit completeness, and generates operational modes. If validation fails (e.g., missing inputs/outputs or recursion), it returns error messages. On success, it returns processed devices, modes, and an empty ...
def getDevsModes(proj): try: devices = db.GqlQuery("SELECT * FROM LODevice WHERE ANCESTOR is :1", proj).fetch(1000) conns = db.GqlQuery("SELECT * FROM LOConnection WHERE ANCESTOR is :1", proj).fetch(1000) devs = ProcessConns(conns, devices) if not devs: return None, None...
def getCircuitFidelityData(project_key, bs_error): try: # check proj = data.Project.get(project_key) if not proj: return None, "No project" # get matrices devs, modes, error = data.getDevsModes(proj) matrix, inv, error = ConstructCircuitMatrixWithError(de...
The function `get_cgate_run` computes and returns a formatted string describing quantum gate operations (X, Y, Z bases) for a given circuit, using fidelity data and state vectors. It calculates transformations of basis states, constructs a LaTeX-like representation of state transitions, and stores the result in the cir...
def get_cgate_run(project_key, base): base = base.lower() circ = data.GetCircuit(project_key) if circ: if base == "x" and circ.cgate_run_x: return circ.cgate_run_x, None if base == "y" and circ.cgate_run_y: return circ.cgate_run_y, None if base == "z" and circ...
def getCircuitFidelityData(project_key, bs_error): try: # check proj = data.Project.get(project_key) if not proj: return None, "No project" # get matrices devs, modes, error = data.getDevsModes(proj) matrix, inv, error = ConstructCircuitMatrixWithError(de...
The code computes quantum gate fidelities for a circuit, determining the optimal gate type (CZ, CY, CX) and calculating probabilities for different error rates (0%, 1%, 5%). It processes density matrices, traces, and fidelity values, returning structured JSON data with probabilities, gate types, and fidelity metrics. E...
def get_fidelity(project_key, errors): # check if we already did the calculation #circ = data.GetCircuit(project_key) #if circ: # if circ.fidelities: # return circ.fidelities fd, error = getCircuitFidelityData(project_key, 0.0) if error: return json.dumps({'error': True, '...
def checkIfInBounds(self, y, x): height, width = self.getEnviromentDimensions() if y >= height: return False if x >= width: return False if y < 0: return False if x < 0: return False return True def isNotWall(self, y, x, d...
This function determines if a coordinate (y,x) represents a door in a grid-based environment. It checks if the position is within bounds, not a wall, and matches door-specific map values (like 124, 45, or 43). It also validates neighboring cells for consistency with door placement rules, ensuring adjacent tiles meet cr...
def isDoor(self, y, x): if self.checkIfInBounds(y,x) and self.isNotWall(y,x): if (y,x) in self.doors: return True if(self.map[y][x] == 124 or self.map[y][x] == 45): if(self.colors[y][x] != 7): #Checks if not a door return True ...
def fetch_search_snippets( self, word: str, limit: int = -1, clean: bool = False ) -> List[str]: """ Task 4. implementation, relies on the previous fetch search result from custom search api implementation """ # NOTE: from google api ducumentation # due to th...
The function computes pairwise word similarities using search snippets and semantic metrics. It tokenizes and stems snippets for each word pair, calculates intersection-based similarity, and computes Wu-Palmer, LCH, and Path similarities. Results are aggregated into a DataFrame for return.
def sim_snippet1(self, *args) -> pd.DataFrame: """ In python styleguide only class names are in CamelCase, funcs are _always_ in lowecase :) However, this is task 5 implementation """ self._load_wordnet if len(args) > 0: wordlist = args else: ...
def get_state(self): robot_pos = self.state_dict["robot"].copy() object_pos = self.state_dict["object"].copy() corner_pos = self.state_dict["corner"].copy() if np.any(robot_pos[:2] > corner_pos[:2]) or np.any(robot_pos[:2] < 0): print("\nOUT OF BOUNDS\n") self.ou...
The code's main task is to conditionally train the agent using a replay buffer when pretraining and loading are disabled and the buffer reaches a specified size. It then retrieves the current state, determines the action to take, checks if the rollout is complete, increments the total step count, and returns the state ...
def step(self): if not self.pretrain and not self.load_agent and self.replay_buffer.size == self.random_steps: train_from_buffer( self.agent, self.replay_buffer, validation_buffer=self.validation_buffer, save_agent=self.save_agent, train_epochs=self.train_epochs, ...
def warmup_test(self): norms = [] heading_diffs = [] n_steps = 2000 for i in trange(n_steps, desc="Warmup Test"): state = self.get_state() # alternate between forward and backward steps action = np.array([1, 1]) * 0.7 * (-1 if i % 2 == 0 else 1) ...
This code runs a robot navigation system, performing warmup steps, state-action logging, training data collection, and online model updates. It checks proximity to a start goal, manages robot states, handles out-of-bounds scenarios, and terminates when all robots reach their goals. The loop processes sensor data, execu...
def run(self): if self.do_warmup_test: self.warmup_test() self.take_warmup_steps() while not rospy.is_shutdown(): t = rospy.get_time() if not self.started and self.dist_to_start() < self.tolerance \ and (self.pretrain or self.replay_...
def imprimir_menu(): print("1) Normalizar datos") print("2) Mostrar dato y nombre de heroe") print("3) Mostrar maximo o minimo de algun dato") print("4) Mostrar promedio de algun dato") print("5) Mostrar todos los heroes del mismo dato") def limpiar_consola(): os.system("cls") def obtener_dato_y...
This code creates an interactive menu-driven application to manage and analyze Marvel character data, allowing users to normalize data, retrieve specific hero attributes, calculate max/min values by gender, compute averages, and display counts/list of heroes based on attributes like eye color or intelligence.
def stark_marvel_app(): flag = True flag2 = False while flag or pregunta == "s": imprimir_menu() print("------------------------------------------------------------------") eleccion = input("Elija una opcion: ") while True: try: eleccion = int(e...
def get_metadata(self) -> Metadata: if not self.metadata: print("Fetching game metadata...") payload = {"payload": {}} response = self._comlink_post(path="metadata", data=payload) self.metadata = Metadata(response) return self.metadata def _comlink_post(se...
This method retrieves game data by making a POST request to a specified endpoint if the data hasn't been fetched yet. It constructs a payload with version information and a flag to exclude PVE units, then stores the received data in an instance variable. The method ensures data is only fetched once and returns the resu...
def get_data(self) -> Data: if not self.data: print("Fetching game data...") data_payload = { "payload": { "version": self.get_metadata().data_version, "includePveUnits": False, } } response =...
def get_metadata(self) -> Metadata: if not self.metadata: print("Fetching game metadata...") payload = {"payload": {}} response = self._comlink_post(path="metadata", data=payload) self.metadata = Metadata(response) return self.metadata def get_localization...
The main task of the code is to initialize the Comlink system by retrieving metadata, localization data, and core data, followed by printing a confirmation message ("Comlink ready!") to indicate successful setup and readiness for operation.
def _warm(self): self.get_metadata() self.get_localization() self.get_data() print("Comlink ready!")
def parse_args(): parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--tx', type=str, help='Gene-BC-UMI whitelist from 10x data') parser.add_argument('--allInfo', type=str, help='AllInfo file containing Read-Gene mapping information') parser.add_argument('--f...
The main task of the code is to parse command-line arguments, initialize data structures, read and process sequencing data files, map reads to genes, and execute barcode analysis using the chunkAndProcess function to analyze forward and reverse barcode positions against a transcriptome and gene list.
def main(): """ Parse args, create an empty dictionary. Read in the files and start analysis""" args = parse_args() global colNames, bcPosFwd, bcPosRev, legalGenes d = {'ReadName':[], 'Gene':[], 'numFwd' : [],'tx_fwd':[], 'ont_fwd':[], 'numRev' : [],'tx_rev':[],'ont_rev':[]} colNames = list(d.keys()) bcPosFwd = ...
def Sbox(block): a = (block[0] & block[1]) ^ block[2] c = (block[1] | block[2]) ^ block[3] d = (a & block[3]) ^ block[0] b = (c & block[0]) ^ block[1] block = [a,b,c,d] return block def BitSlice(block): bs = 8*[0] for i in range(4): for x in range(8): bs[7-x] |= ((...
The main task of the code is to implement a block cipher encryption algorithm called Mysterion128. It processes the input message `m` using a key `key` through multiple rounds (`NR`), applying transformations like S-box substitution, L-box linear transformation, ShiftColumns permutation, and round-specific constants. T...
def Mysterion128(key, m, NR): # adding key initially state = np.array( [x ^ y for x, y in zip(key, m)] ) for round in range(1, NR + 1): # spliting message in blocks blocks = [state[i*4:(i+1)*4] for i in range(4)] # S-box blocks = np.array([Sbox(block) for block in state]) # L-box s = [...
def roundconst(i): # TODO Use constants block = [0] * 16 for idx in range(4): lfsr_in = [0, 0, 0, 0, 0, 0, 0, 0] lfsr_in[idx*2 + 1] = i tmp = lbox(lfsr_in) block[4 * idx] = (tmp[0] << 4) | tmp[1] # output.append(block) output = np.array(block) output = output...
This function decrypts a 128-bit block cipher by applying inverse operations across multiple rounds. It reverses shift columns, applies inverse L-box and S-box transformations, and XORs the key with the state. The process iterates backward from NR rounds, ultimately producing the plaintext by XORing the key and final s...
def InvMysterion128(state, key, NR): for round in range(NR, 0, -1): constant = roundconst(round) state = np.array( [x ^ k ^ c for x, k, c in zip(state, key, constant)] ) blocks = ShiftColumns_128_inv(state) # L-box inverse s = [BitSlice(block) for block in blocks] l = [lbox_rev(i) for i in s...
def enable_timeout(self): """Enable timeout """ self.write_reg(self.REG_I2CTO, 0x67) def i2c_write(self, data_bytes:bytes, i2c_addr=None) -> None: """I2C: Transmits in master mode an amount of data Args: data_bytes (bytes): Data i2c_addr (optional): Targe...
This function scans the I2C bus for connected devices by iterating through possible 7-bit addresses (0x01 to 0x7E). For each address, it sends a write command and checks the I2C status register. If the status indicates a successful communication (I2CStat_I2C_OK), the address is recorded. The function returns a list of ...
def i2c_device_search(self) -> list[int]: """Search and get I2C device address list Returns: list[int]: Found I2C address list """ self.enable_timeout() dev_addr_list = [] print('*I2C Device Search Start*') for addr in range(0x01, 0x7E, 1): ...
def test_attribute(): #self explanatory - allows bot to be started in live trading mode if satisfied with set up. parser = argparse.ArgumentParser() parser.add_argument('--live', help='Runs bot in live trading mode', action='store_true') args = parser.parse_args() if args.live is True: retur...
The code initializes a trading system by setting up test mode, fetching historical data, updating balance/position, calculating RSI, and triggering the valley_spring algorithm. It logs startup progress and configures global variables for asset balance, position status, trade amount, and test mode. The main task is to p...
def start_up(): print('\n##########################################################\n\nStarting up...') logging.info('\n##########################################################\n\nStarting up...') global asset_balance global in_position global trade_amount global test_mode #check test mode...
def has_active_device(self): current_playback = self.sp.current_playback() if current_playback is None: self._log("No active device") return False else: # for device in self.sp.devices()['devices']: # if device['is_active']: # ...
This method toggles playback between play and pause based on the current device state. It checks if a device is active, then verifies if music is playing. If playing, it pauses; otherwise, it starts playback. Exceptions are logged as errors, and the operation proceeds without interruption.
def play_pause(self) -> None: if self.has_active_device(): try: if self.sp.current_playback()['is_playing']: self._log("Pause") self.pause(False) else: self.play(False) except Exception as e: ...
def honeycomb(row, col, dist=HELIXDIST): """Cadnano honeycomb lattice into cartesian""" # k = distance between helixes ANGLE = 30.0 x = col * dist * math.cos(math.radians(ANGLE)) if (row % 2) != 0: y = (row * 3 + 1 - col % 2) * dist * math.sin(math.radians(ANGLE)) else: y = (row ...
The function generates and outputs particle coordinates with modifications, handling insertions/deletions, and updating data structures. It calculates positions using honeycomb/square grids, processes chain-specific parameters, and writes results to an output file via `addtoout`, considering various particle types and ...
def createatom(z, chain, tname, length, end, modif): """Print particles in the interval -- calculate coords etc""" global a_sc, dif [row, col] = [Rows[chain], Cols[chain]] if not SQ: [ox, oy] = list(honeycomb(row, col)) else: [ox, oy] = list(square(row, col)) if a_sc == 1: ...
def _most_common_label(self, y): # Finds and returns the most common label in the given array of target labels. counter = Counter(y) value = counter.most_common(1)[0][0] return value def _best_split(self, X, y, feat_idxs): # Initialize variables to keep track of the best split so...
This function recursively builds a decision tree by selecting the optimal feature and threshold to split data, creating left and right subtrees until stopping conditions are met (max depth, insufficient samples, or pure node). It returns a tree node representing the split or a leaf node with the most common label.
def _grow_tree(self, X, y, depth=0): n_samples, n_feats = X.shape n_labels = len(np.unique(y)) # Stop recursion if any of these conditions are met: # 1. The maximum depth of the tree has been reached # 2. The number of samples at this node is less than the minimum required for ...
def display_welcome(self): print("welcome to Robots vs Dinosaurs!!") print('Each Dinosaur and Robot will start with 100 health') print('Dinosaurs belong to a heard while Robots belong to a fleet') print('The game will be over once you have defeted the Dinosaurs or the Dinosaurs have defe...
The main task of the code is to execute a game loop by sequentially displaying a welcome message, initiating a battle, and showing the winners. The `run_game` method orchestrates these steps: first welcoming the player, then processing the battle logic, and finally displaying the results. This structure ensures a clear...
def run_game(self): self.display_welcome() self.battle() self.display_winners()
def load_data(i, path): data = pd.read_csv(path) #ind = eval(data['ind'][i]) ind = get_ind(vals=data.filter(like = 'multiplier').to_numpy().tolist()[i]) return(ind) def change_ind_data(ind, cond_combo): vals = list(ind.values()) labs = list(ind.keys()) for i in list(range(0, len(vals))...
The function `collect_pop_data` processes input data by loading, modifying, and combining multiple datasets based on conditional parameters. It generates experimental data using `define_pop_experiment`, prefixes keys with condition-specific tags, and merges all results into a unified dictionary for downstream analysis.
def collect_pop_data(args): i, cond_combo_co_pos, cond_combo_co_neg, cond_combo_ind, cond, purturb, p, p_models = args #ind = load_data(i, p_models+'pop_models.csv') ind = load_data(i, p_models) coex_pos = change_ind_data(ind, cond_combo_co_pos) coex_neg = change_ind_data(ind, cond_combo_co_neg) ...
def is_polish(self) -> bool: self.wait_for_element(locator=(By.XPATH, SlowhopScrapper.LANGUAGE_XPATH)) language = self.driver.find_element( By.XPATH, SlowhopScrapper.LANGUAGE_XPATH ).get_attribute("content") return language == "pl-PL" def set_polish(self) -> None: lan...
This code performs web scraping to retrieve a list of places based on an input query. It navigates to a base URL, ensures the Polish language setting, prepares URL parameters from the query, executes scraping, closes the browser, and returns the collected results as a list of Place objects.
def run(self, query: Query) -> List[Place]: self.driver.get(self.BASE_URL) if not self.is_polish(): self.set_polish() self.make_url_parameters(query) self.scrap() self.driver.close() return self.results
def get_valid_username(): """ prompts the user for a username and keeps asking until a valid username is entered. Args: None Returns: username: user input for username choice """ console = Console() while True: username = input("Enter Username (at least 3 characters): ") ...
(The main task of the code is to collect a valid username and password through validation functions, then save them using the `save_credentials` function. It ensures inputs are validated before persisting credentials.)
def signup(): """ calls relevant validation functions before calling save_credentials with valid username & password Args: None Returns: None """ username = get_valid_username() password = get_valid_password() save_credentials(username, password)
def get_reward_memory(self): return self.emu.memory.read(self.reward_function_addr,self.reward_function_addr,2,signed=True) def simulate_branches(self): # the possible branches of the Trainer AI branches = [(30, 32), (25, 32), (20, 32), (15, 32), (10, 32), (5, 32), (0, 0), (5...
The code trains an agent by simulating decision branches in a game environment. It selects paths based on a probability distribution, prioritizing optimal choices while occasionally diversifying training data by choosing suboptimal branches. Progress is tracked, and training data is generated when optimal paths improve...
def train(self): self.emu.input.keypad_update(1) self.emu.savestate.save(BASE_SAVESTATE) delta_progress = [] for t in range(1000): # simulate all the branches at this timestep and get the resulting scores pre_progress_score = self.get_reward_memory() b...
def build_laplacian_pyramid(im, max_levels, filter_size): """ Builds a laplacian pyramid for a given image :param im: a grayscale image with double values in [0, 1] :param max_levels: the maximal number of levels in the resulting pyramid. :param filter_size: the size of the Gaussian filter ...
The function `pyramid_blending` blends two grayscale images (`im1`, `im2`) using a boolean mask (`mask`) through multi-scale pyramid decomposition. It constructs Laplacian pyramids for both images and a Gaussian pyramid for the mask. The blended pyramid combines weighted Laplacian levels from `im1` and `im2` using the ...
def pyramid_blending(im1, im2, mask, max_levels, filter_size_im, filter_size_mask): """ Pyramid blending implementation :param im1: input grayscale image :param im2: input grayscale image :param mask: a boolean mask :param max_levels: max_levels for the pyramids :param ...
def molecule_universe_grid(moleculer=new_molecule, num_molecules: Union[int, Tuple[int, int]] = 5): try: num_rows, num_cols = num_molecules except TypeError: num_rows = num_cols = num_molecules proteins = [] prev_row = None for _ in range(num_rows): protein = moleculer() ...
The code generates an animation visualizing protein molecules, transforms them into HIV antibodies, and illustrates a Machine Learning Model (MLM) process. It creates a grid of proteins, applies transformations, and animates the transition from proteins to antibodies with frames and labels, demonstrating molecular stru...
def construct(self): rng = np.random.RandomState(self.seed) moleculizer = partial(new_molecule, colors=lambda: rng.choice(MOLECULE_COLORS, size=3, replace=True)) proteins = molecule_universe_grid(moleculizer, num_molecules=(5, 8)).scale(0.3).center() proteins_frame = SurroundingRectan...
def atom_environment(self, atom_index: int, radius: int): # https://www.rdkit.org/docs/GettingStartedInPython.html#explaining-bits-from-morgan-fingerprints atom_environment = AllChem.FindAtomEnvironmentOfRadiusN(self.molecule, radius, atom_index, False) atom_map = {} # atom_index_molecule -> at...
This code initializes a molecular visualization object by setting up atoms (nodes) and bonds (edges) using specified representations. It configures submolecule data based on a central atom and radius, adds visual elements for each atom and bond, and stores molecular structure information for rendering or analysis.
def __init__(self, molecule: AllChem.Mol, conformer: int = 0, node_repr=Circle, edge_repr=Line, sub_center: int = None, sub_radius: int = 2, **kwargs): super().__init__(**kwargs) self...
def _get_named_style(self, named_style: str, latex_font_package: str, latex_font_options: str, additional_latex_packages: str or [str], additional_rcparams: dict, presentation_style: bool): if named_style not in _named_style_options: ...
This function configures Matplotlib's runtime settings to match a predefined journal style (e.g., AAS, AGU). It applies LaTeX font packages, additional packages, and custom rcParams, while updating figure dimensions and color schemes specific to the chosen style. Optional parameters allow overriding defaults, specifyin...
def set_named_style(self, named_style: str, latex_font_package: str = None, latex_font_options: str = None, additional_latex_packages: str = None, additional_rcparams: dict = None, print_info: bool = ...
def create_image(width, height): return Image.new("RGB", (width, height), Styles.BGCOLOR) def render_lines(cell_coordinates, canvas): for i in range(len(cell_coordinates)): for j in range(len(cell_coordinates[i])): #render horizontal lines if j+1 < len(cell_coordinate...
The main task of the code is to generate a graphics image by creating a canvas, drawing lines and dots based on cell coordinates, rotating the image by a specified angle, saving it to a given output path, and displaying it in a Jupyter Notebook with hidden axes. The function combines image creation, transformation, and...
def render_graphics(self, rotation, output_path): image = create_image(self.image_dimentions, self.image_dimentions) canvas = ImageDraw.Draw(image) render_lines(self.cell_coordinates, canvas) render_dots(self.cell_coordinates, canvas) image = image.rotate(rotation, Image.NEARE...
def filter_nones(self, array): num_of_rows = len(array[0]) clean_array = [] for i in range(num_of_rows): row = [] for j in range(num_of_rows): if array[i][j] is not None: row.append(array[i][j]) clean_array.append(row) ...
This code initializes a board representation by calculating dimensions, filtering cells, determining coordinates for each cell, and rendering graphical lines between neighboring cells based on rotation and output path.
def __init__(self, board, rotation, output_path): self.board = board self.board_dimentions = (len(board) - 1) * Styles.CELLMARGIN self.image_dimentions = self.board_dimentions + 2 * Styles.PADDING self.image_centre = self.image_dimentions / 2 self.board = self.filter_nones(boar...
def getNode(self, nodeName): for node in self.nodes: if node.name == nodeName: return node return None def calculateDistance(self, srcNodeName, trgNodeName): return self.getNodeLoc(srcNodeName).euclideanDist(self.getNodeLoc(trgNodeName)) def calculateTotalCost(self, s...
The code implements the A* algorithm to find the shortest path from a source node to a goal node in a graph. It uses a priority queue to explore nodes, prioritizing paths with the lowest combined cost (actual distance + heuristic estimate to the goal). The algorithm tracks visited nodes and updates the path iteratively...
def AStar(self, srcNodeName, goalNodeName): ## Guard if self.getNode(srcNodeName) == None or self.getNode(goalNodeName) == None: return None, None, False ## PriorityQueue elements as tuple index TOTALCOST_INDEX = 0 CURRENTNODENAME_INDEX = 1 VISITEDNODE_INDEX =...
def rand_init_weights(size_in, size_out): epsilon_init = 0.12 return np.float128( np.random.rand(size_out, 1 + size_in).astype(dtype=np.float128) * 2 * epsilon_init - epsilon_init) def read_npy_chunk(filename, start_row, num_rows, datatype): assert start_row >= 0 and num_rows > 0 with open(filena...
The code implements distributed gradient descent for a neural network, initializing weights, distributing training data via MPI, computing local gradients, aggregating global gradients, updating weights, and synchronizing across processes. It handles both distributed and non-distributed cases, saving model parameters p...
def gradient_descent( learningrate=0.8, iteration=50): ''' @return cost and trained model (weights). ''' if Distributed is True: if comm.rank == 0: theta1 = rand_init_weights(Input_layer_size, Hidden_layer_size) theta2 = rand_init_weights(Hidden_layer_size, Output_layer_s...
def model_hidden_state(mt, prompt): inp = make_inputs(mt.tokenizer, prompt) outputs_exp = mt.model(**inp, output_hidden_states=True, output_attentions=True) return outputs_exp def get_all_results(mt, prompt, kind, subject=None, noise=0.1, modelname=None, directory = None): # for kind in [None, "mlp", "a...
The main task of the code is to analyze a language model's hidden states and attention/MLP layers for a given prompt, visualize layer-wise activations, and save results. It loads a transformer model, traces token predictions, computes baseline hidden states, generates layer-specific plots for input tokens, and stores a...
def main(model_name, prompt, subject, kind, noise, model_layer_size): # model_name = "gpt2-xl" # or "EleutherAI/gpt-j-6B" or "EleutherAI/gpt-neox-20b" or "gpt2-xl" or "EleutherAI/gpt-neo-1.3B" mt = ModelAndTokenizer( model_name, torch_dtype=(torch.float16 if "20b" in model_name else None), ...
def calculate_all_portfolio_pnl() -> DictFrame: """ Calculate the profit and loss (PnL) for all portfolios. Returns: A dictionary containing the calculated PnL for each portfolio. """ logging.info("Calculating portfolio PnLs") result_dict = {} file = config.get("Input", "file") ...
The code generates a summary report for a specified timeframe by calculating portfolio Profit & Loss (P&L), retrieving Assets Under Management (AUM), logging key metrics, and producing performance visualizations. It logs the timeframe, computes P&L using `calculate_all_portfolio_pnl()`, derives AUM with `get_aum()`, lo...
def summary() -> None: """Run a summary report, printing the outputs. Run a report for a specific timeframe, calculates portfolio P&L, retrieves AUM (Assets Under Management), generates a summary, and plots performance charts. """ logging.info( f"Running report for {args.timeframe} ({start_...
def open_website(driver, url:str, wait_time:int=5) -> None: driver.get(url) time.sleep(wait_time) def parse_page(driver) -> np.ndarray: online_table = np.zeros((6,7)) html = driver.page_source soup = BeautifulSoup(html, "html.parser") table_rows = soup.find_all("tr", attrs={"class": "ng-star-ins...
This code automates a Connect 4 game by controlling an AI player via a web browser. It parses the game board, uses minimax with alpha-beta pruning to determine optimal moves, and interacts with the game website to play against a human. The AI (Player 2) checks for win/loss conditions, adjusts search depth, and makes au...
def start_game(): room = input("Enter the 4 digit game room: ") url = f"http://connect-4.org/?lb{room}" AI_PIECE = 2 options = Options() options.add_argument("start-maximized") if not os.path.exists(f"{os.getcwd()}/chromedriver"): # Check if chromedriver exists in current directory pr...
def halt_and_destroy(): """ Halt and destoy virtual machine """ with lcd(os.path.dirname(__file__)): if os.path.exists('Vagrantfile'): local('vagrant halt') if version() >= (0, 9, 99): local('vagrant destroy -f') else: local('va...
The code runs a test suite on multiple virtual machines (VMs). It iterates through base boxes, starting each VM, configuring sudo permissions, updating package indexes, executing tests via `unittest.BaseTestSuite.run()`, then stopping and cleaning up each VM. The process ensures isolated testing environments by resetti...
def run(self, result): """ Run the test suite on all the virtual machines """ # Clean up halt_and_destroy() for base_box in self.base_boxes: # Start a virtual machine using this base box self.current_box = base_box self.start_box() ...
def menu(): global ch ch = False print("1. Buat Akun Baru") print("2. Login ") print("3. Exit ") print() while ch == False: try: ch = int(input("Pilih sesuai dengan nomornya: ")) except: print("Tolong hanya masukkan angka.") def start(): #called ...
The main task of the code is to display a menu, initiate a process via 'start()', and repeatedly prompt the user to order more items (via 'pesan_lagi()') unless the user selects option '3' to exit. It manages a loop based on user input to control order repetition.
def main(): menu() start() if ch !=3: pesan_lagi()
def namepick (y): z = [x for x in y.players if x.games > 15] p = [] if len(z) < 20: return '' z.sort(key = lambda x: x.runs, reverse = True) p = p + z[:5] z.sort z.sort(key = lambda x: x.wickets, reverse = True) p = p + z[:5] z.sort(key = lambda x: x.games, reverse = True) p = p + z[:5] return ran...
The main task of the code is to generate unique trophy names between two randomly selected entities (a and b) from list t, ensuring no duplicate trophies exist in the global 'trophies' list. It checks validity conditions (e.g., non-empty tests, player eligibility), constructs trophy names using name fragments, and appe...
def trophymaker (x, t): global trophies if random.random() > 0.5: return trophies else: a = random.choice(t) b = random.choice(t) if a == b or a.tests == [] or b.tests == []: return trophies else: for i in trophies: if (i[1] == a.name and i[2] == b.name) or (i[1] == b.name and i[2] == a.name): return...
def era (): eradata = [] with open ('eradata.txt') as f: for line in f: line = line[:-1] #pass #print (line) x = line.split(', ') x[0] = int(x[0]) x[1] = float(x[1]) #pass #print (Year, x[0]) eradata.append(x) return eradata def setup (x): nation = x.replace(" ",'') coun...
This code initializes a cricket simulation by setting up global variables, clearing a folder, defining countries, and configuring teams based on user-selected modes (historical, random, etc.). It processes player data, prepares match structures, and returns teams, test data, player lists, and trophies for further simul...
def startup(): global current, eradata, PaceFactor, SpinFactor, inns, bowls, folder, pause, dualtours current = 1877 PaceFactor,SpinFactor = 1, 1 folder = 'altcricket' if not os.path.exists(folder): os.makedirs(folder) fileList = os.listdir(folder) for fileName in fileList: os.remove("{}/{}".format(folder,fileN...
def returning (a, p): if p in a.xi or p.end < current or p.games < 10: return a a.xi.sort(key = lambda x: tagvalue (x), reverse = False) for i in a.xi: if (tagvalue(i)*1.1 < value(p, quickorder(i.tag))) or (p == a.captain and tagvalue(i) < value (p, quickorder(i.tag))): a.xi.remove(i) a.xi.append(p) #prin...
This function simulates sports team injury management by randomly removing players from the injured list, applying injury conditions based on age, attributes, and random chance, updating player statuses, and handling squad replacements during games. It adjusts team composition by adding/removing injured players, markin...
def injury (a, game = True): h = [] for i in a.inj: if random.random() < 2/3: h.append(i) for i in h: a.inj.remove(i) if i.status == 'inj': i.status = '' if i not in a.unav: a = returning (a, i) for i in a.squad: if i not in a.inj: if random.random() < 0.02: a.inj.append(i) continue if ra...
def skip (s): if s.games[0][2] == 'England' and s.games[0][1] != 'Australia' and s.games[0][0] < 1945: x = 1/10 elif s.games[0][0] < 1918: x = 2/3 elif s.games[0][0] < 1945: x = 3/4 elif s.games[0][0] < 1970: x = 4/5 elif s.games[0][0] < 2000: x = 9/10 else: x = 19/20 return x def quicksort (x): x.sort(key = la...
This function generates a cricket team squad for a given match/series, selecting players based on historical context (e.g., 1930 England vs. South Africa), player availability, performance stats (batting/bowling), and random selection. It filters out ineligible players, manages captain selection, and outputs the final ...
def squad (x, s): global dualtours, current c = [] if s.games[0][0] < 1915: n = random.randrange(13,16) else: n = random.randrange(15,18) t = skip(s) if len(x.active) > n: for i in x.active: if s.year == 1930 and i in dualtours and s.away.name == 'England' and s.home.name != 'South Africa': continue if r...
def generate_mosaic(self): if len(self.frames): prev_img = create_mosaic( self.frames, self.sb_images_per_line.value(), self.sb_max_images.value(), self.sb_increment.value(), ...
The code handles tab changes in a GUI application. If the active tab is index 1, it triggers mosaic generation; otherwise, it updates a preview image using the current frame and label info, provided frames exist.
def tab_changed(self): if self.tabWidget.currentIndex() == 1: self.generate_mosaic() else: if len(self.frames): self.l_preview_image.setPixmap(update_preview(self.frames[self.sl_frame.value()], self.label_info()))
def tab_changed(self): if self.tabWidget.currentIndex() == 1: self.generate_mosaic() else: if len(self.frames): self.l_preview_image.setPixmap(update_preview(self.frames[self.sl_frame.value()], self.label_info())) def click_btn_image_path(self): path, ext ...
This code initializes a GUI application for a flipbook tool by setting up the user interface, configuring macOS-specific focus rectangle settings, initializing variables for image processing, and connecting UI elements to event handlers for functionality like image path selection, frame generation, and rendering.
def __init__(self): super(Flipbook, self).__init__() self.setupUi(self) self.l_logo.setPixmap(QPixmap(":logo/logo2.png")) """-----------------For mac-------------------""" if os.name == 'posix': self.fld_image_path.setAttribute(Qt.WA_MacShowFocusRect, 0) s...
def read_data(): words = [] with open('./data.txt', 'r', encoding='utf-8') as f: for line in f: words.append(line) new_words = [line[:-1] for line in words] return new_words def read_introduction(): introduction = open('ahorcado3.txt', 'r') mensaje = introduction.read() ...
The code reads and processes a dataset, selects a random word, hides it with underscores, inserts 'hola' at position 1, displays the word in uppercase, and outputs random characters. Its main task is to initialize a word-guessing game by preparing hidden word representation and auxiliary data, though the 'hola' inserti...
def run(): data_set = read_data() print(read_introduction()) data_set = normalize(data_set) tuplas_list_data_Set = list(enumerate(data_set)) tupla_word_to_guess = select_word(tuplas_list_data_Set) word_to_guess = tupla_word_to_guess[1] len_word_to_guess = len(word_to_guess) list_len_wo...
def PeriodOptimisation(given_data, region = "VIC"): ''' A function to optimise battery charging and discharging period. This is where mainly the optimisations are performed with the helper functions. Parameters ---------- - given_data : pandas dataframe targeted dataset Retu...
The function `fullMaximisation` optimizes energy dispatch over a specified time period for a given region (default: VIC) by iteratively applying a period-based optimization algorithm. It processes the input dataframe in chunks, computes raw power, market dispatch, and capacity values for each period, updates the datafr...
def fullMaximisation(dataframe, period, region = "VIC"): ''' The second version of main model to run the optimisation algorithm. This algorithm generates over a period given that there is no dependency, maximising both region initially with zero capacity and the region with non zero capacity. P...
def removeNullChunks(): global CHUNKS_INVENTORY_DICT log_generic("removeNullChunks() has been invoked. Current status of the dictionary: " + str(CHUNKS_INVENTORY_DICT)) CHUNK_LOCK.acquire() if "null" in CHUNKS_INVENTORY_DICT['chunks']: log_generic("found 'null' chunk in dict, deleting") ...
The function `resetWIPchunks` resets all "WIP" (Work In Progress) chunks in the global `CHUNKS_INVENTORY_DICT` to "TODO" status. It first removes null chunks via `removeNullChunks()`, iterates through the inventory, updates "WIP" entries to "TODO" using `setChunkState()`, and logs a confirmation message. The task ensur...
def resetWIPchunks(): global CHUNKS_INVENTORY_DICT removeNullChunks() #print(CHUNKS_INVENTORY_DICT) for key in CHUNKS_INVENTORY_DICT['chunks']: if CHUNKS_INVENTORY_DICT['chunks'][key] == 'WIP': setChunkState(key, 'TODO') log_generic("WIP chunks have been reset")
def removeNullChunks(): global CHUNKS_INVENTORY_DICT log_generic("removeNullChunks() has been invoked. Current status of the dictionary: " + str(CHUNKS_INVENTORY_DICT)) CHUNK_LOCK.acquire() if "null" in CHUNKS_INVENTORY_DICT['chunks']: log_generic("found 'null' chunk in dict, deleting") ...
The main task of the code is to reset all chunks in the CHUNKS_INVENTORY_DICT by removing null chunks, marking each remaining chunk's state as 'TODO', and logging a confirmation message. This ensures all chunks are reinitialized to a pending state for processing.
def resetALLchunks(): global CHUNKS_INVENTORY_DICT removeNullChunks() for key in CHUNKS_INVENTORY_DICT['chunks']: setChunkState(key, 'TODO') log_generic("All chunks have been reset")
def getTODOChunk(): global CHUNKS_INVENTORY_DICT CHUNK_LOCK.acquire() for item in CHUNKS_INVENTORY_DICT['chunks']: #thread_debugMessage(999, item) if CHUNKS_INVENTORY_DICT['chunks'][item] == 'TODO': CHUNK_LOCK.release() return item #thread_debugMessage(999, "No...
The function `getTodoChunk` assigns an available TODO chunk to a client, ensuring exclusive access via a lock. It retrieves a chunk, marks it as 'WIP', updates client tracking, and returns the chunk file. If no chunks remain, it logs the error and returns a 404. Key tasks include concurrency control, client state manag...
def getTodoChunk(): # makes sure no two clients get the same chunk CLIENT_CHUNK_REQUEST_LOCK.acquire() todoChunk = getTODOChunk() setChunkState(todoChunk, 'WIP') CLIENT_CHUNK_REQUEST_LOCK.release() if todoChunk == None: log_clientActivity(request.headers['clientID'], request.re...
def setChunkState(chunkName, state: str): global CHUNKS_INVENTORY_DICT removeNullChunks() # specified only 1 chunk if (type(chunkName) == str): CHUNK_LOCK.acquire() CHUNKS_INVENTORY_DICT['chunks'][chunkName] = state CHUNK_LOCK.release() return # specified multple c...
The code handles file uploads by validating the request, saving the uploaded file to a specified directory, updating chunk status, managing client data, and logging activity. It ensures proper file handling, updates system state, and maintains client tracking for chunk management in a distributed system.
def submitChunk(): # Check if the POST request has a file part if 'file' not in request.files: return jsonify({'error': 'No file part'}) file = request.files['file'] # If the user does not select a file, the browser submits an empty file without a filename if file.filename == '': ...
def log_generic(message: str): line = "[{}] {}".format( csvUtils.getTimeStamp(), message ) LOG_LOCK.acquire() with open(LOG_PATH,'a') as f: f.write(line + "\n") LOG_LOCK.release() def getTotalConnectedClients(self): self.CLIENTS_LOD_LOCK.acquire() ...
This function periodically identifies and handles inactive clients by revoking their chunks, deleting their records, and saving inventory updates. It runs indefinitely, checking every specified interval, and only acts if active clients exist. Inactive clients are logged, their chunks revoked, and their data removed, en...
def inactiveClientsHandler(self): global CHUNKS_DIRECTORY log_generic("inactiveClientsThread started. Will look for inactive clients every {} seconds.".format(self.INACTIVE_CLIENT_CHECK_FREQUENCY)) while True: # if no clients are online, no need to check if self.getTot...
def _prepare_input(self, obj, copy=True, **kwargs) -> pd.Series: assert isinstance(obj, pd.Series) logging.debug(f"len: {len(obj)}") if copy: obj = obj.copy() return obj def _get_rm(self, s, **kwargs) -> pd.Index: return self._current.index.difference(s.index) def _ge...
The code updates the current data state by comparing input series against existing data, tracking removed, added, and modified elements. It checks if changes exceed a threshold relative to current data size, replacing the base if so. It constructs update instructions, validates consistency, and applies changes, handlin...
def update(self, series: pd.Series, copy=True, **kwargs): s = self._prepare_input(series, copy=copy, **kwargs) rm = self._get_rm(s, **kwargs) add = self._get_add(s, **kwargs) mod = self._get_modified(s, **kwargs) dtype = self._get_dtype(s, **kwargs) logging.debug( ...
def validLoop(): ui = userInput() while ui is None: ui = userInput() return ui def isPos(i): while i < 0: print("Only positive numbers can be accepted. Please try again.") i = validLoop() return i def factorial(i): if i <= 1: return i if factorial: return i * fact...
This program calculates the factorial of a user-input number. It validates the input, ensures it's positive, computes the factorial using a dedicated function, and displays the result in a formatted string.
def main(): print("This program computes the factorial of a value the user inputs.") vl = validLoop() posCheck = isPos(vl) print("The value of {0}! is {1}".format(posCheck,factorial(posCheck))) return
def validLoop(): inp = validCheck() while inp is None: inp = validCheck() else: return inp def isPos(i): while i < 0: print("Negative numbers cannot be accepted. Please try again.") i = validLoop() else: return i def fib(i): if i <= 1 or i is None: ...
The main task of the code is to calculate the nth Fibonacci sequence value at a user-specified position. It validates user input to ensure a positive integer is provided, then computes and prints the corresponding Fibonacci number using the `fib` function. The program includes input validation loops and positional chec...
def main(): print("This program will calculate the nth value of the Fibonacci sequence.") userInput = validLoop() posCheck = isPos(userInput) print("The value of the fib sequence at position {0} is {1}".format(posCheck,fib(posCheck))) return
def validLoop(): inp = validCheck() while inp is None: inp = validCheck() else: return inp def isPos(i): while i < 0: print("Negative numbers cannot be accepted. Please try again.") i = validLoop() else: return i def topHalf(n): count = 1 while count <...
This program generates a diamond pattern of asterisks based on user input for the number of rows up to the middle. It validates the input, constructs the top half of the diamond, and mirrors it to form the complete diamond.
def main(): print("This program prints out a diamond of asterisks. You get to input how many rows it has until it reaches its middle point.") valVar = validLoop() posVar = isPos(valVar) top = topHalf(posVar) bottomHalf(top) return
def is_valid_hp(hp: str) -> bool: assert isinstance( hp, str ), "The input type for a hp (hierarchy path) must be a string." # assert hp[0] == "/", "A hp (hierarchy path) should start with '/' at a root." return True def is_wildcard_hp(hp: str) -> bool: "Predicate for If path string has a wi...
This function retrieves values from a nested dictionary using a "hierarchy path" string (hp), supporting wildcards (*) for globbing. It handles both direct paths and wildcard paths, returning matching values or a default if not found. For wildcard paths, it recursively processes list elements to collect results.
def get_in_hp(hp: str, d: dict, default=None, no_default=False): """Toolz's `get_in` function takes a tuple and a dict, and returns the value at that place in the dict. get_in_hp does basically the same thing, but rather than a tuple takes a "hierarchy path" (hp) string. The enhancement here is a ...
def is_valid_hp(hp: str) -> bool: assert isinstance( hp, str ), "The input type for a hp (hierarchy path) must be a string." # assert hp[0] == "/", "A hp (hierarchy path) should start with '/' at a root." return True def hp_to_list(hp: str) -> list: """Converts a hp (hieriarchy path) to a li...
The function `assoc_in_hp` updates a nested dictionary structure by associating a value with a specified hierarchy path. It validates the path, converts it to a list, and delegates to `assoc_in_coll` to insert/update the value in the dictionary, using a factory function to create nested structures if needed.
def assoc_in_hp(d: dict, hp: str, value, factory=dict) -> dict: "Wrapper around assoc_in_coll() to use a hierarchy path." is_valid_hp(hp) coll = hp_to_list(hp) return assoc_in_coll(d, coll, value, factory)
def is_valid_hp(hp: str) -> bool: assert isinstance( hp, str ), "The input type for a hp (hierarchy path) must be a string." # assert hp[0] == "/", "A hp (hierarchy path) should start with '/' at a root." return True def is_wildcard_hp(hp: str) -> bool: "Predicate for If path string has a wi...
This function expands a hierarchical path (hp) with wildcards into all possible specific paths by recursively resolving wildcard segments against a nested dictionary structure, returning a list of fully qualified paths.
def explode_path(hp: str, d: dict, parent=None): is_valid_hp(hp) if not is_wildcard_hp(hp): # if it's not a wildcard hp, actually we can just return 'it' (there is only one.) return [hp] else: parent_path, rest_path = hp.split("/*/", 1) child_data = get_in_hp(parent_path, d) ...
def orthogonalize_vectors(vectors): """ tool function, adjust vectors so that they are orthogonal to each other, takes O(num_vector^2) time :param vectors: vectors, shape = (num_dimension, num_vector) :return: orthorgonal vectors, shape = (num_dimension, num_vector) """ vectors_orthogonal = vect...
This function disentangles correlated features in a given feature axis by making specified target features orthogonal to base features. It uses orthogonalization for base features and disentangles target features relative to them. If no base features are provided, it returns the original features. Results can be normal...
def disentangle_feature_axis_by_idx(feature_axis, idx_base=None, idx_target=None, yn_normalize=True): """ disentangle correlated feature axis, make the features with index idx_target orthogonal to those with index idx_target, wrapper of function disentangle_feature_axis() :param feature_axis: all ...
def next(self) -> str: return self.line[self.i] if self.i < len(self.line) else "" def take(self) -> str: char = self.next() self.i += 1 if self.i < len(self.line) else 0 return char def make_operator(self) -> Token: string = self.take() if self.next() == "/": ...
This function generates a token by identifying the next character in the input stream. It skips whitespace, recognizes parentheses as punctuators, handles arithmetic operators, parses numbers (including decimals), and raises an error for unrecognized symbols.
def make_token(self) -> Token: while self.next().isspace(): self.take() if self.next() in "()": return Token(self.take(), "Punctuator") if self.next() in "+-*/%": return self.make_operator() if self.next().isdigit() or self.next() == ".": ...
def dprint (self, s): self.terminal.dprint(s) def fetch (self): self.dprint("Fetch addr " + str(self.reg_pc)) self.reg_inst = self.memory_load(self.reg_pc) if self.interrupt == 0: self.reg_pc = self.reg_pc + 1 def decode (self): self.dprint("Decode inst " + str(self.reg_inst)) self.decoded_inst['type...
This method executes a CPU cycle by fetching, decoding, and executing instructions if no interrupt occurs. If interrupted, it restores the program counter and handles the interrupt via the OS handler (if enabled). It increments the cycle counter after processing.
def run_cycle (self): self.dprint("---------------------------------") self.dprint("Cycle " + str(self.cycle)) if self.interrupt == 0: pc = self.reg_pc self.fetch() if self.interrupt == 0: self.decode() if self.interrupt == 0: self.execute() if self.interrupt != 0: self....
def load_task (self, bin_name): if not os.path.isfile(bin_name): self.printk("file "+bin_name+" does not exists") return None if (os.path.getsize(bin_name) % 2) == 1: self.printk("file size of "+bin_name+" must be even") return None task = task_t() task.bin_name = bin_name task.bin_size = os.pa...
The code initializes a system component by setting up CPU, memory, and terminal resources, enabling curses for the terminal, configuring memory blocks, loading an idle task from "idle.bin", and scheduling it as the initial process. It also prepares the console for user input and initializes task management structures f...
def __init__ (self, cpu, memory, terminal): self.cpu = cpu self.memory = memory self.terminal = terminal self.terminal.enable_curses() self.console_str = "" self.tasks = [] self.page = 0 self.next_task_id = 0 self.current_task = None self.next_sched_task = 0 self.idle_task = None self.idle...
def load_task (self, bin_name): if not os.path.isfile(bin_name): self.printk("file "+bin_name+" does not exists") return None if (os.path.getsize(bin_name) % 2) == 1: self.printk("file size of "+bin_name+" must be even") return None task = task_t() task.bin_name = bin_name task.bin_size = os.pa...
The code interprets user commands in a simulated system. It terminates the system ("bye"), lists tasks ("tasks"), or runs specified binaries ("run <name>"). If a binary exists, it loads and schedules the task; otherwise, it reports an error. Invalid commands trigger an error message. The core task is command parsing an...
def interpret_cmd (self, cmd): if cmd == "bye": self.cpu.cpu_alive = False elif cmd == "tasks": self.task_table_print() elif cmd[:3] == "run": bin_name = cmd[4:] self.terminal.console_print("\rrun binary " + bin_name + "\n") task = self.load_task(bin_name) if task is not None: self.tasks.app...
def printk(self, msg): self.terminal.kernel_print("kernel: " + msg + "\n") def un_sched (self, task): if task.state != PYOS_TASK_STATE_EXECUTING: self.panic("task "+task.bin_name+" must be in EXECUTING state for being unscheduled (state = "+str(task.state)+")") if task is not self.current_task: self.panic("...
The code handles a general protection fault (GPF) by logging the error, unscheduling the current task, terminating it, and invoking the scheduler. It retrieves the active task, prints the error with the task's binary name, stops its execution, marks it for termination, and triggers rescheduling to manage system state.
def handle_gpf (self, error): task = self.current_task self.printk("gpf task "+task.bin_name+": "+error) self.un_sched(task) self.terminate_unsched_task(task) self.escalonador()
def printk(self, msg): self.terminal.kernel_print("kernel: " + msg + "\n") def un_sched (self, task): if task.state != PYOS_TASK_STATE_EXECUTING: self.panic("task "+task.bin_name+" must be in EXECUTING state for being unscheduled (state = "+str(task.state)+")") if task is not self.current_task: self.panic("...
The code handles system calls by executing different operations based on the service number from CPU register 0. For service 0, it terminates the current task and triggers scheduling; service 1 prints a string from register 1; service 2 prints a newline; service 3 outputs register 1's value. Invalid services trigger a ...
def syscall(self): service = self.cpu.get_reg(0) task = self.current_task if service == 0: self.printk("app " + self.current_task.bin_name + " solicita finalizacao") self.un_sched(self.tasks) self.terminate_unsched_task(task) self.escalonador() elif service == 1: self.print_string_service(ta...
def handle_gpf (self, error): task = self.current_task self.printk("gpf task "+task.bin_name+": "+error) self.un_sched(task) self.terminate_unsched_task(task) self.escalonador() def interrupt_keyboard (self): key = self.terminal.get_key_buffer() if ((key >= ord('a')) and (key <= ord('z'))) or ((key >= or...
This method handles specific interrupt types by invoking corresponding actions: memory protection faults trigger handle_gpf, keyboard/timer interrupts call their respective methods, and unknown interrupts cause a panic. It routes interrupt signals to appropriate processing functions based on their type, ensuring system...
def handle_interrupt (self, interrupt): if interrupt == pycfg.INTERRUPT_MEMORY_PROTECTION_FAULT: self.handle_gpf("invalid memory address") elif interrupt == pycfg.INTERRUPT_KEYBOARD: self.interrupt_keyboard() elif interrupt == pycfg.INTERRUPT_TIMER: self.interrupt_timer() else: self.panic("invalid i...
def create_color_frequency_bars(self, width=2000, random=False, ordered=False, save=True): """ Creates a color frequency bars image file :param width: int width of the resulting image, default: 2000 :param random: bool whether to randomize the order of colours, default: False :pa...
This code generates multiple color visualizations for an image by creating frequency bars and grids with varying configurations—random, ordered, with/text labels—using specified grid spacing and swatch width parameters to display color distributions and suggestions in different formats.
def create_basic_selection(self, grid_spacing=10, swatch_width=200): """ Creates a basic selection of all graphics for an image """ self.create_color_frequency_bars() self.create_color_frequency_bars(random=True) self.create_color_frequency_bars(ordered=True) sel...
def gaussian_pyramid(I,nlev,subwindow): (r,c)=I.shape if subwindow is None: subwindow=[0,r,0,c] if nlev is None: nlev=numlevels([r,c]) pyr=np.empty((nlev),dtype=object) pyr[0]=I fil=pyramid_filter() for i in range(1,nlev): I,sub=downsample(I,fil) pyr[i]=I ...
The code constructs a multi-scale Laplacian pyramid to apply a non-linear filtering operation on an image. It generates a Gaussian pyramid of the input image, then iteratively builds a Laplacian pyramid by modifying each level with a reference-dependent Gaussian-like transformation. The output is reconstructed from the...
def llf(I,sigma,fact,N): (height,width)=I.shape n_levels=math.ceil(math.log(min(height,width))-math.log(2))+2 discretisation=np.linspace(0,1,N) discretisation_step=discretisation[1] input_gaussian_pyr=gaussian_pyramid(I,n_levels,None) output_laplace_pyr=laplacian_pyramid(np.zeros((height,width))...
def gaussian_pyramid(I,nlev,subwindow): (r,c)=I.shape if subwindow is None: subwindow=[0,r,0,c] if nlev is None: nlev=numlevels([r,c]) pyr=np.empty((nlev),dtype=object) pyr[0]=I fil=pyramid_filter() for i in range(1,nlev): I,sub=downsample(I,fil) pyr[i]=I ...
The code generates an image F by combining Laplacian pyramids from transformed versions of I1, using a Gaussian pyramid from I2. It applies a non-linear mapping involving sigma and fact, thresholds based on discretization steps, and reconstructs the final image via pyramid blending. The main task is to create a filtere...
def xllf(I1,I2,sigma,fact,N): (height,width)=I1.shape n_levels=math.ceil(math.log(min(height,width))-math.log(2))+2 discretisation=np.linspace(0,1,N) discretisation_step=discretisation[1] input_gaussian_pyr=gaussian_pyramid(I2,n_levels,None) output_laplace_pyr=laplacian_pyramid(np.zeros((height,...
def create_server_socket(client_type): # Create a TCP/IP socket if client_type == client_SUMO: PORT = 90 else: PORT = 80 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (HOST, PORT) print (sys.stderr, 'starting up on ',server_address,' port ',sock.b...
The code defines a function `work()` that continuously processes tasks from a queue. Depending on the task value (1, 2, or 3), it either creates and manages server sockets for "SUMO" or "MOBILE" connections, handles existing connections, or performs unspecified connection handling. Each task is marked as completed usin...
def work(): while True: x = queue.get() if x == 1: sock = create_server_socket("SUMO") accepting_connections(sock,"SUMO") if x ==2: connection_handle() if x == 3: sock = create_server_socke...
def connect(self,db_filename=''): #logging.debug("connect() : [*] Connecting to database {}...".format(db_filename)) if not db_filename: db_filename = self.db_filename if not self.db_connection: self.db_connection = sqlite3.connect(self.db_filename) def get...
This function retrieves a user's record from a specified or default database table by executing a SQL query. It connects to the database, validates the table name, and fetches the user data matching the given userid. If the table doesn't exist, it logs a warning.
def get_user(self, userid, table_name=''): self.connect() logging.info("get_user() : [*] Getting record for user {} from {}...".format(userid, table_name)) if not table_name: table_name = self.table_name if self.get_table(table_name): query = "SELECT * FROM ...
def get_table(self, table_name): logging.debug("get_table() : [*] Getting table {}...".format(table_name)) query = "SELECT name FROM sqlite_master WHERE type='table' AND name='{}'".format(table_name) o = self.execute(query) if o: logging.debug("get_table() : [+] Got table {...
This code imports user data from a file into a specified database table, checking for existing entries before inserting new ones. It reads usernames from a file, verifies the target table's existence, and either skips duplicates or creates new records with a timestamp. The function ensures data integrity by avoiding re...
def import_list(self, filename, table_name='', keyname=''): if not self.get_table(table_name): logging.warn("[-] Table '{}' doesn't exist".format(table_name)) return with open(filename, 'r') as f: names = f.read().splitlines() f.close() ...
def validate_transaction(self, sender_address, message, signature): verified = self.verify_signature(sender_address, message, signature) if not verified: return False trans_inputs = message['transaction_inputs'] ids_list = [] for x in self.utxos[sender_address]: if type(x['id']) != str and type(x['id'])...
This code processes incoming transactions by validating their authenticity using the sender's address and signature. If mining is active, it queues the transaction temporarily. Otherwise, it processes the signature, converts the message into a transaction object, adds it to the current block, and checks if the block is...
def receive_transaction(self, message, signature): sender_address = message['sender_address'] if self.event_mining_take_place.isSet(): self.temp_queue.append([message, signature]) return if not self.validate_transaction(sender_address, message, signature): return signature = transaction.preproccess_re...
def _check_keydown_events(self, event): if event.key == pygame.K_RIGHT: self.ship.moving_right = True elif event.key == pygame.K_LEFT: self.ship.moving_left = True elif event.key == pygame.K_q: sys.exit() elif event....
This function processes Pygame events: exits on QUIT, restarts music on USEREVENT, and delegates KEYDOWN/KEYUP/mouse clicks to specialized methods for game control and interaction.
def _check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.USEREVENT: pygame.mixer.music.play(-1) # Restart the music elif event.type == pygame.KEYDOWN: self._...
def _check_fleet_edges(self): for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _ship_hit(self): if self.stats.ships_left > 0: self.stats.ships_left -= 1 self.ship_hit.play() ...
The function `_update_aliens` updates alien movement, checks for collisions between aliens and the player's ship, triggers ship hit responses, verifies if aliens reach the screen bottom, and detects collisions with plasma projectiles, invoking corresponding hit handlers to manage game interactions and outcomes.
def _update_aliens(self): self._check_fleet_edges() self.aliens.update() if pygame.sprite.spritecollideany(self.ship, self.aliens): self._ship_hit() self._check_aliens_bottom() if pygame.sprite.spritecollideany(self.ship, self.plasmas): ...
def _check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.USEREVENT: pygame.mixer.music.play(-1) # Restart the music elif event.type == pygame.KEYDOWN: self._...
The code runs the game's main loop, handling events, updating game elements (ship, bullets, aliens), managing game states, and rendering the screen at 60 FPS. It also sets a music end event for audio control.
def run_game(self): #start the main loop of the game pygame.mixer.music.set_endevent(pygame.USEREVENT) # Music end event while True: #keyboard and mouse events self._check_events() if self.game_active: self.ship.update() self....
def load_price_data(pair, granularity, ma_list): # load the data frame for pair and granularity granularity df = pd.read_pickle(f"../data/{pair}_{granularity}.pkl") # calculate moving averages for ma in ma_list: df[get_ma_col(ma)] = df.mid_c.rolling(window=ma).mean() df.dropna(inplace=True) ...
The function `analyse_pair` evaluates trading strategies for a financial instrument by analyzing moving average (MA) crossover signals. It loads historical price data, iterates through combinations of long and short MA periods, assesses each pair's performance, and collects results. The outcomes are processed into a st...
def analyse_pair(instrument, granularity, ma_long, ma_short, filepath): ma_list = set(ma_long + ma_short) pair = instrument.name # load price data price_data = load_price_data(pair, granularity, ma_list) # print(pair) # print(price_data.head(3)) # saving the results list results_l...
def spider_pages(index_url): """Set the base condition for the recursive crawl""" links = [] # collect index if index_url: pages = { index_url: { "page_file_name": "/index.html", "page_content": capture_page(uri=index_url), } } ...
The main task of the code is to build a static website by processing scraped page data, converting links to HTML, managing a build directory (deleting old content and creating new files), copying static assets, and writing generated HTML pages to the correct paths. It ensures directory structure integrity and handles e...
def build_static_site(data): """Build a static site""" index_page = "" pages_to_build = spider_pages(index_page) if pages_to_build: # Change a links to point to html pages for key, value in pages_to_build.items(): pages_to_build[key]["page_content"] = htmlify_links(value["p...
def log(message: str): if not shared.opts.data.get('civitai_link_logging', True): return print(f'Civitai Link: {message}') def on_activities_list(payload: CommandActivitiesList): payload['activities'] = civitai.activities payload['status'] = 'success' command_response(payload) def on_activities_clea...
This function processes incoming commands by routing them to specific handler functions based on the command type, logs the command, and adds an activity to Civitai. It supports commands related to activities (list, clear, cancel) and resources (list, add, remove), as well as image generation via 'image:txt2img'.
def on_command(payload: Command): command = payload['type'] log(f"Incoming Command: {payload['type']}") civitai.add_activity(payload) if command == 'activities:list': return on_activities_list(payload) elif command == 'activities:clear': return on_activities_clear(payload) elif command == 'acti...
def get_resource_by_hash(hash: str): resources = load_resource_list([]) found = [resource for resource in resources if hash.lower() == resource['hash'] and ('downloading' not in resource or resource['downloading'] != True)] if found: return found[0] return None def log(message): """Log a m...
The main task of the code is to remove a resource file based on its hash and type, verify its existence, delete it if valid, log the action, and reload corresponding model lists (e.g., Checkpoints, Hypernetworks) to update the system state. It handles cases where the resource is invalid or not found, ensuring proper cl...
def remove_resource(resource: ResourceRequest): removed = None target = get_resource_by_hash(resource['hash']) if target is None or target['type'] != resource['type']: removed = False elif os.path.exists(target['path']): os.remove(target['path']) removed = True if removed == True: ...
def get_resource_by_hash(hash: str): resources = load_resource_list([]) found = [resource for resource in resources if hash.lower() == resource['hash'] and ('downloading' not in resource or resource['downloading'] != True)] if found: return found[0] return None def log(message): """Log a m...
This function loads a resource by checking if it already exists via its hash. If not, it adds the resource to a list and triggers type-specific loading processes (e.g., models, configs) using dedicated functions. The 'downloading' flag is set to track progress, and a progress callback is optionally used.
def load_resource(resource: ResourceRequest, on_progress=None): resource['hash'] = resource['hash'].lower() existing_resource = get_resource_by_hash(resource['hash']) if existing_resource: log(f'Already have resource: {resource["name"]}') return resources.append({'type': resource['type'...
def get_model_version_by_hash(hash: str): response = req(f"/model-versions/by-hash/{hash}") return response def log(message): """Log a message to the console.""" print(f'Civitai: {message}') def load_resource(resource: ResourceRequest, on_progress=None): resource['hash'] = resource['hash'].lower() ...
The function fetches a machine learning model checkpoint by a given hash. It retrieves the model version, identifies the primary file, creates a resource request with the file's metadata, and loads the resource. If the hash is invalid, it logs an error and returns None.
def fetch_model_by_hash(hash: str): model_version = get_model_version_by_hash(hash) if model_version is None: log(f'Could not find model version with hash {hash}') return None file = [x for x in model_version['files'] if x['primary'] == True][0] resource = ResourceRequest( name=...
def rk4(derivs, y0, t): """ Integrate 1-D or N-D system of ODEs using 4-th order Runge-Kutta. Example for 2D system: >>> def derivs(x): ... d1 = x[0] + 2*x[1] ... d2 = -3*x[0] + 4*x[1] ... return d1, d2 >>> dt = 0.0005 >>> t = np.arange(0.0, 2...
This code computes the next environment state using RK4 integration after applying torque limits and noise. It updates the state, checks termination conditions, calculates reward, and returns observations, reward, done flag, barrier value, and target status for reinforcement learning training.
def step(self, a): s = self.state assert s is not None, "Call reset before using AcrobotEnv object." torque = a #add torque limit torque = np.clip(torque, a_min=self.min_torque, a_max=self.max_torque) # Add noise to the force action if self.torque_noise_max > 0:...
def print_board(board): for i in range(0, 9, 3): print(f"{board[i]} | {board[i+1]} | {board[i+2]}") if i < 6: print("---------") def is_board_full(board): return " " not in board def player_move(board): while True: try: move = int(input("Enter your move (1-9):...
The code implements a Tic-Tac-Toe game where a player (O) and computer (X) take turns. It prints the board, checks for wins/ties, and alternates moves until a win or tie is declared. The player's move is manually input, while the computer's move is determined by the `computer_move` function. The game ends with a messag...
def main(): print("Welcome to Tic-Tac-Toe!") print_board(board) player_turn = True while True: if not is_board_full(board): if player_turn: move = player_move(board) board[move] = "O" else: move = computer_move(board) ...
def Wannier_centers(hamfunc, params_dict, filled_bands, N): k = np.linspace(0., 2.*np.pi, N, endpoint=False) ham = hamfunc(k, params_dict) evals, evecs = np.linalg.eigh(ham) evecs_occ = evecs[...,filled_bands] F = Wilson_line_elements(evecs_occ, unitary=True) basepoint =...
The code computes and visualizes the polarization of a SSH model as a function of parameters t1 and m. It iterates over t1 and m values, calculates polarization using a Hamiltonian, and plots the results. The main task is to analyze how polarization varies with t1 and m in the model.
def plot_polarizations(): np.set_printoptions(linewidth=750) params_dict = {'t1':0.99, 't2':1., 'm':0., 'e0':0.} N = 100 filled_bands = [0,1] centers = Wannier_centers(hamSSH, params_dict, filled_bands, N) smartprint('cent...
def getPGA(self): # coords = [[0.000000, 0.000000, 0.000000], # [0.000000, 0.000000, 1.089000], # [1.026719, 0.000000, -0.363000], # [-0.513360, -0.889165, -0.363000], # [-0.513360, 0.889165, -0.363000]] # methane = Molecule(["C", "H", "H", "H", "H"], coords) r...
The code groups atoms by their labels using equivalent atom indices. It retrieves unique atom indices from `getPGA()`, iterates over unique labels, filters atoms matching both the label and index, and maps each label to its corresponding atom list in a dictionary. The result is a dictionary where keys are labels and va...
def getUniqueElementsByLabels(self): unique_indices = self.getPGA().get_equivalent_atoms()["eq_sets"].keys() dict_atoms={} for lbl in self.getUniqueLabels(): list_atoms=[] for idx in range(len(self.getAtoms())): if idx in unique_indices and self.getAtoms()...
def getPGA(self): # coords = [[0.000000, 0.000000, 0.000000], # [0.000000, 0.000000, 1.089000], # [1.026719, 0.000000, -0.363000], # [-0.513360, -0.889165, -0.363000], # [-0.513360, 0.889165, -0.363000]] # methane = Molecule(["C", "H", "H", "H", "H"], coords) r...
The function generates a unique molecular structure by selecting one representative atom from each symmetry-equivalent set, converts these atoms into a pymatgen Molecule object, and saves it to the specified file. It ensures symmetry-uniqueness by leveraging equivalent atom groups, outputting the filename as a result.
def writePymatgenMoleculeSymmetryUnique(self, filename): equivalent_atoms = self.getPGA().get_equivalent_atoms() atoms=[] for k in equivalent_atoms["eq_sets"].keys(): atoms.append(self.getAllcenters()[k]) molecule = atoms2Molecule(atoms) molecule.to(filename=filename)...
def validate_block(self, block, custom_balances): if block.size > G.max_size: return False balances_copy = custom_balances[:] for txn in block.txns: if not self.validate_txn(txn, balances_copy): return False balances_copy[txn.sender.id] -= txn....
This code broadcasts a mined block in a blockchain simulation. It validates the block, adds it to the blockchain if valid, logs the event, records the block's arrival time, and schedules a ForwardBlock event for transmission. It also schedules the next block mining.
def broadcast_mined_block(self, sim): block = self.next_mining_block block.setID() assert self.blockchain.current_block.id == block.parent.id is_valid = self.validate_block(block, self.balances) # do not add an invalid block, only transmit it to other peers validity = "...
def free_blocks_dfs(self, block, cur_balances, blocks_to_add, deepest_block, sim): if not self.validate_block(block, cur_balances): self.delete_invalid_free_blocks(block, sim) return deepest_block blocks_to_add.add(block) if deepest_block is None or block.depth > deepest...
The main task of the code is to handle the reception of a new block in a blockchain network. It checks if the block is already known, records its arrival time, and forwards it to other nodes. It then validates the block's parent, identifies the longest chain via LCA computation, updates balances and transaction pools i...
def receive_block(self, sim, sender, block): chain_it = block.id in self.chain_blocks.keys() free_it = block.id in self.free_blocks.keys() reject_it = block.id in self.rejected_blocks # already received this block if chain_it or free_it or reject_it: return ...
def parse_timestamp(packet): b_timestamp = packet[INDEX_PACKET_LENGTH:INDEX_TIMESTAMP] timestamp = convert_timestamp(b_timestamp) return timestamp def parse_temperature(current_index, packet): b_temperature = packet[current_index:current_index + SIZE_TEMPERATURE] temperature = convert_temperature(b_...
The main task of the code is to parse a binary packet into a structured log entry containing a timestamp, device name, and sensor data (temperature and/or humidity). It extracts the timestamp, decodes the device name from the packet, and identifies temperature/humidity values based on the packet's remaining size, popul...
def parse_packet(self, packet): log_entry = {} timestamp = parse_timestamp(packet) log_entry['timestamp'] = timestamp name_length = None try: name_length = packet[INDEX_TIMESTAMP] except IndexError as ex: print(ex, ', ', packet, ', ', INDEX_TIMES...
def make_new_state(): return { 'metadata': None, 'dwells': None, 'darks': None, 'n_darks': None, 'index': 0, 'current_exposures': None, 'current_masks': None, 'position': None, 'frame_cleaner': None, 'resampler': None, 'mask': N...
The code listens for raw data from `pystxmcontrol`, preprocesses it, saves results to `.cxi` files, and broadcasts cleaned data. It uses ZeroMQ for communication, handling `start`/`stop` events to manage data accumulation, configuration updates, and file creation. The script dynamically reloads configurations, triggers...
def main(argv=sys.argv): # I'm just using this so the script has a help printout parser = argparse.ArgumentParser( prog = 'process_live_data', description = 'Runs a program which listens for raw data being emitted by pystxmcontrol. It assembles and preprocesses this data, saving the results ino...
def get_tag(text): text_vectors = preprocess_input(text) prediction = clf.predict(text_vectors) tag = le.inverse_transform(prediction) return tag[0] def manual_corrections(text): if text.lower() == "bye": return "Exit", True elif text.lower() == "hi" or text.lower() == "hello": return "Intro",True ...
The code processes input text by determining a tag, applying manual corrections if specified, and retrieving a response based on the final tag.
def ask_bot(text): tag = get_tag(text) tag_manual, override = manual_corrections(text) if override: tag = tag_manual response = get_response_for_tag(tag) return response
def recommendPopularSong(self): L = self.getNmostPopularSongs(N = 20) popularSong = [] for s in L: i = r.randint(0,100) if i% 4 == 0: popularSong.append(s) return popularSong def getClusterOfaSong(self, song): return list(self.clusters[self...
The code recommends songs based on user listening history and preferences. If no history exists, it suggests popular songs; otherwise, it analyzes clusters/artists from past listens to recommend similar tracks. It handles users with <4 listening entries by leveraging recommended song clusters and extends recommendation...
def recommend(self): # self.recommendedSongs = list(self.history[ self.history.userID == self.userID ].songList) if self.recommendedSongs == []: self.recommendedSongs.extend(self.recommendPopularSong()) elif len(self.listeningHistory) < 4: # CREATE THE RECOMMENDE...
def make_list_of_ints_and_prime_labels(start_num, end_num): """ return two lists: nums = [0,0,1,3,...] and labels = [0,0,1,1,...] where label 0 means non-prime and 1 means prime. """ nums = list(range(start_num, end_num)) labels = [0] * end_num for num in nums: labels[num] = is_prime_int(num) ...
The code demonstrates prime number analysis by generating a list of integers with prime labels, calculating the probability of a random integer being prime, counting primes up to a large number, and creating a prime data frame. It combines data generation, mathematical computation, and data structuring for prime-relate...
def demo(): print(make_list_of_ints_and_prime_labels(0, 200)) # get_prime_to_integer_ratios() print(prob_rand_int_less_than_n_is_prime(10000000)) print(prime_counting_function(10000000)) print(make_primes_df(11))
def gp_predict(self, reps, plot_gp, regular_interval = False): """ """ gp = fit_gaussian_process(self.obs) fitted_gp = gp[0] self.parameters = gp[2] if plot_gp: gp_figure, gp_axis = plt.subplots() plot_light_curve(self.obs, self.obj_name +...
This function generates augmented light curves using Gaussian Process prediction, saves them as CSV files when enabled, and plots them if requested. It iterates over multiple repetitions, creates unique filenames, and stores results in designated folders.
def augment_curve(self, save_csv, save_graph, make_graph, reps = 1, plot_gp = False, regular_interval = False, aug_folder = None): """plotting the augmented curve""" for aug_lc, i in self.gp_predict(reps, plot_gp, regular_interval): filename = self.obj_name + '_augmented_' + str(i) ...
def delay_to_geo(self, delay_matrix): # Establish the coordinates of each server according to the delay matrix size = len(delay_matrix) # No of nodes mds_model = manifold.MDS(n_components=2, random_state=0, dissimilarity='precomputed', normalized_stress="auto") # MDS(dissimilarity='precomputed', normali...
The code processes input data to model request distribution, node coverage, and user-node relationships. It generates synthetic data for node delays, user locations, and request assignments based on workload matrices. It calculates geographic coordinates, checks coverage within a radius, and initializes variables for f...
def load_input(self, data: Data): self.data = data max_delay = 2000 # millis num_nodes = data.sources num_users = 8 # creates a diagonal matrix of delays (in Neptune this is given) b = np.random.randint(0, max_delay, size=(len(num_nodes),len(num_nodes))) delay_m...
def delay_to_geo(self, delay_matrix): # Establish the coordinates of each server according to the delay matrix size = len(delay_matrix) # No of nodes mds_model = manifold.MDS(n_components=2, random_state=0, dissimilarity='precomputed', normalized_stress="auto") # MDS(dissimilarity='precomputed', normali...
The code simulates a network environment by generating node and user coordinates, distributing requests among nodes/users, calculating geographical coverage using the Haversine formula, and initializing variables for criticality analysis and optimization. It processes workload data, assigns requests to functions, and e...
def load_input(self, data: Data): self.data = data max_delay = 2000 # millis num_nodes = data.sources self.num_users = 8 # creates a diagonal matrix of delays (in Neptune this is given) b = np.random.randint(0, max_delay, size=(len(num_nodes),len(num_nodes))) d...
def delay_to_geo(self, delay_matrix): # Establish the coordinates of each server according to the delay matrix size = len(delay_matrix) # No of nodes mds_model = manifold.MDS(n_components=2, random_state=0, dissimilarity='precomputed', normalized_stress="auto") # MDS(dissimilarity='precomputed', normali...
The main task of this code is to initialize and configure an optimization model for resource allocation, where requests are assigned to nodes considering coverage constraints, node capacity limits, and function deployment requirements. It processes input data, generates geographical coordinates, computes request-node c...
def load_input(self, data: Data): self.data = data max_delay = 2000 # millis num_nodes = data.sources num_users = 8 # creates a diagonal matrix of delays (in Neptune this is given) b = np.random.randint(0, max_delay, size=(len(num_nodes),len(num_nodes))) delay_m...
def down_branch(inp): pool1, conv1 = down_block(inp, num_filter=32, kernel=(3,3), pad=(1,1), block=1) pool2, conv2 = down_block(pool1, num_filter=64, kernel=(3,3), pad=(1,1), block=2) pool3, conv3 = down_block(pool2, num_filter=128, kernel=(3,3), pad=(1,1), block=3) pool4, conv4 = down_block(pool3, num_...
This function constructs a U-Net model for image segmentation. It builds an encoder-decoder architecture by calling down_branch (feature extraction) and up_branch (feature reconstruction), applies a sigmoid activation for binary segmentation, and returns the decoded output for inference. For training, it computes a dic...
def build_unet(inference=False): data = mx.sym.Variable(name='data') down_features = down_branch(data) decoded = up_branch(down_features) decoded = mx.sym.sigmoid(decoded, name='softmax') if inference: return decoded else: net = mx.sym.Flatten(decoded) label = mx...
def get_data(f_path): train_X = np.load(os.path.join(f_path,'train_X_crops.npy')) train_Y = np.load(os.path.join(f_path,'train_Y_crops.npy')) validation_X = np.load(os.path.join(f_path,'validation_X_crops.npy')) validation_Y = np.load(os.path.join(f_path,'validation_Y_crops.npy')) return train_X, tr...
The code trains a U-Net model using MXNet for image segmentation, handling distributed training across multiple GPUs. It loads data from a specified channel, initializes the model with Xavier weights, and uses the Adam optimizer. Training includes validation, early stopping based on validation loss, and saving the best...
def train( batch_size, epochs, learning_rate, num_gpus, training_channel, # testing_channel, hosts, current_host, model_dir, beta1, beta2, burn_in ): # retrieve the hyperparameters we set in notebook (with some defaults) # batch_size = hyperparameters.get('batch_s...