dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _setup_deposit_verifiers(self, get_contract, maintainer): self.eth_deposit_verifier = get_contract('EthDepositVerifier', sender=maintainer) self.erc20_deposit_verifier = get_contract('Erc20DepositVerifier', sender=maintainer) def _setup_vaults(self, get_contract, maintainer): self.eth_vault ...
This code initializes a Plasma blockchain framework by deploying the PlasmaFramework contract with specified parameters, activating the child chain, and setting up essential components like deposit verifiers, vaults, output guards, and exit games, all under the authority and maintainer roles.
def __init__(self, get_contract, maintainer, authority): self.plasma_framework = get_contract( 'PlasmaFramework', args=( EXIT_PERIOD, INITIAL_IMMUNE_VAULTS, INITIAL_IMMUNE_EXIT_GAMES, authority.address, maint...
def place(self, weight, module_id, mode): if mode == 2: self.fill_main(module_id, self.length_2, 1, int(weight[0] + weight[1]), mode) self.fill_buffer(module_id, self.length_2, 0, int(weight[0])) self.length_2 += int(weight[0] + weight[1]) elif mode == 3: ...
This function determines the placement position of a module based on its area (2, 3, or 4) and compares predefined length values (length_2/length_3) to select appropriate coordinates. It uses conditional logic to call the place() method with specific coordinate patterns and module IDs, then generates an image after pla...
def ini_place(self, module_area, module_id): if module_area == 2: self.place([0, 1], module_id, 2) elif module_area == 3: if self.length_2 < self.length_3: self.place([1, 0], module_id, 2) else: self.place([0, 1], module_id, 3) ...
def resolve_path( self, path: PathLike, directory: Optional[Directory] = None ) -> Union[File, Directory, PathLike]: parts = list(filter(bool, str(path).split("/"))) temp_path = self.temp.joinpath("/".join(parts)) if temp_path.exists(): return temp_path db_enti...
This code implements a file open operation for a FUSE-based file system, resolving paths to either temporary or blob storage, tracking file lifecycle events, and handling readable/writable file access with appropriate path resolution and handle management.
def open(self, path: PathLike, flags: int) -> int: original_path = Path(str(path)[1:]) file_name = os.path.basename(path) result = self.resolve_path(path) if isinstance(result, File): path = self.blobs.joinpath(result.hash) elif isinstance(result, Directory): ...
def resolve_path( self, path: PathLike, directory: Optional[Directory] = None ) -> Union[File, Directory, PathLike]: parts = list(filter(bool, str(path).split("/"))) temp_path = self.temp.joinpath("/".join(parts)) if temp_path.exists(): return temp_path db_enti...
This function creates a file at a specified path, resolves the path based on the result type (File/Directory), ensures the temporary directory exists, tracks the file's lifecycle, and returns a file handle. It handles path resolution, directory creation, lifecycle logging, and opens the file with write/create/truncate ...
def create( self, path: PathLike, mode: int, fi: Optional[bool] = None ) -> int: file_name = os.path.basename(path) result = self.resolve_path(path) if isinstance(result, File): path = self.blobs.joinpath(result.hash) elif isinstance(result, Directory): ...
def resolve_path( self, path: PathLike, directory: Optional[Directory] = None ) -> Union[File, Directory, PathLike]: parts = list(filter(bool, str(path).split("/"))) temp_path = self.temp.joinpath("/".join(parts)) if temp_path.exists(): return temp_path db_enti...
This method manages file release by closing handles, generating hashes, updating database records for files/directories, moving/deleting temporary files, and logging lifecycle events. It checks if the file exists, updates metadata if present, or inserts new records, ensuring blob storage consistency by handling hash co...
def release(self, path: PathLike, fh: int) -> None: original_path = Path(str(path)[1:]) file_name = os.path.basename(path) result = self.resolve_path(path) if isinstance(result, File): path = self.blobs.joinpath(result.hash) elif isinstance(result, Directory): ...
def first_population(self): for i in range(POPULATION): new_creature = Creature() self.all_sprites.add(new_creature) self.all_creatures.append(new_creature) def generate_food(self): for i in range(START_FOOD): new_food = Food() self.all_sprites...
The code initializes a Pygame simulation for an "Evolution" game by setting up the display window, initializing audio, creating sprite groups, generating the first population of creatures, spawning food, and starting the main game loop to handle updates and rendering.
def __init__(self): pygame.init() pygame.mixer.init() self.screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Evolution") self.clock = pygame.time.Clock() self.last_update = 0 self.all_sprites = pygame.sprite.Group() self.all_cr...
def royal_flush(self): flush, high_card = self.flush() return flush and all(card.value in [10, 11, 12, 13, 14] for card in self.cards) def straight_flush(self): flush, high_card = self.flush() straight, high_card = self.straight() return straight and flush def four_of_a_kind(self...
This code calculates a poker hand's score by evaluating its rank (e.g., royal flush, straight, pairs) and assigning a base value with tie-breaking adjustments. It checks each possible hand type, adds corresponding points, and returns the total score for comparison.
def score_hand(self): score = 0 # pre-calculate all hand possibilities royal_flush = self.royal_flush() straight_flush = self.straight_flush() four_of_a_kind, kind = self.four_of_a_kind() full_house, highest_rank = self.four_of_a_kind() flush, high_card = self.fl...
def lstm_layer(self, X, layer_i=0, seq=False): X = np.flipud(np.rot90(X)) #load weights w = self.layers[layer_i] W_i = w["W_i"] ; U_i = w["U_i"] ; b_i = w["b_i"] #[n,m] ; [m,m] ; [m] W_f = w["W_f"] ; U_f = w["U_f"] ; b_f = w["b_f"] W_c = w["W_c"] ; U_c = w["U_c"] ; b_c = w["b_c"] W_o = w["W_o"] ; U_o = w...
This code performs a prediction using a neural network model with LSTM layers, dropout regularization, and a dense layer. It processes input X through two LSTM layers (with different sequence handling), applies dropout, uses a dense layer, applies softmax activation, converts the output to a vector, and samples the fin...
def predict_i(self, X, diversity): assert not not self.layers, "Weights must be loaded before making a prediction!" h = self.lstm_layer(X, layer_i=0, seq=True) ; X = h h = self.dropout(X, .2) ; X = h h = self.lstm_layer(X, layer_i = 2, seq=False) ; X = h h = self.dropout(X, .2) ; X = h h = self.dense(X, lay...
def lstm_layer(self, X, layer_i=0, seq=False): X = np.flipud(np.rot90(X)) #load weights w = self.layers[layer_i] W_i = w["W_i"] ; U_i = w["U_i"] ; b_i = w["b_i"] #[n,m] ; [m,m] ; [m] W_f = w["W_f"] ; U_f = w["U_f"] ; b_f = w["b_f"] W_c = w["W_c"] ; U_c = w["U_c"] ; b_c = w["b_c"] W_o = w["W_o"] ; U_o = w...
The code processes input data through a neural network model involving LSTM layers, a repeat vector operation, a time-distributed dense layer, and softmax activation to classify inputs into predicted classes. It ensures weights are loaded before prediction, transforms sequences via LSTM, applies dense layers for featur...
def predict_classes(self, X): assert not not self.layers, "Weights must be loaded before making a prediction!" h = self.lstm_layer(X, layer_i=0, seq=False) ; X = h h = self.repeat_vector(X, 4) ; X = h h = self.lstm_layer(X, layer_i=2, seq=True) ; X = h h = self.timedist_dense(X, layer_i=3) ; X = h h = self....
def move_right(self, execute_move=True): """Shift all tiles right.""" global RIGHT_AVAILABLE RIGHT_AVAILABLE = 0 for i in range(0, self._size): for k in range(0, self._size): for j in range(0, self._size - 1): if j + 1 <= self._size - 1: ...
The method checks if any valid moves exist by simulating tile shifts in all directions (left, right, up, down) without altering the board state. It determines if the game is over by verifying if no tiles can move, indicating no possible swaps or combinations remain.
def check_available_moves(self): """Count the number of swaps and tile combinations in each shift direction.""" # False is used an argument instead of the default argument since # no tiles should move around the board when checking if the game is over. # NOTE: A game is over ...
def initialize_tiles(self): """Create the tiles that will be used in the game.""" # Initialize a n x n list of positions where the tiles will go self.tile_positions() # Size of each tile tile_size = 500 // self._size # Initialize an n x n list of Tiles for i in ...
The code processes game events by handling the "New Game" button press to reset the game, moving tiles in response to arrow key inputs, adding new tiles when possible, and managing the game over popup to allow restarting or exiting the game.
def process_events(self, event): """Process the game events and trigger a game over pop-up if applicable.""" # Check if the player presses the New Game button self._new_game.process_events(event) if self._new_game.pressed: self.initialize_tiles() self._score = 0 ...
def prepare_docs(docs,clean=lambda x:x,filter_func=lambda x: not x,stem=False,resolve_entities=True,return_e2e=False,phrases=False,run_in_memory=True,max_tokens=150000,verbose=False,index_files=True,index_folder='temp_indexed/',max_lans=3,trans_lans = {'sv':'da','no':'da'},detector=False): """Function for preparing...
The function `generate_similarity_network` constructs a graph (network) from input documents, where nodes represent entities/words and edges reflect similarities (PMI, Jaccard, or Word2Vec). It filters tokens by frequency, computes pairwise similarities, and builds a network using top edges sorted by the chosen measure...
def generate_similarity_network(docs,min_cut = 10,max_frac=0.25,phrases=False,min_edgecount=5,maximum_nodes = 10000,stem=False,topn_edges = 100000,target_average_degree=False,edge_window=128,large_component_size=False, custom_filter=lambda x: not x, sorting_measure='pmi',pmi_min=1.2,build_from_pmi_weighted_sims=True,in...
def runSimulation(shouldVisualize = False): """ Runs a single simulation. Parameters ---------- shouldVisualize : bool Whether to visualize the simulation using pygame Returns ------- preyPopulations : 1d scalar array The number of prey alive at each time step predat...
The main task of the code is to execute multiple simulations of predator-prey population dynamics, store results in 2D arrays, rerun failed simulations, and optionally plot average population trends and lag correlations. It returns arrays of prey and predator populations across simulations and time steps, ensuring non-...
def runSet(): """ Runs a single set of simulations. Returns ------- preyPopulations : 2d scalar array The number of prey alive at each time step in each simulation predatorPopulations : 2d scalar array The number of predators alive at each time step in each simulation """ ...
def runSet(): """ Runs a single set of simulations. Returns ------- preyPopulations : 2d scalar array The number of prey alive at each time step in each simulation predatorPopulations : 2d scalar array The number of predators alive at each time step in each simulation """ ...
The function `runSets()` executes multiple simulation sets, computes average prey and predator populations across all simulations and time steps, and calculates the average standard deviations of these populations at each time step. It prints these statistics and generates plots (if enabled) of average population trend...
def runSets(): """ Runs multiple sets of simulations, then prints average populations at the end of the simulation and the average standard deviations of those sets of populations at each time step. """ preyPopulations = np.zeros((SET_NUM, SIMULATION_NUM, TIME_STEPS)) predatorPopulations = n...
def _get_cash(self): """ getter of bot cash :return: value of holding cash """ return self.holdings.cash def _get_stock_available(self): """ getter of _stock_available : return: list of _stock_available """ return self._stock_available def ...
The function `_realise_note` sells notes to generate cash when the bot's cash balance falls below a specified threshold. It checks if notes are available and a buy order exists for notes. If conditions are met, it places a limit sell order at a price one unit below the best buy price, using the maximum allowed units, t...
def _realise_note(self): """ Sell notes to realise cash when the bot have low cash """ if self._get_cash() <= LOW_CASH_THRESHOLD \ and self._get_stock_available()[Stock.NOTE.value] > 0 \ and 'BUY' in self._best_price['Note'].keys(): self._place...
def get_potential_performance(self, orders): """ Returns the portfolio performance if the given list of orders is executed. The performance as per the following formula: Performance = ExpectedPayoff - b * PayoffVariance, where b is the penalty for risk. :param orders: list of ord...
This method checks if the current portfolio holdings are optimal by comparing the potential performance of each stock's best order against the current portfolio's performance. If any best order yields higher performance than the current holdings, it returns False; otherwise, it returns True.
def is_portfolio_optimal(self): """ Returns true if the current holdings are optimal (as per performance formula and best price), false otherwise. :return: boolean """ for stock, best_order in self._best_price.items(): for order in best_order.values(): ...
def _get_stock_holding(self): """ getter of _stock_holding :return: list of _stock_holding """ return self._stock_holding def _get_cash(self): """ getter of bot cash :return: value of holding cash """ return self.holdings.cash def get_poten...
The function _find_optimal_portfolio generates a list of orders to optimize a portfolio by evaluating each potential order's performance against the current holdings and cash. It iterates through stock-price pairs, checks if an order improves performance, adds valid orders to the list, and updates prospective holdings/...
def _find_optimal_portfolio(self): """ Returns list of orders should be executed aim to optimise portfolio respect to the best price : return: list of order """ order_list = [] prospect_holdings = self._get_stock_holding().copy() prospect_cash = self._get_cash() ...
def get_potential_performance(self, orders): """ Returns the portfolio performance if the given list of orders is executed. The performance as per the following formula: Performance = ExpectedPayoff - b * PayoffVariance, where b is the penalty for risk. :param orders: list of ord...
The function identifies the optimal order to realize cash with the least loss by evaluating each potential buy order's impact on performance. It compares the potential performance of executing an order against the current performance, updating the best order if a higher performance gain is found. The result is the orde...
def _find_best_realise_order(self): """ find the least loss order to realise cash """ delta_performance = PERFORMANCE_LOSS_FLOOR realise_order = [] for stock_id, best_price in self._best_price.items(): for order in best_price.values(): if orde...
def _benchmark_order(self, position): new_order = Order(None) if position == OrderSide.SELL: new_order.price = self._public_market.max_price else: new_order.price = self._public_market.min_price return new_order def _available_trade(self, order: Order): if...
The code processes incoming orders to update market benchmarks (highest buy, lowest sell) and executes proactive/reactive trading strategies. It handles private orders by inserting them into a list, checks for bot type (proactive/reactive), and places new orders based on price spreads, profit margins, and market condit...
def received_orders(self, orders: List[Order]): lowest_sell = self._benchmark_order(OrderSide.SELL) highest_buy = self._benchmark_order(OrderSide.BUY) self._waiting_for_server = True cur_order_dict = Order.current().items() # iterating order book for order_id, order in...
def _match_order_ref(self): """ match local dict of ref number and server my order to renew pending order """ if len(self._sent_order) != 0 or len(Order.my_current()) > 0: try: exist_order = [] inactive_order = [] # check order ...
The function processes incoming orders by updating price references, resetting best prices, and renewing prices. It checks if the portfolio is optimal and adjusts the bot's behavior (reactive/proactive) accordingly. If reactive, it finds and executes optimal trades; if proactive, it finalizes actions and switches to re...
def received_orders(self, orders: List[Order]): try: self._match_order_ref() except Exception: self.inform("match order error") try: self._reset_best_price() except BaseException: self.inform("_reset_best_price error") try: ...
def _get_cash(self): """ getter of bot cash :return: value of holding cash """ return self.holdings.cash def _find_best_realise_order(self): """ find the least loss order to realise cash """ delta_performance = PERFORMANCE_LOSS_FLOOR realis...
The function `_realise_stock` sells stocks to generate cash when the bot's available cash falls below a predefined threshold. It identifies the optimal stock to sell, places a limit-order sell transaction using maximum units, and updates the bot's state to indicate the order is no longer pending. This ensures liquidity...
def _realise_stock(self): """ Sell stocks to realise cash when bot have low cash """ if self._get_cash() <= LOW_CASH_THRESHOLD: realise_order = self._find_best_realise_order() if type(realise_order) == Order: self._place_order(market=realise_order....
def prepare(self, predictions, iou_type): if iou_type == "bbox": return self.prepare_for_coco_detection(predictions) elif iou_type == "segm": return self.prepare_for_coco_segmentation(predictions) elif iou_type == "keypoints": return self.prepare_for_coco_keyp...
This code updates the evaluation of model predictions by processing each image and IoU type. It extracts unique image IDs, prepares results, loads them into a COCO evaluation object, sets parameters, runs evaluation, and appends results to stored evaluations.
def update(self, predictions): img_ids = list(np.unique(list(predictions.keys()))) self.img_ids.extend(img_ids) for iou_type in self.iou_types: results = self.prepare(predictions, iou_type) coco_dt = loadRes(self.coco_gt, results) if results else COCO() coco_...
def getFunctionNameTerms(f_string): # This function gets a string that includes # the function name with its arguments # and returns them separated i_first = f_string.index("(") i_last = f_string.index(")") name = f_string[0:i_first] terms = f_string[i_first + 1:i_last] term = terms.stri...
This function generates a dictionary mapping grounded action names to bit sequences by combining binary representations of actions and their arguments. It uses binary tables for actions and terms, pads sequences with False bits if arguments are fewer than the maximum, ensuring uniform length. The mapping is built for e...
def generateBOLSmapping(self, alist): # This function generates a dictionary where the keys are # the names of grounded actions and the values are the # corresponding bit sequences. # Actions with a number of arguments smaller than the maximum # get assigned a sequence with the s...
def nameActions(self): # This function generates a list with the name of all possible # grounded actions actions_names = [] for action in self.actions: nargs = len(action.args) combinations = generatePossibleSets(nargs, self.terms_list) for comb in com...
The code generates logical clauses to enforce exactly one action per time step: an "at-least-one" clause (disjunction of all valid grounded actions) and "at-most-one" clauses (pairwise negations to prevent simultaneous actions). It excludes discarded or conflicting actions, ensuring constraints are applied only to feas...
def oneActionPerTimeStep(self, t): # This function is called when the classical representation for actions is # used. It consists of creating the at-least-one and at-most-one clauses # encompassing all grounded actions; # To create the at-least-one clause, it is only necessary to get all...
def generateBinaryTable(list): # Receives a list with all the possible names # for the actions after constant substitution and # computes the necessary number of binary variables # necessary to represent those actions and then # assigns one binary number to each action, returning # a dictionary ...
This function generates logical clauses representing the preconditions and effects of grounded actions, ensuring consistency by checking for contradictions. It processes each action's parameters, creates clauses with negated actions and their conditions/effects, and avoids conflicts by discarding invalid actions. The i...
def actionsImplications(self, t): # This function generates the clauses that correspond to the actions # implicating their preconditions and their effects; # It has condition statements in order to create the clauses # for the classical and the bitwise representation of actions; ...
def nameActions(self): # This function generates a list with the name of all possible # grounded actions actions_names = [] for action in self.actions: nargs = len(action.args) combinations = generatePossibleSets(nargs, self.terms_list) for comb in com...
This function ensures unassigned binary action sequences (those not corresponding to valid actions) are excluded by generating clauses that render them false. It checks all possible bit combinations against a mapping of grounded actions. If a combination lacks a valid action, it's added to the clause list to prevent in...
def negateUnassignedActions(self,t): # This function is used only for the bitwise representation # of actions; # It is necessary because the chosen number of bits to represent # all grounded actions may result in a number of combinations # greater than the number of grounded acti...
def nameActions(self): # This function generates a list with the name of all possible # grounded actions actions_names = [] for action in self.actions: nargs = len(action.args) combinations = generatePossibleSets(nargs, self.terms_list) for comb in com...
This function interprets a SAT solver's solution to extract and print actions assigned as 'True' across time steps (t=0 to t=h). It handles three action representations (bitwise, overloaded bitwise, classical), maps variables to action names using predefined tables, and prints the corresponding action names for each ti...
def printSolution(self,t,Sol): # This function is responsible for reading the list # with the solution from the SAT solver and for # interpreting the result in order to retrieve the actions # that have been assigned True in the solution; # It has three different approaches for bi...
def initialStateClauses(self): # From the constructor of the Encoder class, the initial state # grounded literals are already available. This function computes # all the possible combinations of arguments for all those literals # and negates the ones that do not correspond to the initial...
This function generates a SAT problem representation for a planning task by encoding initial states, action preconditions/effects, steady-state propagation, and goal conditions over time steps. It constructs clauses for the current time step, manages state transitions, enforces constraints (e.g., one action per time st...
def generateSentence(self, t): # This is the function that generates the SAT sentence to # be fed to the SAT solver. if t == 0: # First, create unit clauses for the initial state self.initialStateClauses() else: # Remove goal state clauses from previou...
def printo(*args, **kwargs): super_print('DB_2019-12333>', *args, **kwargs) def selectTableExistenceError(tname): return f"Selection has failed: '{tname}' does not exist" def test_where(boolean_expr, columns, columns_only, tables): boolean_tests = boolean_expr.find_data("boolean_test") for boolean_test ...
The code processes SQL SELECT queries by joining tables via Cartesian products, applying WHERE clause filters, selecting specified columns, and formatting the output. It handles table existence checks, column resolution, and result display with proper syntax and error handling.
def select_query(self, items): # printo('\'SELECT\' requested') # from clause table_names = next(items[2].find_data("table_reference_list")).find_data("table_name") temp_from_table = [] # final cartesian from table table_col_names = [] # final col names of temp_from_table ...
def printo(*args, **kwargs): super_print('DB_2019-12333>', *args, **kwargs) def test_where(boolean_expr, columns, columns_only, tables): boolean_tests = boolean_expr.find_data("boolean_test") for boolean_test in boolean_tests: if boolean_test.children[0].data=='predicate': if boolean_tes...
This function processes a DELETE SQL query by identifying and removing records from a specified table that match the WHERE clause conditions. It validates the clause, evaluates records against the conditions, constructs a new table excluding deleted records, and updates the database. If no WHERE clause exists, all reco...
def delete_query(self, items): # printo('\'DELETE\' requested') table_name = items[2].children[0].lower() table = myDB.get(pickle.dumps({'record': table_name})) if not table: printo(noSuchTable) return items table = pickle.loads(table) deleted_indi...
def construct_adjacency_matrix(self, I): """ Constructs the adjacency matrix for the Ford-Fulkerson algorithm. Parameters: - I: numpy.ndarray Input image array. Returns: - A: numpy.ndarray Adjacency matrix representing the graph. """ ...
The code segments an input image using the Ford-Fulkerson algorithm to compute the minimum cut, identifying foreground pixels. It constructs an adjacency matrix from the image, calculates max flow and min cut between source and sink nodes, then generates a binary mask where pixels in the min cut are marked as foregroun...
def segment_image(self, I): """ Segments the input image using the Ford-Fulkerson algorithm. Parameters: - I: numpy.ndarray The input image. Returns: - mask: numpy.ndarray The mask representing the foreground pixel...
def generate_domino(): all_domino = [[i, j] for j in range(0, 7) for i in range(j, 7)] random.shuffle(all_domino) return all_domino def take_and_give(where, amount): to = [where.pop() for _ in range(amount)] return where, to def who_starts(computer, player): mx = [-1, -1] giver = None f...
The code prepares a domino game by generating dominoes, distributing them to stock, computer, and player, determining the starting player, and initializing the game state. It loops until a valid starting domino is selected, removes the starting piece from the winner's hand, sets the turn, and launches the game with the...
def preparing(): while True: all_domino = generate_domino() all_domino, stock_pieces = take_and_give(all_domino, 14) all_domino, computer_pieces = take_and_give(all_domino, 7) all_domino, player_pieces = take_and_give(all_domino, 7) giver, domino_snake = who_starts(computer...
def take_valid_start(num, col=None, row=None): msg = ("Enter your board dimensions: ", "Enter the knight's starting position: ") while True: print(msg[num], end="") try: x, y = [int(i) for i in input().split()] if x <= 0 or y <= 0: raise NegativeZeroResul...
The code implements a knight's tour puzzle game. It initializes a grid, places a knight at a starting position, marks possible moves, and allows the user to either solve the puzzle interactively or view a precomputed solution. The game tracks moves, checks for valid input, and displays results like "no solution" or con...
def start(): col, row = take_valid_start(0) cell_size = len_int(col * row) my_plate = [["_" * cell_size for _ in range(col)] for _ in range(row)] x_st, y_st = take_valid_start(1, col, row) x_st -= 1 y_st = row - y_st my_plate[y_st][x_st] = " " * (cell_size - 1) + "X" possible_moves =...
def validate_model_syntax(name: str, population: str, timestamp: int) -> Tuple[bool, object]: sandbox_collection(True).delete_many({ "$and":[ {"name": name}, {"population": population}, {"timestamp": timestamp} ] }) try: sandbox_collection(False).a...
The function validates a model's syntax and logic, then checks if a matching document exists in a MongoDB collection. If validations pass, it merges the data into the default collection and returns True; otherwise, it returns False.
def include_validated_model(name: str, population: str, timestamp: int) -> bool: validated = validate_model_syntax(name, population, timestamp) if not validated[0]: return False validated = validate_model_logic(name, population, timestamp) if not validated[0]: return False sandbox_co...
def delete_files(): os.system("rm -rf data") def get_title(contents): start_tag = '<title>' end_tag = '</title>' start_index = contents.find(start_tag) end_index = contents.find(end_tag) return contents[(len("<title>") + start_index):end_index] def parse_words(contents): start_index = 0 ...
The main task of the code is to crawl a webpage starting from a seed URL, collect text and link data, compute term frequencies (TF), inverse document frequencies (IDF), and TF-IDF values, track incoming/outgoing links for PageRank calculation, and store all processed data in files for further analysis.
def crawl(seed): delete_files() incoming_links = {} word_appears = {} outgoing_helper = {} queue = [seed] links_visited = {} map_ID_to_URL = {} ID = 0 links_visited[seed] = ID map_ID_to_URL[ID] = seed # while queue is not empty while queue: # read the top URL ...
def execute_handlers(test, key): """ Runs list of commands from selected execution block. @param test: test. @param key: block identifier. """ # Run list of commands for cmd in test["setup"]: result = run_cmd(cmd) if result.returncode != 0: raise RuntimeError(f"...
This function executes a test by performing setup, initializing a constable (if enabled), running pre-execution steps, executing the test, validating results via a validator, handling post-execution tasks, and cleanup. It logs progress, manages the constable process, and handles exceptions by notifying the validator of...
def run_single_test(test, validator): """ Main execution function for test. @param test: test to execute. @param validator: validator object. """ constable = None try: # Run setup if has_key(test, "setup"): logger.info(f"{test['name']}: running setup.") ...
def create_constable(): """ Creates medusa.conf from template. """ src_path = os.path.join(env_root, "medusa-template.conf") dest_path = os.path.join(env_root, "medusa.conf") content = "" with open(src_path, "r") as f: content = f.read() with open(dest_path, "w") as f: ...
The code runs multiple tests by executing setup, pre-execution, execution, post-execution, and cleanup phases for each test. It initializes a constable process, runs test handlers, captures outputs, validates results via a provided validator, and terminates the constable. Error handling ensures failures are logged, and...
def run_multiple(tests, validator): logger.info(f"Creating constable.") create_constable() # Setup block for test in tests: try: # Run setup for each test if has_key(test, "setup"): logger.info(f"{test['name']}: running setup.") execute_ha...
def adj4(addr, dims = None): has_dims = isinstance(dims, tuple) if not dims: n = len(addr) else: n = dims if not has_dims else len(dims) addrs = (add_t(addr, offset) for offset in _get_offsets(n)) return addrs if not has_dims else (a for a in addrs if in_dims(a, dims)) def dist_...
This function implements the A* algorithm to find the shortest path from a start node to a goal node in a graph. It uses a customizable heuristic function, neighbor generator, and cost function. The algorithm explores nodes using a priority queue, updating shortest paths and tracking predecessors. If the goal is reache...
def astar(start, goal, graph, neighbours = None, cost = None, heuristic = None, max_value = None): if not neighbours: neighbours = lambda n: (a for a in adj4(n) if a in graph) if not heuristic: g = goal heuristic = lambda n: dist_taxi(n, g) if not cost: cost = lambda _, __:...
def to_vec(t): if len(t) == 2: return vec2(*t) elif len(t) == 3: return vec3(*t) elif len(t) == 4: return vec4(*t) return t def dist_taxi(a, b): return len_taxi(sub_t(b, a)) def sub_t(a, b): if len(a) == 2: return vec2(a[0] - b[0], a[1] - b[1]) elif len(a) == ...
The function generates all integer grid points along the Manhattan path between two points pa and pb by iteratively moving one unit in the normalized direction vector, yielding each step's coordinates as integers.
def aaline(pa, pb): pa, pb = to_vec(pa), to_vec(pb) length = dist_taxi(pa, pb) dir = sub_t(pb, pa) dir = to_vec(tuple(v / abs(v) if v != 0 else 0 for v in dir)) yield pa for _ in range(length): pa = add_t(pa, dir) yield to_vec(tuple(int(v) for v in pa))
def getLaplacianPyramids(images, kernel, level): laplacian_pyramids = [] for image in tqdm.tqdm(images, ascii=True, desc="Laplacian Pyramids Generation"): laplacian_pyramid = generateLaplacianPyramid( image=rgb2yiq(image), k...
The code processes input video images by constructing Laplacian pyramids, applying frequency-based filtering with parameters like cutoff wavelength, attenuation, and frequency range, then reconstructing the filtered pyramids into an output video. The main task is video enhancement or modification through multiresolutio...
def laplacian_evm(images, fps, kernel, level, alpha, lambda_cutoff, freq_range, attenuation): laplacian_pyramids = getLaplacianPyramids( images=images, kernel=kernel, ...
def getGaussianPyramids(images, kernel, level): gaussian_pyramids = np.zeros_like(images, dtype=np.float32) for i in tqdm.tqdm(range(images.shape[0]), ascii=True, desc='Gaussian Pyramids Generation'): gaussian_pyramids[i] = generateGaussianPyramid( ...
The main task of the code is to process video frames using Gaussian pyramids for frequency-domain filtering. It constructs Gaussian pyramids from input images, applies frequency-selective filtering with parameters like `freq_range`, `alpha`, and `attenuation`, and reconstructs the filtered video. The process involves p...
def gaussian_evm(images, fps, kernel, level, alpha, freq_range, attenuation): gaussian_pyramids = getGaussianPyramids( images=images, kernel=kernel, level=level ) print("Gaussian P...
def add_doctor(self, doctor): doctor_id = self.get_doctor_by_name(doctor["name"]) if doctor_id is None: insert_query = 'insert into doctor (name,city,address,rate,page) values("'+str(doctor["name"])+'","'+str(doctor["city"])+'","'+str(doctor["address"])+'", '+str(doctor["rate"])+',"'+str(doc...
The main task of the code is to insert doctor information into a database, including their specialties, reviews, and review details. It processes each doctor's data by adding the doctor, their associated specialties (if not existing), and their reviews and reviewer details, ensuring all related entities are properly st...
def insert_info(self, doctors_info: list): for doctor_info in doctors_info: doctor_result = self.add_doctor(doctor_info) if doctor_result[1] == False: doctor_id = doctor_result[0] specialties_id = [] for specialty in doctor_info["specialty"...
def dprint(text): log(text) text = ' {} '.format(text) print('[{}] {}'.format(now(),text.center(100,'*'))) def getResfilePath(self): print('ResfileBuilder.getResfilePath: Joining {} and {}'.\ format(self.resfile_dir, self.getFullFilename())) return os.path.join(self.resfile_dir...
The code generates a resfile by writing packable and mutable residues with their possible mutations. It uses `mutDict` (liberal or conservative) to map amino acids to mutations, formats residue lines with chain and tag info, and writes them to the file. The method handles both residue types, ensuring mutation data is i...
def build(self): dprint('ResfileBuilder.build: Writing File --> {}'.format(self.filename)) if self.mut_liberal: mutDict = liberalMutMap else: mutDict = conservMutMap with open(self.getResfilePath(),'w') as rfile: rfile.write(self.getFileHeader()) if len(self.packa...
def dprint(text): log(text) text = ' {} '.format(text) print('[{}] {}'.format(now(),text.center(100,'*'))) def log(text='', no_stamp=False): with open(sesCache,'a') as f: for line in text.splitlines(): if no_stamp: f.writelines(line + '\n') else: ...
This code performs a minimization loop on a protein pose using a specified score function and movement map. It configures MoveMap for backbone/chi atoms, initializes MinMover with the map, sets up MonteCarlo for energy sampling, and applies repeated minimization cycles via RepeatMover. The process refines the pose's st...
def apply(self,pose): if self.repeats > self.printCutoff: dprint('Perfoming A Minimization Loop {:3d}'.format(self.repeats)) log( '`--> {}'.format(self)) movemap = MoveMap() self.setMovemapBB(movemap,pose) self.setMovemapChi(movemap,pose) self.movemap = mo...
def dprint(text): log(text) text = ' {} '.format(text) print('[{}] {}'.format(now(),text.center(100,'*'))) def log(text='', no_stamp=False): with open(sesCache,'a') as f: for line in text.splitlines(): if no_stamp: f.writelines(line + '\n') else: ...
This code performs an annealing loop on a protein pose using Monte Carlo simulations. It cycles through heating and cooling phases, adjusting angles and kT values to optimize the pose via SmallShearMover operations. The process repeats for multiple cycles, applying moves and logging scores at each step to refine the st...
def apply(self,pose): dprint('Beginning Anneal Loop Mover') log(' `--> {}'.format(self)) angles = ([self.angle_max] * self.heat_time + [self.angle_max / self.angle_ratio] * self.anneal_time) kT2s = ([self.kT_max] * self.heat_time + [self.kT_max / self.kT...
def dprint(text): log(text) text = ' {} '.format(text) print('[{}] {}'.format(now(),text.center(100,'*'))) def log(text='', no_stamp=False): with open(sesCache,'a') as f: for line in text.splitlines(): if no_stamp: f.writelines(line + '\n') else: ...
The code applies a mutant packer to a protein pose by creating a packing task, parsing a residue-specific file (resfile), and using a rotamer packing mover to optimize side-chain conformations. It logs progress, modifies the pose, and prints the resulting score with a specified identifier.
def apply(self,pose): dprint('Beginning Mutant Pack Mover') log(' `--> {}'.format(self)) task = TaskFactory.create_packer_task(pose) parse_resfile(pose, task, self.resfile) pack_mv = PackRotamersMover(self.scorefxn, task) pack_mv.apply(pose) printScore(pose,'Mutan...
def dprint(text): log(text) text = ' {} '.format(text) print('[{}] {}'.format(now(),text.center(100,'*'))) def log(text='', no_stamp=False): with open(sesCache,'a') as f: for line in text.splitlines(): if no_stamp: f.writelines(line + '\n') else: ...
(The code performs mutation minimization on a protein pose by iteratively applying a series of movers: mutation, rotamer repacking, annealing, ligand packing, and backbone minimization. It uses Monte Carlo sampling with a score function to optimize the pose for each mutation pattern in `mut_pattern`, logging progress a...
def apply(self, pose): dprint(('MMM.ID {} - Beginning Mutation ' 'Minimization Mover').format(self.identifier)) log(' `--> {}'.format(self)) mc = MonteCarlo(pose, self.scorefxn, self.kT) n = len(self.mut_pattern) for i,mut_residues in enumerate(self.mut_pattern): ...
def dprint(text): log(text) text = ' {} '.format(text) print('[{}] {}'.format(now(),text.center(100,'*'))) def now(formatNum=0): if formatNum == 0: return datetime.now().strftime('%H:%M:%S %m-%d-%y') elif formatNum == 1: return datetime.now().strftime('%y%m%d') elif formatNum == ...
(The code sets up initial protein structures, generates mutation patterns for decoy creation, configures movers for structural refinement, and prepares directories/log files. It loads original and relaxed poses, creates decoy generation parameters, and initializes a scoring log for subsequent structural analysis.)
def setup(): dprint('Setting Things Up') date_id = now(3) original_pdb_file = 'new_3vi8_complex.pdb' try: origPose = loadInPose(original_pdb_file) namePose(origPose,'original') except FileExistsError as err: print('setup: Failed, cannot load in initial pose') raise ...
def now(formatNum=0): if formatNum == 0: return datetime.now().strftime('%H:%M:%S %m-%d-%y') elif formatNum == 1: return datetime.now().strftime('%y%m%d') elif formatNum == 2: return datetime.now().strftime('%H:%M:%S') elif formatNum == 3: return datetime.now().strftime('...
The code compares two protein structures (original and mutant) by identifying sequence mutations, calculates energy scores using a scoring function, and computes the change in energy (ΔΔG) between the original and mutant complexes, both with and without ligands, to assess thermodynamic differences.
def comparePDBs(): global dateId dateId = now(3) original = loadInPose('3vi8_complex_fastRelaxed.pdb') new = loadInPose('lowest_e_decoy.pdb') original_no_lig = loadInPose('3vi8_complex_fastRelaxed_no_ligand.pdb') new_no_lig = loadInPose('lowest_e_decoy_no_ligand.pdb') names = [['Starting ...
def login_menu(self): print(''' User Menu 1. Login 2. Register 0. quit application ''') try: input_prompt = int(input(">")) if input_prompt == 1: username_input = input("Username: ") password_input = input("Password: ") pri...
The code presents a role-based menu system, continuously looping to display appropriate menus (login, admin, user, or owner) based on the user's role. It checks the user's role in each iteration and directs them to the corresponding menu function until a valid role is established or changed.
def menu(self): while True: if not self.user: self.login_menu() elif self.user.get_role().name == "admin": self.admin_menu() elif self.user.get_role().name == "user": self.user_menu() elif self.user.get_role().name =...
def Start_layer(self, inputs: tf.Tensor, training: bool) -> tf.Tensor: """Defines the start layer of the network. Args: inputs (tf.Tensor): Input tensor to the layer. training (bool): Boolean indicating whether the network is in training mode. Returns: tf.Te...
The main task of the code is to construct a neural network with residual blocks. It processes input tensors, applies a start layer, iterates through residual layers with dynamically adjusted filters, uses middle stack layers for feature extraction, and outputs final results via an output layer, with training mode affec...
def build_network(self, inputs: tf.Tensor, training: bool) -> tf.Tensor: """Construct the network layers. Args: inputs: Input tensor. training: Training mode flag. Returns: Constructed network as a tensor. """ inputs = tf.cast(inputs, tf.floa...
def tuple_to_list_board(board): '''Convert tuple of tuples to list of lists. Creates deep copy.''' b = [] for row in board: b.append(list(row)) return b def get_rotations(piece): '''Given a piece, return list of pieces that it will become when rotated''' if piece[0] == "O": retur...
The code evaluates all possible placements and rotations of the current piece on the board, simulates their outcomes using recursive simulations, and selects the move with the highest average score. It iterates through each rotation, tests valid positions, calculates scores via simulations or direct scoring, updates th...
def run(self, curr_piece, curr_board, num_sims, num_pieces, num_c): '''Returns piece and location of highest score''' curr_board = tuple_to_list_board(curr_board) best_move = BestPiece(curr_piece, (-1, -1), -1000) #{ # "piece": curr_piece, # "location": (-1, -1), ...
def analyze_PIDs(self, PIDs): pos=[None,None,None] center=[None,None,None] type=self.mode for PID in PIDs: pcode=PID.getText() if pcode[0]=='X': pos[0]=float(pcode[1:]) elif pcode[0]=='Y': pos[1]=float(pcode[1:]) ...
The main task of the code is to analyze and execute G-code commands (types 0-3) by calculating tool paths. It retrieves the current tool position, processes PID data to determine target points, adjusts positions, and invokes type-specific G-code execution functions (run_gcode0-3) with appropriate parameters, including ...
def analyze_gsmt(self, gcode_type, PIDs): p1=self.current_tip_position p2,center=self.analyze_PIDs(PIDs) p2=self.analyze_points(p1,p2) if gcode_type==0: self.run_gcode0(p1,p2) elif gcode_type==1: self.run_gcode1(p1,p2) elif gcode_type==2: ...
def analyze_gsmt(self, gcode_type, PIDs): p1=self.current_tip_position p2,center=self.analyze_PIDs(PIDs) p2=self.analyze_points(p1,p2) if gcode_type==0: self.run_gcode0(p1,p2) elif gcode_type==1: self.run_gcode1(p1,p2) elif gcode_type==2: ...
This method processes G-code commands from the context. It checks each GID, determines if it's active or passive, and executes corresponding analysis or execution functions. If no GIDs are present, it uses the last recorded G-code. Finally, it delegates to child nodes for further processing.
def visitGstmt(self, ctx:GcodeParser.GstmtContext): GIDs=ctx.GID() if len(GIDs)>0: for GID in GIDs: gcode=GID.getText() code_type=gcode[0] if code_type=="G": gcode_type=int(gcode[1:]) if gcode_type in sel...
def io_get_choice(i, l, u): c = input(i) if not c.isdigit(): return False c = int(c) if l <= c <= u: return c else: return False def system_exit(): print("Goodbye!") exit() def io_get_state(): try: with open("data", "r") as i: return jsonload(i...
The main task of the code is to manage a city-building game's main menu and gameplay loop, allowing users to start a new game, load a saved game, view high scores, or exit. It handles custom grid size configuration, building selection, game state management, score calculation, and leaderboard integration. The game runs...
def main(): print("Welcome, mayor of Simp City!") print("----------------------------") while True: print("1. Start new game") print("2. Load saved game") print("3. Show high scores") print() print("0. Exit") while True: choice = io_get_choice("Y...
def io_get(i, l, u): c = input(i) if not c.isdigit(): return False c = int(c) if l <= c <= u: return c else: return False def system_exit(): print("Goodbye!") exit() def game_turn(points, state=None): if state is None: state = DEFAULT_GAME_STATE if sta...
The main task of the code is to run a city-building game where the user can start a new game, choose city size (default or custom), place tiles on a grid, and calculate scores. It handles input validation, game state management, and displays the final grid layout and score after completing all turns.
def main(): print("Welcome, mayor of Simp City!") print("----------------------------") print("1. Start new game") print("2. Load saved game") print() print("0. Exit") while True: choice = io_get("Your choice? ", 0, 2) if choice is not False: break print("...
def mosaic_by_date(self, imgCol): """ mosaic_by_date is a function that merges images together that have the same date. @ imgCol: [ee.ImageCollection] mandatory value that specifies the image collection to merge by dates with. Returns ee.ImageCollection """ # Convert th...
The main task of the code is to generate image processing tasks for specified types (e.g., RGB, MNDWI, cloud) from a collection of satellite images. It creates mosaic images by date, handles cloud masking, and returns a list of tasks for exporting or further processing. If `mask=True`, it uses masked images; otherwise,...
def get_all_mosaic(self, types=["mndwi", "rgb", "cloud"], mask=False): if mask == False: collection = self.mosaic_by_date(self.get_images()) # get s2cloudless images error = False try: collection_s2cloudless = self.mosaic_by_date(self.get_s2_cloudl...
def print_location(location, indent=12): string = '' if location['kind'] == 'local': string = location['name'] else: assert False, location['kind'] projs = location['projections'] for p in projs: if p['kind'] == 'deref': string = f'(*{string})' print(' ' * ...
The main task of the code is to parse compiler output JSON containing intermediate representation (IR), validate its structure, and print functions, locals, and basic blocks in a structured format. It reads input, checks for JSON validity, ensures required fields exist, then iterates through modules and functions to ou...
def main(): compiler_output = sys.stdin.read() parsed = None try: parsed = json.loads(compiler_output) except json.JSONDecodeError: print('Could not parse json') exit(-1) if 'ir' not in parsed: print("No ir in compiler output") exit(-2) modules = parsed...
def get_data_property(goal,with_indi = False): indi_properties = get_properties(goal,with_indi) data_properties = [prop for prop in indi_properties if isinstance(prop, DataPropertyClass)] return data_properties def sort_dataproperty_destination(dataproperty): property_order = [ "PositionX", "Pos...
This code recursively extracts and sorts data properties of a product's location hierarchy. It checks if the input is a Product or Location instance, then either recursively processes the product's location or retrieves/sorts data properties of the location. The goal is to gather structured information about a product'...
def find_info_about_goal(goal_instance): if goal_instance.__class__ == onto.Product: # print(goal_instance.tag) # print(goal_instance.located) location = find_info_about_goal(goal_instance.located) elif goal_instance.__class__ == onto.Location: goal_location_dp = get_data_propert...
def find_individual(goal): goal_instances = [] for goal_instance in onto.individuals(): if goal in goal_instance.name: goal_instances.append(goal_instance) if len(goal_instances)==1: return goal_instances[0] return goal_instances def get_data_property(goal,with_indi = False):...
This function retrieves detailed information about a specific goal, including its data properties and location details. It handles cases where multiple goal instances exist by filtering with optional 'details' input, sorts data properties by destination, and returns the goal instance, its tag, and sorted data propertie...
def get_goal_details(goal, details=None): goal_instance = find_individual(goal) try: if len(goal_instance)>1: if details is not None: for goal_indi in goal_instance: if goal_indi.tag[0] == details: goal_instance = goal_indi ...
def get_goal_details(goal, details=None): goal_instance = find_individual(goal) try: if len(goal_instance)>1: if details is not None: for goal_indi in goal_instance: if goal_indi.tag[0] == details: goal_instance = goal_indi ...
The function `parse_goal` extracts relevant checks and actions from a goal definition, identifies the action matching `action_required`, and returns associated checks, actions, tags, and locations. It handles optional destination parameters and defaults to the first check/action if postchecks fail.
def parse_goal(action_required,goal_direct,goal_details,destination): goal_instance,tag ,location = get_goal_details(goal_direct,goal_details) if destination is not None: _,_,destination = get_goal_details(destination) # print("##############",tag) checks, actions = find_checks_and_actions(goal...
def evaluate(self, bo): eval = 0 for i in range(8): for j in range(8): if bo[j][i] != 0: eval += bo[j][i].value return eval def get_every_move(self, bo): board = bo.board moves = [] for i in range(8): for j in r...
The code implements the minimax algorithm with alpha-beta pruning to determine the optimal move for a game, evaluating board states recursively. It alternates between maximizing and minimizing players, exploring possible moves, and pruning branches to improve efficiency. The function returns the best move and its evalu...
def minimax(self, bo, depth, alpha, beta, maxPlayer, maxColor): self.counter += 1 if depth == 0 or bo.is_game_over(): return None, self.evaluate(bo.board) moves = self.get_every_move(bo) if len(moves) == 0: if self.check(WHITE): return -99...
def im_diff_filter(pic, thresh, h_filter): pic = pic.transpose(5) size = pic.size row = size[0] col = size[1] h_len = len(h_filter) cutout = int(h_len / 2) num_pic = numpy.array(pic, "double") num_pic = (num_pic[:,:,0] + num_pic[:,:,1] + num_pic[:,:,2])/3.0 row_pic = numpy.zeros((c...
The main task of the code is to process an input image through filtering, alignment, morphological transformations, and filling to clean and refine it. It applies difference filters, combines results, crops and aligns the image, performs dilation/erosion, fills gaps, realigns, and saves the final processed image as a B...
def cleanup_image(im_input): print("starting filtering") im_filter_1 = im_diff_filter(im_input, 14, [1, -1]) im_filter_2 = im_diff_filter(im_input, 14, [1, 0, 0, -1]) show_image(im_filter_1) show_image(im_filter_2) s = im_filter_1.shape both_pic = numpy.zeros((s[0], s[1])) both_pic[(i...
def cleanup_image(im_input): print("starting filtering") im_filter_1 = im_diff_filter(im_input, 14, [1, -1]) im_filter_2 = im_diff_filter(im_input, 14, [1, 0, 0, -1]) show_image(im_filter_1) show_image(im_filter_2) s = im_filter_1.shape both_pic = numpy.zeros((s[0], s[1])) both_pic[(i...
The main task of the code is to process an image of a screw to extract its geometric parameters. It reads and crops the image, identifies key features (e.g., center, bounds), calculates acceleration-based outlines, and estimates dimensions like total length, body/head widths, and thread count. The function returns thes...
def get_parameters(file_loc): dpi = 326 print("start") img = cv.imread(file_loc) print(file_loc) im_crop = img[27:1065,315:1760] im_crop = Image.fromarray(im_crop) im_fill,x_center,y_center,x_bounds,y_bounds, filledImageLocation = cleanup_image(im_crop) show_image(im_fill) y_out...
def make_identity_matrix(size): return [ [0 if j != i else 1 for j in range(size)] for i in range(size) ] def find_column_index(column, mat): return get_columns(mat).index(column) def get_column(index, mat): return [row[index] for row in mat] def make_x_sym(index): return symbols('x' + str(i...
The code identifies basic variables by matching columns from an identity matrix to the input matrix 'a', associating each matched column with a symbolic variable and its index, returning a list of these variable-index pairs.
def find_basic_vars(a): size = len(a) id_mat = make_identity_matrix(size) basic_vars = [] for i in range(size): col_index = find_column_index(get_column(i, id_mat), a) basic_var = (make_x_sym(col_index), i) basic_vars.append(basic_var) return basic_vars
def read_from_file(): file = open(FILE_PATH) file_str = reduce( lambda acc, line: acc + line, file.readlines()) file.close() data = json.loads(file_str) z = to_symbols(data['z']) a = to_symbols(data['a']) b = to_symbols(data['b']) kind = data['kind'] form = data...
The main task of the code is to solve a linear programming problem using the simplex method. It reads input data, adds slack variables if necessary, constructs a simplex table, and attempts to solve it. If an error occurs during solving, it is caught and displayed.
def main(): z, a, b, kind, form = read_from_file() if form != '=': a = add_slack_vars(a) table, basic_vars = make_simplex_table(z, a, b, kind) try: solve_simplex_table(table, basic_vars, kind) except Exception as e: print(e)
def submit(entries): """ This function is executed when the user fills in all the inforamtion and clicks submit. It takes all the entered information an writes it to a .json file (users.json) :param entries: an array of entries that contain the entered information :return: void """ # Uncomme...
The function creates four buttons (Submit, Read, Clear, Quit) and links them to respective methods. Submit triggers `submit(my_ents)`, Read calls `read(my_ents)`, Clear invokes `clear(my_ents)`, and Quit executes `quit_program`. Buttons are organized in a top frame, left-aligned, with Submit having a light gray backgro...
def create_buttons(): """ This function creates 3 buttons (submit, clear, and quit) and associates them with the appropriate methods :return: void """ top = Frame(my_root) top.pack(side=TOP) submit_button = Button(my_root, text="Submit", command=lambda: submit(my_ents), bg='#e4e4e4') rea...
def calc_alpha(self): x_len = len(self.x_train) y_len = len(self.y_train) symmetric_matrix = np.zeros(shape=(x_len, x_len)) for i in range(x_len): for j in range(x_len): symmetric_matrix[i][j] = self.y_train[i] * self.y_train[j] * self.mapping(self.x_train[i].reshape((2, 1)), self.x...
This code trains a model by validating the consistency of training data and labels, storing them, and computing essential parameters like alpha values, support vector indices, and bias for model optimization.
def fit(self, x_train, y_train): if len(x_train) != len(y_train): raise ValueError("Length of training data and label must be same.") self.x_train = x_train self.y_train = y_train self.calc_alpha() self.calc_support_vector_indices() self.calc_bias()
def get_seqs(infile_pileup_list, gene_oi, infile_seqs, use_minor=False, minor_cutoff=5, min_covg = 10, cutoff = 0.90, getref=False): """ Given a list of pileups, this reconstructs the sequence of a gene of interest :param infile_pileup_list: :param gene_oi: :param use_minor: :param minor_cutoff:...
The code generates a dendrogram (Figure2A) by combining metagenome-derived and genome sequences for a specific gene, removing redundant strains, and clustering them using a cutoff threshold to define groups. It returns the resulting tree structure for analysis.
def create_tree(infile_pileup_list, infile_seqs_ei, infile_db, infile_genome_names, cutoff_use = 20, gene_oi = "I_6_9343__bti1"): """ Creates the dendrogram from Figure2A and defines clusters :return: """ # Get the reconstructed sequences from the metagenomes seqs_metagenomes = get_seqs(infile_...
def compare(self, var1, var2): if var1 > var2: return var1 else: return var2 def Height(self, node): if node is None: return 0 else: return node.height def balance(self, node, val): bs = self.balance_state(node) if bs > 1 an...
(Inserts a value into a binary tree, recursively placing it in the left or right subtree based on comparison, updates the node's height, and balances the tree to maintain AVL properties.)
def insert(self, root, val): if root is None: root = Node(val) else: if val < root.val: root.left = self.insert(root.left, val) else: root.right = self.insert(root.right, val) root.height = 1 + self.compare(self.Height(root.lef...
def Chess_grid(canvas, gridcolor): global GRIDWIDTH_START, GRID_WIDTH, GRIDHEIGHT_START, GRID_HEIGHT grid_centers= [] counter = 0 for j in range(GRIDHEIGHT_START, GRID_HEIGHT, GRIDUNIT_SIZE): for i in range(GRIDWIDTH_START, GRID_WIDTH, GRIDUNIT_SIZE): grid_centers....
The main task of the code is to render an interactive chessboard UI with a frame, queens, buttons (submit, help, reset, close), and grid elements. It initializes visual components, positions queens on the side grid, creates a bottom bar with controls, and binds mouse movement for queen interaction, enabling gameplay fe...
def Chess_main(canvas): global SCREENWIDTH, SCREENHEIGHT, GRIDUNIT_SIZE, FRAMEGRIDUNIT_SIZE global wall_space, AnchorPos,queenList global queenimg_filepath, greenArrow_filepath, blueHelp_filepath, redArrow_filepath global closeButton_filepath,chessboardframe_filepath gridcolor = True bottom...
def highlight_box(canvas, boxes, x, y): ''' ''' for tx in range(9): for ty in range(9): canvas.itemconfig(boxes[tx][ty], fill=DEFAULT_COLOR) canvas.itemconfig(boxes[x][y], fill=HIGHLIGHT_COLOR) def change_focus(canvas, x, y): global current_box_focus current_box_focus = (x, ...
This function processes mouse clicks on a Sudoku grid and side options. It identifies grid cell clicks to highlight/focus cells, prints coordinates and board values, and handles side option clicks to input numbers into the focused cell, updating the canvas and board state accordingly.
def mouse_parser(event, canvas, boxes): global current_box_focus ''' Figure where mouse was clicked, and use that info ''' #figure the mouse presses print(f"X:{event.x}, Y:{event.y}") #determine if the mouse was clicked in the 9x9 grid for x in range(9): for y in range(9): ...
def make_grids(canvas): ''' make the 9x9 grid thats blank inputs: canvas ''' #boxes = numpy.array(boxes) print(boxes) #part 1 make boxes for i in range(9): for j in range(9): top_x, top_y = TOP_LEFT_X + GRID_SIZE*i, TOP_LEFT_Y + GRID_SIZE*j bot_x,...
The code initializes a Sudoku game interface by clearing the canvas, generating grids, setting up a puzzle board, drawing the board with numbers, displaying number options, and binding mouse and keyboard events for user interaction. It prepares the canvas for gameplay with event handlers for clicks and spacebar input.
def call_sudoku(canvas): global board print("Hello World from planet Soduku") canvas.delete('all') boxes = make_grids(canvas) board = [[1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 0, 0, 0, 0, 0, 0, 0], [0, 0, 3, 0, 0, 0, 0, 0, 0], [0, 0, 0, 4, 0, 0, 0, 0, 0], [...
def loc_exists(self, loc_name: str): if loc_name in self.mylocs: return True else: raise KeyError("Unknown location name {0} for dict with keys {1}".format(loc_name, self.mylocs)) def get_abs_path(self, loc_name: str): if self.loc_exists(loc_name): return self...
The function generates a directory path from a dictionary's key-value pairs, combining them with underscores, and optionally adds a prefix or suffix. It checks if the location exists, constructs the directory name, and creates the directory at the specified path.
def make_dir_from_dict(self, loc_name: str, mydict: dict, prefix: str = None, suffix: str = None): if self.loc_exists(loc_name): dir_name = "" for key, value in mydict.items(): dir_name += key + '_' + str(value) + '_' # Remove trailing '_' dir_name...
def speak(TXT, args): show_text(TXT) if SELECTED_VOICE == '0': if SELECTED_MODIFIER == '0': BMO_voice = ' pitch +540 tempo -s 1.70 speed 0.82 treble +6 gain -B +1' elif SELECTED_MODIFIER == '1': BMO_voice = '' system('gtts-cli "' + TXT + '" ' + args + ' | pla...
The main task of the code is to implement an interactive voice assistant named BMO that listens for user commands, processes them, and responds with appropriate actions such as speaking, playing GIFs, retrieving information (e.g., time, jokes, Wikipedia), executing tasks (e.g., playing music, games), and handling speci...
def BMO_listen(): ############## INITS ################ global input_nr global input_test global responseGIF global _responseGIF global gifPlayer global weather global gamepad global reddit ############## GREET ################ system('play /home/pi/Desktop/BMO/Assets/B...
def XmlEncode(object): return parseString(dicttoxml(object)).toprettyxml() def BytesToObject(bytes): ans = { 'data': [] } for i in range(0, len(bytes), 128): ans['data'].append({ 'name': DeserializeString(bytes[i:i+32]), 'login': DeserializeString(bytes[i+32:i+48]...
The main task of the code is to convert a binary file into an XML format. It reads the binary data from the specified file path, converts it into an object, serializes the object into XML, and saves the resulting XML data to a new file with the same base name but a .xml extension.
def process_bin(file_path): print(f'Processing file {file_path}') bytes = Path(file_path).read_bytes() serializedObject = XmlEncode(BytesToObject(bytes)) output_filename = f'{file_path[:-4]}.xml' XmlSaveEncoded(serializedObject, output_filename) print(f'Xml data written to {output_filename}')
def start_file_position(self, forward_shift=0, bot=True, exclude=None, number=0): target = self.start_positions[number] # if some cars on the same trajectory add distance between them if self.num_bots: space = 6*self.bot_targets.count(target[0]) - 3 - forward_shift else: ...
This code processes a reinforcement learning environment step by updating a car's controls (steer, gas, brake) based on an action, managing autonomous bot cars (path following, collision avoidance, target replacement), simulating physics, checking collisions, calculating rewards, and returning the environment state, re...
def step(self, action): # self.car.go_to_target(CarPath) if action is not None: self.car.steer(action[0]) self.car.gas(action[1]) self.car.brake(action[2]) if self.num_bots: prev_stop_values = [] # keep values of bot_cars for stop on cross ans res...
def _destroy(self): if not self.road: return for t in self.road: self.world.DestroyBody(t) self.road = [] self.car.destroy() self.car2.destroy() def _create_track(self): ######################################################################## t_p = PL...
The code resets the environment by destroying existing elements, reinitializing variables (reward, time, track data), generating a new track, creating multiple cars with specific positions/angles, and returning the initial state via a step call.
def reset(self): self._destroy() self.reward = 0.0 self.prev_reward = 0.0 self.tile_visited_count = 0 self.t = 0.0 self.road_poly = [] self.human_render = False while True: success = self._create_track() if success: break ...
def _destroy(self): if not self.road: return for t in self.tiles: self.world.DestroyBody(t) for t in self.road: self.world.DestroyBody(t) self.road = [] self.tile = [] if self.agent: self.car.destroy() self.world.DestroyBody...
The main task of the code is to reset the simulation environment by destroying existing elements, reinitializing reward counters, generating a new track, creating bot cars and the agent with randomized or predefined positions, setting up path targets, and preparing the environment for a new episode. It ensures the simu...
def reset(self): self._destroy() self.reward = 0.0 self.prev_reward = 0.0 self.tile_visited_count = 0 self.t = 0.0 self.road_poly = [] self.human_render = False self.moved_distance.clear() while True: success = self._create_track() ...
def debug(state=False): exec('%s %s; %s = %s' %('global', debugger, debugger, 'state'), globals(), locals()) # open global and local both-ways channels! if state: print(Back.RED + '%s: Debugging Mode' %debugger.replace('debug', '')) return def Initiate(): rs = address(mdlname, reset=eval(debugge...
The main task of the code is to execute a testing routine for a system (likely hardware or device-related) by either running detailed debug operations with voltage sweeps or a basic I/O test. It initializes a system, checks the debugger mode, performs voltage-based sweeps if enabled, and terminates the session, with co...
def test(detail=True): debug(detail) print(Back.WHITE + Fore.MAGENTA + "Debugger mode: %s" %eval(debugger)) s = Initiate() if eval(debugger): output(s, 1) # sweep(s, 0, 7, 371) factor = 1 V = 8 * factor sweep(s, V, V, pulsewidth=3) V = 10 * factor ...
def _create_and_parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(help='Options', required=True, dest='cmd') _create_bracket_args(subparsers) _create_visualize_args(subparsers) _create_compare_args(subparsers) return parser.parse_args...
The main task of the code is to process command-line arguments and execute corresponding operations related to brackets. Depending on the parsed command (`args.cmd`), it calls either `create_bracket`, `visualize_bracket`, or `compare_brackets` functions to handle bracket creation, visualization, or comparison tasks, re...
def main(): args = _create_and_parse_args() if args.cmd == 'create': create_bracket(args) elif args.cmd == 'visualize': visualize_bracket(args) elif args.cmd == 'compare': compare_brackets(args)
def calculate_average_scale(self, data): # Calculate the 'average scale' of data distance_matrix = self.calculate_distance_matrix(data) M = np.percentile(distance_matrix, 25) # lower quartile distance n = data.shape[0] # number of samples average_scale = M / np.log10(n) ...
This code evaluates data quality by iterating through combinations of normalization and dimensionality reduction methods. For each combination, it runs clustering multiple times, calculates an average quality index, and identifies the method pair with the highest score, using a progress bar to track iterations.
def evaluate_data_quality(self, data, num_runs): # Evaluate the data qualities best_score = -np.inf best_methods = None total_iterations = len(self.normalization_methods) * len(self.dimension_reduction_methods) * num_runs pbar = tqdm(total=total_iterations, disable=not self.verbo...
def prune_unlikely_connections(G, likelihood_threshold): resG = nx.Graph(G) for u, v, l in list(G.edges.data("likelihood")): if l < likelihood_threshold: print( "Pruning edge %s <-> %s due to likelihood l=%s below threshold" % (u, v, l) ) ...
The code processes a graph by pruning unlikely connections, partitioning each connected component into compact subgraphs, selecting the most affinity-aligned partitions, and updating the graph structure by fully connecting nodes in each partition. It returns the modified original graph and a new graph with optimized su...
def algorithm(G, likelihood_threshold=LIKELIHOOD_THRESHOLD): G = prune_unlikely_connections(G, likelihood_threshold) full_partition = [] for subG_nodes in nx.connected_components(G): subG = G.subgraph(subG_nodes) # print("Input edges: %s" % subG.edges) # get all viable partitio...
def has_left_child(self,i): return self.left_child(i) < len(self.heap) def get_max_child(self, i): if (self.has_left_child(i)): left = self.left_child(i) if(self.has_right_child(i)): right = self.right_child(i) if(self.heap[left] >...
This function restores the max-heap property by repeatedly swapping the element at index i with its largest child until the heap property is satisfied. It checks if the current node is smaller than its maximum child, swaps them if true, and continues downward until no larger children exist or the element is properly po...
def heapifydown(self, i): while(self.has_left_child(i)): max_child_index = self.get_max_child(i) if max_child_index == -1: break if(self.heap[i] < self.heap[max_child_index]): self.swap(i, max_child_index) ...
def clearScreen(): if OSname == 'nt': OSsys('cls') else: OSsys('clear') my_print_routine() my_print_routine() def gameloop(): player = main_menu() clearScreen() gameOver = False if player is None: my_print_routine("***POKEMON WORLDDD!!!!!...\n"); sleep(0.5) my_print_...
The main task of the code is to navigate a grid-based game where the player moves using WASD keys, collects items, captures Pokémon, and engages in battles with CPU trainers. The function updates the player's position, checks terrain types, handles game interactions (e.g., healing, Pokémon collection), and triggers win...
def navigate_A(a,counter=4): print("**KEY TO MAP**\n**0 for an inaccessible spot on the grid\n**1 for an accessible spot \n**2 for an item\n **3 for a Pokemon \n**4 for a CPU-trainer \n5**The actual player has a number like 5") print("Press WASD to move in grid\n") while(True): clearScreen() ...
def token_calculator(route_object: RouteModel, user: User): tokens = 0 user_rank = user.rank if route_object.mode == "car": tokens = 1*user_rank elif route_object.mode == "taxi": tokens = 2*user_rank else: walking_km = route_object.walking_distance/1000 bus_km = ...
The function `presentable_data` aggregates route metrics (e.g., time, cost, emissions) from a `RouteModel` and compares them to a car route, calculating additional values like tokens, health benefits, CO2 emissions, and an eco-score. It packages these into a `RouteResponse` object for structured output, incorporating u...
def presentable_data(route_object: RouteModel, car_route_object: RouteModel, user: User) -> RouteResponse: mode = route_object.mode arrival_time = route_object.arrival_time total_time = route_object.duration walking_distance = route_object.walking_distance walking_duration = route_object.walking_dur...
def get_last_release(releases: List[GitRelease]) -> Optional[GitRelease]: sorted_releases = sorted(releases, key=lambda r: r.created_at, reverse=True) if sorted_releases: return sorted_releases[0] return None def get_sorted_merged_pulls( pulls: List[PullRequest], last_release: Optional[GitRele...
The function constructs release notes for a repository by compiling recent changes, new contributors, and a changelog. It retrieves closed pull requests, identifies merged ones since the last release, and generates markdown sections for updates and contributors. If new contributors exist, they are highlighted. The outp...
def contruct_release_notes(repository: Repository, next_tag_name: str) -> str: repo_name = repository.full_name last_release = get_last_release(repository.get_releases()) all_pulls = repository.get_pulls(state="closed") sorted_merged_pulls = get_sorted_merged_pulls(all_pulls, last_release) old_cont...
def get_db_connection(pool): """ psycopg2 connection context manager. Fetch a connection from the connection pool and release it. """ connection = None try: connection = pool.getconn() # print('Got connection') yield connection except (db.OperationalError, PoolError) ...
This function inserts or updates data into a database using a temporary table. It establishes a connection, creates a temporary table, populates it with input data, merges the temp table's data into the main table, and then cleans up by dropping the temp table. This approach ensures efficient batch operations while min...
def push_by_temp_table(self, data): with get_db_connection(self.pool) as conn: with get_db_cursor(conn) as cur: set_buffer_timeout(conn, cur) tmp_name = create_temp_table(conn, cur) temp_update(conn, cur, data, tmp_name) merge_temp_tabl...
def error(iris_objects, weights, names, desired_output): # Computing the difference between the expected desired_output and observed output of single_layer network error_sum = 0 n_of_points = 0 for name in names: for (x, y) in zip(iris_objects[name].petal_lengths, iris_objects[name].petal_widths): n_of_points ...
The code performs gradient descent to minimize the mean squared error (MSE) for classifying Iris data using given weights. It iteratively updates weights until the MSE decrease falls below 0.0000002, tracking errors and weight changes. It visualizes the decision boundary and error reduction across iterations, plotting ...
def descent(iris_objects, weights, names, desired_output): errors = [0.0001 + error(iris_objects, weights, names, desired_output), error(iris_objects, weights, names, desired_output)] weights_array = [weights, weights] iteration = 1 # for gradient descent to converge prev_error - current_error has to be > 0 # gra...
def read_file(name): data = [] with open(name) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: line_count += 1 else: data.append(row) return data def converter(data, color_map): # to make it more general, color coding can be...
The main task of the code is to visualize logistic regression on the Iris dataset, creating scatter plots, decision boundaries, and logistic curves. It compares classifications using different weight sets, calculates classification errors, and applies gradient descent to iteratively update weights, demonstrating how mo...
def main(): data = read_file('irisdata.csv') color_map = {"virginica": "blue", "versicolor": "green", "setosa": "red"} iris_objects = converter(data, color_map) # General Legend weights = [-10, 1.2, 3] # These separate the two important things nicely names = ['green', 'blue'] desired_output = {'green': float(0...
def can_attend(self, start, end): from pathfinding.core.diagonal_movement import DiagonalMovement from pathfinding.core.grid import Grid from pathfinding.finder.a_star import AStarFinder matrix = GameData.copy(GameData.FIELD) for i in range(10): for j in range(10):...
This function processes a click event in a game, validating moves on a grid, updating cell values, calculating scores by tracking cleared paths, managing color transitions, and resetting the game state while ensuring proper cell updates and point accumulation based on path lengths and field rules.
def click_detected(self, x, y): # print(x, y) field = GameData.FIELD.field current_pos = (x, y) if (self.__x != -1) and (self.__y != -1) and (field[self.__x][self.__y] != 0): if self.can_attend((self.__x, self.__y), current_pos) and (self.__x, self.__y) != current_pos: ...
def lookup_dns(domain): # ip list to store dns resolutions ip_list = list() # run the dig command and add the IP's to the ip list result = subprocess.check_output(['dig', domain, '+short']) ip_list.append(result.decode().strip().split('\n')) print(result.decode().strip()) # ask the user if...
The code defines a function `run` that processes command-line arguments to perform tasks like DNS lookup, IP/domain threat checks, or retrieving threat block lists. It routes execution based on flags like `nameservers`, `threatblockr`, or `tb_lists`, executing corresponding functions such as `lookup_dns`, `file_search`...
def run(args): if args.nameservers: lookup_dns(args.domain) elif args.threatblockr: if args.ip_file: file_search(file=args.ip_file) else: search(ip=args.ip_addr, domain=args.domain) elif args.tb_lists: print(get_lists()) else: pass
def create_embeddings(): embeddings_kwargs = {'device': 'cuda'} if gpu_is_enabled else {} return HuggingFaceEmbeddings( model_name=ingest_embeddings_model if ingest_embeddings_model else args.ingest_embeddings_model, model_kwargs=embeddings_kwargs ) def does_vectorstore_exist(persist_directo...
The code ingests documents into a vectorstore (Chroma DB) by either appending to an existing database or creating a new one. It uses embeddings for text representation, checks if the target directory already contains a vectorstore, processes documents from the source directory if creating new, and persists the database...
def main(source_dir: str, persist_dir: str, db_name: str, sub_collection_name: Optional[str] = None): embeddings = create_embeddings() collection_name = sub_collection_name or db_name if does_vectorstore_exist(persist_dir): print(f"Appending to existing vectorstore at {persist_dir}") db = g...
def initialize_state(): if 'db_states' not in st.session_state: st.session_state['db_states'] = {} if 'current_db' not in st.session_state: st.session_state['current_db'] = '' if 'selected_database' not in st.session_state: st.session_state['selected_database'] = '' if 'select...
The main task of the code is to manage a conversation interface for a fitness application, allowing users to select databases, clear history, and interact with selected database data. It maintains session state for history tracking, source documents, and current database selection, while handling user queries and dynam...
def main(): initialize_state() print(st.session_state) st.header("Fitness on finger-tips") # Query section handle_database_and_collection_selection() selected_database = st.session_state['selected_database'] clear_history_button = st.button("Clear History") if clear_history_button: ...
def setupLocation(self): self.__setupLocation() sleep(2) def encodeUrl(self,keyword): keyword = urllib.parse.quote_plus(keyword) url = AMZ_LINK + '/s/ref=nb_sb_noss?url=search-alias%3Dfashion&keywords={}'.format(keyword) return url def getAllProducts(self, url,app,db): # ...
The code's main task is to search for products related to a keyword by encoding the keyword into a URL, retrieving all products from that URL using provided app and database connections, and returning the product count stored in `self.counter` after setting up location configurations.
def search4keyword(self, app,db,keyword=DEFAULT_KEYWORD): self.setupLocation() url = self.encodeUrl(keyword) self.getAllProducts(url,app,db) return self.counter
def framework(ncols=1, nrows=1, title=None, subtitle=None, title_x=0, grid=True, y_size_factor=1, x_size_factor=1, y_adjustment=0, subtitle_adjustment=0, fig_creation_args={}): # Background color facecolor = '.9' # Create figure fig, axs = plt.subplots(nrows=nrows, ncols=ncols, **fig_creation_args) ...
The main task of the code is to generate a 2x2 visualization of residual histograms and SNR distributions for P- and S-wave data. It normalizes residuals, filters values below a threshold, plots histograms with shared axes, and annotates SNR relationships while highlighting the proportion of hidden data in each wave ty...
def residual_histogram(metrics, subtitle=None, **kwargs): fig, axs = framework(2,2, 'Resdidual Histogram', subtitle, title_x=-.1, subtitle_adjustment=-0.02) p_res = metrics["p_res"] / 100 s_res = metrics["s_res"] / 100 snr = metrics["snr"] p_indices = np.abs(p_res) < 1 s_indices = np.abs(s_res)...
def framework(ncols=1, nrows=1, title=None, subtitle=None, title_x=0, grid=True, y_size_factor=1, x_size_factor=1, y_adjustment=0, subtitle_adjustment=0, fig_creation_args={}): # Background color facecolor = '.9' # Create figure fig, axs = plt.subplots(nrows=nrows, ncols=ncols, **fig_creation_args) ...
The code generates a ROC curve plot using provided metrics, calculates the AUC score, customizes axis labels and limits, adds an inset zoom on a specific region, and returns the figure. It utilizes a framework for consistent plotting with adjustable parameters like title, subtitle, and axis scaling.
def roc_plot(metrics, subtitle=None, **kwargs): fig, ax = framework(ncols=1, nrows=1, title='ROC Curve', subtitle=subtitle, title_x=-.03, y_size_factor=14/6, y_adjustment=0.19, subtitle_adjustment=0.06) fpr, tpr, threshold = metrics["det_roc"] roc_auc = auc(fpr, tpr) ax.plot(fpr, tpr, label=f"AUC = {roc...
def sample_z(self, n: int) -> torch.Tensor: return torch.rand(n, self.z_dim) * 2 - 1 def get_gen_order(self) -> list: dense_dag = np.array(self.get_dag()) dense_dag[dense_dag > 0.5] = 1 dense_dag[dense_dag <= 0.5] = 0 G = nx.from_numpy_matrix(dense_dag, create_using=nx.DiGraph) ...
The code implements a training step for a GAN, alternating between training the discriminator (optimizer_idx=0) and generator (optimizer_idx=1). It computes discriminator loss using real/fake samples and gradient penalty, while the generator minimizes adversarial loss, privacy loss, and L1 regularization. The function ...
def training_step( self, batch: torch.Tensor, batch_idx: int, optimizer_idx: int ) -> OrderedDict: # sample noise z = self.sample_z(batch.shape[0]) z = z.type_as(batch) if self.hparams.p_gen < 0: generated_batch = self.generator.sequential(batch, z, self.get_gen_...
def RSA_decrypter(items): global secret_phrase encrypted_aeskey=items[0] private_key_der = open('Serverprivatekey.der', 'rb').read() RSA_privatekey = RSA.import_key(private_key_der, passphrase=secret_phrase) decryptor = PKCS1_OAEP.new(RSA_privatekey) decrypted_aeskey = decryptor.decrypt(encrypte...
The main task of the code is to securely log client payment details and ordered items into a file after verifying the transaction. It decrypts the price using RSA, encrypts the items and payment amount with AES, writes them to 'logfile.txt' with timestamps and client identifiers, and sends an acknowledgment back to the...
def fileLogging(con, fileContents): global my_id,timeNow,datetime AES_key = "WmZq4t7w!z%C*F-J".encode() #AES Key count = 1 items = con.recv(255).decode() price = RSA_decrypter(fileContents) fileContents[0] = price if verifier(fileContents , con) == True: print("reached here") ...
def getnewsocket(): return socket.socket(socket.AF_INET, socket.SOCK_STREAM) def RSA_encrypting(DayClosingToSendToServer): public_key_pem = open("Serverpublickey.pem" , 'r').read() RSAPublicKey = RSA.import_key(public_key_pem) public_encryptor = PKCS1_OAEP.new(RSAPublicKey) encrypted_aeskey = public_en...
The code securely logs transaction data by encrypting a price value and generating a digital signature, sending them via a socket connection to a server along with concatenated cart items. It then verifies a received receipt to ensure data integrity and authenticity.
def fileLogging(price,cartItems): fileLogList = [] global host,clientsocket, secret_phrase clientBought = '' clientsocket = getnewsocket() host = 'localhost' clientsocket.connect((host ,8089)) msg = 'file' encodedMsg = msg.encode() clientsocket.send(encodedMsg) time.sleep(2.5) ...