dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def default(val, d): if exists(val): return val return d() if callable(d) else d def q_sample(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) return ( extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + extract...
This function computes the loss for a diffusion model by predicting either noise, initial image (x0), or velocity (v) from a noisy input, depending on the objective. It samples a noisy version of the input, optionally uses self-conditioning to improve predictions, and calculates the mean squared error (MSE) between the...
def p_losses(self, x_start, t, cond, noise = None): b, c, h, w = x_start.shape noise = default(noise, lambda: torch.randn_like(x_start)) # noise sample x = self.q_sample(x_start = x_start, t = t, noise = noise) # if doing self-conditioning, 50% of the time, predict x_start fro...
def compute_total_distance(road_map): d = compute_city_distance(road_map) return sum(d) def shift_cities(road_map): """ For every index i in the `road_map`, the city at the position i moves to the position i+1. The city at the last position moves to the position 0. Return the new road map. "...
The function `find_best_cycle` optimizes a route (road map) by iteratively applying 10,000 random swaps or shifts of cities. It evaluates each modified route's total distance, retaining the shortest path found. Starting with an initial road map, it generates new configurations using `shift_cities` and `swap_cities`, co...
def find_best_cycle(road_map): """ Using a combination of `swap_cities` and `shift_cities`, try `10000` swaps/shifts, and each time keep the best cycle found so far. After `10000` swaps/shifts, return the best cycle found so far. Args: road_map (List): List of tuples each with city names an...
def read_cities(file_name): """ Read in the cities from the given `file_name`, and return them as a list of four-tuples: [(state, city, latitude, longitude), ...] Args: file_name (text file): File name to read in Return: List : Contains a list of tuples in the following ...
The main task of the code is to solve the Traveling Salesman Problem (TSP) by reading city coordinates from a file, calculating the initial route distance, optimizing the route through 10,000 iterations, and visualizing the improved path. It prints the original and optimized routes, their distances, and generates a vis...
def main(): """ Run the program """ # Initialise print(pyfiglet.figlet_format('FDM TSP PROJECT', font="slant")) iterations_n = 10000 file_path = 'city-data.txt' # Read in text file road_map = read_cities(file_path) # Print original road map print_cities(road_map) # Comp...
def compute_doubling_slope(pt: EPoint): # Note that y cannot be zero: assume that it is, then pt = -pt, so 2 * pt = 0, which # contradicts the fact that the size of the curve is odd. x_sqr = bigint_mul_mod(pt.x, pt.x, SP) y_2 = 2 * pt.y slope = bigint_div_mod((3 * x_sqr + SA), y_2, SP) return sl...
This function computes the doubling of a point on an elliptic curve using the point doubling formula. It calculates the slope, derives new x and y coordinates via modular arithmetic, and returns the resulting point. Special handling occurs if the input x-coordinate is zero, returning the original point.
def ec_double(pt: EPoint): if pt.x == 0: return pt slope = compute_doubling_slope(pt) slope_sqr = bigint_mul_mod(slope, slope, SP) new_x = bigint_div_mod(slope_sqr - 2 * pt.x, 1, SP) x_diff_slope = bigint_mul_mod(slope, (pt.x - new_x), SP) new_y = bigint_sub_mod(x_diff_slope, pt.y, S...
def deploy_market(): io = connect() io.sendline(b"1") io.recvuntil(b"deployer account: ") deployer_address = io.recvline().strip() io.recvuntil(b"token: ") token = io.recvline().strip() print(f"{deployer_address=}") print(f"{token=}") input(f"Claim testnet ETH to {deployer_address.d...
The main task of the code is to deploy a market contract, execute an exploitation attack on it, and retrieve a flag using the obtained token and transaction hash. The `deploy_market()` initializes the market, `exploit()` performs the attack, and `get_flag()` extracts the flag from the system using the token and transac...
def main(): token, market_address = deploy_market() tx_hash = exploit(market_address) get_flag(token, tx_hash)
def bigint_sub_mod(x, y, P): sub = x - y res = bigint_div_mod(sub, 1, P) return res def fast_ec_add(pt0: EPoint, pt1: EPoint): if pt0.x == 0: return pt1 if pt1.x == 0: return pt0 slope = compute_slope(pt0, pt1) slope_sqr = bigint_mul_mod(slope, slope, SP) new_x = bigin...
The function `ec_add` performs elliptic curve point addition. It checks if the x-coordinates of two points differ (using `fast_ec_add` for distinct points). If x-coordinates are equal, it checks if y-coordinates sum to zero (returning the zero point for inverses or identical zero points). Otherwise, it doubles the poin...
def ec_add(pt0: EPoint, pt1: EPoint): x_diff = bigint_sub_mod(pt0.x, pt1.x, SP) if x_diff != 0: # pt0.x != pt1.x so we can use fast_ec_add. return fast_ec_add(pt0, pt1) y_sum = bigint_add_mod(pt0.y, pt1.y, SP) if y_sum == 0: # pt0.y = -pt1.y. # Note that the case pt0 = p...
def ec_double(pt: EPoint): if pt.x == 0: return pt slope = compute_doubling_slope(pt) slope_sqr = bigint_mul_mod(slope, slope, SP) new_x = bigint_div_mod(slope_sqr - 2 * pt.x, 1, SP) x_diff_slope = bigint_mul_mod(slope, (pt.x - new_x), SP) new_y = bigint_sub_mod(x_diff_slope, pt.y, S...
This function performs elliptic curve scalar multiplication, computing r*P where P is an elliptic curve point and r is a scalar. It uses the double-and-add algorithm, iterating over each bit of r (from MSB to LSB) to efficiently calculate the result by repeatedly doubling the current value and conditionally adding P ba...
def mult(P, r): # multiplication r*P # P.affine() a = r R = EPoint(0, 0) k = 256 for i in range(k - 1, -1, -1): R = ec_double(R) if bit(a, i) == 1: R = fast_ec_add(R, P) return R
def verify_point(pt: EPoint): y_sqr = bigint_mul_mod(pt.y, pt.y, SP) x_sqr = bigint_mul_mod(pt.x, pt.x, SP) x_cub = bigint_mul_mod(x_sqr, pt.x, SP) a_x = bigint_mul_mod(pt.x, SA, SP) right1 = bigint_add_mod(x_cub, a_x, SP) right = bigint_add_mod(right1, SB, SP) diff = bigint_sub_mod(y_sqr, r...
The function verifies an ECDSA signature by validating the public key and signature components (r, s), computing scalar multiplications with the generator point and public key, adding the results, and checking if the x-coordinate of the sum matches r modulo SP. It returns 1 for a valid signature, 0 otherwise.
def verify_ecdsa(public_key_pt: EPoint, msg_hash, r, s): if verify_point(public_key_pt) != 1: return 0 if validate_signature_entry(r, SN) != 1: return 0 if validate_signature_entry(s, SN) != 1: return 0 gen_pt = EPoint(SGX, SGY) # Compute u1 and u2. u1 = bigint_div_mod(...
def random(m, s): x1 = 0x53B907251BC1CEB7AB0EB41323AFB7126600FE4CB2A9A2E8A797127508F97009 y1 = 0xC7B390484E2BAAE92DF41F50E537E57185CB18017650A6D3220A42A97727217D x2 = 0xACBC2999FB58C6E9015A12A4C5F3849E301649B2271EAAAF21906ED03CAFDF45 y2 = 0x146AAC3F7F74047FD45CF0098FADEE5CD00F7F6871440387BA402F2390D7276...
This code implements the ECDSA (Elliptic Curve Digital Signature Algorithm) signing process. It generates a digital signature (r, s) using a private key (sk) and message hash (msg_hash) by selecting a random nonce (k), computing an elliptic curve point (pg), and deriving signature components via modular arithmetic oper...
def sign_ecdsa(sk, msg_hash): gen_pt = EPoint(SGX, SGY) k = random(msg_hash, sk) pg = mult(gen_pt, k) r = bigint_mul_mod(pg.x, 1, SN) rsk = bigint_mul_mod(r, sk, SN) m_rsk = bigint_add_mod(msg_hash, rsk, SN) s = bigint_div_mod(m_rsk, k, SN) return r, s
def is_train_test_file_exists(self)->bool: try: logging.info(f"Checking if training and test file is available") is_train_file_exist = False is_test_file_exist = False train_file_path = self.data_ingestion_artifact.train_file_path test_file_path = sel...
The main task of the code is to validate data by checking the existence of train/test files, verifying the dataset schema, and detecting data drift. If all validations succeed, it creates a `DataValidationArtifact` with specified file paths and a success message. The function returns this artifact or raises an exceptio...
def initiate_data_validation(self)->DataValidationArtifact: try: self.is_train_test_file_exists() self.validate_dataset_schema() self.is_data_drift_found() data_validation_artifact=DataValidationArtifact( schema_file_path=self.data_validation_conf...
def linear_regression(data: list) -> tuple: """Perform a linear regression on the given points, returns an averaged value over the course of the year based on individual months. From the points refers to a list of pairs of floats [(x_1, y_1), (x_2, y_2), ...] This function returns a pair of floats (a,...
The function `current_future` extrapolates future carbon and temperature data using linear regression models derived from historical datasets. It calculates a combined coefficient from the regression results, then generates future predictions for the specified number of years, returning a list of date-value tuples repr...
def current_future(c_data: list, t_data: list, years: int) -> List[Tuple[datetime.date, float]]: """Extrapolates the future based on previous carbon data, temperature data, and a year given by the slider Preconditions: - c_data.length == t_data.length - years >= 0 """ c_reg = linea...
def linear_regression(data: list) -> tuple: """Perform a linear regression on the given points, returns an averaged value over the course of the year based on individual months. From the points refers to a list of pairs of floats [(x_1, y_1), (x_2, y_2), ...] This function returns a pair of floats (a,...
The function `possible_future` extrapolates future carbon and temperature data over a specified number of years using linear regression on historical temperature data and a provided coefficient of change. It combines the input coefficient with the regression slope to model future trends, then appends these predicted va...
def possible_future(c_data: list, t_data: list, years: int, input: float) -> List[Tuple[datetime.date, float]]: """Extrapolates the future based on previous carbon data, temperature data, a year given by the current_future(c_data, t_data, 2) slider and a coefficient of change Preconditions: - c_dat...
def _createTextFields(self): """ Creates and positions the Line Edits on the tab :return: None """ # Number of times to clone self.textAmount = QLineEdit() self.textAmount.setMaximumWidth(80) self.textAmount.setContentsMargins(25, 0, 0, 0) self.lay...
The code initializes a GUI widget with a QGridLayout, sets column width, creates UI elements via private methods, and configures font and data attributes. It sets up text fields, labels, buttons, and other components for a structured interface, initializing data structures and styling with a custom font.
def __init__(self): super().__init__() self.layout = QGridLayout() self.setLayout(self.layout) self.layout.setColumnMinimumWidth(0, 220) # Run functions to create all the little guys self._createTextFields() self._createLabels() self._createMisc() ...
def build_parser(): parser = ArgumentParser() parser.add_argument('--checkpoint', type=str, dest='checkpoint_dir', help='dir or .ckpt file to load checkpoint from', metavar='CHECKPOINT', required=True) parser.add_argument('--in-path', ...
This code performs style transfer on input images using a pre-trained model, applying color space transformations to merge stylized and original image colors. It handles both single images and directories, saving processed results with optional color blending and channel merging for enhanced visual output.
def main(): parser = build_parser() opts = parser.parse_args() check_opts(opts) if not os.path.isdir(opts.in_path): if os.path.exists(opts.out_path) and os.path.isdir(opts.out_path): out_path = \ os.path.join(opts.out_path,os.path.basename(opts.in_path)) ...
def __single_player(self): self.__check_for_fold() self.__last_man_winner() def __print_statements(self, player): print(player.name + "'s hand:") print(player.hand.view_cards()) print(player.name + "'s chips: " + str(player.chips)) print("Type bet, check or fold.") ...
This method processes each player's action by prompting input and executing corresponding game actions like betting, checking, or folding, while handling invalid inputs with an error message.
def player_actions(self): for player in self.players: self.__single_player() self.__print_statements(player) choice = input().lower() if choice == "bet": player.bet() elif choice == "check": player.check() el...
def get_dataset(self, gt_csv_path): return CsvDataset(gt_csv_path) def get_predictions_no_mask(self, image): #im = self.read_image(impath, image_id) #print(impath) results = self.model.detect([image]) return results[0] def assign_predictions(self, gt_rois, gt_classes, results): ...
The main task of this code is to generate and visualize saliency maps for ground truth objects in an image, compare them with model predictions, and save the results. It loads an image and its annotations, computes saliency maps, matches predictions to ground truth, and generates visualizations (overlayed saliency maps...
def explain_one(self, gt_csv_path=None, impath = None, imID = None, prediction_saliencies = True): if gt_csv_path is not None: dataset = self.get_dataset(gt_csv_path) if impath is not None: image_id = dataset.get_image_id(impath) elif imID is not None: impath ...
def set_to_forward_canonical( mps: List[jnp.ndarray], ) -> jnp.ndarray: r = jnp.eye(1) lognorm = 0. if len(mps) == 0: return lognorm for i, ker in enumerate(mps): ker, r = _push_r_backward(ker, r) norm = jnp.linalg.norm(r) r /= norm lognorm += jnp.log(norm) ...
This function truncates a list of MPS tensors by reducing their size while ensuring the error remains below a specified threshold. It first converts the MPS to a canonical form, truncates it using the error tolerance, and then normalizes the result by multiplying with a log norm scalar.
def truncate_mps_by_error( mps: List[jnp.ndarray], error: float, ): log_norm = set_to_forward_canonical(mps) truncate_forward_canonical_by_error(mps, error) mul_by_log_scalar(mps, log_norm)
def __extract_product_quantity(self, quantity: list) -> PredictedItem: return self.__extract_number(quantity[1][0], quantity[1][1], self.__product_quantity_re, 'factor', 1e-3) def __extract_product_price(self, price: list) -> PredictedItem: return self.__extract_number(price[1][0], price[1][1], self.__p...
The main task of the code is to extract structured product information from a prediction list by identifying a specific pattern using a regex, then parsing quantity, price, name, and total price from grouped entries starting at a determined index, compiling valid results into a list of dictionaries.
def __extract_products(self, prediction: Union[None, List[list], list]) -> List[Dict[str, PredictedItem]]: start_index = -1 for index in range(len(prediction)): if re.search(self.__lei_re, prediction[index][1][0], flags=re.IGNORECASE) is not None: start_index = index + 1 ...
def __extract_company(self, prediction: Union[None, List[list], list]) -> PredictedItem: value = prediction[0][1][0] score = prediction[0][1][1] return PredictedItem(value, self.__is_safe(score)) def __extract_products(self, prediction: Union[None, List[list], list]) -> List[Dict[str, PredictedI...
The code processes an input image (as string or bytes) using OCR via PaddlePaddle, extracts structured data including company name, product details, and total amount from the OCR results, and returns these as a dictionary.
def process(self, img: Union[str, bytes]) -> dict: __img = self.__pp_srv.process(img) prediction = self.__paddle.ocr(__img, cls=True) result = { 'company': self.__extract_company(prediction), 'products': self.__extract_products(prediction), 'total': self.__ext...
def handle_error(error): global _TEST if not _TEST: raise error def _check_keywords(self, name): # Raise error if keywords are used. if name in self._kwds: raise KeywordError(f'Keyword {name} cannot be used here') def _parse_one_arg(self, name): """Parse one declared ...
This code adds a new argument to a parser, validating uniqueness of full/short names, handling boolean arguments by creating positive/negative name views, and immediately parsing if allowed. It returns the created argument object.
def add_argument(self, full_name, short_name=None, default=None, dtype=None, nargs=None, help='', force=False): if self._parsed and not _ParserNode._unsafe: handle_error(ParsedError('Already parsed.')) unsafe = self._parsed and _ParserNode._unsafe if not force: self._ch...
def handle_error(error): global _TEST if not _TEST: raise error def help(self): print('Usage:') for k, a in self._args.items(): print(' ' * 9, a) sys.exit(0) def _parse_one_arg(self, name): """Parse one declared argument. Args: name (str):...
The code parses command-line arguments, handling three modes: resolving declared arguments, processing CLI inputs, and loading config defaults. It processes CLI flags, enables unsafe mode for dynamic arguments, loads config file defaults, overrides with CLI inputs, and sets up a log directory. The method ensures argume...
def parse_args(self): """ There are three ways of parsing args. 1. Provide the declared argument (and its full name as the key) and find matching CLI arguments (unparsed). This is handled by ``_parse_one_arg`` function. 2. Provide the CLI arguments, and find matching declared arguments. ...
def read_file(file): data = pd.read_csv(file) attributes = data[["cut", "color", "clarity"]] shape = data[["depth", "table", "carat"]] predict = data[["price"]] dictionary = defaultdict(lambda: (list(), list())) for attribute, shape, predict in zip(attributes.values, shape.values, predict.valu...
The main task of the code is to evaluate regression models and K-Fold cross-validation performance on diamond data. It processes each data split, runs regression analysis with 2 parameters, computes optimal K-Fold results, and visualizes outcomes through metrics and graphical representations for comparative analysis.
def main(): data = read_file("diamonds.csv") print("\n Regression performance:") for i, splits in enumerate(data.values()): print("Split " + str(i + 1) + "/" + str(len(data.values())) + ":") shape = np.array(splits[0]) predict = np.array(splits[1]) regression = regression_mo...
def passMove(self): """Gives the other player the turn.""" if self.info_on: print("Pass from player {}".format(self.turn)) self.turn = -self.turn self.movesPassed += 1 def createGroup(self,x,y,player): return self.createGroupRec(x,y,set(),lambda color: color == player) def createSurroundingOpponentGroups(s...
The code attempts to make a legal move on a board by placing a stone at (x,y), checking if the cell is empty, capturing surrounded opponent groups, validating the move for suicide or ko rule violations, updating the board state, and switching turns if valid. It returns True for a legal move or False if illegal due to f...
def makeMove(self, x, y): """Tries to make a move on the board if it's legal.""" if (x,y) == (-1,-1): self.passMove() else: if self.info_on: print("Making move: {},{} by player {}".format(x,y,self.turn)) if self.board[y][x] == 0: amount_captured = 0 changed_group = self.createGroup(x,y,self.t...
def findAllGroups(self, player): stones_considered = set() stone_groups = [] for x in range(self.gamesize): for y in range(self.gamesize): new_group = set() if self.board[y][x] == player and not (y,x) in stones_considered: new_group = self.createGroup(x, y, player) stones_considered.update(new...
The code identifies unconditionally alive groups using Benson's algorithm by iteratively filtering groups based on vital counts and region sizes. It starts by finding all groups, partitioning regions, and removing small ones. Through repeated refinement, it updates groups (X) and regions (R) until stability is achieved...
def findUnconditionallyAliveGroups(self, player): """Finds unconditionally alive groups according to Bensons algorithm""" X = self.findAllGroups(player) partitioned_regions = self.findPartionedRegions(X, player) R = self.filterSmallRegions(partitioned_regions, player) X_old = X R_old = R vital_counts = s...
def displayBackground(screen, game, BLITS_DICT): bg = BLITS_DICT["bg"] back = BLITS_DICT["back"] backDark = BLITS_DICT["backDark"] shade = BLITS_DICT["shade"] menuButton = BLITS_DICT["menuButton"] screen.blit(bg, (0, 0)) font = pygame.font.Font('freesansbold.ttf', 20) text = font.render(...
The function animates a card being thrown from a player's starting position to a target location on the screen, updating the display in a loop. It adjusts player index for 2-player games, loads/scales the card image, blits it at incrementally calculated positions, and handles quit events. If 'toAppend' is 1, the card i...
def displayCardThrow(screen, card, game, playerIndex, blitDict, BLITS_DICT, toAppend): if card == 0: return if len(game.players) == 2 and playerIndex == 1: playerIndex = 2 playerIndex = str(playerIndex) posX = PLAYER_INDEX_TO_START_POS[playerIndex][0] posY = PLAYER_INDEX_TO_START_POS...
def getTableCoords(self): tableCoords = [] for key in TABLE_CARDS_START_POS: if key[0] == "0" or key[0] == "2": ht0 = 0 wd0 = 0 ht1 = CARD_HEIGHT wd1 = CARD_WIDTH elif key[0] == "1": ht0 = 0 ...
The main task of the code is to handle player interactions for selecting and throwing cards in a card game. It calculates card positions, processes mouse events for card selection, manages card throwing logic, updates the display dynamically, and handles special actions like setting optimal cards or placing cards on th...
def pickCard(self, game, screen, blitDict, BLITS_DICT): cardPos = [] length = len(self.cardsInHand) xStartPos = PLAYER_INDEX_TO_START_POS['0'][0] yStartPos = PLAYER_INDEX_TO_START_POS['0'][1] xEndPos = PLAYER_INDEX_TO_END_POS['0'][0] yEndPos = PLAYER_INDEX_TO_END_POS['0']...
def _load_model(self, path): if self.mode == 'multiclass': self.class_names = [ 'air_conditioner', 'car_horn', 'children_playing', 'dog_bark', 'drilling', 'engine_idling', 'gun_shot', ...
This code initializes a class for audio processing, setting up parameters like mode, model paths, and sound/image directories. It loads a pre-trained model and audio files if paths are provided, generates attention melspectrograms, and initializes a dataloader for processing sounds. The class likely handles tasks like ...
def __init__( self, mode='binary', path_to_model=None, path_to_sounds=None, path_to_images=None, ): self.mode = mode self.sounds_fnames = [] self.sounds = [] self.predicted_values = None self.predicted_probabilities = None...
def _load_sounds(self, path=None, to_append=False): if not path: raise ValueError('Nothing to load, please set path to sound files') if not isinstance(path, Path): try: path = Path(path) except: raise TypeError('path has to be str or Pa...
The function `load_sounds_segments` loads sound data from a specified path, optionally appending it to existing data. It then generates attention masks for mel-spectrograms and initializes a data loader for processing the loaded sounds. The core tasks involve loading audio files, creating attention mechanisms for model...
def load_sounds_segments(self, path, to_append=False): self._load_sounds(path, to_append=to_append) self._gen_attention_mels() self._init_dataloader()
def update_df(input_dfs, new_data, user_number, day_lim, expected_days): input_df_weekday = input_dfs[0] input_df_weekend = input_dfs[1] new_data_weekday = new_data[0] new_data_weekend = new_data[1] expected_days_weekday = expected_days[0] expected_days_weekend = expected_days[1] # proces...
The function processes user event data by aggregating app usage durations into time bins, separating weekday/weekend activity, applying Z-score normalization, and saving structured CSV outputs. It filters popular apps, groups data by users, tracks daily activity, and enforces user/day limits for efficient data analysis...
def process_data(input_file, output_file, time_gran=1440, pop_apps=(), weekdays_split=True, z_score=True, day_lim=7, selected_days=WEEKDAYS + WEEKENDS, user_lim=10000): # Read in the days to be selected - these are global variables since the need to be accessed elsewhere # Also verify that this...
def wholeQuery_simple(nodes,queries): for query in queries: nodes = singleQuery_simple(nodes,query) return nodes def parseQuery_simple(query): res = [] # sample: # query = "class//stundent/mark" # ['class', '//', 'stundent', '/', 'mark'] queryArray = re.sp...
This function evaluates a predicate against a node's value using comparison operators. It checks if the node is None or the predicate is whitespace, then parses the predicate to identify the operator and comparison value. It queries nodes based on the parsed predicate, compares the node's value with the extracted value...
def singlePredicate(node, predicate): # print(predicate) # node is None if node is None: return False # predicate is white space if len(predicate.strip()) < 1: return True # todo: Circumstance 1: position # Circumstance 2: evaluate value # identify operator dou...
def mover_email(): service = create_service() labels = get_etiqueta() resultado = service.users().messages().list(userId = 'me', labelIds= ['INBOX'], q = 'is:unread', maxResults = 1).execute() mensaje = resultado.get('messages', []) for id in mensaje: service.users().messages().modify(userId...
The main task of the code is to process classified emails by applying specific templates, updating Gmail labels, migrating data, and recording legal requests. It iterates through email data, checks classifications (e.g., 'Despido'), generates draft emails with predefined content, modifies email labels (marking as read ...
def main(): mover_email() service = create_service() data = clasificador() etiqueta = get_etiqueta() plantilla = consulta_plantilla() for i in range(len(data)): email = data[i] if email[5] == 'Despido': asunto = plantilla[0] cuerpo = plantilla[1] ...
def integration_const(initial): return np.log(initial/(1-initial)) def analytic_sol(x, beta, c): return np.exp(beta*x+c) / (1 + np.exp(beta*x+c)) def smooth(G, initial, threshold, T, M, beta = 0.6): smoothed = [] runs = [] for i in range(M): #print(str(round((i+1)*100/M, 1)) + '%') # display...
The code compares analytical and simulated results of an SI model by plotting both solutions against time. It generates an analytical solution using `analytic_sol` and a simulation via `smooth`, then visualizes them with labels and parameters in the title. The function returns the graph for analysis, highlighting diffe...
def comparison(G, params, name = 'Placeholder'): plt.figure() analytic_time = np.arange(0, params['Time'], params['Increment']) const = integration_const(params['Initial']) analytic_activity = analytic_sol(analytic_time, params['Beta'], const) plt.plot(analytic_time, analytic_activity, linewidth = 3...
def load_urdf(filename): # reads as URDF or XACRO depending on file name if filename.endswith('.urdf'): with open(filename) as f: return f.read() else: urdf = check_output(('xacro ' + filename).split(), encoding='UTF8') if urdf[0] == 'w': return check_output((...
(The function parses a URDF file to extract geometric parameters between specified base and end-effector frames. It identifies the kinematic chain, computes homogeneous transformation matrices for each joint, distinguishes prismatic/revolute joints, and returns transformation matrices, joint axes, types, and constants ...
def parse_urdf(filename, base_frame, ee_frame, use_joint_names = False): ''' Parse the URDF file to extract the geometrical parameters between given frames ''' robot = etree.fromstring(load_urdf(filename).encode()) # find all joints parents = [] children = [] all_joints = robot....
def working(): expander = st.expander("Working of genres page") expander.write("User Input : ") expander.info("""Three inputs are\n Multiple Genres can be selected Number of Movies to be recommended Threshold IMDB rating for filtering""") expander.write("Outputs : ") expander.info( ...
The main task of the code is to create a Streamlit interface where users select a movie genre, input the number of recommendations (5–20), and view sorted movie results. It displays an image, collects user input, retrieves sorted data via `run()`, and renders the results using `result()` if data exists.
def load_view(): working() st.title('Choose your favourite Genre') col1, col2 = st.columns(2) with col1: st.image("assets/images/genre.jpg") with col2: no_of_reco = st.number_input( 'Number of movies:', min_value=5, max_value=20, step=1) sorted_table = run(no_o...
def hash_image(image_filepath): ''' Generate a unique identifier of an image. :param filepath_to_image: filepath to the image to be hashed :type filepath_to_image: str :return hash_of_image: a sha256 hash of the image :rtype hash_of_image: str ''' image = Image.open(image_filepath...
The main task of the code is to store facial features of an image in a pickle file. It generates a unique image hash, extracts facial embeddings and skin tones if the image hasn't been processed, updates a dictionary with these features, and saves the dictionary to the specified pickle file. The function ensures each i...
def store_face_features_single(pickle_filepath, image_filepath): ''' Store the facial features in the image at the given filepath. :param pickle_filepath: filepath to the pickle file that stores the facial features :type pickle_filepath: str :param image_filepath: filepath to an image that...
def delete_face_features(pickle_filepath, image_directory): ''' Delete all the face features in the `pickle_filepath` but not in the `image_directory`. ''' # if pickle file not found, return None if not os.path.exists(pickle_filepath): return None # store image hashes of image ...
The function identifies the top N most similar faces to a target image by comparing facial embeddings stored in a pickle file, returning their filepaths and similarity scores. It processes image features, calculates similarity scores, and sorts results in descending order, truncating to the specified top N entries.
def get_top_similar_faces(image_filepath, pickle_filepath, image_directory, top_n=5): ''' Obtain the top few most similar faces :return most_similar_faces: the filepaths and similarity scores of the most similar faces :rtype most_similar_faces: list of dict ''' most_similar_faces = [] ...
def delete_face_features(pickle_filepath, image_directory): ''' Delete all the face features in the `pickle_filepath` but not in the `image_directory`. ''' # if pickle file not found, return None if not os.path.exists(pickle_filepath): return None # store image hashes of image ...
The function identifies the top N most similar skins to a target image by comparing skin tone features extracted from preprocessed images. It calculates similarity scores between the target's skin tones and those of other images, then returns a sorted list of the most similar skins with their scores and filepaths.
def get_top_similar_skins(image_filepath, pickle_filepath, image_directory, top_n=5): ''' Obtain the top few most similar skins :return most_similar_faces: the filepaths and similarity scores of the most similar skins :rtype most_similar_faces: list of dict ''' most_similar_faces = [] ...
def preprocess_page(self): try: self.set_main_div() try: self.set_artist_and_record_name() except Exception as e: logger.error(f" --> Couldn't get tags_and_date_field\n{e}") try: self.set_section() ...
This code initializes an object to parse and extract data from a webpage URL. It sets up attributes for parsing, processes the page, assigns extracted data (like artist, record details, tags), removes unnecessary attributes, and prepares the object's dictionary for database storage or further processing.
def __init__(self, page_url): # parameter needed to init object self.page_url = page_url # parameters usefull to build object (will be removed after remove_unwanted_attributes() ) self.main_div = None self.artist_and_record_name = None self.tags_and_date_field = None ...
def get_dataset(self, name): for dataset in self.get_datasets(): if dataset['id'] == name: return dataset raise Exception(f'No such dataset {name}') def _get_evalscript_and_defaults_from_dataset(self, dataset, bands, wavelengths, transparent, visual): if wavelengths: ...
This function retrieves an evaluation script and default parameters for a specified layer. It attempts to fetch data from a dataset, then a BYOD collection, and finally a layer configuration, returning the corresponding script and defaults based on the available source.
def get_evalscript_and_defaults(self, layer_name, style_name=None, bands=None, wavelengths=None, transparent=False, visual=True): try: dataset = self.get_dataset(layer_name) except: pass else: return self._get_evalscript_and...
def RewardFunction(self): if self.kind == "DSR": self.set_action_space() self.calculate_action_returns() for i in range(1, self.trading_periods,1): self.DSR[i] = self.DifferentialSR(decay=0.5,t=i) self.dDSRdR[i] = self.calc_dDSRdR(decay=0.5,t=i...
The code implements an experience replay mechanism for optimizing a DSR (Dynamic Stochastic Reward) algorithm. It iterates over epochs, updating weights based on reward calculations, tracking optimal DSR values, and logging progress. The method simulates trading data, transfers learned weights to real data, and handles...
def ExperienceReplay(self): pre_epoch_times = len(self.epoch_training) self.optimised_weight = self.w.copy() self.RewardFunction() logging.info("INFO: Epoch loop start. Intial DSR: {}".format(str(self.DSR[-1]))) if self.kind == "DSR": self.optimised_Reward = self.DSR[...
def adversarial_loss(self, y, y_hat): return -torch.mean((y)) + torch.mean((y_hat)) def mse1(x,y): s = y; t = x.shape[2] s_hat = 0 for i in range(t): s_hat += spec(x[:,:,i])[1]/t if x.is_cuda: s_hat = s_hat.cuda(x.device.index) s = s.cuda(x.device.index) return to...
This code defines a training step for a neural network with multiple optimizers, handling different components like discriminators (D, D_time, D_norm) and a generator (netG). It computes adversarial losses, gradient penalties, and mean squared errors (MSE) for generated fields, incorporating stream vorticity when enabl...
def training_step(self, batch, batch_nb, optimizer_idx): real_field = batch self.s1 = self.s1.type_as(real_field) self.s2 = self.s2.type_as(real_field) t = real_field.shape[2] if not self.hparams.nv: omega = stream_vorticity(real_field[:,:,0]).type_as(real_field[:,:,0])...
def get_data(): X = pd.read_csv('X.csv', header = None, prefix = 'X') Y = pd.read_csv('Y.csv', names = ['Y']) return X, Y def group_data(Y): # copy raw data df = Y.copy() # separate data into 10 groups, only store index group_size = df.shape[0]//10 group = [] for i in range(10):...
The code's main task is to organize data processing and problem-solving steps for a machine learning task. It reads input data, groups labels, and prepares for multiple subtasks (a-f). However, most problem-specific functions (a-d, e-f) are commented out, leaving only the call to `problem_c()` executed. The code includ...
def main(): # read data X, Y = get_data() # grouping list group = group_data(Y) # problem a print('Problem a') #lambda_0, lambda_1 = problem_a(X,Y,group) # problem b print('Problem b\n') #problem_b(lambda_0, lambda_1) # problem c print('Problem c\n') problem_c(X, Y, g...
def _get_python_api_config(config_file=None): if config_file: # 1. Try argument, if any return _read_config(config_file) try: # 2. Try Python import machinery import jpyconfig return jpyconfig except ImportError: # 3. Try 'JPY_PY_CONFIG' environment variabl...
The function `init_jvm` configures and initializes a Java Virtual Machine (JVM) for use with the `jpy` library. It accepts parameters to specify JVM settings like memory limits, classpath, system properties, and options. If no JVM is already running, it constructs the JVM using provided or default configurations, loads...
def init_jvm(java_home=None, jvm_dll=None, jvm_maxmem=None, jvm_classpath=None, jvm_properties=None, jvm_options=None, config_file=None, config=None): """ Creates a configured Java virtual machine which will be used by jp...
def validate_clients_request(self, content, request_type: str): """ Called by the method self.check_datatype_valid(self, entity_name, content, request_type: str) Used to validate request body for clients entity route Data validation depends on the request_type POST: Requires ...
This function validates data based on the entity name and request type by calling specific validation methods. It checks if the entity is "clients", "projects", or "team_members", then invokes the corresponding validation function (e.g., validate_clients_request) with the provided content and request type. It returns T...
def check_datatype_valid(self, entity_name, content, request_type: str): """ Calls data validation methods depending on the respective entity_name and request type [1] self.validate_clients_request(content, request_type) [2] self.validate_projects_request(content, request_type) ...
def create_cache(path=None): if path: with open(path, 'rb') as f: cap_cache_dict = pickle.load(f) Cnt_empty = sum([v==None for k, v in cap_cache_dict.items()]) print(Cnt_empty) manager = Manager() shared_dict = manager.dict(cap_cache_dict) else: ...
The main task of the code is to evaluate a machine learning model on multiple datasets using test-time adaptation, with support for few-shot learning scenarios. It handles model configuration, caching of results, normalization of data, and saving evaluation outcomes in CSV format for analysis. The code dynamically adju...
def main_worker(gpu, args): args.gpu = gpu set_random_seed(args.seed) print("Use GPU: {} for training".format(args.gpu)) # load model if args.test_sets in fewshot_datasets: classnames = eval("{}_classes".format(args.test_sets.lower())) print('=> Using native Torch AMP. Training in m...
def create_socket(): try: global host, port, server host = str(sys.argv[1]) port = int(sys.argv[2]) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setblocking(0) except socket.error as message: print("Socket Creation Error: " + str(message)) ...
The main task of the code is to set up a socket server by creating and binding a socket, then using `SELECT()` to monitor and manage incoming network connections. This enables the server to handle multiple client requests concurrently through I/O multiplexing, ensuring efficient communication and responsiveness.
def main(): create_socket() bind_socket() SELECT()
def create_socket(): try: global host, port, server host = str(sys.argv[1]) port = int(sys.argv[2]) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setblocking(0) except socket.error as message: print("Socket Creation Error: " + str(message)) ...
The main task of the code is to create and bind a socket, then use the SELECT system call for I/O multiplexing to monitor and manage network connections efficiently.
def main(): create_socket() bind_socket() SELECT()
def create_socket(): try: global host global port global s host = str(sys.argv[1]) port = int(sys.argv[2]) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as message: print("Socket Creation Error: " + str(m...
The main task of the code is to create and bind a socket, then continuously accept incoming connections in an infinite loop. The `create_socket()` and `bind_socket()` functions initialize the server socket, while the `while 1:` loop with `socket_accept()` waits for and handles client connections indefinitely.
def main(): create_socket() bind_socket() while 1: socket_accept()
def rgb2K(r, g, b): rMap = remap(r, 0, 255, 0, 1) gMap = remap(g, 0, 255, 0, 1) bMap = remap(b, 0, 255, 0, 1) return (1 - max(rMap, gMap, bMap)) def rgb2CMY(r, g, b): # px = (1-0.686275-0.098039)/(1-0.098039) = 0.23913 K = rgb2K(r, g, b) # print(K) rMap = remap(r, 0, 255, 0.0, 1) gMa...
The function `pxOnlyCyan` extracts and isolates the cyan color channel from an input RGB color. It converts the RGB values to CMY (Cyan, Magenta, Yellow) and sets the Magenta and Yellow components to zero, retaining only the Cyan channel. The result is then converted back to RGB using the K (black) component derived ea...
def pxOnlyCyan(src): K = rgb2K(src.red(), src.green(), src.blue()) c, m, y = rgb2CMY(src.red(), src.green(), src.blue()) # print(c) # Representasikan channel c nya saja r, g, b = cmy2RGB(c, 0, 0, K) # print((r, g, b)) return QColor(r, g, b)
def rgb2K(r, g, b): rMap = remap(r, 0, 255, 0, 1) gMap = remap(g, 0, 255, 0, 1) bMap = remap(b, 0, 255, 0, 1) return (1 - max(rMap, gMap, bMap)) def rgb2CMY(r, g, b): # px = (1-0.686275-0.098039)/(1-0.098039) = 0.23913 K = rgb2K(r, g, b) # print(K) rMap = remap(r, 0, 255, 0.0, 1) gMa...
The function isolates the magenta color channel from an input RGB color. It converts the RGB values to CMY (cyan, magenta, yellow) and K (black) components, then sets the cyan and yellow components to zero, retaining only the magenta component. Finally, it converts the modified CMY values back to RGB and returns the re...
def pxOnlyMagenta(src): K = rgb2K(src.red(), src.green(), src.blue()) c, m, y = rgb2CMY(src.red(), src.green(), src.blue()) # Representasikan channel c nya saja r, g, b = cmy2RGB(0, m, 0, K) return QColor(r, g, b)
def rgb2K(r, g, b): rMap = remap(r, 0, 255, 0, 1) gMap = remap(g, 0, 255, 0, 1) bMap = remap(b, 0, 255, 0, 1) return (1 - max(rMap, gMap, bMap)) def rgb2CMY(r, g, b): # px = (1-0.686275-0.098039)/(1-0.098039) = 0.23913 K = rgb2K(r, g, b) # print(K) rMap = remap(r, 0, 255, 0.0, 1) gMa...
The function converts an input RGB color to CMYK, isolates the yellow (Y) component by setting cyan (C) and magenta (M) to zero, then converts back to RGB using the black (K) component. It returns a QColor representing the isolated yellow component with adjusted black balance.
def pxOnlyYellow(src): K = rgb2K(src.red(), src.green(), src.blue()) c, m, y = rgb2CMY(src.red(), src.green(), src.blue()) # Representasikan channel c nya saja r, g, b = cmy2RGB(0, 0, y, K) return QColor(r, g, b)
def refine(list): teams2 = [] for i in list: if i not in teams2 and list.count(i) > 1: teams2.append(i) return teams2 def synergyBuild(requiredMon, list, dimension, count): if dimension < count: reqMonWeak = getWeak(requiredMon) for mon in names: temp = g...
This code generates a Pokémon team by selecting top-performing mons based on their Base Stat Total (BST), adjusting team composition using parameters like 'slide' and 'count', and formatting the final team with items, abilities, EVs, and moves into a structured string for output.
def getTeam(requiredMon, slide, count): if count.get() == 0: counter = 1 else: counter = 6 - ((math.floor(math.floor(count.get() - 100) / 50)) + 1) teams2 = refine(synergyBuild(requiredMon, [], 0, counter)) totals = [] for mon in teams2: bst = 0 for i in getStats(m...
def init_hidden(self, bsz): weight = next(self.parameters()) return (weight.new_zeros(self.num_layers, bsz, self.rnn_size), weight.new_zeros(self.num_layers, bsz, self.rnn_size)) def _prepare_feature(self, fc_feats, att_feats, att_masks): att_feats, att_masks = self.clip_att(att_...
The main task of the code is to generate sequence outputs (log probabilities) for each time step using features from a pre-trained model, incorporating attention mechanisms. It processes input features, initializes hidden states, and iteratively computes outputs while applying stochastic sampling during training to enh...
def _forward(self, fc_feats, att_feats, seq, att_masks=None): batch_size = fc_feats.size(0) state = self.init_hidden(batch_size) outputs = fc_feats.new_zeros(batch_size, seq.size(1) - 1, self.vocab_size+1) # pdb.set_trace() # Prepare the features p_fc_f...
def _prepare_feature(self, fc_feats, att_feats, att_masks): att_feats, att_masks = self.clip_att(att_feats, att_masks) # embed fc and att feats fc_feats = self.fc_embed(fc_feats) att_feats = pack_wrapper(self.att_embed, att_feats, att_masks) # Project the atten...
The function `_sample_beam` performs beam search to generate sequences (e.g., captions) from input features (`fc_feats`, `att_feats`). It initializes states, prepares features, and iterates through the batch to apply beam search for each image. The beam size (default 10) determines the number of candidate sequences exp...
def _sample_beam(self, fc_feats, att_feats, att_masks=None, opt={}): beam_size = opt.get('beam_size', 10) batch_size = fc_feats.size(0) p_fc_feats, p_att_feats, pp_att_feats, p_att_masks = self._prepare_feature(fc_feats, att_feats, att_masks) assert beam_size <= self.vocab_size + 1, 'l...
def _sample_beam(self, fc_feats, att_feats, att_masks=None, opt={}): beam_size = opt.get('beam_size', 10) batch_size = fc_feats.size(0) p_fc_feats, p_att_feats, pp_att_feats, p_att_masks = self._prepare_feature(fc_feats, att_feats, att_masks) assert beam_size <= self.vocab_size + 1, 'l...
The code generates sequences (e.g., captions) using either beam search (for beam_size > 1) or greedy/sampled decoding (based on temperature). It processes input features (fc_feats, att_feats) and iteratively predicts tokens, applying decoding constraints to avoid repetition. Outputs include generated sequences and thei...
def _sample(self, fc_feats, att_feats, att_masks=None, opt={}): # pdb.set_trace() sample_max = opt.get('sample_max', 1) beam_size = opt.get('beam_size', 1) temperature = opt.get('temperature', 1.0) decoding_constraint = opt.get('decoding_constraint', 0) if beam_size > 1: ...
def init_IRC(channel_name): server = 'irc.chat.twitch.tv' port = 6667 channel = '#' + channel_name sock = socket.socket() sock.connect((server,port)) sock.send(f"PASS {settings.token}\n".encode('utf-8')) sock.send(f"NICK {settings.username}\n".encode('utf-8')) sock.send(f"JOIN {channel}...
The main task of the code is to monitor chat activity in an IRC channel by continuously retrieving messages, calculating the average activity per cycle, and determining whether to trigger a clip (e.g., recording or alert) based on the average message count. It prints real-time metrics like the average activity and mess...
def main(channel_name): sock = init_IRC(channel_name) while True: cur_cycle_messages = get_messages(cycle_time, sock) chat_activity_avg = update_avg(cur_cycle_messages) print("Chat avg.: ", chat_activity_avg) print("Amount of messages in current cycle: ", len(cur_cycle_me...
def handle_login(browser, username, password, cookie_path): cookie_file_exists = os.path.isfile(cookie_path) #If we have cookies saved, use them to login if cookie_file_exists: load_cookie(browser, cookie_path) browser.refresh() check_for_mature_filter(browser, cookie_path) #else...
This function automates creating a Twitch clip by logging into a specified channel, generating a clip with given title and duration, submitting it, and saving the clip link. It uses Selenium to control a browser, handles login credentials, waits for ads, and records the clip's timestamp and URL for later use.
def create_twitch_clip(username, password, clip_length_in_seconds, channel = 'greekgodx', clip_title="title:)", clip_link_path = './clip_links.txt', driver_path="webdrivers/chromedriver", cookie_path = './cookies.txt'): #start time to compensate for time difference between the method is called and the clip is saved...
def calculate_M_Tau(self, x, y=None): # Given a folder which contains videos # calculate the MHI for each video # return a tuple of 2 elements: # data: a list of np.arrays # video_label: a list of strings containing video's name data = [] video_label = [] ...
The main task of the code is to preprocess training data by calculating motion and Hu moments, scaling features, and storing processed data for model training. It loads input data, extracts labels, computes statistical features, applies scaling, and saves transformed features for later use in training machine learning ...
def add_training_data(self,x_train, y_train): # add data into the class for later training (if needed) # filled in the scaler. print('loading data...') self.trainData, self.trainVideoLabel = self.calculate_M_Tau(x_train, y_train) self.trainLabel = [i[2] for i in pd.Series(self.t...
def calculate_M_Tau(self, x, y=None): # Given a folder which contains videos # calculate the MHI for each video # return a tuple of 2 elements: # data: a list of np.arrays # video_label: a list of strings containing video's name data = [] video_label = [] ...
The code performs prediction using a machine learning model by preprocessing test data, extracting moments and Hu moments as features, scaling them, and generating predictions. It groups results by video, comparing predicted labels with actual labels if provided, and returns aggregated predictions per video.
def predict(self, learner, x_test, y_test = None): # Make predictions based on a given learner and the test set print('preprocessing the test data...') self.testData, self.testVideoLabel = self.calculate_M_Tau(x_test, y_test) self.testLabel = [i[2] for i in pd.Series(self.testVideoLabe...
def handle_setup_scene(self): # Display "Start Game" button self.display_button("Start Game", self.screen.get_width() // 2 - self.BUTTON_WIDTH // 2, self.screen.get_height() // 2, self.BUTTON_WIDTH, self.BUTTON_HEIGHT, self.GREEN, self.DARKGREEN, self.start_game) def handle_in_game_scene(self, current_player): ...
This code runs a game loop using Pygame, handling different scenes (setup, in-game, game over) by updating the screen, processing events, and managing game state transitions. It initializes the game, limits frame rate to 60 FPS, and quits when the user closes the window.
def run_game(self, game): self.game = game clock = pygame.time.Clock() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Handle events based on current scene if self.current_scene == "setup": self.s...
def create_widgets(self): tensor_shape = self.tensor1.shape for i in range(len(tensor_shape)): checkbox = QCheckBox(f"Dimension {i}") checkbox.stateChanged.connect(lambda state, checkbox=checkbox: self.checkbox_changed(checkbox)) self.checkboxes.append(checkb...
The code initializes a GUI window for visualizing multidimensional heatmaps by setting up tensors, interactive controls (checkboxes, dropdowns), and a canvas. It configures layouts, connects UI elements to update heatmap visuals and statistics, and enables dynamic adjustments for error types, color schemes, and dimensi...
def __init__(self, tensor1, tensor2): super().__init__() self.setWindowTitle("Multidimensional Heatmap Window") self.tensor1 = tensor1 self.tensor2 = tensor2 self.errors_dict = {} self.tensor1_2d = None self.tensor2_2d = None self.checkboxes = [] ...
def updateResult(self): row = self.row_input.text() col = self.col_input.text() view_size = (int(row), int(col)) return view_size def divide_tensor(tensor_size, tile_size): rows, cols = tensor_size tile_rows, tile_cols = tile_size num_rows = rows // tile_rows num_col...
The main task of the code is to handle the "Graph View" button click by dividing a tensor into tiles based on selected view sizes, updating a combo box with tile information, and connecting UI events to update statistics and draw histograms. It retrieves tensor shapes, generates tile descriptions, populates a dropdown ...
def graph_view_button_clicked(self): try: view_size = self.updateResult() self.tiles= divide_tensor(self.errors_dict[self.dropdown.currentText()].shape, view_size) view_list = [] for i in range(len(self.tiles)): view_list.append(f"Tile...
def delayPrint(string): # print one character in a specific time interval for char in string: sys.stdout.write(char) sys.stdout.flush() time.sleep(5e-2) def pokemonDesc(self): return f'{self.name}\n' \ f'TYPE/ {self.type}\n' \ f'ATTACK/ {self.attack}...
This code simulates a Pokémon battle between two entities. It prints battle details, applies type-based bonuses, and alternates turns for attacks. The loop continues until one Pokémon faints, with the winner receiving random Stardust as a reward.
def pokemonFight(self, enemy): # Print the information delayPrint('\n\tPOKEMON BATTLE\n\n') delayPrint(self.pokemonDesc()) delayPrint(enemy.pokemonDesc()) self.setPokemonBonusForType(enemy) self.setSkillEnergyRatio() time.sleep(2) while len(self.health)...
def show_all_rates(self): if self.all_rates is not None: print(f"\nCurrency rates for entire {self.table.upper()} table:") show_json_dict(self.all_rates[0]['rates']) def show_currency_rates(self): if self.currency_rates is not None: print(f"\n\nRate of {self.currency_...
The code's main task is to display all exchange rates, currency rates, and optionally the gold price if the 'gold' attribute is True. It sequentially calls methods to show all rates, specific currency rates, and conditionally the gold price based on the 'gold' flag.
def describe(self): self.show_all_rates() self.show_currency_rates() if self.gold: self.show_gold_price()
def inputValidation(user_input): while True: if user_input.isdigit() and int(user_input) in (1, 2): return int(user_input) else: print('Your enter should be an integer: either 1 or 2') def getAge(): while True: age = input('Please enter your age:\n') if ag...
The code determines a user's age by either directly inputting it if known or calculating it from their birthdate. It prompts the user to choose between knowing their age or providing their date of birth, validates input, and returns the computed age using helper functions for data collection and calculation.
def userDefinedAge(): print('Do you know your age?\n1) Yes\n2) No') user_input = input('Enter 1 or 2 to proceed further.\n') age = 0 if inputValidation(user_input) == 1: print("Your answer is 'Yes'") age = getAge() elif inputValidation(user_input) == 2: print("Your answer is ...
def userDefinedSex(): while True: user_input = str(input('Please enter your gender: \n(F)emale\n(M)ale\n')).replace(' ', '') if user_input.lower() == 'f': return 'Female' elif user_input.lower() == 'm': return 'Male' else: print("You've entered inc...
The main task of the code is to calculate and display a person's Basal Metabolic Rate (BMR) and Total Daily Energy Expenditure (TDEE) by collecting user-defined attributes like sex, age, weight, height, and activity level. It sets these parameters on the person object, prints their descriptions, and outputs the compute...
def dailyEnergyExpenditure(person): person.sex = userDefinedSex() print(person.sex_desc) person.age = userDefinedAge() print(person.age_desc) person.weight = userDefinedWeight() print(person.weight_desc) person.height = userDefinedHeight() print(person.height_desc) person.activit...
def get_full_path(input_str): return Path(input_str).expanduser().resolve() def evaluate_dir_path(base_dir, exts): """ Scan folder and all subfolders for packed EXE, etc. files. """ # Putting the glob generator directly in the for-loop allows real-time file # checking. Otherwise, all the files have to...
The main task of the code is to detect if EXE or similar files are "packed" with extra data, potentially indicating corruption or viral infection. It processes command-line arguments to check files, recursively scan directories, display Portable Executable metadata, or delete flagged files. The script uses argparse for...
def main(): description = "Quickly determine if EXE or other similar file has been \"packed\" with extra data; i.e. it has been corrupted by a virus." parser = argparse.ArgumentParser( description=description, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argumen...
def get_all_options(self): """Fetch all options via inquirer or cfg""" prev_options = {} if os.path.exists(CONFIG_FILE): with open(CONFIG_FILE, "r", encoding="utf-8") as config_fh: prev_options = json.loads(config_fh.read()) confirm = inquirer.confirm( ...
The code initializes an object's attributes by retrieving all options, loading playlists, initializing a play queue, and obtaining a client instance, preparing the object for operation.
def setup(self): self.options = self.get_all_options() self.playlists = self.load_playlists() self.play_queue = self.init_play_queue() self.client = self.get_client()
def setup_dir(dir_name): dir_path = os.path.join(main_dir, local_dir_name, 'SubjectsHTML') if not os.path.exists(dir_path): print('Could not locate data directory, creating one now...\n') os.makedirs(dir_path) print('Located subject data directory\n') return dir_path def get_subject_co...
This function gathers subject pages from a specified URL, using a session to retrieve subject codes and corresponding pages. It handles directory setup, partitions subjects based on the test_partition_length parameter, and returns collected pages while managing session state and file paths.
def subject_pages(given_url = None, dir_name = None, test_partition_length = -1): print('Initiating Session...') global s s = requests.session() global url url = given_url if given_url is not None else default_url global local_dir_name local_dir_name = dir_name if dir_name is not None else...
def _get_headers(self, current_time, params): """ This function is used to get headers for requests to be signed using AWS Signature Version 4. :param current_time: Current timestamp at time of making request :param params: Request URL params return: Headers generated by following AWS I...
This function makes a REST API call to an AWS IAM server, handling parameters, authentication, and error checking. It sorts parameters alphabetically for AWS signature compatibility, executes the request using the specified HTTP method, and returns processed results or errors.
def _make_rest_call(self, action_result, params=None, data=None, method='get', timeout=None): """ This function is used to make the REST call. :param action_result: Object of ActionResult class :param params: Request parameters :param data: Request body :param method: GET/POST/P...
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
The main task of the code is to assign an AWS IAM policy to a specified user by making an API call. It retrieves parameters like username and policy ARN, prepares them for a REST request to attach the policy, handles temporary credentials validation, processes the API response, and returns success/failure status based ...
def _handle_assign_policy(self, param): """ This function is used to assign the policy to specified user. :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.__save_action_handler_progress() action_result = self.a...
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
This function removes an AWS IAM policy from a specified user by making a REST API call. It validates temporary credentials, constructs parameters with the username and policy ARN, detaches the policy via AWS's endpoint, and returns success/failure status based on the API response.
def _handle_remove_policy(self, param): """ This function is used to remove the policy from specified user. :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.__save_action_handler_progress() action_result = self...
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
The main task of the code is to remove a specified AWS IAM user from a group by making a REST API call using parameters like username and group name. It checks for temporary credentials, executes the removal, and returns success/failure status with progress updates.
def _handle_remove_user(self, param): """ This function is used to remove user from the specified group. :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.__save_action_handler_progress() action_result =...
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
The main task of the code is to add a user to a specified AWS IAM group by making a REST API call using provided parameters. It validates temporary credentials, constructs the API request, executes the call, and returns success/failure status along with response metadata. The function also logs progress and formats a s...
def _handle_add_user(self, param): """ This function is used to add user to the specified group. :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.__save_action_handler_progress() action_result = self.ad...
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
This function detaches a specified AWS IAM policy from a role using REST calls. It validates temporary credentials, checks if the role exists, and if valid, sends a request to detach the policy. It returns success/failure status based on execution, with error handling for missing roles or API failures.
def _handle_detach_policy(self, param): """ This function is used to detach the policy from specified role :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.__save_action_handler_progress() action_result = self....
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
This function attaches an IAM policy to a specified role by validating temporary credentials, checking role existence, making a REST API call to AWS, and returning success or error status based on the operation's outcome.
def _handle_attach_policy(self, param): """ This function is used to attach the policy to specified role. :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.__save_action_handler_progress() action_result = self.a...
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
This function adds an IAM role to an AWS account by creating a role with a specified policy document, validating parameters, checking for existing roles/profiles, and attaching an instance profile. It trims JSON spaces, validates paths, and returns success/failure status via REST API calls.
def _handle_add_role(self, param): """ This function is used to add the role to AWS account. :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.__save_action_handler_progress() action_result = self.add_action_res...
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
This function disables an AWS IAM user's login profile and access keys. It first disables the user via a REST call, handles 404 errors if the login profile doesn't exist, then inactivates all access keys if specified. It uses temporary credentials, lists access keys, and updates their status to inactive. The task invol...
def _handle_disable_user(self, param): """ This function is used to disable the login profile and access keys of user. :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.__save_action_handler_progress() action_re...
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
This function enables an AWS IAM user's login profile and optionally activates their access keys. It checks temporary credentials, makes REST API calls to enable the user, handles errors for existing profiles, lists access keys if enabled, and activates them. The result is stored, and a success status is returned with ...
def _handle_enable_user(self, param): """ This function is used to enable the login profile and access keys of user. :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.__save_action_handler_progress() action_resu...
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
The main task of the code is to remove a specified AWS IAM role by first detaching all associated instance profiles and policies, then deleting the role itself. It checks if the role exists, ensures temporary credentials are provided, and executes REST calls to detach and delete resources, returning success or error st...
def _handle_remove_role(self, param): """ This function is used to remove the managed role from AWS account. :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.__save_action_handler_progress() action_result = sel...
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
The function deletes an AWS IAM user and all associated resources, including their login profile, attached policies, group memberships, and access keys. It performs this by making REST API calls to detach policies, remove group associations, delete access keys, and finally delete the user. Error handling ensures proper...
def _handle_delete_user(self, param): """ This function is used to delete the user and all associations with login profile, polices, roles, groups, and access keys for the same user. :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) ...
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
The main task of the code is to retrieve and compile details of user groups and attached policies for a specified AWS IAM user. It uses temporary credentials, fetches group and policy data via API calls, organizes the results, updates a summary with counts, and returns a success status. The function ensures progress tr...
def _handle_get_user(self, param): """ This function is used to fetch entire details for user groups and attached policies to the user. :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.__save_action_handler_progress() ...
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
The function fetches AWS account groups based on the provided group path parameter, validates the path format, retrieves group data using temporary credentials, processes the response, and returns success/failure status. It checks for valid credentials, ensures proper path formatting, collects group details, updates th...
def _handle_list_groups(self, param): """ This function is used to fetch groups of an AWS account :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ group_path = param.get(AWSIAM_PARAM_GROUP_PATH, '/') self.__save_ac...
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
This function fetches AWS IAM users based on user_path or group_name parameters, validates input, retrieves user data via API endpoints, and returns success/failure status with user details. It handles temporary credentials, constructs request parameters, validates paths, and populates action results with user listings...
def _handle_list_users(self, param): """ This function is used to fetch users of an AWS account based on user_path and group_name. :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.__save_action_handler_progress() ...
def __save_action_handler_progress(self): self.save_progress(f'In action handler for: {self.get_action_identifier()}') def _get_temp_credentials(self, action_result, param=None): temp_credentials = dict() if param and 'credentials' in param: try: temp_credentials = as...
This function retrieves AWS IAM roles using provided temporary credentials, processes the response data, and returns the list of roles along with a success status. It checks for valid credentials, fetches roles via an API call, formats the response, updates the summary with the total role count, and ensures proper prog...
def _handle_list_roles(self, param): """ This function is used to fetch roles of an AWS account. :param param: Dictionary of input parameters :return: Status(phantom.APP_SUCCESS/phantom.APP_ERROR) """ self.__save_action_handler_progress() action_result = self.add_action...
def get_y(q, g, R): return(Q(q).T @ g + np.random.multivariate_normal(mean=np.zeros(3), cov=R).reshape(-1, 1)) def quat_normalize(q): s = np.sign(q[0]) quat_norm = np.linalg.norm(q) return(np.array([s * q[i] / quat_norm for i in range(4)])) def get_q(q, w, Q): return(A(w) @ q) def F_x(w): return(A(w)) def F...
This code implements a Kalman filter for orientation estimation using IMU data. It initializes parameters, iterates through prediction-correction steps to estimate orientation (quaternion), and compares true vs filtered values. The filter uses covariance matrices, quaternion normalization, and saves plots of each orien...
def main(): images_root = 'imgs/{}' iters_num = 120 sigma = 0.021 mu = 0.04 p_sigma = 0.01 g = np.array([0,0,9.81]).reshape(3, 1) #* Cov matrix for moving noize Q_values = np.eye(3, 3) * pow(mu, 2) #* Cov matrix for obs R_obs = np.eye(3, 3) * pow(sigma, 2) #* Initia...
def getWordListByLanguage(choice: languageChoice): with open(choice, 'r', encoding='utf-8') as file: word_list = [] words = file.readlines() for word in words: word_list.append(word[:5]) return word_list def chooseLanguage(): choice = str(input("Choose what language you ...
The code implements a word guessing game where the user has 6 attempts to guess a selected word. It retrieves a word list based on the chosen language, randomly or manually selects a target word, and checks each attempt. If correct, it declares a win; if all attempts fail, it reveals the answer and declares a loss.
def round(): word_list = getWordListByLanguage(chooseLanguage()) attempts = [] if isRandomWord(): answer = randomWord(word_list) else: answer = chooseWord(word_list) for round in range(6): if attempt(answer, attempts, word_list): print("You won!") ...
def adjacency(pos, navigation_map): adjacent = [] for i in range(-1, 2): y = pos[0] + i for j in range(-1, 2): x = pos[1] + j if (i or j) and is_navigable(y, x, navigation_map): adjacent.append((y, x)) return adjacent def matrix(value): """Initiali...
This code implements a pathfinding algorithm using a modified Dijkstra's approach with a priority queue. It finds the shortest path from a start position to a goal on a navigation map by exploring adjacent nodes, updating costs, and backtracking through parent pointers once the goal is reached.
def run(start, goal, navigation_map): goals = adjacency(goal, navigation_map) closed = set() opened = {start} parents = matrix(None) cost = matrix(1e9) cost[start[0]][start[1]] = 0 score = [(distance(start, goal), start)] # list of (score, position) tuples while opened: _, cur...
def forward(Rover): Rover.throttle = min(Rover.max_vel - Rover.vel, Rover.throttle_set) Rover.brake = 0 def angle_diff(a, b): return (a - b + 180 + 360) % 360 - 180 def rotate_to_angle(Rover, a): Rover.throttle = 0 if Rover.vel > 0.2: Rover.brake = 1 else: Rover.brake = 0 ...
This function controls a rover's navigation and decision-making. It handles path tracing, obstacle avoidance, stuck recovery, sample collection, and alignment. It decrements path frames, checks if the rover is near a sample or home, applies stuck recovery logic, adjusts steering for rocks, and follows paths or walls. I...
def decision_step(Rover): global aligning global target_yaw global frames_to_path_trace global stuck frames_to_path_trace -= 1 going_home = Rover.samples_found == Rover.samples_to_find - 1 if going_home: if a_star.distance(Rover.pos, Rover.start_pos) < 10: print("Done")...
def makeBlock(self, key): node = self.iNodeD[key] return self.makeBlockWithInslots(key, node.state.locals, node.state.stack) def _addOnException(self, block, fallthrough, outslot_norm): parent = self.parent assert block.throwvars and block.chpairs is not None ephi = ssa_ops.Excep...
This function manages block transitions in a control flow graph by creating or reusing a block associated with the given key. It handles exceptions or direct jumps from the current block to the new block, merges slot information, and updates the current block/state to the new block.
def _startNewBlock(self, key): ''' We can't continue appending to the current block, so start a new one (or use existing one at location) ''' # Make new block if key not in self.blockd: self.makeBlock(key) # Finish current block block = self.current_block cur...
def _chPairsAt(self, address): chpairs = [] for (start, end, handler, catchtype) in self.exceptionhandlers: if start <= address < end: chpairs.append((catchtype, handler)) return chpairs def toBits(x): return [i for i in range(x.bit_length()) if x & (1 << i)] def getE...
This function appends an instruction to a basic block, handling exception propagation and control flow. It updates the block's lines, jump targets, and exception variables. If the instruction terminates the block (e.g., RETURN, THROW, CheckCast), it adds an on-exception fallthrough. It merges output slots when jumps ex...
def _appendInstr(self, iNode, vals, outslot_norm, check_terminate=True): parent = self.parent block = self.current_block line, jump = vals.line, vals.jump if line is not None: block.lines.append(line) assert block.jump is None block.jump = jump if lin...
def getUsedLocals(iNodes, iNodeD, exceptions): # For every instruction, find which locals at that point may be used in the future except_ranges = [(h, [node.key for node in iNodes if s <= node.key < e]) for s, e, h, i in exceptions] old = collections.defaultdict(int) while 1: data = old.copy() ...
This code initializes a control flow graph for a method, setting up blocks, exception handlers, and SSA form. It processes visited nodes, tracks live variables, creates entry/return blocks, handles jumps, and ensures proper block structure for static analysis and optimization.
def __init__(self, parent, iNodes, inputTypes, returnTypes, except_raw, opts): self.parent = parent self.blocks = [] self.blockd = {} self.iNodes = [n for n in iNodes if n.visited] self.iNodeD = {n.key: n for n in self.iNodes} exceptions = [eh for eh in except_raw if eh....
def log(self, msg): self.event_log.append('"{0}"'.format(msg)) print(msg) def protect(self): if self.controllers['roof']['active'] is True: self.controllers['roof']['obj'].do_close() self.status_update() def unprotect(self): if self.controllers['roof']['active'] i...
This function processes a JSON command string by parsing it, checking for a 'protect' key, and executing 'protect' or 'unprotect' methods accordingly. It validates input, handles errors, updates system status, and sends MQTT messages if the command succeeds.
def process_cmd(self, json_cmd): cmd_success = False print('Received json command, will parse: {0}'.format(json_cmd)) try: jobj = json.loads(json_cmd) except: print("Invalid JSON:", json_cmd) return if 'cmd' in jobj: for c_key, ...
def _is_mbr_partition(self) -> bool: """Check if the beginning of the disk matches a MBR magic number Returns: True if it is a MBR partition table Raises: ValueError: If the disk size is 0 """ return self._read_int(0) == MBR_MAGIC def _get_partitions(sel...
The code reads an EWF file, checks for an MBR partition, exits if none is found, then retrieves partition information and identifies NTFS partitions for further processing.
def read_ewf(self): """Read the EWF file, and parse the partition tables""" if not self._is_mbr_partition(): print("[!] No MBR partition found, exiting...") exit(-1) print("[+] MBR partition found.") self._get_partitions() self._find_ntfs_partitions()
def analyze_mft(self, out_file: str): """Analyze the MFT Args: out_file: Where to store the output """ print("[?] Analyzing MFT") mft_entry_nb = -1 while True: mft_entry_nb += 1 mft_file = self.read_mft_entry(mft_entry_nb, verbose=F...
This function analyzes the NTFS header of a specified partition by loading or generating an MFT (Master File Table) dump file. It clears existing cache if instructed, processes the MFT data either freshly or from cache, and resolves the MFT into a JSON file for further analysis. The task involves handling file operatio...
def analyze_ntfs_header(self, partition_idx: str, resolve_mft_file: str, clear_cache): """Analyze the NTFS header Args: out_file: Where to store the output dump_file: Where the output has been stored in a previous run resolve_mft_file: Where the resolved MFT in JSON ...
def getEndingSunit(self): """ get all node in cfg that either: a return node (if that is void, return previous line) a node that direct to no """ res=[] for node in self.cfg.nodes: if self.cfg.out_degree(node)==0: if self.isIso...
The main task of the code is to compose a list of code lines by combining heuristic-based "sunit" elements (data and control units) through iterative deduplication and aggregation, then generating the final source code using `getNewBody` with the processed list.
def composeSunit(self): """ get compose first 3 sunit heuristic get data sunit from previous heuristic get control sunit from previous heuristic sort by code line in class return list of lines of code """ res=[] res+=self.getEndingSunit() r...
def _build_model(self, load_model_name: str = None, use_mlflow=True): if self.train_generator is None and load_model_name is None: raise ValueError( "Generator not found. Please fit the data first or load a model" ) if load_model_name: self.registered...
The main task of the code is to fit a machine learning model using the provided DataFrame. It handles scenarios where a model is either loaded from a specified name, trained with a given configuration, or fitted directly with data. The function validates input parameters, ensures consistency between configuration and m...
def fit( self, df: pd.DataFrame, model_config: Dict[str, Any] = None, model_config_name: str = None, load_model_name: str = None, ): if self.train_df is not None and load_model_name: self._build_model(load_model_name) if (model_config and not mode...
def isdir(d, parent): path = str(parent) + "/" + str(d) return os.path.isdir(path) def diffdir(dir1, dir2): # recursive dir1_list = os.listdir(dir1) dir2_list = os.listdir(dir2) dir1_list.sort() dir2_list.sort() if((not dir1_list) and (not dir2_list)): return for i in dir1_list...
The code compares two files or directories based on user input. It checks if both items are files or both are directories, then initiates the comparison process. If invalid inputs are provided, it returns an error message.
def diff(argv): if(len(argv) < 4): print("usage: vfu diff item1 item2") return item1 = argv[2] item2 = argv[3] if(os.path.isdir(item1) and os.path.isdir(item2)): print("Comparing directories...") diffdir(item1, item2) elif(os.path.isfile(item1) and os.path.isfile(it...
def make_divisible(v, divisor, min_value=None): if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v def inverted_re...
This function constructs a MobileNetV2-based neural network with an encoder-decoder architecture for image classification or segmentation. It processes input images through inverted residual blocks (expansion, depthwise, projection) to reduce spatial dimensions, then upsamples via skip-connected transposed convolutions...
def get_MobileNetV2_1_224(picture_size=256 ,batch_size=64, include_top=True, num_classes=10, build_Classificator=False): # If build_Classificator is False, method return input as MakiTensor and output as MakiTensor # NOTICE checkpoint have "prediction" layer at the end for 1001 classes alpha = 1 first_f...
def get_endpoints(self, type=None): """Returns all deployed endpoints. Examples -------- .. sourcecode:: python {"clustering": {"description": "", "docstring": "-- no docstring found in query function --", "creation_time": 146951...
The main task of the code is to deploy a user-defined Python function as a server endpoint. It checks for existing endpoints, handles versioning (incrementing if overriding), validates inputs/outputs for JSON serialization, and uploads the function with metadata. The function either adds a new endpoint or updates an ex...
def deploy(self, name, obj, description='', schema=None, override=False): """Deploys a Python function as an endpoint in the server. Parameters ---------- name : str A unique identifier for the endpoint. obj : function Ref...