dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def enemy_tracker(self, finalMapSizey, finalMapSizex, mapCornery, mapCornerx, mode=0): # Searches For All Enemy Units On The Map # SELECTION SORT & BINARY SEARCH IMPLEMENTATION enemies = self.find_all_enemy_map ( finalMapSizey, finalMapSizex, mapCornery, mapCornerx) enemy_close = False c...
The main task of the code is to track enemy proximity on a game map and execute automated combat actions when enemies are detected. It uses nested loops to monitor enemy status, control unit movement (e.g., bringing units back to safe positions), trigger attacks, manage skill toggles, and enforce fire-at-will modes. Th...
def mainTrackerTrait(self): halt = 0 counter = 0 halt_counter = 0 back_unit = 0 back_unit_far = 0 enemy_close = self.enemy_tracker ( finalMapSizeY, finalMapSizeX, mapCornerY, mapCornerX, mode=2) while enemy_close is False: while halt == 0: ...
def battle_master_bop_player(self, finalMapSizex, mapCornerx): # Calculates how much the player is winning by spell_browserx, spell_browsery = pyautogui.center ( pyautogui.locateOnScreen ( 'SpellBrowser.png', confidence=.8, grayscale=True ) ) balace_of_power = (mapCornerx - ((mapCornerx - f...
The main task of the code is to automate a battle in a game by detecting a "Red Capture Point," controlling units, attacking enemies, toggling skills, and repeating this process until the battle ends. The loop continues until the battle_end value exceeds 60, ensuring persistent gameplay actions like unit selection, ene...
def mainBattleMasterTrait(self): battle_end = self.battle_master_bop_player ( finalMapSizeX, mapCornerX) while battle_end <= 60: captured_point = pyautogui.locateOnScreen ( 'RedCapturePoint.png', confidence=0.9, ) if captured_point is None: self.select_AllUnits ()...
def commander_position_monster(self, placement, mon_up, mon_down, mon_side, mon_rotate): # Positions Monster Units self.unitPositionUp ( mon_up ) self.unitPositionDown ( mon_down ) if placement == 1: self.unitPositionRight ( mon_side ) placement = 2 elif placement...
This function categorizes and positions units (monsters, missiles, infantry) on a map using specific line counters and spacing rules. It separates units into arrays, adjusts missile positions every two placements, and triggers an autofire efficiency check. The task involves strategic unit deployment based on type-speci...
def commander_placement(self, unit_array, total_units, finalMapSizey, finalMapSizex, mapCornerx): # Places Units Depending On Assignment mon_line = 1 ranged_array = [] monster_array = [] infantry_array = [] m_line = 1 i_line = 1 missile_counter = 0 monster...
def place_AllUnitsCapPoint(self, capturePointX, capturePointY, total_units, mapY, mapX, mapCornerx): # Places All Units To The Capture Point time.sleep ( .5 ) x = 1 time.sleep ( .5 ) self.place_AllUnitsCenter (mapY, mapX, mapCornerx) time.sleep ( 1 ) press ( key='TAB', se...
The main task of the code is to initialize and place units on a map by calling `place_AllUnitsCapPoint` and `commander_placement`, then append specific monster unit IDs (4 and 13) to the `monster_array`, and activate guard mode via `toggle_GuardMode`. This function manages unit distribution, monster type additions, and...
def mainCommanderTrait(self): global ranged_array, monster_array, infantry_array self.place_AllUnitsCapPoint ( capturePointX, capturePointY, total_units, finalMapSizeY, finalMapSizeX, mapCornerX ) ranged_array, monster_array, infantry_array = self.commander_...
def mainTacticianTrait(self): global finalMapSizeY, finalMapSizeX, mapCornerY, mapCornerX, mapCenterY, mapCenterX, capturePointX global capturePointY, total_units, units, lord_card_position_x, lord_card_position_y self.mapDrag () self.toggleuniticon () finalMapSizeY, finalMapSize...
This function updates global variables with input parameters and triggers a sequence of battle-related methods in a specific order: initialization, preparation, battle execution, and tracking. It assigns received values to global state variables and sequentially calls methods like mainTacticianTrait, mainCommanderTrait...
def smActive(self, sent_mon_values, sent_m_values, sent_i_values, sent_battle_master_bop_adjust_x, sent_battle_master_bop_adjust_y, sent_defense_line, sent_confidence, sent_game_Pointx , sent_game_Pointy): global mon_values, m_values, i_values, battle_master_bop_adjust_x, battle_master_bop_adjust_y, defense_lin...
def generarRandom(self): stringc = ''.join(self.generate_conjunto(5)) +'E'+''.join(self.generate_conjunto(5)) return stringc def generarIgualdad(self): conjunto = ''.join(self.generate_conjunto(5)) stringc = conjunto +"E"+conjunto return stringc def generarPertenencia(self): ...
The code generates a random number between 0-100 and conditionally executes one of four methods: `generarRandom` (0-49%), `generarIgualdad` (50-69%), `generarPertenencia` (70-79%), or `generarSubconjunto` (80-100%), likely for randomized set-operation tasks.
def generar(self): choice = random.randint(0,100) print(choice) if choice >= 0 and choice < 50: return self.generarRandom() if choice > 49 and choice < 70: return self.generarIgualdad() if choice > 69 and choice < 80: return self.generarPertenencia() if choice > 79 and ch...
def update_balance(self, current_node): if current_node == None: return current_node.height = 1 + max(self.get_height(current_node.left_child), self.get_height(current_node.right_child)) current_node.balance_factor = self.get_height(current_node.left_child) - self.get_height(current_...
This method inserts a monthly expense node into a tree structure by comparing its total cost with the current node's cost. If the new node's cost is lower, it is added to the left child (or created if none exists); if higher, to the right child. After insertion, it updates and checks the tree's balance to maintain stru...
def __add_monthly_expense(self, current_node, l): #inserts monthly total cost to either the left or right based on relative value of the root: #if monthly total is less than root: if l.total_cost() < current_node.total_cost(): #if no root is present, create one if curre...
def update_balance(self, current_node): if current_node == None: return current_node.height = 1 + max(self.get_height(current_node.left_child), self.get_height(current_node.right_child)) current_node.balance_factor = self.get_height(current_node.left_child) - self.get_height(current_...
This method inserts a new monthly expense node into a tree structure by comparing total costs. If the new node's cost is less than the current node's, it is added to the left child; otherwise, to the right. If a child is absent, the node is placed there, and balance updates are triggered. The process recurses until the...
def __add_monthly_expense(self, current_node, l): if l.total_cost() < current_node.total_cost(): if current_node.left_child == None: current_node.left_child = l current_node.left_child.parent = current_node self.update_balance(current_node) ...
def join_public_group(client): group_name = public_group_name group_members = groups[group_name]['members'] group_members.append(client) client.send(f"You have joined {group_name}.".encode('utf-8')) client.send("You are now connected!".encode('utf-8')) broadcast(f"{names[clients.index(client)]} ...
This function handles client interactions in a chat application. It automatically joins the public group, processes commands (e.g., connecting, grouping, broadcasting messages), broadcasts regular messages to the public group, and manages client disconnections by removing them from the list and notifying others. It han...
def handle_client(client): join_public_group(client) # Automatically join the public group while True: try: message = client.recv(1024).decode('utf-8') if not message: break elif message.startswith('%'): print("Message") ...
def generateAllRules(n, arr, i, rules): if i == n: rule = [int(i) for i in arr] rules.ruleset.append(rule) return arr[i] = 0 generateAllRules(n, arr, i + 1, rules) arr[i] = 1 generateAllRules(n, arr, i + 1, rules) arr[i] = 2 generateAllRules(n, arr, i + 1, rules) def...
The code runs a cellular automaton simulation with user interaction, analyzing grid patterns using predefined rules. It tracks metrics like average value, connectedness, and chaos, logging results to a file. The simulation can be paused/resumed via the spacebar, with mouse clicks triggering updates. The main loop handl...
def main(): clock = pygame.time.Clock() previous = time.time() * 1000 run = True click = False right_click = False paused = True step = 0 dead = False waiting = False counter = 0 cells = [[random.randint(0, 1) for j in range(0, (HEIGHT // CELLSIZE))] for i in range(0, SIMWI...
def should_stop(self) -> bool: pass def _new_generation(self): new_population: List[T] = [] for i in range(len(self.population)): parents = self.select_parents() child = self._merge(parents[0], parents[1]) if not self.is_valid(child): child = s...
The code repeatedly generates new iterations until a stopping condition is met, then returns the value of the most fitted individual. It initializes an iteration counter, loops while `should_stop()` is false, prints the current iteration, creates a new generation via `_new_generation()`, increments the counter, and fin...
def run(self): iteration = 1 while not self.should_stop(): print("Running generation {}".format(iteration)) self._new_generation() iteration += 1 return self._most_fitted().value
def read_and_process_file(filename): try: with open(filename, 'r') as file: data = file.read() # Create DataFrame from the file data df = pd.DataFrame({'text': data.split('\n')}) # Assign group numbers based on occurrence of 'metadata:' df['group']=df['text'].ap...
The main task of the code is to generate a structured `.rivet-project` file by integrating presets, methods, flows, and a playground into a unified graph template. It exports each component, assigns unique IDs, combines them with legacy data, and writes the result to a file. The function returns graph IDs and the final...
def build_project( name, presets=[], methods=[], flows=[], prompts={}, api_base="http://localhost:8000", height=4000, width=16000, padding=200, secondary_padding=50, ): legacy_graphs=read_and_process_file(f'{name}.rivet-project') graphs=[] graph_ids={} for pr...
def evaluateErrors(self, right, left): error = self.error_function(self, self.distances_1[right], self.distances_1[left]) + self.error_function( self, self.distances_2[right], self.distances_2[left]) return error def normalize_errors(self, errors): threshold = self.errors_z_value_thr...
This function runs a genetic algorithm for a specified number of generations to evaluate and track the fitness of sample pairings. It calculates error scores for each generation, normalizes them, computes a fitness score, and stores results. The algorithm iteratively improves pairings by skipping pre-paired indices, pr...
def _geneticAlgorithm2(self): fitness_scores = [] flag = True for GENERATION in range(self.max_generation): self.right_samples_indices = self.next_generation errors = [] for index, (left, right) in enumerate(zip(self.left_samples_indices, self.right_samples_in...
def evaluateErrors(self, right, left): error = self.error_function(self, self.distances_1[right], self.distances_1[left]) + self.error_function( self, self.distances_2[right], self.distances_2[left]) return error def normalize_errors(self, errors): threshold = self.errors_z_value_thr...
This code implements a genetic algorithm to evaluate and track fitness scores across generations. It processes paired samples, calculates errors, normalizes them, computes fitness scores, and logs results. The algorithm iterates for a specified number of generations, updating fitness metrics and detecting symmetry, ult...
def _geneticAlgorithm(self): fitness_scores = [] for GENERATION in range(self.max_generation): self.right_samples_indices = self.next_generation errors = [] for index, (left, right) in enumerate(zip(self.left_samples_indices, self.right_samples_indices)): ...
def decode_netout(self, netout, anchors, obj_thresh, net_size, nb_box, scales_x_y): grid_h, grid_w = netout.shape[:2] netout = netout.reshape((grid_h, grid_w, nb_box, -1)) boxes = [] netout[..., :2] = self._sigmoid(netout[..., :2]) # x, y netout[..., :2] = netout[..., :2] * sca...
This function processes an input frame using a TFLite model for object detection. It normalizes the image, runs inference to get class and bounding box predictions, decodes YOLO outputs, corrects box coordinates, applies non-max suppression, and visualizes detected objects. It updates the camera's last image, tracks ob...
def iteration_step(self, frame, image_data, cam, publish=True): image_data = image_data / 255. # Int -> Float64 image_data = image_data[np.newaxis, ...].astype(np.float32) self.interpreter.set_tensor(self.input_details[0]['index'], image_data) self.interpreter.invoke() class_pre...
def as_hex(self): return self.hash.hex() def as_base64(self): number = base64.b64encode(self.as_bytearray()) return number.decode() def as_decimal(self): number = int.from_bytes(self.as_bytearray(), 'big') return str(number)
The code generates a password plaintext string based on the object's settings. If a custom password is defined, it returns that. Otherwise, it constructs the password using methods corresponding to the specified type (hex, Base64, or Deciml). It optionally truncates the result to a set crop length and appends a suffix ...
def __repr__(self): "Generates password plaintext with current settings" if self.custom: return self.custom else: if self.type == "hex": result = self.as_hex() elif self.type == "Base64": result = self.as_base64() elif self.type == "Deciml": result = self.as_d...
def ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets): if stats.ships_left > 1: stats.ships_left -= 1 aliens.empty() bullets.empty() boom = Explosion(ai_settings, screen) boom.blitme() create_fleet(ai_settings, screen, ship, aliens) ship.center_s...
This function updates alien behavior by checking collisions between the ship and aliens, handling collision responses, checking if aliens reach screen edges or the bottom (triggering game events), and updating alien positions for movement in the game.
def update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets): if pygame.sprite.spritecollideany(ship, aliens): print("Ship hit!!!") ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets) check_fleet_edges(ai_settings, aliens) check_aliens_bottom(ai_settings, screen, stat...
def getGpsLocation(self): """ Gets GPS coordinates of the vehicle. (Lat, Lon, Alt) """ pos = self.getCarState().kinematics_estimated.position gps = self.nedToGps(pos.x_val, pos.y_val, pos.z_val) return gps def updateError(self): self.d_error = self.cte - s...
The function calculates the Cross Track Error (CTE) between the vehicle's current GPS position and a predefined path (defined by two GPS points). It uses the `cross_track_distance` method to determine the perpendicular deviation from the path, updates the error, computes a steering value, and applies it to the car's co...
def getCTEFromGPS(self, current_lat, current_lon, next_lat, next_lon): current_pos = self.getGpsLocation() pointA1 = self.frame.GeoPoint(current_lat, current_lon, degrees=True) pointA2 = self.frame.GeoPoint(next_lat, next_lon, degrees=True) pointB = self.frame.GeoPoint(current_pos[1], cu...
def read_file(path: str) -> str: with open(path, "r", encoding="UTF-8") as file: css_content = file.read() return css_content def css_to_dict(css_content: str) -> dict[str, dict[str, str]]: "Reads, parses, converts CSS to dictionary." css_dict: dict[str, dict[str, str]] = {} sheet: cssuti...
The code processes CSS files to sort their declarations either alphabetically or by HTML element order, based on command-line arguments. It reads input files, converts CSS into structured data, sorts rules according to specified criteria, handles media queries, and outputs the formatted CSS either in-place or to stdout...
def main() -> None: parser = argparse.ArgumentParser( prog="sort_css", description="""Sorts CSS declarations. Without the "--by_html" it sorts first the tags alphabetically, then IDs and classes. """, ) parser.add_argument( "filenames", metavar="target", nargs="*", ...
def getNumberOfPages(soupMP): pagination = soupMP.find("ul", class_="pagination") if pagination == None: return 1 else: pages = pagination.find_all("li") return (len(pages) - 1) def routeToPage(url, pageNumber): if pageNumber == 1: url = url else: url = url + ...
The main task of the code is to scrape room URLs from a website by iterating through multiple pages, parsing HTML content, collecting room data, and filtering the results based on specified criteria. It retrieves URLs from search result pages, extracts relevant room links, and returns filtered URLs matching the provide...
def getRoomURLs(url, filters): rooms = [] mainPageResponse = requests.get(url) soupMP = BeautifulSoup(mainPageResponse.content, "html.parser") nbrPages = getNumberOfPages(soupMP) for pg in range(1, nbrPages+1): mainPage = routeToPage(url, pg) pageId = "search-results-page-" + str(...
def _check_dataset_compatability(self, rds): if rds.output_dims != self.input_dims: raise ValueError('Dataset outputs images with dimension %s, model expects %s'% (str(rds.output_dims), str(self.input_dims))) elif rds.output_channels != self.input_channels: ...
The code trains a neural network model using a two-phase approach (pretraining and full training) with two loss components (classification and attentional). It iterates over epochs, processes training data, computes losses, performs backpropagation selectively during pretraining, and evaluates the model on test data pe...
def train(self, rds, epochs, serialization_format, pretrain_epochs=10, learning_rate=1e-5, test_every_n_epochs=5, num_heatmaps=1): # TODO dynamic optimizer selection self._check_dataset_compatability(rds) last_acc = 0 max_acc = 0 pretrain_finished = False ...
def create_temp_model_for_existing_table(self, table_name: str): model_path = TMP_MODELS_DIR_PATH.joinpath(f"{table_name}.sql") model_path.touch() # Just need the file to exist, the contents doesn't matter try: yield finally: model_path.unlink() def seed(self, da...
This function creates and runs DBT tests by generating temporary YAML configurations for tables/models, handling parameters like test rules, columns, and data. It validates input constraints, seeds test data if provided, executes tests via DBT, and returns results as a dictionary or list based on the 'multiple_results'...
def test( self, test_id: str, dbt_test_name: str, test_args: Optional[Dict[str, Any]] = None, test_column: Optional[str] = None, columns: Optional[List[dict]] = None, data: Optional[List[dict]] = None, as_model: bool = False, *, multiple_re...
def simulation(wave_func, potential=0, steps=100000, dt=0.003, orthogonal_to = 0, save_every=1000): '''This method simulates a wave function evolving in time according to Schroedinger equation. Condition for normalization and orthogonality check to some certain eigenstates are implemented. It returns an array with ...
The code simulates quantum tunnelling by evolving an initial wave function through a potential, animates the process, and calculates the probabilities of finding the particle before and after a specified measuring point, returning reflected and transmitted wave probabilities.
def quantum_tunnelling(wave_func, V, measuring_point): '''This function takes an initial wave function, a potential (which should be suited for the tunnelling effect) and a point of the space grid. It simulates the wave function interacting with the potential, makes an animation of it and returns the probability of...
def simulation(wave_func, potential=0, steps=100000, dt=0.003, orthogonal_to = 0, save_every=1000): '''This method simulates a wave function evolving in time according to Schroedinger equation. Condition for normalization and orthogonality check to some certain eigenstates are implemented. It returns an array with ...
The code computes the ground state eigenfunction and its coefficient for a given wave function and potential, then generates an animation showing the time evolution of the eigenstate, where only the phase changes over time.
def ground_state(wave_func, V): '''This method takes a wave function, a potential and returns the ground state eigenfunction with its corresponding coefficient. It also makes an animation of the eigenstate evolving in time (showing that only the phase will change).''' ground_eigenstate = simulation(wave_func, d...
def simulation(wave_func, potential=0, steps=100000, dt=0.003, orthogonal_to = 0, save_every=1000): '''This method simulates a wave function evolving in time according to Schroedinger equation. Condition for normalization and orthogonality check to some certain eigenstates are implemented. It returns an array with ...
This code computes the first excited eigenstate of a quantum system by orthogonalizing an input wave function to the ground state, simulates its time evolution, and generates an animation showing phase-only changes. It returns the eigenfunction and its coefficient relative to the input wave function.
def first_state(wave_func, ground_func, V): '''This method takes a wave function, a potential and returns the first excited eigenfunction with its corresponding coefficient. It also makes an animation of the eigenstate evolving in time (showing that only the phase will change).''' phi_1 = wave_func - np.sum(np....
def simulation(wave_func, potential=0, steps=100000, dt=0.003, orthogonal_to = 0, save_every=1000): '''This method simulates a wave function evolving in time according to Schroedinger equation. Condition for normalization and orthogonality check to some certain eigenstates are implemented. It returns an array with ...
The function computes the second excited eigenstate by projecting the input wave function onto the ground and first excited states, subtracting their contributions, and simulating its time evolution. It generates an animation showing the eigenstate's phase change over time and returns the final eigenstate and its coeff...
def second_state(wave_func, ground_func, first_func, V): '''This method takes a wave function, a potential and returns the second excited eigenfunction with its corresponding coefficient. It also makes an animation of the eigenstate evolving in time (showing that only the phase will change).''' phi_0 = np.sum(n...
def ground_state(wave_func, V): '''This method takes a wave function, a potential and returns the ground state eigenfunction with its corresponding coefficient. It also makes an animation of the eigenstate evolving in time (showing that only the phase will change).''' ground_eigenstate = simulation(wave_func, d...
The code calculates the first three eigenstates of a given wave function and potential, prints their coefficients' magnitudes, and generates animations showing time evolution where only the phase changes.
def eigenstates(wave_func, V): '''this method takes a wave function and a potential. It calculates the first three eigenstates and print theire corrresponding coefficients. It also makes animations of the eigenstates evolving in time (showing that only the phase will change).''' ground_eigenstate, c_0 = ground_...
def getBalanceForThis(self, addresses:list) -> dict: self.log.INFO() balance = {} for adr in addresses: self.log.INFO(adr) transactions, balance[adr] = self.getTransactionTableFor(adr) return balance def getTop100(self, onlyPrivate:bool=False, pageNo=1) -> dict: ...
The main task of the code is to initialize an object that retrieves Bitcoin address balances and transaction tables from BitInfoCharts. It fetches balances either for specified addresses or the top 100 private addresses, then processes these balances to generate transaction table data for analysis or display.
def __init__(self, addresses:list=NULL, onlyPrivate:bool=True): self.log = logging("biggestBtcAddress") self.log.INFO() self.__urlPrefix = "https://bitinfocharts.com/" self.__adrsBalances:dict = self.getBalanceForThis(addresses) if addresses else self.getTop100(onlyPrivate) ...
def velocity_rf_line(lambda_0, lambda_1, vel): '''get the relative velocity of a feature assuming another line Parameters ---------- lambda_0 : float wavelength of the original line [angstrom] lambda_1 : float wavelength of the new line [angstrom] vel : float the velocit...
This function computes the log-posterior probability for a Gaussian absorption model by combining a prior probability (lnprior) and likelihood (lnlike_gaussian_abs). It calculates velocity differences across spectral lines, evaluates parameter constraints, and sums the prior and likelihood terms. The result represents ...
def ln_prob( theta, rel_strength, lambda_0, blue_vel, red_vel, vel_rf, norm_flux, lines=[], vel_flat=[-1e5, 0], var_max=1e8, mu_prior=[], var_prior=[], norm_flux_unc=1, blue_fl=[1, .1], red_fl=[1, .1], free_rel_strength=[] ): '''log-posterior probabili...
def neg_lnlike_gaussian_abs(theta, rel_strength, lambda_0, blue_vel, red_vel, vel_rf, norm_flux, lines=[], ...
The function performs Bayesian parameter estimation using an MCMC sampler (emcee) to infer model parameters from spectral data. It samples posterior distributions defined by priors (velocity, variance ranges) and a likelihood function, normalizing uncertainties if specified. Key tasks include initializing walkers, runn...
def MCMC_sampler(self, mu_prior=[], var_prior=[], vel_flat=[-1e5, 0], var_max=1e8, nwalkers=100, max_nsteps=50000, nburn=-1, thin=-1, initial=[], normalize_unc='None', Plot_...
def _check_keydown_events(self, event): """Respond to key presses""" if event.key == pygame.K_RIGHT: self.ship.moving_right = True elif event.key == pygame.K_LEFT: self.ship.moving_left = True elif event.key == pygame.K_ESCAPE: # Game closes if ESc is pressed ...
This function handles user input events in a Pygame application. It checks for quit requests, keyboard presses/releases to control movement, and mouse clicks to detect button interactions. Events trigger corresponding methods to manage game actions like movement and initiating gameplay.
def _check_events(self): # Check the keyboard and mouse actions for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: # If the key is pressed, the ship moves self._check_keydown_events(event) ...
def _check_fleet_edges(self): """React when an alien reaches the edge of the screen""" for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _ship_hit(self): """Processing of chip collision "with the alien...
This method updates alien positions, checks fleet edges, detects collisions between aliens and the player's ship, and verifies if aliens have reached the screen's bottom to trigger game-over logic.
def _update_aliens(self): """Update the positions of all aliens in the fleet""" self.aliens.update() self._check_fleet_edges() # Check collision alien-ship if pygame.sprite.spritecollideany(self.ship, self.aliens): self._ship_hit() # Check if alliens at the mi...
def _check_events(self): # Check the keyboard and mouse actions for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: # If the key is pressed, the ship moves self._check_keydown_events(event) ...
The code runs the main game loop, continuously checking for events, updating game elements (ship, bullets, aliens) if the game is active, and rendering the screen to create an interactive gaming experience.
def run_game(self): """Start of the main cycle of the game""" while True: self._check_events() if self.stats.game_active: self.ship.update() self._update_bullets() self._update_aliens() self._update_screen()
def _ensure_plottable(*args): """ Raise exception if there is anything in args that can't be plotted on an axis. """ plottypes = [np.floating, np.integer, np.timedelta64, np.datetime64] # Lists need to be converted to np.arrays here. if not any(_right_dtype(np.array(x), plottypes) for x in ...
This function generates 2D plots from xarray DataArrays using matplotlib. It validates input dimensions, extracts coordinates/values, configures colormaps and contour levels, adds labels/colorbars, and returns the plot primitive. It handles both contour and filled contour plots, ensuring proper data formatting and visu...
def newplotfunc(darray, ax=None, xincrease=None, yincrease=None, add_colorbar=True, add_labels=True, vmin=None, vmax=None, cmap=None, center=None, robust=False, extend=None, levels=None, **kwargs): # All 2d plots in xray share this function signature. ...
def update_screen(self, image=None): """Update current image""" if image is not None: self.heart = image heart = self.convert_() new_image = ImageTk.PhotoImage(heart.image.resize((500, 500))) self.canvas.configure(image=new_image) self.canvas.image = new_ima...
This code configures UI widgets to control a heart graphic's appearance. Each widget's command triggers specific drawing methods on 'self.heart' (gradients, colors, outlines) and updates the display. It links UI elements to dynamic properties like color selection, gradient styles, line patterns, and random generation, ...
def config_commands(self): """Configure widgets""" self.gradient1.config( command=lambda: (self.heart.gradient_filled(self.color1, self.color2), self.update_screen())) self.gradient2.config( command=lambda: (self.heart.gradient_center(self.color1, self.color2), self.updat...
def update_screen(self, image=None): """Update current image""" if image is not None: self.heart = image heart = self.convert_() new_image = ImageTk.PhotoImage(heart.image.resize((500, 500))) self.canvas.configure(image=new_image) self.canvas.image = new_ima...
The code's main task is to initialize and start a graphical application by updating the screen and stripes, configuring commands and tooltips, packing UI components, and launching the application's main loop. This method serves as the entry point to activate the app's interface and functionality.
def start(self): """Start the app""" self.update_screen() self.update_stripes() self.config_commands() self.config_tooltips() self.pack() self.run()
def find_corr(xyz0, xyz1, F0, F1, subsample_size=-1): ''' find corresboundings based on nearest neighbors ''' subsample = len(F0) > subsample_size if subsample_size > 0 and subsample: N0 = min(len(F0), subsample_size) N1 = min(len(F1), subsample_size) inds0 = np.random.choice...
The code performs point cloud registration using the FCGF (Fast Point Feature Histograms) method. It loads a pre-trained ResUNet model, extracts features from input point clouds, identifies correspondences between source and target point clouds, estimates a transformation matrix, and applies it to align the source clou...
def alignment(config): ''' Core part of performing registration using FCGF input:config return: alined source point cloud transformation matrix ''' device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') voxel_size = config.voxel_size checkpoin...
def get_transformation_matrix(theta,axis,translation): ''' Create rotation matrix for random rotation and translation ''' axis = axis / np.linalg.norm(axis) a = np.cos(theta / 2) b, c, d = -axis * np.sin(theta / 2) aa, bb, cc, dd = a*a, b*b, c*c, d*d bc, ad, ac, ab, bd, cd = b*c, a*d, a*...
The main task of the code is to process LAS point cloud files by extracting 4-digit identifiers, applying random transformations, performing FCGF registration, simplifying selected classes, and saving transformation matrices and registered point clouds for analysis. It handles both full and subset registrations, ensuri...
def main(): #root path for file_name in os.listdir(path): if file_name.endswith('.las'): file_path = os.path.join(path, file_name) #prepare file path match = re.search(r'\d{4}', file_name) if match: number = match.g...
def construct_steps(file): cfg = json.load(file) if len(cfg) == 0: return [], [] steps = [(PREPROCESSING_OPTIONS[step['type']](**step.get('params', {})), step.get('params', {})) for step in cfg] return zip(*steps) def magic_predict(data: pd.DataFrame, steps: List[PreprocessingStep], ...
The code's main task is to load and preprocess data, select a model (LightGBM or neural network), generate predictions using either a standard or "magic" prediction method, and save results to a CSV file. It handles data extension, categorical encoding, formatting, merging, and type optimization before applying the cho...
def predict(args): from models import LightGBMModel print("Loading data...") data = load_data_raw(read_csvs=args.evaluation, evaluation=args.evaluation) steps, params = construct_steps(args.config) data = ExtendData(upto=EVAL_DATA_MAX if args.evaluation else VAL_DATA_MAX)(data) data = Categor...
def fillDiagonal(grid): i = 0 while i < n: fillBox(grid, i, i) i += base def fillRemaining(grid): numbers = [i for i in range(1, 10)] for i in range(0, 81): row = i // 9 col = i % 9 if grid[row][col] == 0: shuffle(numbers) for num in number...
The code generates a 9x9 Sudoku puzzle by initializing a grid, filling diagonal and remaining cells with valid numbers, removing `k` elements to create empty cells, and returning the partially filled puzzle.
def generator(k): grid = [[0 for i in range(0, 9)] for j in range(0, 9)] fillDiagonal(grid) fillRemaining(grid) remove(grid, k) return grid
def algorithm_row(possible_value_, solution_): """ :param possible_value_: the dict of storing all possible numbers of each cell :param solution_: the list of existing solution Apply Crook's algorithm on each row """ for i in range(1, 10): possible_list = {key: value for key, value in po...
The function `loop_algorithm` repeatedly applies Crook's algorithm (via row, column, and box constraints) to update the `solution_` list until no further changes occur. It uses a deep copy to compare the current solution with the previous state, halting when they match. The goal is to iteratively refine the solution by...
def loop_algorithm(possible_value_, solution_): """ :param possible_value_: the dict of storing all possible numbers of each cell :param solution_: the list of existing solution Apply Crook's algorithm until there is no update on solution_ """ while True: solution_old = copy.deepcopy(sol...
def filter_config(config, target_prefix): return { k.replace(target_prefix, ''): v for k, v in config.items() if target_prefix in k } def send_to_destination(job_id, dest_config, constants, query_resource, row): # get state from datastore resources = load_from_datastore(job_id) ...
The main task of the code is to process a response by extracting data from the source using a configuration, sending it to a destination, and handling pagination by recursively processing subsequent pages if a pagination URL is specified. It uses cached parsing to locate data, iterates over results, and triggers furthe...
def process_response(config, source): # get results job_id = config['id'] query_resource = config.get('query_resource', None) dest_config = filter_config(config, 'dest_') constants = config.get('constants', {}) # optional results_path = config['source_msg_path'] matches = CachedParser.find(...
def build_argparser(): banner = "%(prog)s - Interact with PEPs" additional_description = "\nhttp://eido.databio.org/" parser = VersionInHelpParser( prog=PKG_NAME, description=banner, epilog=additional_description, version=__version__) subparsers = parser...
The code defines a main function handling command-line operations for a project conversion tool. It parses arguments, configures logging based on debug/verbosity flags, and executes commands like 'convert' (to transform projects) or 'list' (to show supported formats). The core tasks involve argument parsing, logging in...
def main(): """ Primary workflow """ parser = build_argparser() args, remaining_args = parser.parse_known_args() if args.command is None: parser.print_help(sys.stderr) sys.exit(1) # Set the logging level. if args.dbg: # Debug mode takes precedence and will listen fo...
def _add_registered_client_auths(self): """Adds the client authorization file for all registered clients with activated remote access. """ for device_name, device_value in self._registered_devices.items(): if device_value["onion_address"] != "": tor.add_onion...
This method manages a client interface for smart home devices, allowing users to add new devices, select registered devices, or exit. It maintains a loop for the main menu, processes user choices, and triggers device-specific operations via '_choose_operation' after device selection.
def start_client(self): """Handles the whole client functionality. Starts a menu where new devices can be added and registered devices can be chosen. """ self._add_registered_client_auths() self._added_client_auths = True # Loop until the main menu is exited whi...
def exit_program(clear=True): print("") message("Good bye", clear) input("\n Press enter to exit.") sys.exit(0) def clear_console(): command = 'clear' if os.name in ('nt', 'dos'): command = 'cls' os.system(command) print("") def error(message, clear=True): if clear: clear_con...
This code presents a menu-driven interface allowing users to select and execute various tools or functions, including content packaging, pixel cleaning, project name generation, and add-on creation, with error handling and an exit option.
def main(): print(Fore.LIGHTBLACK_EX + " 0. Exit") print(Fore.CYAN + " 1. Content Packager") print(Fore.CYAN + " 2. Pixel Cleaner") print(Fore.CYAN + " 3. Project Name Generator") print(Fore.CYAN + " 4. Add-on Project Creator") print(Fore.CYAN + " 5. Add-on Commentor") operation = inpu...
def initialize_array(size, starting_element=1): """Create a numpy array with the number of rows and columns equal to size. Find the midpoint of the array given by the position indicated by the (size / 2, size / 2) rounded down. Initialize the position of the array at that midpoint to be the starting_ele...
The main task of the code is to compute the sum of the diagonals of a square matrix of size 1001x1001, ensuring the size is odd. It initializes and populates a 2D array, then calculates the sum of its main diagonals (from top-left to bottom-right and top-right to bottom-left), returning the result. The code emphasizes ...
def main(): SIZE = 1001 assert SIZE % 2 == 1, "SIZE must be odd." array = initialize_array(SIZE) array = populate_array(array, SIZE) answer = sum_diagonals(array, SIZE) return answer
def inputNonZeroFloat(msg): """ Further wraps inputFloat() with the additional constraint that the float input must be non-zero. :param msg: input prompt to display :return: inputted valid non-zero float """ x = inputFloat(msg) if x != 0: return x print("Error: this value may not be 0")...
The code defines a test function for a linear equation. It prompts the user to input values for slope (m) and intercept (c), then computes and prints the result of the linear function using these values. The main task is to validate the linear function's output with user-provided parameters.
def test_linear(): """ Test the linear() function with user input """ m = inputNonZeroFloat("Please enter a value for m: ") c = inputFloat("Please enter a value for c: ") print(f"x = {linear(m, c)}")
def exit(self): self.connector.disconnect() sys.exit(0) def sqlrunner(self): print("Entering Query Tool") while True: userstring = input("Enter SQL Query: ") if userstring == "exit": self.exit() if userstring == "back": ...
This function processes user commands in a loop, validating inputs and invoking methods like 'exit', 'sqlrunner', 'explore', 'view', 'new', or 'delete' based on the command. It checks for required parameters, provides error messages for invalid inputs, and continues until 'exit' is entered.
def commandrunner(self): while True: userstring = input("Enter Command: ") verify = userstring.split(" ") if userstring == "": continue elif userstring == "exit": self.exit() elif userstring == "query tool" or userstrin...
def display_boot_message(): print(f"Welcome to Kontact Keeper {VERSION_NUMBER}!") print("Please report any issues via e-mail to bugs@kontact_keeper.net\n") def load_or_create_contact_store(): print("Attempting to load existing contact data...") if os.path.exists(CONTACT_DATA_FILE_PATH): with op...
The main task of the code is to manage a contact store by initializing it, enabling user interactions to modify contacts, and saving changes. It starts with a boot message, loads or creates the contact store, processes user input to edit contacts, saves the updated store, and displays an exit message to conclude the se...
def main(): display_boot_message() contacts = load_or_create_contact_store() contacts = begin_user_interaction(contacts) save_contact_store(contacts) display_exit_message()
def fen_to_2d_array(self,fen): pieces_mapping = { 'r': '♜', 'n': '♞', 'b': '♝', 'q': '♛', 'k': '♚', 'p': '♟', 'R': '♖', 'N': '♘', 'B': '♗', 'Q': '♕', 'K': '♔', 'P': '♙' } rows = fen.split('/') board = [] for row in rows: new_row = [] ...
The code processes chess puzzles from a CSV file, initializing a chess board with each puzzle's FEN string. It iterates through pre-defined move sequences, applying opponent moves and prompting users to input their moves. The program validates user moves against the puzzle's solution, providing feedback and progressing...
def solve_puzzle(self, csv_file_path): # Read the CSV and play through puzzles with open(csv_file_path, mode='r') as csv_file: csv_reader = csv.reader(csv_file) header = next(csv_reader) # Skip the header row all_rows = [row for row in csv_reader] # Store all rows ...
def draw_board(self): # Draw the chessboard for row in range(8): for col in range(8): x1 = col * 50 y1 = row * 50 x2 = x1 + 50 y2 = y1 + 50 color = "white" if (row + col) % 2 == 0 else "grey" sel...
The code displays a new screen with a chessboard, controls, and message area. It hides the current screen, creates a new frame with a title, initializes a chessboard layout, adds buttons for puzzle interactions (move, hint, next puzzle, back), and a message label. The screen is designed for a puzzle-solving interface, ...
def show_new_screen(self, screen_name, csv_file_path): self.current_screen.pack_forget() # Hide the current screen main_container = tk.Frame(root) main_container.pack(padx=15, pady=15, expand=True, fill='both') self.current_screen = main_container # Adding a label to display th...
def __fetch_event_history(self): """ For each sensor in project, request all events since --starttime from API. """ # initialise empty event list self.event_history = [] # iterate devices for device in self.devices: # isolate device identifier ...
The main task of the code is to process historical event data by iterating through it, updating progress, and sending each event to a director for handling. It also initializes plots for visualization if enabled, with a blocking plot for history and a non-blocking one for the stream, while optionally displaying debug p...
def run_history(self): """ Iterate through and calculate occupancy for event history. """ # do nothing if starttime not given if not self.fetch_history: return # get list of hsitoric events self.__fetch_event_history() # estimate oc...
def initialise_plot(self): """ Create figure object used in results visualization. """ self.fig, self.ax = plt.subplots(3, 1, sharex=True) def plot_progress(self, blocking): """ Plot the stream and all its devices with desk occupancy status. """ # refr...
The code continuously listens for real-time sensor stream data, processes incoming Server-Sent Events (SSE), and estimates occupancy. It handles disconnections with up to `n_reconnects` attempts, parses event data, updates a director component, and optionally updates a live plot. The function runs indefinitely until ma...
def run_stream(self, n_reconnects=5): """ Estimate occupancy on realtime stream data from sensors. Parameters ---------- n_reconnects : int Number of reconnection attempts at disconnect. """ # cout print("Listening for events... (press CTRL-...
def initialize(self,n,dim,ub,lb): ans=np.zeros((n,dim),dtype="float") #randomly generating all the elements for i in range(0,n): for j in range(0,dim): #point to note: rand(a,b) means [a,b] both ranges inclusive ans[i][j]=(random.random())*(ub[j]-lb[j])+lb[j] return ans def find_ne...
The code implements a Dragonfly Swarm Optimization (DSO) algorithm to find the optimal solution for a given objective function within specified bounds. It initializes a population of dragonflies, iteratively updates their positions using social forces (separation, alignment, cohesion), attraction to the best solution (...
def optimize(self,obj,dim,bound,n,max_it): #getting the dimensions # dim=np.size(bound)[2] ub=np.zeros((dim),dtype="float") lb=ub.copy() #setting the values of the range for i in range(0,dim): lb[i]=bound[i][0] ub[i]=bound[i][1] #setting the initial r. In paper code, th...
def login(self, browser: Chrome, driver: Driver): if self.logged_in(browser): return browser.bypass() if "queue" in browser.current_url: self._logger.info("Queuing...") while "queue" in browser.current_url: sleep(2) randsleep(3) browse...
The main task of the code is to locate and verify current test booking details, check for cancellation/exceeded limits, extract test date and center information, and search for available test dates across specified centers while handling navigation and logging.
def find_tests(self, browser: Chrome, driver: Driver): self.login(browser, driver) main = browser.find_element(value="main").get_attribute("innerHTML") if "has been cancelled" in main: raise ScraperError("Booking Cancelled.") elif "has now been exceeded" in main: ...
def dvsa_disabled(self): return datetime.now() < datetime.combine( dt.date.today(), self.DVSA_OPENS ) or datetime.now() > datetime.combine(dt.date.today(), self.DVSA_CLOSES) def find_tests(self, browser: Chrome, driver: Driver): self.login(browser, driver) main = browser.find...
The code continuously searches for driver tests via a browser, handling website unavailability and errors. It loops through drivers, logs progress, and sleeps between attempts. If five errors occur within 10 minutes, it aborts to prevent IP blacklisting.
def __call__(self): while True: self._logger.info("Starting search loop") if self.dvsa_disabled(): self._logger.info("Website not currently available; sleeping.") while self.dvsa_disabled(): randsleep(60) # has spinner while not...
def adjustLink(self, url): if not self.hasHost(url): url = self.addHostToUrl(url) return url def fetch(self, url): logger.opt(ansi=True).info(f'<b>Fetch</b>: <blue>{url}</blue>') self.result = requests.get(url) def getPictureOfTheDay(self): if self.parseContent()...
(The method `getAllPictures` iterates through a list of links, adjusts each to target the "apod/" endpoint, fetches the content, and checks if a Picture of the Day (APOD) is successfully retrieved. If not, it logs an error and skips the link. The task involves processing each link to extract and validate APOD images, h...
def getAllPictures(self): for link in self.list_of_links: link_to_fetch = self.adjustLink('apod/' + link["href"]) self.fetch(link_to_fetch) if not self.getPictureOfTheDay(): logger.opt(ansi=True).error(f'<b>Picture not found</b>... ' + \ f...
def predict_eps(self, x_t, t, ema=False): if ema: return self.ema(x_t, t) return self.unet(x_t, t) def save(self, path): torch.save({'net': self.state_dict(), 'optim': self.optim.state_dict(), 'losses': self.losses, ...
The main task of this code is to train a diffusion model by iteratively predicting noise added to data samples. It processes batches from a loader, generates random noise, computes predicted noise using the model, calculates the loss between true and predicted noise, and updates model parameters via gradient descent. T...
def train_loop(self, steps, loader): self.train() with tqdm(initial=self.step, total=steps) as tbar: while self.step <= steps: for x_0, _ in loader: x_0 = x_0.to(self.dev) t = np.random.randint(1, self.diffusion_steps) ...
def merge_title_files(self): self.title_file_pointers={} i=1 heap=[] for fname in self.title_files: fp=open(self.title_directory+fname,'r',encoding='utf-8') self.title_file_pointers[i]=fp first_line=fp.readline().rstrip() heap.app...
The main task of the code is to merge multiple types of data files (title, infobox, category, body, and reference) into a unified structure. The `merge_files` method sequentially calls specialized helper methods to combine these distinct components, likely aggregating or integrating content from separate files into a c...
def merge_files(self): self.merge_title_files() self.merge_infobox_files() self.merge_category_files() self.merge_body_files() self.merge_reference_files()
def is_phrase_query(query): ftq=['b:','c:','i:','r:','t:','l:'] for q in ftq: if q in query: return False return True def search_phrase_query(query,num_results): titles=search_in_index(query,'title',num_results) bodys=search_in_index(query,'body',num_results) refs=search...
The code executes a query, either as a phrase query or a field-based search, retrieves up to `num_results` results, and writes them to a file alongside execution time metrics. It handles phrase queries by timing and logging results, while non-phrase queries use field-based search, logging top scores and average time pe...
def execute_query(query,num_results): if is_phrase_query(query): start=time() phrase_result=search_phrase_query(query,num_results) end=time() for i in range(num_results): try: result_file.write(f'{phrase_result[i][0]},{phrase_result[i][1]}\n') ...
def existee (): filename = r"C:\Users\USER\Desktop\json\jumia.json" if os.path.exists(filename): return filename else: remplir(filename) return filename def ver(ch): for i in range(len(ch)): if ch[i] not in ['0','1','2','3','4','5','6','7','8','9'] : return False ...
The code filters phone data based on user input (name and price range) from a POST request, validates inputs, processes JSON data, and renders a filtered list in 'home.html' with error handling for invalid inputs or no results.
def home(request): dicf = [] if request.method=='POST': x=request.POST['d'] y=request.POST['t2'] y1=request.POST['t3'] fil=existee() with open(fil,'r') as f: data=json.load(f) if x and ver(y) and ver(y1): ...
def _get( self, endpoint: str, dryrun: bool = False ) -> Union[Response, None]: """ Calls the api and returns the response if a successful status code :param endpoint: The extension of the base url with any filters added :param dryrun: If True it ...
The function `get` sends API requests to specified endpoints, validates responses using a schema, handles custom IDs for specific endpoints, checks available credits, and returns data or `None` based on parameters. It ensures endpoint validity, raises errors for invalid inputs, and updates credit usage after successful...
def get( self, endpoint: str, dryrun: bool = False, validate: bool = True, validation_schema: Dict = None, custom_ids: Dict = None, ) -> Union[Dict, None]: """ Can be used to run against any arbitrary endpoint. Using this functi...
def collision(self, start_node, end_node, map): collided = False buffer = 50. # make sure that we are not close to any obstacle pts = self.pointsAlongPath(start_node, end_node) for i in range(len(pts)): col_n = np.abs(map.building_north - pts[i, 0]) < ( ...
The main task of the code is to plan a collision-free 3D path from a start waypoint to an end waypoint using a tree-based algorithm. It initializes a start/end node structure, checks for direct connectivity, extends the tree iteratively, finds the minimum-cost path, smooths it, and assigns waypoints with airspeed and c...
def planPath(self, wpp_start, wpp_end, map): # desired down position is down position of end node pd = wpp_end.item(2) # specify start and end nodes from wpp_start and wpp_end # format: N, E, D, cost, parentIndex, connectsToGoalFlag, start_node = np.array([wpp_start.item(0), wp...
def normalize_imgs(data): """Normalize images.""" return normalize(data, type_=1) def imgs_to_grayscale(imgs): '''Transform RGB images into grayscale spectrum.''' if imgs.shape[3]==3: imgs = normalize_imgs(np.expand_dims(np.mean(imgs, axis=3), axis=3)) return imgs def invert_imgs(imgs, cuto...
The main task of the code is to preprocess images by normalizing pixel values, optionally converting them to grayscale, and inverting colors to create dark backgrounds. These steps standardize image data for further analysis or model training, with parameters allowing customization of grayscale conversion and inversion...
def preprocess_raw_data( x_test, grayscale=False, invert=False): """Preprocessing of images and masks.""" # Normalize images and masks x_test = normalize_imgs(x_test) print('Images normalized.') if grayscale: # Remove color and transform images into grayscale spectrum. x_test = im...
def normalize_imgs(data): """Normalize images.""" return normalize(data, type_=1) def trsf_proba_to_binary(y_data): """Transform propabilities into binary values 0 or 1.""" return np.greater(y_data,.5).astype(np.uint8) def normalize_masks(data): """Normalize masks.""" return normalize(data, ty...
The function preprocesses image and mask data by normalizing pixel values, optionally converting images to grayscale, and inverting colors to darken backgrounds. It prepares training and test datasets for machine learning tasks, ensuring consistent input formatting and enhancing model performance through standardizatio...
def preprocess_raw_data(x_train, y_train, x_test, grayscale=False, invert=False): """Preprocessing of images and masks.""" # Normalize images and masks x_train = normalize_imgs(x_train) y_train = trsf_proba_to_binary(normalize_masks(y_train)) x_test = normalize_imgs(x_test) print('Images normali...
def normalize_imgs(data): """Normalize images.""" return normalize(data, type_=1) def trsf_proba_to_binary(y_data): """Transform propabilities into binary values 0 or 1.""" return np.greater(y_data,.5).astype(np.uint8) def normalize_masks(data): """Normalize masks.""" return normalize(data, ty...
The main task of the code is to preprocess raw image and mask data by normalizing pixel values, optionally converting images to grayscale, and optionally inverting image colors to standardize data for machine learning tasks like segmentation. It prepares training and test datasets by applying these transformations to e...
def preprocess_raw_data(x_train, y_train, x_test, grayscale=False, invert=False): """Preprocessing of images and masks.""" # Normalize images and masks x_train = normalize_imgs(x_train) y_train = trsf_proba_to_binary(normalize_masks(y_train)) x_test = normalize_imgs(x_test) print('Images normali...
def run_init(ctx, inputs): target_view = ctx.target_view() run_key = get_new_run_key(ctx, inputs) if run_key is None and run_key != "None": return False get_embeddings(ctx, inputs, target_view) return True def _handle_basic_inputs(ctx, inputs): method_choices = types.DropdownView() ...
The main task of the code is to process input parameters for a clustering workflow. It initializes input objects, validates readiness, handles basic inputs, routes method configurations, sets the view target, and determines execution mode. The function prepares structured input data for clustering based on embeddings, ...
def resolve_input(self, ctx): inputs = types.Object() form_view = types.View( label="Clustering", description="Create clusters from embeddings" ) ready = run_init(ctx, inputs) if not ready: return types.Property(inputs, view=form_view) _handle_ba...
def get_private_key_obj(self): """Return the private key object.""" key_pem = self.get_pki_asset("key") key = serialization.load_pem_private_key(key_pem, password=None, backend=default_backend()) return key def build_x509_name(self): ...
The main task of the code is to generate a self-signed X.509 certificate using a private key, define its subject/issuer details, validity period, and subject alternative name (SAN) extension, then serialize and save the certificate in PEM format to disk. The certificate is valid for 10 days from issuance and signed wit...
def generate_selfsigned_certificate(self): """Generate a self-signed certificate, write to disk.""" key = self.get_private_key_obj() issuer = subject = self.build_x509_name() subject_alt_name = self.build_subject_alt_name() cert = x509.CertificateBuilder( ).subject_name(s...
def verify_transaction_signature(self, sender_public_key, signature, transaction): public_key = RSA.importKey(binascii.unhexlify(sender_public_key)) verifier = PKCS1_v1_5.new(public_key) h = SHA.new(str(transaction).encode('utf8')) try: verifier.verify(h, binascii.unhexlify(s...
The code submits a buy transaction by verifying its signature, appending it to the transaction list if valid, then creating a new block after resolving conflicts across nodes. It increments a transaction counter, triggers block creation when transactions exist, and communicates with other nodes to synchronize the block...
def submit_buy_transaction(self,sender_public_key,recipient_public_key,signature,amount): transaction = OrderedDict({'sender_public_key': sender_public_key, 'recipient_public_key': recipient_public_key, 'amount': amount}) signature_ve...
def verify_transaction_signature(self, sender_public_key, signature, transaction): public_key = RSA.importKey(binascii.unhexlify(sender_public_key)) verifier = PKCS1_v1_5.new(public_key) h = SHA.new(str(transaction).encode('utf8')) try: verifier.verify(h, binascii.unhexlify(s...
The function submits a transaction by verifying its digital signature, appending it to the blockchain if valid, creating a new block with the previous hash, and resolving conflicts across nodes. It increments a transaction counter, triggers block creation when transactions exist, and resets the counter post-processing....
def submit_transaction(self,sender_public_key,recipient_public_key,signature,amount): transaction = OrderedDict({'sender_public_key': sender_public_key, 'recipient_public_key': recipient_public_key, 'amount': amount}) signature_verifi...
def caption2tags(caption): # Split the string by comma tags = reversed(caption.split(',')) # Strip whitespace from each tag and filter out empty strings cleaned_tags = {tag.strip() for tag in tags if tag.strip()} return cleaned_tags def create_caption_dictionary(directory): file_pairs = list_f...
This code processes files by generating tags from captions, reducing tag dimensions via matrix transformation, and associating each file with a ranked set of tags. It uses thresholding to filter tags, combines default tags with reduced results, and outputs labeled files to a specified directory.
def main(args): path = args['<path>'] threshold = float(args['--threshold']) n = int(args['--num-tags']) outdir = args['--output'] default_tags = caption2tags(args['--prompt'] or '') captions = create_caption_dictionary(path) file2tags = {file: caption2tags(caption) for file, caption in capt...
def __get_vertex_type(self, p1, p2, p3): if p2.y > p1.y and p2.y > p3.y and compute_angle(p1, p2, p3) < 180: return "start" elif p2.y > p1.y and p2.y > p3.y and compute_angle(p1, p2, p3) > 180: return "split" elif p2.y <= p1.y and p2.y <= p3.y and compute_angle(p1, p2, p3...
The code performs polygon triangulation via ear clipping by identifying 'split' and 'merge' vertices, adding diagonals to decompose the polygon into triangles. It processes input vertices, checks polygon orientation, constructs edges, and iteratively determines diagonals based on vertex types, returning the list of dia...
def split_to_convex(self, polygon_vertices): """ Perform triangulation of a given polygon by clipping all ears and returns triangles polygon consists of. :param polygon_vertices: array, size=(n, 2) :return: """ polygon = [] polygon_vertices = polygon_vertices ...
def float_to_binary(x, m, n): """Convert the float value `x` to a binary string of length `m + n` where the first `m` binary digits are the integer part and the last 'n' binary digits are the fractional part of `x`. """ x_bin = '' for i in range(len(x)): x_scaled = int(np.round(x[i] * 2 ...
The function generates transformed data from input sentences using specified algorithms. It converts sentence embeddings to binary representations, applies algorithm-specific processing (e.g., fRR, latent, DM, PM), scales results, and returns stacked arrays. The process involves encoding, binary conversion, transformat...
def gen_data(sentences, m1, m2, alpha, eps, l, name, alg): #Sentences are encoded by calling model.encode() # sentence_embeddings = bc.encode(sentences) # sentence_embeddings = model.encode(sentences) #Print the embeddings np.random.seed(1) data = [] c = 0 for sent in sentences: ...
def duchi(x, eps): lower = -1 upper = 1 C = (np.e ** eps + 1)/(np.e ** eps -1) p = (x - lower) / (upper - lower) x_ = torch.where(torch.rand_like(x) < p, upper*torch.ones_like(x), lower*torch.ones_like(x)) x_perturb = torch.where(torch.rand_like(x) < eps2p(eps), x_, -x_) return C*x_perturb d...
This function performs a local update in a federated learning setting by training a neural network on selected data, applying gradient transformations based on the specified algorithm (e.g., Duchi, PM), and returning the difference between the updated local model weights and the initial global weights. It uses SGD with...
def LocalUpdate(idx, train_fed, train_label_fed, net, learning_rate, weight_decay, eps, alg, num_w): net.cuda() net.train() global_w = deepcopy(net.state_dict()) optimizer = optim.SGD(net.parameters(), lr=1.0, weight_decay=weight_decay) criterion = nn.CrossEntropyLoss() data = [] data_label...
def LocalUpdate(idx, train_fed, train_label_fed, net, learning_rate, weight_decay, eps, alg, num_w): net.cuda() net.train() global_w = deepcopy(net.state_dict()) optimizer = optim.SGD(net.parameters(), lr=1.0, weight_decay=weight_decay) criterion = nn.CrossEntropyLoss() data = [] data_label...
The main task of the code is to perform federated gradient descent training on a distributed dataset. It aggregates local model updates from randomly selected users, averages their gradients, and updates the global model. The function tracks training/test accuracy, AUC, FPR, and TPR metrics over epochs, saving results ...
def run_gradient_descent(model,netw,train_fed, train_label_fed, user_idx,train,train_label,test, test_label,batch_size,learning_rate,weight_decay,num_epochs, eps, alg, num): model.cuda() epochs = [] iters, losses = [], [] iters_sub, train_fpr, test_fpr = [], [], [] train_tpr, test_tpr, = [], [] ...
def needs_parsing(snippet): # type: (Any) -> bool return isinstance(snippet, string_types) \ and ("$(" in snippet or "${" in snippet) def jshead(engine_config, rootvars): # type: (List[Text], Dict[Text, Any]) -> Text # make sure all the byte strings are converted # to str in `rootvars` dict. ...
The function `do_eval` evaluates an expression (`ex`) within a specified context, handling both Python and JavaScript-based expressions. It prepares runtime parameters, processes input variables, adjusts paths for Windows compatibility, and interpolates expressions using provided variables and requirements. If `ex` is ...
def do_eval(ex, # type: Union[Text, Dict] jobinput, # type: Dict[Text, Union[Dict, List, Text, None]] requirements, # type: List[Dict[Text, Any]] outdir, # type: Optional[Text] tmpdir, #...
def toggle_darkmode(self, value): if value == '1': self.theme_cls.theme_style = "Dark" else: self.theme_cls.theme_style = "Light" self.platform_check_for_statusbar(self.check_screen()) def toggle_intro_screen(self, value): if value == '1': self.screen....
This function handles configuration changes by printing updates and adjusting settings. It toggles dark mode or intro screen based on 'darkmode' or 'bool' keys. For 'saveoptions', it enables/disables digit/special/uppercase settings when value is '1' or '0', respectively, updating the config file accordingly.
def on_config_change(self, config, section, key, value): print(config, section, key, value) if key == 'darkmode': self.toggle_darkmode(value) elif key == 'bool': self.toggle_intro_screen(value) elif key == 'saveoptions' and value == '1': self.set_digit...
def HOGSVD_fit_S(self, X): N = len(X) data_shape = X[0].shape A = [torch.matmul(x.transpose(0, 1), x).float().cuda() for x in X] A_inv = [self.inverse(a.double()).float().cuda() for a in A] S = torch.zeros((data_shape[1], data_shape[1])).float().cuda() for i in range(N)...
The main task of the code is to implement a HOGSVD (Higher-Order Generalized Singular Value Decomposition) fitting algorithm. It processes input data `X` by normalizing it to compute matrix `S`, performs eigen-decomposition on `S` to obtain `V`, constructs matrix `B` using `V`, and finally decomposes `B` into singular ...
def HOGSVD_fit(self, X): """A reference implementation of a fitting function for a transformer. Parameters ---------- X : array-like, shape (n_samples, (n_rows_i, n_cols) List of training input samples. Eah input element has the same numbe of columns but can have ...
def compute_window(token_index, tokens_in_line, window_size): # get context window tokens context_start = max(token_index-window_size, 0) context_end = min(token_index+window_size+1, len(tokens_in_line)) window = tokens_in_line[context_start:token_index] + tokens_in_line[token_index+1:context_end] ...
This function updates the sentence graph (sg) by ablating a specific token. It removes the token from the model's vocabulary, re-encodes the text, calculates token offset changes, ensures context windows remain consistent before/after ablation, subtracts original window contributions, and adds updated window contributi...
def update_sg_per_instance_of_token_mp(model, token_to_ablate, i, \ line, tokens_in_line_ints, tokens_in_line_pieces, \ last_times_accumulate_offset, \ current_total_sg, current_vocab, \ ...
def get_unread_ids(self, folder_name): return self._get_message_ids(folder_name=folder_name, unread=True) def get_all_message_ids(self, folder_name): return self._get_message_ids(folder_name=folder_name) def get_message_objs(self, uids, from_folder, include_attach=False): if uids is None or len(...
This function retrieves message UIDs from a specified mail folder based on search criteria (senders, dates, subjects, etc.), combining results using "and" or "or" logic. It filters messages by unread status, date ranges, and attachments, dynamically applying IMAP queries for each criterion and intersecting/unionizing r...
def get_message_uids(self, folder_name, searchspec, merge="or"): """Get messages from mail folder with criteria in a dictionary such as: { "senders": "zhvmk@example.com", "since": date(2000, 6, 30), "unread": True } valid keys: senders, recipients, since, before, unread, subject """ ...
def listify(obj): if isinstance(obj, str): ls = obj.split() if len(ls) > 1: return ls return [obj] if not isinstance(obj, (list)): return [obj] return obj def get_message_uids(self, folder_name, searchspec, merge="or"): """Get messages from mail folder wit...
The code processes email account rules by applying move/delete actions to messages in the INBOX based on rule criteria. It reads rule files, searches for matching messages, creates missing folders if needed, and performs or simulates (via dryrun) actions like moving/deleting messages, with progress logging.
def process_rules(self, dryrun=False): rulefiles = MailSession.get_account_rules(self.name) if rulefiles is None: return for rulefile in rulefiles: print(" Processing rule file: %s" % (rulefile)) rules = metayaml.read(rulefile, disable_order_dict=True) ...
def fetch_ci_runs(): if os.path.exists("data/builds/manifest.json"): manifest = load_json("data/builds/manifest") else: manifest = { "builds": [], "last-fetched-id": -1, "last-processed-id": -1 } print("Fetching a list of recent ci-runs") con...
The main task of the code is to organize and process CI/CD data by setting up directories, parsing command-line arguments, fetching CI runs and issues, processing test failures, and performing analysis. It disables colored output, ensures directory structure, and handles data reindexing if specified, ultimately analyzi...
def main(): # because otherwise g() returns results with ASCII escape codes to colorize os.environ['NO_COLOR'] = '1' os.makedirs("data/builds", exist_ok=True) os.makedirs("data/failures", exist_ok=True) os.makedirs("data/issues", exist_ok=True) shutil.rmtree("data/open", ignore_errors=True) ...
def _get_board_state(self, board): return tuple([ 1 if element == self._symbol else 0 if element == ' ' else -1 for line in board for element in line ]) def _check_winner(self, state): for i in range(3): line_value = sum(state[3*i:3*(i+...
The code processes a game board by checking for a winner, updating the last action's value if the winner isn't 1 or the current player is the same as 'self', and storing the board state for future reference in decision-making or learning processes.
def process(self, board, current_player): state = self._get_board_state(board) winner = self._check_winner(state) if winner != 1 or current_player is self: self._update_last_action_value(state) self._last_state = state
def _get_board_state(self, board): return tuple([ 1 if element == self._symbol else 0 if element == ' ' else -1 for line in board for element in line ]) def _get_action_space(self, state): action_space = [ idx for idx, element in enumer...
This code determines the next move in a game by evaluating the board state, selecting an action from the available action space using a greedy strategy (or fallback to a random action), and returning the corresponding line and column coordinates for the move.
def get_input(self, board): state = self._get_board_state(board) action_space = self._get_action_space(state) use_greedy_action = True # TODO set epsilon if use_greedy_action: action = self._get_greedy_action(action_space, state) else: action = action_sp...
def choose_image(name): dir = os.listdir(f"./{name}/") num_choice = random_choice(len(dir)) image_choice = dir[num_choice] attributes[name]=image_choice.split(".")[0] image_location = f"./{name}/{image_choice}" add_to_count(name, image_choice.split(".")[0]) return image_location de...
The code generates a series of images by randomly combining traits like heads, shirts, shoes, and accessories, applying them to a background or legs image. It avoids specific trait combinations, saves each image with a unique name, and tracks statistics for trait occurrences. The process repeats based on a command-line...
def main(): for i in range(0, int(sys.argv[1])): if len(sys.argv) >= 3: if sys.argv[2] == "--no-bg" or sys.argv[2] == "-nb": legs_img = choose_image("Legs") background = Image.open(legs_img) else: background = Image.open(choose_image("Backgrou...
def print_grid(grid): print("_____________\n") print(" A B C D E F G H I J ") print(" ___________________________________________________________ ") print(" | | | | | | | | | | |") print_ships(grid) print_legend...
The main task of the code is to let the user place five types of battleships (carrier, battleship, cruiser, submarine, destroyer) on their grid. It displays the grid, prompts for ship placements via individual functions, and sets a global flag 'placed_ships' to True upon successful placement.
def place_ships(): print("_____________") print("\n Your Grid\n") print_grid(myGrid) print("This is your grid") print("Where do you want to place your battleships?") place_carrier() place_battleship() place_cruiser() place_submarine() place_destroyer() print("Placed ships su...
def print_grid(grid): print("_____________\n") print(" A B C D E F G H I J ") print(" ___________________________________________________________ ") print(" | | | | | | | | | | |") print_ships(grid) print_legend...
The main task of the code is to manage a turn-based game connection, handle player setup by placing ships, synchronize game states between players, and execute gameplay logic. It checks for game status (connected, setup phase, ongoing, or over), updates grids, determines turns, processes moves, and displays win/loss ou...
def main(): print("Trying to connect to a game...") run = True n = Network() player = int(n.get_player()) print("You are player", player) print("Looking for opponent...") time.sleep(3) # Run until game is over or player quits/disconnects while run: try: # Gets ...
def _compute_embedding(self, x, datalength, filenames, eval_flag=False): """ definition of forward method Assume x (batchsize, length, dim) Output x (batchsize * number_filter, output_dim) """ # resample if necessary #x = self.m_resampler(x.squeeze(-1)).unsqueeze(-1) ...
The code computes embeddings and scores for audio segments and utterances during training, preparing multi-scale segmental and utterance-level cosine similarity scores along with targets. During evaluation, it validates data lengths, computes scores, generates alignment targets, and debugs by saving alignment data for ...
def forward(self, x, fileinfo, dev_flag=False): filenames = [nii_seq_tk.parse_filename(y) for y in fileinfo] datalength = [nii_seq_tk.parse_length(y) for y in fileinfo] batch_size=len(filenames) if self.training: outs = self._compute_embedding(x, datale...
def get_relevant_reviews(self,product_id,question): text = question text = re.split('\W+',text) unique_words = set() for term in text: unique_words.add(term) qa_vec_lcl = [] for term in unique_words: if term in self.model.wv.vocab: qa_vec_lcl.append(self.model[term]) qa_vec_lcl = self.compute_ce...
This code evaluates the precision, recall, and accuracy of a model on a test dataset by iterating through product questions, calculating metrics for binary answer types (Y/N), and writing results to a file. It aggregates performance across all products, normalizes values, and outputs category-level statistics as percen...
def test_code(self,fp): product_precision = 0.0 product_accuracy = 0.0 product_recall = 0.0 count = 1 tot_prods = len(self.test_questions) for product_id in self.test_questions: ''' print count sys.stdout.write("\033[F") count += 1 ''' for question in self.test_questions[product_id]: a...
def get_reviews(test_question,num_of_reviews,product_id): global ob x,y,z,reviews = ob.predict(test_question,num_of_reviews,[],product_id) return reviews def get_sentiment(reviews,sentiment): result=[] for r in reviews: if r[1]==sentiment: result.append(r) return result def g...
The function processes reviews by analyzing sentiment, ranking relevant sentences, and compiling a structured answer. It retrieves reviews, separates them into positive/negative sentiment groups, ranks all sentences, and formats the top results into a response containing selected reviews and sentences based on the inpu...
def review_2_sent(question,num_r,p_id): reviews = get_reviews(question,50,p_id) #print reviews pos_reviews = get_sentiment(reviews,"Yes") neg_reviews = get_sentiment(reviews,"No") wt_sent_pos=[] wt_sent_neg=[] wt_sent_all = get_ranked_sent(reviews,question) # if len(pos_reviews)>0: #...
def generate_trained_df(run_id, trainer): """ Given a run id load the trained model in run_id dir to its respective trainer and return the generated dataframe :param run_id: run_id :param trainer :return: """ if trainer.dataGroup == "outer": generator = nn.DataParallel(OuterGenerator...
The main task of the code is to analyze and visualize results from a machine learning run by plotting KL divergence and discriminator loss curves, performing chi-squared/K-S tests on data distributions, generating correlation plots, and saving statistical results in JSON format. It handles both trained models and pre-s...
def check_run(run_id, innerData, outerData, innerTrainer=None, outerTrainer=None): run_dir = 'Output/run_' + run_id + '/' fig_path = run_dir + 'plots' if not os.path.isdir(fig_path): os.mkdir(fig_path) fig_path += '/' if (innerTrainer is not None) and (outerTrainer is not None...
def heading_marker(level): '''Add a heading marker at given level relative to the top level as defined by the top-heading-level yaml parameter''' s = '' for i in range(top_heading_level + level): s += '=' return s + ' ' def format_text_from_array(input_array): ''' Concatenates an array o...
(The main task of the code is to generate a top-level AsciiDoc (adoc) index file from an API definition, including a title, notes, and module links. It creates a structured documentation outline by iterating through defined modules, generating separate adoc files for each, and embedding references to them in the index....
def generate_c_adoc(api_definition, out_dir): ''' Top level function which builds a top level index adoc file then iterates through modules defined in the api definition to build module documentation. Input parameters are the api_definition object and the output directory for the a...
def _get_revenue_by_manager(user_id): user = User.objects.get(pk=user_id) reporting_to = user.hierarchy_manager.all() # Get revenue for each sales rep under this manager revenue = [] for sales_rep in reporting_to: revenue.extend(_get_revenue_by_sales_rep(sales_rep.employee.id)) return...
This function retrieves revenue data based on a user's role (sales rep, manager, or director) by checking their hierarchy relations. It validates the user ID, determines their role via database queries, and returns revenue using corresponding helper functions for each role, handling errors for invalid inputs.
def get_revenue_by_sales_rep(request, user_id): try: user = User.objects.get(pk=user_id) except ObjectDoesNotExist: return JsonResponse({ "Error": f"User with user_id {user_id} does not exist"}) except ValueError: return JsonResponse({ "Error": f"Field 'id' expected a number but got...
def load_cols(df): """ adds calculated columns to a DataFrame that are used regardless of filter""" df['Start Time'] = pd.to_datetime(df['Start Time']) df['Month'] = df['Start Time'].dt.month_name() df['Start Hour'] = df['Start Time'].dt.hour df['Weekday'] = df['Start Time'].dt.day_name() return...
The function loads bike-sharing data for a specified city, filters it to include only rides from a given month, and displays time-based statistics and other metrics for that filtered dataset.
def load_data_filtered_by_month(city, month): """ takes in a city value and a month value and displays stats based off the values""" path = h.path_builder(city) df = pd.read_csv(path) load_cols(df) df = df.loc[df['Start Time'].dt.month == month] show_time_stats_month_filter(df) run_stats(df,...
def load_cols(df): """ adds calculated columns to a DataFrame that are used regardless of filter""" df['Start Time'] = pd.to_datetime(df['Start Time']) df['Month'] = df['Start Time'].dt.month_name() df['Start Hour'] = df['Start Time'].dt.hour df['Weekday'] = df['Start Time'].dt.day_name() return...
The main task of the code is to load and filter bike-sharing data for a specified city and day, then display relevant statistics. It constructs a file path, reads CSV data, processes columns, filters rows by the 'Start Time' day, and computes time-based statistics and other metrics for the filtered dataset.
def load_data_filtered_by_day(city, day): """takes in city and day value and displays stats based off the values""" path = h.path_builder(city) df = pd.read_csv(path) load_cols(df) df = df.loc[df['Start Time'].dt.day == day] show_time_stats_day_filter(df) run_stats(df, city)
def load_cols(df): """ adds calculated columns to a DataFrame that are used regardless of filter""" df['Start Time'] = pd.to_datetime(df['Start Time']) df['Month'] = df['Start Time'].dt.month_name() df['Start Hour'] = df['Start Time'].dt.hour df['Weekday'] = df['Start Time'].dt.day_name() return...
The code loads and displays unfiltered data for a specified city by reading a CSV file, processing columns, showing time statistics, and generating city-specific statistics.
def load_unfiltered_data(city): """ displays unfiltered data based on a given city""" path = h.path_builder(city) df = pd.read_csv(path) load_cols(df) show_time_stats_no_filter(df) run_stats(df, city)
def load_conf(): cp = ConfigParser() with open(conffile_path) as f: cp.read_file(f) return cp["DEFAULT"] def destroy_drained_droplets(db_conn, api, draining_time_minutes, live_droplets): q = """SELECT name FROM test_helper_instances WHERE provider = 'Digital Ocean' AND draining_at IS NOT...
The main task of the code is to manage DigitalOcean droplets by monitoring active instances, draining outdated ones, creating new droplets when needed, deploying SSL certificates, and updating DNS records. It enforces constraints on droplet counts, validates configurations, connects to a database, and ensures infrastru...
def main(): conf = load_conf() dig_oc_token = conf["token"] assert dig_oc_token assert len(dig_oc_token) == 64 draining_time_minutes = int(conf["draining_time_minutes"]) assert draining_time_minutes >= 0 active_droplets_count = int(conf["active_droplets_count"]) assert 0 <= active_drop...
def parse_args(): os.environ["TZ"] = "UTC" ap = ArgumentParser(__doc__) ap.add_argument("src_bucket") ap.add_argument("dst_bucket") ap.add_argument("--day", type=lambda d: parse_date(d)) ap.add_argument( "--jsonltbl", choices=["dryrun", "insert", "upsert"], default="upser...
The main task of the code is to process and transfer measurement data from Amazon S3 to a PostgreSQL database. It downloads and processes CAN files containing measurement data for a specific day, avoids duplicates, and writes results to S3 and the database. The code handles data parsing, database setup, S3 client inter...
def main(): conf = parse_args() format_char = "n" collector_id = "L" identity = f"{format_char}{collector_id}" log.info(f"From bucket {conf.src_bucket} to {conf.dst_bucket}") s3sig = create_s3_client(conf) # signed client for writing db_conn = psycopg2.connect(conf.db_uri) db.setup(conf...
def read_data(train_dir,test_dir): train_data = pd.read_excel(train_dir,sheet_name=4) train_data = train_data[features+label] test_id = pd.read_csv(test_dir) test_data = test_id[features] return train_data,test_data, test_id def preprocess(train_data,test_data,method='knn'): # for mean and 0.5 i...
The function `model_main` processes training and test datasets by reading, preprocessing, training a model, and generating predictions. It returns preprocessed data, model predictions, the trained model, and test IDs for further analysis or evaluation.
def model_main(train_dir,test_dir): ## DATASET train_data,test_data,test_id = read_data(train_dir,test_dir) train_fea, train_label, test_fea = preprocess(train_data, test_data) ## MODELS best_model = train_model(train_fea, train_label) test_predict = test_model(best_model, test_fea) return train_fe...
def setLRButtonHandler(self): self.root.bind("<Left>", lambda event: self.racket.move("Left",self.parentW,0)) self.root.bind("<Right>", lambda event: self.racket.move("Right",self.parentW,0)) def move(self): step = self.check_hit_border_in_the_next_step(self.parentW, self.par...
This code initializes a game by drawing a racket and ball, setting up left/right button handlers for movement, creating a grid of 200 bricks, and launching the GUI main loop to start the game.
def start(self): self.racket.draw() self.setLRButtonHandler() self.ball.draw() self.move() for i in range(200): self.createBrick(i//20,i%20) self.root.mainloop()