dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def is_position_empty(game_state, move, current_position): """ check if proposed new position is empty and if there is a crate can it move """ crate_moved = False future_position = get_new_position(current_position, move) if future_position in game_state.wall_position: return False, crat...
This function handles a player's movement in a puzzle game, checking if the move is legal and whether a crate is pushed. If valid, it updates the player's position and, if applicable, moves a crate in the same direction. Illegal moves trigger an error message and return False.
def move(self, direction): position_empty, crate_moved = is_position_empty(self, direction, self.man_position) if check_move_legal(self, direction): if position_empty: if crate_moved: crate_index = self.crate_position.index(get_new_position(self.man_positi...
def create_timing_lists(wanted_char_count): """ Creates two lists of timings (press and release) and one of keys. :param wanted_char_count: The wanted amount of chars to be measured :return: Lists of press times, release times, and keys names """ key_press_lst = [] key_release_lst = [] k...
The code records user typing data by capturing key press/release timings, calculates key hold and interval durations, structures this into a pandas DataFrame, normalizes the data, and returns the processed DataFrame for analysis of typing patterns.
def record(wanted_char_count): """ Gets the user typing data by the param. :param wanted_char_count: The wanted amount of chars to be measured :return: Pandas data frame """ print("record") key_press_times, key_release_times, keys_list = create_timing_lists(wanted_char_count) hold_durati...
def __init(host,port): reciever = s.socket(s.AF_INET,s.SOCK_STREAM) reciever.setsockopt(s.SOL_SOCKET,s.SO_REUSEADDR,1) reciever.bind((host,port)) reciever.listen(1) print("[*]Listening...\n") return reciever def writeout(reciever,path): file=open(path,"w") try: file.write(recvall...
This code defines a function `ftpdest` that initializes an FTP receiver on a specified port, writes received data to a given file path, and processes the destination. However, it contains undefined methods (`__init__`, `writeout`, `__dest`) and lacks proper implementation, making its functionality incomplete or non-fun...
def ftpdest(port,path): reciever = __init("0.0.0.0", port) writeout(reciever, path) __dest(reciever)
def start_db(self, database: str): self.cursor.execute("SHOW DATABASES") databases = self.cursor.fetchall() if (database, ) not in databases: self.cursor.execute(f"CREATE DATABASE {database}") self.log(f"Database {database} created successfully.") self.cursor.ex...
This code initializes a database connection, sets up a cursor, loads SQL schema and insert queries, and conditionally drops or creates database tables based on the provided flags `drop_tables` and `create_tables` to manage the database structure.
def __init__(self, create_tables: bool = False, drop_tables: bool = False): self.db = connect_to_mysql() self.cursor = self.db.cursor(buffered=True) self.schemas = create_queries self.insert_queries = insert_queries self.start_db("is3107g6") if drop_tables: self.drop_sche...
def extract(self) -> list: """ Extracts data from data source and ingest to data lake. """ pass def transform(self, result: list) -> list: """ Transforms data extracted. """ pass def load(self, result: list) -> None: """ Loads data into data warehouse. """ self.dw_loader(...
The code initializes an object with DataLake and DataWarehouse components, and conditionally executes an ETL pipeline: extracting data, transforming it, and loading the result if `run_pipeline` is True. The main task is to set up and optionally run an ETL process for data handling.
def __init__(self, run_pipeline: bool = True): self.id = str(self.__class__.__name__) self.dl = DataLake() self.dw = DataWarehouse() if not run_pipeline: return data = self.extract() transformed_data = self.transform(data) self.load(transformed_data)
def get_world_size(): if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() def is_main_process(): return get_rank() == 0 def save_checkpoint(model, tokenizer, args, epoch, iteration, num_trial=10): checkpoint_dir = op.join(args.outp...
The code trains a model using distributed data parallelism, sets up an AdamW optimizer with layered weight decay, initializes a learning rate scheduler, and performs gradient accumulation. It logs training metrics, saves checkpoints periodically, and handles backpropagation with gradient clipping. The main task is to o...
def train(args, train_dataloader, model, tokenizer): if args.distributed: model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True, ) t_total = len(train_dataloader) // ...
def ensure_init_process_group(local_rank=None, port=12345): # init with env world_size = int(os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1 if world_size > 1 and not dist.is_initialized(): assert local_rank is not None print("Init distributed training on local rank {}".format...
The main task of the code is to train and evaluate a question generation model using BART, with options for training, testing, or evaluation. It processes CSV datasets, configures hyperparameters, loads a pre-trained BART model, adds special tokens, and performs training/inference based on flags like `--do_train` or `-...
def main(): # Hyper Parameters parser = argparse.ArgumentParser() parser.add_argument('--csv_file', default='/media/abhidip/2F1499756FA9B1151/data/CU-stroy-QA-Data/train_split.csv', help='path to datasets') parser.add_argument('--model_name_or_path', default='/media/abhidip/2F14...
def background(): set_clear_color(0, 0, 0) clear() dots() obstacles() def pacman(): set_fill_color(1, 1, 0) disable_stroke() change_pacman_direction() draw_circle(ball_x, ball_y, ball_r) set_fill_color(0, 0, 0) draw_triangle(ball_x, ball_y, mouth_x1, mouth_y1, mouth_x2, mouth_y2)...
The code defines a `window()` function that orchestrates the rendering of a game scene by calling multiple sub-functions: `background()` to set the visual backdrop, `pacman()` to draw the Pac-Man character, `red_ghost()`, `blue_ghost()`, and `orange_ghost()` to render colored ghosts, and `text()` to display textual ele...
def window(): background() pacman() red_ghost() blue_ghost() orange_ghost() text()
def fillSeasonAttributes(season): return { 'name' : season.name, 'title' : season.title, 'endingText' : season.endingText, 'date_start' : season.date_start.strftime('%Y-%m-%d'), 'date_end' : season.date_end.strftime('%Y-%m-%d'), 'tot...
The function `getToday` gathers and returns today's date, current season attributes, level requirement, events, and next season details. It extracts data from the input `calend`, queries the database for upcoming seasons, and formats the response in a dictionary with date variations, last update timestamp, and seasonal...
def getToday(calend): seasonAttr = '' #current season attributes if available lvl = '' #current level requirement if available nextSeason = '' #next season if information available daysnext = '' #days till next season if information available try: seasonAttr = fillSeasonAttributes(currentSe...
def getSeasonLevels(): calendar = calendarRange() calendar = fillSeasonDates(calendar) for current_season in Season.objects.all(): required_exp = current_season.totalexp days_count = (current_season.date_end - current_season.date_start).days + 1 help_index = 0 level_exp = [...
The code initializes a global calendar by fetching seasonal levels, updating today's date and corresponding data, adding events and community events, and configuring a modal with event and season-specific data.
def setToday(): global globalcalendar globalcalendar = getSeasonLevels() keyDate = date.today() + timedelta(0) global today today = getToday(globalcalendar[keyDate.strftime('%Y-%m-%d')]) globalcalendar['today'] = today globalcalendar['events'] = addEvents() globalcalendar['communityEvent...
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 share data for a specified city and month, filters the dataset by the given month using the 'Start Time' column, and displays time-related statistics and other metrics based on the filtered data.
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 bike-sharing data for a specified city, filter it by a given day using the 'Start Time' column, and display time-related statistics and other analytics based on 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 unfiltered data for a specified city by reading a CSV file, processes its columns, displays time statistics without filtering, and generates additional statistics. The main task is to retrieve and showcase raw data and analytical insights specific to the given city.
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 setStatusMessage(self, string, *args): string = string % args self.statusmsg = string self.statusmsgTime = time.time() def refreshScreen(self): self.screencols = os.get_terminal_size().columns self.screenrows = os.get_terminal_size().lines - 2 self.scroll() ...
This code creates an interactive prompt editor that captures user input character by character, handles backspace/delete, escape key termination, and Enter submission. It updates the display in real-time, invokes a callback function with the current input and key pressed, and returns the final input string when Enter i...
def editorPrompt(self, prompt, callback): userInput = "" while True: self.setStatusMessage(prompt, userInput) self.refreshScreen() c = self.readKey() if c == "": continue if c == Keys.DEL or c == '\x08' or c == Keys.BACKSPACE:...
def editorPrompt(self, prompt, callback): userInput = "" while True: self.setStatusMessage(prompt, userInput) self.refreshScreen() c = self.readKey() if c == "": continue if c == Keys.DEL or c == '\x08' or c == Keys.BACKSPACE:...
The main task of the code is to save the editor's content to a file. It checks if a filename is provided; if not, it prompts the user to specify one. If canceled, it aborts the save. Otherwise, it writes the editor's content (converted from rows) to the file, updates the status message with bytes written, and marks the...
def editorSave(self): if self.filename == "": self.filename = self.editorPrompt( "Save as: %s (ESC to cancel)", None) if self.filename == "": self.setStatusMessage("Save aborted") return file = open(self.filename, "w+") string = self.r...
def readKey(self): x = self.poller.poll(250) c = "" if x == []: # There's no data to read return "" else: # There is data to read c = sys.stdin.read(1) if c == "\u007f": return Keys.BACKSPACE if c == "\x1b": seq = [] ...
This function processes keyboard inputs in a text editor, handling navigation (arrows, page scroll), editing (insert/delete), quitting (Ctrl-Q with unsaved warning), and search (Ctrl-F). It updates the cursor, manages screen rendering, and triggers save operations, with fallback to character insertion for unhandled key...
def processKeyPress(self): c = self.readKey() match c: case "": return case "\x11": # CTRL-Q if self.dirty and self.quitTimes > 0: self.setStatusMessage( f"Warning: file has unsaved changes. Press Ctrl-Q...
def listen_for_wake_word(): p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=4000) stream.start_stream() recognizer = KaldiRecognizer(model, 16000) while True: try: data = stream.read(4000) if recogni...
The code's main task is to continuously listen for a wake word. Upon detection, it processes voice commands, executes responses, and exits to re-enter wake word listening mode if an "EXIT_COMMAND" is received.
def main(): while True: if listen_for_wake_word(): # Listens for the wake word print("Wake word detected. Ready for command.") while True: command = listen_and_recognize() response = respond(command) if response == "EXIT_COMMAND": ...
def game_loop(): global player, background, om, fm mx = 0 my = 0 speed = 5 global shark,limit main = True while main: background = pygame.image.load(back).convert() background = pygame.transform.scale(background, (worldx, worldy), screen) for event in pygame.event...
The code defines a game introduction screen with buttons for starting the game, quitting, viewing the leaderboard, and starting an alternative game mode. It handles mouse interactions, including hover effects and click events to trigger corresponding actions. A scrolling background image is displayed, and the loop upda...
def game_intro(): intro = True buttom1 = buttom(430, 375, 100, 50, (255, 255, 255), 'Start') buttom2 = buttom(430, 455, 100, 50, (255, 255, 255), 'Quit') buttom3 = buttom(360, 535, 260, 50, (255, 255, 255), 'LeaderBoard') buttom0 = buttom(360, 255, 250, 50, (255, 255, 255), 'Hungry Shark') butto...
def death(self): if(self.health <= 0): self.invisible = True def move(self): self.rect.x += self.direction.x * self.speed self.pos = (self.rect.x, self.rect.y) def run_anim(self): if self.direction.x == -1: self.run_anim_left() else: self.run_...
This code updates an object's state by handling death logic, movement, animations, collision checks, and gravity. If not invisible, it moves and plays regular animation; otherwise, it plays death animation. It then checks horizontal and vertical collisions, applies gravity, and resets the hero detection flag.
def update(self): self.death() if(self.invisible == False): self.move() self.run_anim() else: self.run_anim_death() self.horizontal_collision() self.apply_gravity() self.vertical_collision() self.hero_inRange = False
def death(self): if (self.health <= 0): self.invisible = True def move_vision(self): for sprite in self.collision_sprites.sprites(): if (sprite.rect.colliderect(self.get_view_rect())): self.see_hero = False for hero in self.collision_hero: if ...
This code updates an entity's state by handling death, movement, animations, and collisions. It checks visibility to decide between hunting the hero (with horizontal collision) or normal movement. Gravity and vertical collision are applied regardless of state, while death animations trigger if the entity is invisible.
def update(self): self.death() if(self.invisible == False): self.move_vision() self.run_anim() if (self.see_hero == True): self.set_hunt() self.hunt_horizontal_collision() else: self.move() s...
def move(self): self.rect.x += self.direction.x * self.speed self.pos = (self.rect.x, self.rect.y) def horizontal_collision(self): dummy = pygame.Rect(-70, 360, 50, 50) dummy2 = pygame.Rect(360,360, 50, 50) if (self.rect.colliderect(dummy2)): if (self.rect.right >= du...
The code's main task is to update a game object's state by moving it, handling horizontal and vertical collisions, applying gravity, updating animations, and resetting a flag indicating the hero's range. This method likely belongs to a game entity, managing physics, movement, and rendering logic in a game loop.
def update(self): self.move() self.horizontal_collision() self.run_anim() self.apply_gravity() self.vertical_collision() self.hero_inRange = False
def create_block(self): """ Creates a tile block based on type @return: tile block """ if self.type == 0: return self.create_ground() elif self.type == 1: return self.create_block_1() elif self.type == 2: return self.create_bloc...
This code initializes a tile block with given coordinates and type, creating a block object with properties like width, height, position, and collision rectangle. It sets the block type to 'tile_block' and prepares the block for use in a game or grid-based system, likely for rendering or physics interactions.
def __init__(self, init_x, init_y, type): super().__init__() """ Block crated from Tile(s) @param init_x: x-coordinate @param init_y: y-coordinate @param type: tile_block """ self.x = init_x self.y = init_y self.type = type # Based on type...
def get_now(): return datetime.datetime.utcnow() def get_end_of_year(self): now = self.get_now() return datetime.datetime(now.year + 1, 1, 1) - datetime.timedelta(1) def get_days_until_midnight(self, dt: datetime = None) -> float: dt = dt or self.get_now() this_day = datetime.dat...
The main task of the code is to calculate the total remaining time in days from a given datetime `dt` to a target date `until_day`, incorporating weighted coefficients for each day. It computes days until midnight for `dt`, then iteratively adds weighted contributions from each day's coefficient multiplied by the numbe...
def get_time_left(self, dt: datetime = None, until_day: datetime = None) -> float: dt = dt or self.get_now() until_day = until_day or self.get_end_of_year() time_in_days = self.get_days_until_midnight(dt) # TODO Cache this_day and time_in_days. Makes sense to recalculate only when this...
def feed_snakes(self): eatenFood = set() for k in self.snakes: if self.snakes[k].head in self.food: self.snakes[k].reset_health() eatenFood.add(self.snakes[k].head) else: self.snakes[k].pop_tail() for food in eatenFood: ...
The code processes a game step by moving each snake according to specified directions, feeding snakes, spawning new food, eliminating snakes, and incrementing the turn counter.
def step(self, moves: Dict[object, Direction]): for k in self.snakes: self.snakes[k].move(moves[k]) self.feed_snakes() self.spawn_food() self.eliminate_snakes() self.turn += 1
def evaluate_state(s: sim.BoardState): winner = s.winner() return {k: get_reward(winner, k) for k in s.snakes} def get_unselected_action_matrices(nodes: Tree, s: sim.BoardState): possibleActions = {} for k in s.snakes: actions = get_safe_actions(s, k) if actions: possibleActi...
This function performs a Monte Carlo Tree Search (MCTS) iteration for a board game. It checks terminal states, selects random unexplored actions, expands the game tree by applying actions to generate new states, recursively plays out the game, updates node visit counts, and propagates results back through the tree to g...
def mcts_duct_iter(nodes: Tree, s: sim.BoardState): if s.winner() != -1: # if in a terminal state return evaluate_state(s) elif s in nodes and (actionMats := get_unselected_action_matrices(nodes, s)): a = actionMats[rd.randrange(len(actionMats))] # Calculate next state sNew = a...
def evaluate_state(s: sim.BoardState): winner = s.winner() return {k: get_reward(winner, k) for k in s.snakes} def get_unselected_actions(nodes: TreeSUCT, s: StateSUCT): # TODO: improve this possible_actions = [] for a in get_safe_actions(s.state, s.current_turn_player()): sNew = apply_actio...
This function performs a Monte Carlo Tree Search (MCTS) iteration for a game state in the SUCT framework. It checks if the state is terminal, evaluates it if so, or selects an unvisited action to expand the tree. If no unvisited actions exist, it selects the best action based on existing nodes. After applying the actio...
def mcts_iter_suct(nodes: TreeSUCT, s: StateSUCT): if s.winner() != -1: # if in terminal state return evaluate_state(s.state) elif s in nodes and (actions := get_unselected_actions(nodes, s)): a = list(actions)[rd.randrange(len(actions))] # Calculate next state sNew = apply_act...
def add_node_suct(nodes: TreeSUCT, s: StateSUCT): nodes[s] = NodeSUCT(0, {k: 0 for k in s.state.snakes}) def mcts_iter_suct(nodes: TreeSUCT, s: StateSUCT): if s.winner() != -1: # if in terminal state return evaluate_state(s.state) elif s in nodes and (actions := get_unselected_actions(nodes, s)): ...
This code implements a Monte Carlo Tree Search (MCTS) algorithm to determine the optimal move for a player in a board game. It initializes a game state, iteratively expands and evaluates possible moves within a time limit, and selects the action with the highest average reward from simulations. The process involves dee...
def mcts_suct(board: sim.BoardState, playerIndex, maxTime=150): tStart = time.time_ns() boardCopy = copy.deepcopy(board) boardCopy.foodSpawnChance = 0 turnOrder = [playerIndex] + [k for k in boardCopy.snakes if k != playerIndex] s = StateSUCT(boardCopy, turnOrder) nodes = {} add_node_suc...
def point_to_index(self, p): return p.x + p.y * self.width def get_neighbours(self, p): # TODO: return a list of neighbours of p all_valid_neighbours = [] for dir in Maze.all_dirs: dir_neighbour = Point.add(p, dir) if self.is_valid(dir_neighbour) and not self.is_...
This function performs a Breadth-First Search (BFS) to find a path from a start point to an end point. It uses a queue to explore neighboring nodes, tracks visited positions in a dictionary, and reconstructs the path from end to start by backtracking through the visited entries. If a path is found, it returns the list ...
def bfs(self, start, end): # TODO: return a list of points from start to end queue = [] queue.append(start) visited = {} visited[self.point_to_index(start)] = "210073" path_found = False while len(queue) > 0: current = queue.pop(0) if curr...
def are_no_enemies(self): for entity in self.entities: if ( entity.name == "Enemy Entity" or entity.name == "Enemy Projectile" or entity.name == "Basic Entity" ): return False return True def activate_scene(self): ...
The code updates the game state by incrementing the age counter, handling events (e.g., quitting), managing scene transitions, updating collisions, processing entities/particles, rendering the active scene, and logging performance metrics for debugging. It ensures entities and particles are updated, removed, or created...
def update(self): self.age += 1 time_begin = time.time() events = pygame.event.get() for event in events: if event.type == pygame.QUIT: self.debug_file.close() sys.exit() time_events_end = time.time() if ( len(self.s...
def revert_to_previous_position(self): self.move_absolute(self.previous_point) self.frozen = True def reflect(self, collided_entity_current_point): # Two cases: either reflect x-axis or y-axis # Case 1: Reflect x-axis -> self.x diff = [0, 0] time_to_connect = [0, 0] ...
This function handles collisions for entities with a rigid body by checking if any collided entity also has a rigid body. If so, it reverts the entity's position, reflects its movement direction, and reapplies its speed. The function returns (False, None) to indicate no new entity creation is needed.
def handle_rigid_body( self, window: pygame.Surface, events: list[pygame.event.Event], collisions: list[tuple[str, point]], ) -> tuple[bool, Optional[EntityCreationRequest]]: # cannot overlap with any other entity with Rigid Body # This means that if there is a collis...
def handle_rigid_body( self, window: pygame.Surface, events: list[pygame.event.Event], collisions: list[tuple[str, point]], ) -> tuple[bool, Optional[EntityCreationRequest]]: # cannot overlap with any other entity with Rigid Body # This means that if there is a collis...
This function processes entity attributes in a specified order, checking for properties like rigid body collisions, screen boundaries, gravity, etc. It calls corresponding handler methods, updates an entity creation request if needed, and returns whether the entity should be deleted along with any new entity request.
def handle_attributes( self, window: pygame.Surface, events: list[pygame.event.Event], collisions: list[tuple[str, point]], ) -> tuple[bool, Optional[EntityCreationRequest]]: """ Handles all of the general attributes in the following order: * rigid_body -> ca...
def get_possible_moves(game: Game) -> list[Position]: return [(row, column) for row, column in get_all_positions(game.rules) if game.board[row][column] == Square.EMPTY] def play_move(position: Position, game: Game) -> Game: row, column = position new_board = [row.copy() for row in game.board] if new_b...
This function recursively determines the winner of a game by exploring all possible moves. It checks if the current player can immediately win; if not, it recursively evaluates deeper game states. If any move leads to a draw, it returns a draw. Otherwise, it returns the first non-draw result, prioritizing immediate win...
def find_winner(game: Game, depth: int = 0) -> GameResult: possible_moves = get_possible_moves(game) is_last_move = len(possible_moves) == 1 results = [] for move in possible_moves: new_game = play_move(move, game) result = get_game_result(new_game) if player_wins(game.player_t...
def _CreateFormatScanner(self): """Creates a signature scanner for required format check.""" scanner_object = pysigscan.scanner() scanner_object.set_scan_buffer_size(65536) # Custom Destinations Jump List (.customDestinations-ms) file. scanner_object.add_signature( 'custom_destination', 4, ...
The main task of the code is to scan files for serialized properties using a format scanner, identify supported formats (e.g., 'custom_destination', 'lnk', 'olecf'), and yield serialized properties with their origin path set. It handles file entries, processes scan results, and delegates property collection to speciali...
def CollectSerializedProperies(self): """Retrieves serialized properties. Yields: SerializedProperty: serialized property. """ if not self._format_scanner: self._CreateFormatScanner() for file_entry, path_segments in self._ListFileEntries(): file_object = file_entry.GetFileObject...
def getAllVenue(): #return all venue in [a,b,c,d,e,f,.......] classdatas = Classdata.objects.all().values() locationDict = {} for eventloc in classdatas: venue = str(eventloc['venue']) if venue in locationDict: locationDict[venue] += 1 else: ...
The main task of the code is to process venue time range data by combining included and excluded time intervals. It retrieves all venues, fetches their class data across all time ranges, calculates excluded times relative to included times, and merges these datasets for further analysis or output.
def secondAnalysis(): venues = getAllVenue() insidedata = getClassDataInAllTimeRange(venues) outsidedata = getExcludedTimeByIncludedTime(venues) data = processVenueTimeRangeData(insidedata,outsidedata) return data
def all_image_urls_to_csv(): folder_names = os.listdir('../Project/raw-img') category = [] files = [] for k, folder in enumerate(folder_names): filenames = os.listdir("../Project/raw-img/" + folder) for file in filenames: files.append("../Project/raw-img/" + folder + "/" + fi...
The code trains a neural network model using shuffled image data, splits it into training/validation/test sets, trains the model with a specified learning rate, evaluates test performance by iterating through batches, computes average performance metrics, and visualizes weights if no hidden layers are present.
def main(learning_rate=learning_rate): train_df = all_image_urls_to_csv() url_category_data = np.array(train_df.iloc[:, :]) np.random.seed(101) np.random.shuffle(url_category_data) x_train = np.zeros((n, batch_size)) y_train = np.zeros((c, batch_size)) x_validation = np.zeros((n, batch_siz...
def get_various_encode_scale(X, numerical_columns, categorical_columns, scalers=None, encoders=None, scaler_name=None, encoder_name=None): if categorical_columns is None: categorical_columns = [] if numerical_columns is None: numerical_columns = [] if len(catego...
The function performs hyperparameter tuning for Decision Tree, Logistic Regression, and Random Forest classifiers using cross-validation on different numerical and categorical feature combinations. It evaluates each model's F1 score, tracks optimal parameters, and returns the best-performing classifier with its optimal...
def do_Classify(X, y, numerical_columns, categorical_columns, n_split_time=None,n_jobs=None): if n_jobs == None: n_jobs = -1 if n_split_time == None: n_split_time = 5 DT_best_score = 0 DT_best_param = [0, 0, 'scaler', 'encoder'] DT_best_index = ['max_depth', 'min_samples_split', 's...
def grad(self, W, w0): # obtain y_pred y_pred = self._score(self.X, W, w0) Wdelta = [] for j in range(self.K): y_p, y_t = y_pred[:, j], self.Y[:, j] tmp = np.zeros((self.D,)) for i in range(self.N): tmp += (y_p[i] - y_t[i]) * y_p[i] *...
The code performs gradient descent optimization to minimize a negative log-likelihood objective function. It iteratively updates model parameters W and w0 using gradients until their changes fall below a threshold (eps). The objective function values are recorded during each iteration and returned as a list.
def optimize(self, grad, eta = 0.01, eps = 1e-1): Wdelta, w0delta = np.ones((self.K, self.D)), np.ones((self.K)) objective_func = [] while np.sqrt(np.sum(Wdelta ** 2) + np.sum(w0delta ** 2)) > eps: Wdelta, w0delta = self.grad(self.W, self.w0) self.W -= eta * Wdelta ...
def find_labels(self): labels = _file_labels(self.args.label_file) taxon_count = self.args.taxa if taxon_count > len(labels): labels += self.most_common_labels(taxon_count - len(labels)) return labels def obs_by_labels(self, labels): by_label = {} for element ...
The main task of the code is to process images grouped by labels, iteratively identifying and counting images until none remain, then generating a script. It uses `find_labels()` to identify labels, groups observations by these labels, processes images in a loop with `images_pass()`, accumulates the count of processed ...
def build(self): labels = self.find_labels() obs_lists = self.obs_by_labels(labels).values() images_found = 1 count = 0 while images_found > 0: images_found = self.images_pass(obs_lists) count += images_found self.print_script()
def items_on_sale(self): self.clear_screen() items = Item.show_items() if items: print(yellow("Items on sale:")) self.print_items(items) else: print("No items are available.") def search_for_item(self): self.clear_screen() ...
This method displays a terminal menu with options for user interaction, such as viewing items on sale, searching items, adding items for sale, buying/removing items, viewing transactions, or exiting. It repeatedly shows the menu, processes the selected option by calling corresponding methods, and exits the loop when "E...
def show_user_options(self): while True: options = ["Items On Sale","Search For Item", "Add Item For Sale", "Buy An Item", "Remove An Item", "Your Transactions", "Exit"] terminal_menu = TerminalMenu(options) menu_entry_index = terminal_menu.show() ...
def closeRing(coordinates): """ checks if the first and last points of a ring are equal and closes the ring """ if not pointsEqual(coordinates[0], coordinates[len(coordinates) - 1]): coordinates.append(coordinates[0]) return coordinates def ringIsClockwise(ringToTest): """ determine ...
The function converts an array of polygon rings into GeoJSON format by identifying outer rings (clockwise) and holes (counter-clockwise). It checks if holes are contained within outer rings, appending them if so. Uncontained holes are tested for intersection with outer rings. If no match, holes are added as separate po...
def convertRingsToGeoJSON(rings): """ do any polygons in this array contain any other polygons in this array? used for checking for holes in arcgis rings """ outerRings = [] holes = [] x = None # iterator outerRing = None # current outer ring being evaluated hole = None # current...
def initialize_network(method): ''' Initialization function for wights and biases. Method - Method to initialize the weights and biases. Possible values - {static: initialization using static weights, random: initialization using random numbers. Max 3, min 0.5, ...
This code trains a neural network on synthetic data using backpropagation. It initializes parameters, iterates over epochs, computes training and validation losses, updates weights/biases with gradient descent, and plots loss curves for training and validation sets to evaluate model performance over time.
def scalar_model(): epochs = 50 (xtrain, ytrain), (xval, yval), random = load_synth() epoch_loss = [] epoch_loss1 = [] w, b, v, c = initialize_network(method = 'random') for i in range(epochs): for j in range(len(xtrain)): inputs = xtrain[j] if ytrain[j] == 1: y =...
def drawSplashScreen(app, canvas): # draw Donner # draw title screen text # buttons for startgame, options, and credits introFontSize = 40 canvas.create_text(app.width/2, 300, font=f'Arial {introFontSize} bold', text='Escape Donner Dungeon') app.creditsButton.drawButton(app, canvas) ...
This function redraws the appropriate UI screen based on the app's current state. It calls specific drawing functions for splash, credits, settings, or game screens. In settings, it additionally draws a control menu if an edit is active. The main task is to render the correct visual interface element corresponding to t...
def redrawAll(app, canvas): if app.currScreen == 'splash': drawSplashScreen(app, canvas) elif app.currScreen == 'credits': drawCreditsScreen(app, canvas) elif app.currScreen == 'settings': drawSettingsScreen(app, canvas) if app.editedControl: app.editedControl.dra...
def __run_perform_ocr_on_pdf(self, in_file_path: Path) -> Path: # Obtains the images from the PDF file. self.__emit_status_event(f'Obtaining images from PDF file {in_file_path}') self.__emit_log_event(f'Obtaining images from PDF file {in_file_path}') pdf_images = pdf2image.convert_from_p...
The code processes multiple input PDF files by performing OCR on each, handling temporary files, moving processed originals, and emitting a 'Finished' event after completion. It tracks progress via file index, clears temp files, and includes a delay for animation.
def run(self) -> None: # Allows progress animation. sleep(0.5) # Processes all the input files. for (in_file_path_index, in_file_path) in enumerate(self.in_file_paths): self.file_index = in_file_path_index temp_file_path = self.__run_perform_ocr_on_pdf(in_file_pa...
def connect_to_database(): db_config = { "host": "localhost", "user": "root", "password": "", "database": "banana_ripeness", } try: connection = mysql.connector.connect(**db_config) return connection except mysql.connector.Error as err: st.error(f...
The main task of the code is to manage a web application for banana ripeness detection, handling user authentication (login/signup), displaying a dashboard with ripeness information, and providing access to webcam analysis, history, and reports. It loads a logo, checks login status, connects to a database, and renders ...
def main(): logo_path = "logo.png" try: logo_image = Image.open(logo_path) st.image(logo_image, width=900) except Exception as e: st.error(f"Error loading logo: {e}") if 'logged_in' not in st.session_state: st.session_state.logged_in = False # Establish d...
def move_in_get_moves(self, pos, move): for item in self.get_moves(pos): if move[0] == item[0] and move[1] == item[1]: if len(item) == 3: return True, item[2] return True, return False, def check_check(self, position, color): old_pi...
This function validates a chess move by checking if the piece at 'initial' position can legally move to 'final', considering the current player's turn, move legality, and whether the move would leave the king in check. It handles special cases like en passant and castling, temporarily applying the move to test for chec...
def check_move(self, initial, final): piece = self.board[initial[0]][initial[1]] if piece and piece.color == self.turn: in_moves = self.move_in_get_moves(initial, final) if in_moves[0]: if len(in_moves) == 1: old_final = self.board[final[0]][fi...
def check_check(self, position, color): old_piece = self.board[position[0]][position[1]] if color == "w": self.board[position[0]][position[1]] = Piece('k', 'w') color = "b" else: self.board[position[0]][position[1]] = Piece('k', 'b') color = "w" ...
The code checks if the current player's king is in check and if there are no legal moves left, indicating checkmate. It initializes a result based on the king's check status, then iterates through the board to verify if any of the player's pieces have legal moves. If so, it resets the result. The function returns the r...
def check_result(self): result = "" if self.check_check(self.find_king(self.turn), self.turn): result = self.turn else: result = "s" for i, row in enumerate(self.board): for j, item in enumerate(row): if item and item.color == self.turn...
def compute_similarity_matrix(graph): #Initialize empty similarity matrix of size V*V sim_matrix = [[None for _ in range(len(graph.vs))] for _ in range(len(graph.vs))] #Calculate similarity using cosine. Similarity is commutative Sim(i,j)=Sim(j,i) for i in range(len(graph.vs)): for j in range(l...
The main task of the code is to perform community detection on a graph using two phases. It reads graph data and attributes, computes a similarity matrix, applies Phase 1 to identify initial communities, refines them in Phase 2, and outputs the final community structure to a text file. The alpha parameter influences th...
def main(): #Check input parameter alpha if len(sys.argv)!=2: print("Enter value of alpha as parameter") return alpha = float(sys.argv[1]) #Convert for preferred output to file alph = 0 if alpha == 0.5: alph = 5 elif alpha == 0.0: alph = 0 elif alpha == 1....
def get_dirs (): dirs = [x for x in os.listdir ('.') if os.path.isdir (x) and '.git' not in x] return dirs def get_category_dict (category_names): categories = {} count = 0 for category in category_names: titles = get_program (category) categories[category] = titles count += len (titles) return (count, cate...
The code generates a README.md file by collecting directory names, categorizing them with counts, and printing the structured data. It then adds the generated README.md to Git version control.
def create_README (): category_names = get_dirs () count, categories = get_category_dict (category_names) print_file (category_names, count, categories) os.system('git add README.md')
def spawn_enemies(self): if self.turn_count % 2 == 0: global enemy_spawn_counter enemy_spawn_counter += 2 print(f"Enemy spawned! Count: {enemy_spawn_counter}") print(f"Enemies alive: {enemy_spawn_counter - self.gold}") for _ in range(2): ...
The `next_turn` method advances the game state by spawning enemies, incrementing the turn count, resetting hero attack flags, moving unblocked enemies, attacking enemies, updating game logic, and rendering the current state.
def next_turn(self): self.spawn_enemies() self.turn_count += 1 for hero in self.heroes: hero.attacked = False for enemy in self.enemies: if not self.should_block_move(enemy): self.move_enemy(enemy) self.attack_enemies() self.upda...
def snap_hero_to_grid(self, hero): # Calculate the grid cell coordinates grid_x = round(hero.rect.x / SQUARE_SIZE) * SQUARE_SIZE grid_y = round(hero.rect.y / SQUARE_SIZE) * SQUARE_SIZE # Check if within hero grid bounds if 0 <= grid_x < 2 * SQUARE_SIZE and 100 <= grid_y < 600: ...
The main task of the code is to finalize the dragging process of a selected hero by snapping it to the grid, handling potential merging with other heroes, resetting all heroes' backgrounds, and marking the dragging state as complete.
def finish_dragging_hero(self): self.snap_hero_to_grid(self.selected_hero) self.handle_hero_merging(self.selected_hero) self.reset_all_heroes_background() self.dragging = False
def next_turn(self): self.spawn_enemies() self.turn_count += 1 for hero in self.heroes: hero.attacked = False for enemy in self.enemies: if not self.should_block_move(enemy): self.move_enemy(enemy) self.attack_enemies() self.upda...
This code handles user interactions in a Pygame game, enabling players to drag and drop heroes on a grid. It detects mouse clicks to select heroes, drags them, snaps them to grid cells, and swaps positions if another hero occupies the target cell. The loop processes events like quitting, dragging, and mouse motion, upd...
def run(self): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: if ...
def spawn_enemies(self): if self.turn_count % 2 == 0: global enemy_spawn_counter enemy_spawn_counter += 2 print(f"Enemy spawned! Count: {enemy_spawn_counter}") print(f"Enemies alive: {enemy_spawn_counter - self.gold}") for _ in range(2): ...
The main task of the code is to advance the game's turn by spawning enemies, managing background scrolling for a continuous grid effect, incrementing the turn count, initializing action queues, processing enemy actions, checking hero attack capabilities, and disabling a UI button if attacks are scheduled. It ensures se...
def next_turn(self): self.spawn_enemies() # Check if any enemy is in the first column enemy_in_first_col = any(enemy.rect.x == 2 * SQUARE_SIZE for enemy in self.enemies) if not enemy_in_first_col: self.bg_x -= SQUARE_SIZE self.bg_x2 -= SQUARE_SIZE # ...
def handle_mouse_button_down(self, event): if event.button == 1: if self.button.rect.collidepoint(event.pos) and self.button_active: self.next_turn() else: self.start_dragging_hero(event) def handle_mouse_button_up(self, event): if event.button == ...
The code processes Pygame events, handling window close requests and delegating mouse interactions (button presses, releases, and motion) to specific methods for further processing.
def handle_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: self.handle_mouse_button_down(event) elif event.type == pygame.MOUSEBUTT...
def get_weather_and_suggest_recipe(): city = input("Enter your city to check the weather: ") weather_data = get_current_weather(city) if weather_data: print( f"Current weather in {city}: {weather_data['weather'][0]['description']}, {weather_data['main']['temp']}°C") return sugges...
This function suggests recipes based on weather, checks user interest, and either displays recipe details, handles nutrition data, and saves ingredients if interested, or switches to user-provided ingredients if not.
def handle_recipe_suggestion_by_weather(): suggested_recipe = get_weather_and_suggest_recipe() if suggested_recipe: print(f"Suggested Recipe: {suggested_recipe['label']}") user_interest = input("Are you interested in this recipe? (yes/no): ") if user_interest.lower() == 'yes': ...
def generate_initial_generation(N, L, size): generation = [] for i in range(size): layers = [] # choose a depth x = random.randint(1, L) for j in range(x): layers.append(random.randint(1, N)) layers = append_zeros(layers, L) generation.append(layers) ...
This code implements a genetic algorithm to evolve neural network structures by training generations of models on a given dataset. It evaluates model performance using MSE and error metrics, tracks the best-performing structure, and employs early stopping if the same optimal structure is repeated consecutively. The alg...
def genetic_config(N, L, trainingSetFile, populationSize, batchSize=250, verbose=0, epochs=500): # create first list of models generations = 20 currentGen = generate_initial_generation(N, L, populationSize) trainingSet = sio.loadmat(trainingSetFile) minError = None bestStructure = None sto...
def filter_laser_scan(self): data = self.get_laser_scan() data_size = len(data.ranges) filtered_laser_scan = [] normalized_laser_scan = [] if 0 < self.config.laser_size_downsampled < data_size: max_n_laser_ranges = self.config.laser_size_downsampled ...
The main task of the code is to reinitialize the observation data for different observation space types (e.g., LiDAR, Tentabot, CNN-based) by processing sensor inputs (laser scans, occupancy grids, waypoints), normalizing data if required, stacking them with target and action data according to configuration parameters ...
def reinit_observation(self): if self.config.observation_space_type == "lidar_FC": # Update laser scan self.filter_laser_scan() if self.config.laser_normalize_flag: obs_laser = self.normalized_laser_ranges else: obs_...
def filter_laser_scan(self): data = self.get_laser_scan() data_size = len(data.ranges) filtered_laser_scan = [] normalized_laser_scan = [] if 0 < self.config.laser_size_downsampled < data_size: max_n_laser_ranges = self.config.laser_size_downsampled ...
The `update_observation` function processes sensor and environmental data to construct the agent's observation based on the configured observation space type (e.g., LiDAR, occupancy grid, waypoints). It filters LiDAR scans, updates target and action data, maintains sliding windows of historical observations, and combin...
def update_observation(self): if self.config.observation_space_type == "lidar_FC": # Update laser scan self.filter_laser_scan() if self.config.laser_normalize_flag: obs_laser = self.normalized_laser_ranges else: obs_...
def get_atoms(self, S): """Given S (clauses) as input, returns a sorted list of atoms in S""" atoms = [] for clause in S: atoms_temp = clause.split() atoms = atoms + atoms_temp atoms = list(set(atoms)) atoms_sorted = sorted(atoms, key=lam...
The code defines a dynamic programming method `dp` that processes input `S` to solve a problem. It retrieves atomic data (`atoms`) and computes a value `V` from them. If `dp1(S, V)` confirms a valid solution, it converts the result into a structured solution format; otherwise, it returns `None`. The core task involves ...
def dp(self, S): atoms = self.get_atoms(S) V = self.get_V(atoms) if self.dp1(S, V): return self.convert_to_solution() else: return None
def detectAnybodyLostAllWepons(self): if self.bluePoints<2 or self.redPoints<2: return True else: return False def calculateResults(self): if self.redPoints!=self.bluePoints: if self.redPoints>self.bluePoints: self.ResultText=s...
This code manages a dice game loop, updating sprites/dice, calculating player points, handling game over conditions, user input for roll counts, timer-based animations, and event processing for quitting or triggering dice rolls. It transitions between game states (playing, rolling, game over) and saves results when app...
def on_loop(self): self.all_sprites_list.update() self.all_Dice_list.update() self.redPoints=self.MrRed.calculatePoints() self.bluePoints=self.MrBlue.calculatePoints() if self.num_chances==0 or self.detectAnybodyLostAllWepons(): self._gameOver = True ...
def on_init(self): self.initPygame() self.loadResources() self.initScene() self._running = True def on_loop(self): self.all_sprites_list.update() self.all_Dice_list.update() self.redPoints=self.MrRed.calculatePoints() self.bluePoints...
This code manages a game loop by initializing resources, processing events, updating game state, rendering graphics at 60 FPS, and cleaning up when exiting. It checks for ESC key presses to terminate the loop, calls on_loop() for logic updates, on_render() for display, and on_cleanup() for resource release.
def on_execute(self): if self.on_init() == False: self._running = False while( self._running ): pygame.event.pump() keys = pygame.key.get_pressed() if (keys[pygame.K_ESCAPE]): self._running = False self.on_loop() ...
def gmm_generate_means (self): means = [ [-4.311822, 117.134418], [-100.440674, 19.032772], [30.423453, -30.253341], [-75.992345, 32.658961], [95.787545, 69.082386], [-5.544384, -105.839754], [-75.992345, 32.658961] ] ...
This function performs Gaussian Mixture Model (GMM) parameter estimation via the EM algorithm. It iteratively updates cluster means, priors, and covariance matrices using gamma values calculated from current parameters. The process refines model parameters over specified iterations to converge toward optimal values, ul...
def run_gmm (self, iterations, x, aux=None): means = self.gmm_generate_means () prior = self.gmm_generate_prior () covariance = self.gmm_generate_covariance (means, x) for i in range (iterations): #print (sum(prior)) #print (covariance) ...
def _before_train(self): # Show Info self._class_notify(f"Training in {self.device_name} device.", notify_type="info") if self.train_loader.batch_size == 1: self._class_notify("The batch_size is set to 1; if the net uses BN will raise an error.", notify_type="warn") self.model.to(self.device) ...
The code trains a machine learning model by iterating through epochs and batches, performing training steps, and implementing early stopping. It initializes with `_before_train()`, processes each epoch with data loading, executes training iterations via `_train_step()`, checks for early termination after each epoch, an...
def train(self): self._before_train() for epoch in range(self.total_epoch): self._before_epoch(epoch) # calc data load time for features, targets in self.train_loader: self._before_iteration() # calc train cost time self._train_step(features, targets) self._after_iteratio...
def formatApostrophes(s): s = s.replace('\'', '\\\'') return s def createDescription(categoryList): global stopWords descriptionArray = [] for cell in categoryList: sArray = parseOutWords(cell) for word in sArray: if word not in stopWords and word not in descriptionArray: descriptionArray.append(word)...
The code writes product data and keyword weights to two files. If the product is not discontinued, it processes title, description, and category data to generate keywords, calculates their weights based on title and description importance, and writes SQL-like records to file f1 and keyword-weight pairs to f2. For disco...
def writeProductToDatabase(ID, ASIN, discontinued, title, group, salesrank, numSimilar, similarList, numCategories, categoryList, numReviews, averageRating): global f1 global f2 if discontinued == False: originalTitle = formatApostrophes(title) descriptionArray = createDescription(categoryList) titleArray = ...
def createTables(): sql = "SET FOREIGN_KEY_CHECKS = 0" db_write(sql) sql = "DROP TABLE IF EXISTS product_weights" db_write(sql) sql = "DROP TABLE IF EXISTS product_information" db_write(sql) sql = "DROP TABLE IF EXISTS product_result" db_write(sql) sql = "SET FOREIGN_KEY_CHECKS = 1" db_write(sql) sql...
The main task of the code is to import Amazon product data into a MySQL database by generating text files with product information and weights, creating database tables, and using LOAD DATA INFILE for bulk insertion. It optimizes the process by disabling autocommit, unique checks, and foreign key constraints during imp...
def importAmazonData(): global f1 global f2 f1 = [open("product_information.txt", 'w').close()] f2 = open("product_weights.txt", 'w').close() f1 = open("product_information.txt", "a") f2 = open("product_weights.txt", "a") createTables() fillTables() f1.close() f2.close() # optimizations for faster load ...
def finish(result): print(str(result[0]) + " " + str(result[1]) + " " + str(result[2]) + " " + \ str(result[3]) + " " + str(result[4]) + " " + str(result[5]) + " " + \ str(result[6]) + " " + str(result[7]) + " " + str(result[8])) print(str(result[9]) + " " + str(result[10]) + " " + s...
This code solves a Sudoku puzzle using backtracking with constraint propagation. It reads an 81-character input grid, initializes constraints for rows, columns, and 3x3 boxes, propagates domain reductions based on initial values, and applies backtracking search to find a valid solution. The result is printed along with...
def main(): cur_time = time.time() assignment = {} initial = input("Type 81 char input: ") print("INITIAL STATE: ") print("---------------------") finish(initial) for i in range(len(initial)): if initial[i] != '.': assignment[i] = int(initial[i]) rows = gen_row() ...
def show_record(): fr = open("record",'r+') knowledge = eval(fr.read()) fr.close print() print("Diagnosis records: ") pprint(knowledge) def patient(): fr = open("patientInfo",'r+') knowledge = eval(fr.read()) fr.close question = "What is your name?\n" reply = ask(qu...
The code's main task is to act as a medical advice agent, using NLP to parse user input for commands like "bye," "records," or "advice." It directs users to view diagnosis records or provides age-specific medical advice by checking keywords and routing to appropriate functions like `show_record()`, `patient()`, `questi...
def main(): print("Hello, I am a medical advice agent.",end="") while True : question = "Do you want to get medical advice or see diagnosis records?\n" reply = input(question) tokens = nltk.word_tokenize(reply) tagged = nltk.pos_tag(tokens) properNouns = [ word for (...
def trim_path(path): if path.startswith('/'): path = path[1:] if path.endswith('/'): path = path[:-1] return path def exists(self, path): path = trim_path(path) return os.path.exists(self.path + path + '.md') def get(self, path, check=True): path = trim_path(path) if check and not self.exists(path): r...
The code creates a directory path if it doesn't exist, ensuring parent directories are created, then returns the result of a get operation on the path. It trims the path, checks existence, constructs parent directories, and uses os.makedirs for creation.
def create(self, path): path = trim_path(path) if self.exists(path): return False directory = '/'.join(path.split('/')[:-1]) if len(directory) > 0 and not os.path.exists(self.path + directory): os.makedirs(self.path + path) return self.get(path, check=None)
def _raise_malformed_node(node): msg = "malformed node or string" if lno := getattr(node, 'lineno', None): msg += f' on line {lno}' raise ValueError(msg + f': {node!r}') def _convert_signed_num(node): if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)): operand = _convert_...
This function converts AST nodes into corresponding Python values by recursively processing different node types such as constants, tuples, lists, sets, dictionaries, and binary operations. It handles type-specific conversions, ensures structural integrity (e.g., matching keys/values in dictionaries), and evaluates exp...
def _convert(node): if isinstance(node, Constant): return node.value elif isinstance(node, Tuple): return tuple(map(_convert, node.elts)) elif isinstance(node, List): return list(map(_convert, node.elts)) elif isinstance(node, Set): return set(map(_convert, node.elts)) ...
def message_tags_to_dict(msg): """Return the message tags as a dictionary""" return {x["key"]: x["value"] for x in msg.tags} def do_command(self, event, cmd): """Do a command""" try: command_instance = self.command_registry[cmd] command_instance.execute(self, event) ...
This code handles public chat messages by either executing commands if the message starts with an exclamation mark or reading the message aloud using text-to-speech with user-specific voice settings, while tracking the last speaker to manage voice transitions.
def on_pubmsg(self, c, event): """Handle a public message""" tags = message_tags_to_dict(event) print(tags) # If a chat message starts with an exclamation point, try to run it as a command if event.arguments[0][:1] == '!': cmd = event.arguments[0].split(' ')[0][1:] ...
def parseCmd(): parser = argparse.ArgumentParser(description='Parse masking coordinates\ from TRF output.') parser.add_argument('trfOutput', type=str, help='Trf output .dat file') parser.add_argument('--minCopies', type=int, default=1, ...
The main task of the code is to parse command-line arguments, process TRF output files to analyze periodic sequence patterns (with minCopies and GC content filters), and optionally generate statistics reports using a specified prefix. It processes period counts, sequence lengths, and base composition data, printing sta...
def main(): args = parseCmd() periodCounts, periodSequenceLengths, baseCounts = parse(args.trfOutput, args.minCopies, args.gc) if args.statisticsPrefix: printStatistics(args.statis...
def display_room_text(room, version): ''' Pass this function a room number (INT) and a version (STR) to Display information to the player. :param room: :param version: :return: ''' _room_info = get_room_info(room) if version == 'name': _key = 'name' elif version == 'short'...
The function processes a directional movement command to determine if the player can move in the specified direction. It checks for blocking obstacles, validates the passage, updates the player's location, awards points, and manages darkness effects. If blocked, it deducts points and alerts the player. If moving, it up...
def initiate_move(command): ''' Pass this function a Directional Move (STR) to determine if the player can move or if blocked :param command: :return: ''' global current_room, score, dark_moves _blocked = False for key, value in game_data.directions.items(): if command in val...
def handle_invalid_row(row): with open(os.path.join(output_folder, 'errors.txt'), 'a+') as f: f.write(f'Invalid data in row: {row} {now}\n') error_label.configure(text=f'Invalid data in row: {row}') def determine_child_folder(col2, col3, col4): if col2 and col3 and col4: return os.path.join(...
This function processes a row by extracting four columns, handling invalid rows, creating a child folder based on columns 2-4, and invoking `process_files` with column 1 and the folder path.
def process_row(row): try: col1, col2, col3, col4 = row except ValueError: handle_invalid_row(row) return child_folder = determine_child_folder(str(col2), str(col3), str(col4)) os.makedirs(child_folder, exist_ok=True) process_files(col1, child_folder, col2)
def validate_paths(): global now # Check if the XLSX file path is valid if not os.path.isfile(xlsx_path) or not xlsx_path.endswith('.xlsx'): with open(os.path.join(output_folder, 'errors.txt'), 'a+') as f: f.write(f'Invalid Excel file\n {now}') error_label.configure(text='Inv...
The main task of the code is to validate Excel file paths, load a worksheet, and process its rows for transformation, likely saving results to an output folder. The function uses global variables for paths, worksheet, and output settings, relying on helper functions to verify paths, retrieve worksheets, and execute row...
def transform_excel(): global xlsx_path, folder_path, choice, output_folder, now, worksheet if validate_paths(): get_worksheet() process_rows()
def create_tags_json(data_dir: str): metadata = pd.read_csv( os.path.join(data_dir, '2022-1107_med_campaign_stereoBRUVs_Lengths.txt'), sep='\t', header=0).fillna(0) coords = pd.read_csv( os.path.join(data_dir, '2022-1107_med_campaign_stereoBRUVs_ImagePtPair.txt'), sep='\t', header=0).fillna(0) ...
This function prepares data for processing by creating directories, generating frames from videos, handling background frames, building a dataframe, and applying augmentations if specified. It manages data types, frame creation, and augmentation parameters to structure video data for machine learning tasks.
def prepare_data(data_dir: str = 'raw_data', frames_dir: str = 'frames', is_converted: bool = False, data_types: int = 0, create_augs: bool = False, num_augs: int = 10, to_create_frames: bool = False, to_create_bg_frames: bool = False): create_tags_json(data_dir=data_dir) with...
def get_rfid(): global ser IV = os.urandom(4) ser.reset_input_buffer() ser.write(IV) ser.flush() data = ser.read(16) res = aes.decrypt(data).split(b'\x00')[0] xorred_uid = res[:4] canary = res[4:] uid = bytes(c ^ k for c, k in zip(res,IV)) if IV != canary: print(red(...
The code's main task is to retrieve an RFID UID, fetch associated credit data, delete the corresponding database record from the 'cards' table, and return the UID.
def remove(): uid = get_rfid() credit = getcredit(uid) sql(f"DELETE FROM cards WHERE hash='{uid}'") return uid
def get_rfid(): global ser IV = os.urandom(4) ser.reset_input_buffer() ser.write(IV) ser.flush() data = ser.read(16) res = aes.decrypt(data).split(b'\x00')[0] xorred_uid = res[:4] canary = res[4:] uid = bytes(c ^ k for c, k in zip(res,IV)) if IV != canary: print(red(...
This code adds a specified amount to a user's credit balance. It retrieves the user's RFID ID, fetches their current credit, increments it by the provided amount, updates the credit in the system, and returns the user's ID along with their new credit total.
def add(amount): uid = get_rfid() credit = getcredit(uid) credit += amount setcredit(uid,credit) return (uid, credit)
def get_rfid(): global ser IV = os.urandom(4) ser.reset_input_buffer() ser.write(IV) ser.flush() data = ser.read(16) res = aes.decrypt(data).split(b'\x00')[0] xorred_uid = res[:4] canary = res[4:] uid = bytes(c ^ k for c, k in zip(res,IV)) if IV != canary: print(red(...
The code processes a payment by checking if a user's credit balance is sufficient for the given amount. If insufficient, it returns (uid, -1). Otherwise, it deducts the amount from the credit, updates the balance, and returns (uid, updated credit).
def pay(amount): uid = get_rfid() credit = getcredit(uid) if credit < amount: return (uid, -1) credit -= amount setcredit(uid,credit) return (uid, credit)
def blue(str): return f"\033[34m{str}\033[0m" def read(): uid = get_rfid() credit = getcredit(uid) return (uid, credit) def yellow(str): return f"\033[93m{str}\033[0m" def add(amount): uid = get_rfid() credit = getcredit(uid) credit += amount setcredit(uid,credit) return (uid, credit) de...
This code implements a command-line interface for managing a system with commands like 'read', 'add', 'pay', 'remove', and 'debug'. It interacts with a serial device to handle user inputs, track credits, and toggle debug mode, providing feedback with colored outputs. The main task is to manage and manipulate credit dat...
def main(): #import readline #readline.set_auto_history(True) global verbose print( "Group 46 presents..." "\n", " ____ ______________ __________ \n", "| | \__ ___/ \______ \_____ .__.__.\n", "| | | | | ______ | ___/...
def get_output(self,inputs=None,network=None,activation="sig",rounding=8): """inputs have to be structured like {"i0":0,"i1":1,"i2":1,"i3":0}""" if inputs==None:inputs={"i0":0,"i1":1,"i2":1,"i3":0} if network==None:network={('i0', 'm0'): -4.074, ('i0', 'm1'): -0.439, ('i0', 'm2'): 4.312, ('i0', ...
This function performs backpropagation on a neural network to adjust weights and biases, minimizing error between actual and desired outputs across multiple states. It calculates gradients using activation derivatives, accumulates errors, and updates connections with learning rate constraints. The process involves trav...
def backpropergation(self,network,desired_outputs,states,strength_range_total,learning_rate,activation="sig"): """You need to make the desired_outputs and states variables lists of lists.""" connectable_neurons={} connected_neurons={} for connection in network: if t...
def update_values(self): try: set_up = wheel_setting() amount = float(self.stake.amount) if self.stake.spinx: if self.win_multiplier==0: odds=1 else: odds=self.win_multiplier else: ...
This method updates user account balances based on game outcomes. It calculates win/loss amounts, adjusts giveaway balances for different result types (win, lose, big win), and updates the user's real account with the final amount, including multiplier calculations for big wins.
def run_update_winner_losser_on_real_account(self): this_user_stak_obj=self.stake user_id = this_user_stak_obj.user.id win_amount, ref_credit = self.update_values() if self.result == 1: ### trans_type = "Ispin Win" self.update_giveaway_tok...
def winner_selector(give_away,bet_amount): wheel_map=settings.WHEEL_MAP#WHEEL_MAP=[20,10,5,0,100,50,20,0,3,2,1,0,500,0,20,10,5,0,200,25,15,0,3,2,1,0,1000,0] chosen=[] #print(len(wheel_map)) for n in range(len(wheel_map)): val_at_n=wheel_map[n] if float(give_a...
This function updates a user's account based on a bet outcome by determining a win multiplier, adjusting the pointer, and updating the database. It calculates winnings, differentiates between real and trial accounts, and applies specific update methods (tokeep_onwin/lose) for real accounts or trial account adjustments,...
def spinnerx_account_update(self): current_bal = float(self.current_update_give_away) amount=self.stake.amount if self.stake.bet_on_real_account: pointer,winner_multiplier = self.winner_selector(current_bal,amount) else: pointer,winner_multiplier = self.winner_sel...
def spinnerx_account_update(self): current_bal = float(self.current_update_give_away) amount=self.stake.amount if self.stake.bet_on_real_account: pointer,winner_multiplier = self.winner_selector(current_bal,amount) else: pointer,winner_multiplier = self.winner_sel...
This method updates either a real or trial account based on stake settings. If `spinx` is active, it calls `spinnerx_account_update`. Otherwise, it checks if the bet is on a real account, sets `pointer` to `segment`, and triggers `run_update_winner_losser_on_real_account` or its trial counterpart. The core task is to r...
def run_account_update(self): if self.stake.spinx: self.spinnerx_account_update() else: stake_obj = self.stake if stake_obj.bet_on_real_account: self.pointer = self.segment self.run_update_winner_losser_on_real_account() ...
def roundTwo(howManyDiceLeftThisRound, howManyDifferentDiceRolled): if howManyDiceLeftThisRound == 0: return roundThree(6 - howManyDifferentDiceRolled) return create( roundTwo(howManyDiceLeftThisRound - 1, howManyDifferentDiceRolled + 1), roundTwo(howManyDiceLeftThisRound - 1, howManyDif...
The function `roundOne` recursively calculates the probability distribution of dice roll outcomes in a game. It explores all possible combinations of rolling dice, tracking the number of remaining dice and unique values rolled. When no dice remain, it transitions to `roundTwo` to finalize results. The recursive calls g...
def roundOne(howManyDiceLeftThisRound, howManyDifferentDiceRolled): if howManyDiceLeftThisRound == 0: return roundTwo(6 - howManyDifferentDiceRolled, howManyDifferentDiceRolled) return create( roundOne(howManyDiceLeftThisRound - 1, howManyDifferentDiceRolled + 1), roundOne(howManyDiceLef...
def buildClientList(count=100): for _ in range(count): ua_string = fake.user_agent() user_agent = parse(ua_string) client = { "country" : random.choice(countries), "user_agent" : ua_string, "ip" : hashlib.md5(fake.ipv4().encode()).hexdigest(),...
The code generates a dataset of events by creating client and company lists, collecting a specified number of event items, and saving them as a CSV file in the designated output directory. It constructs the dataset by iterating 'count' times to gather items, ensures the output directory exists, and writes the full data...
def gen(count=10, output="."): buildClientList(1 + int(count/10)) buildCompanyList() events = [] for _ in range(count): events.append(getItem()) if not os.path.exists(output): os.mkdir(output) writeFullDataset(events, filepath="{}/dataset.csv".format(outpu...
def _replace_shortcuts(self): for to_replace, replacement in SHORTCUTS.items(): self._python_regex = self._python_regex.replace(to_replace, replacement) def _escape_in_brackets(self): regex_temp = [] in_brackets = False ...
This code initializes a regex processor by validating and preprocessing a regex pattern. It converts non-string inputs to regex patterns, checks validity, applies transformations for shortcuts, escaping, and syntax handling, trims leading backslashes, then passes the processed regex to the parent class constructor for ...
def __init__(self, python_regex): if not isinstance(python_regex, str): python_regex = python_regex.pattern else: re.compile(python_regex) # Check if it is valid self._python_regex = python_regex self._replace_shortcuts() self._escape_in_brackets() ...
def getAllCoordsOf(self, types): result = [] for index, val in np.ndenumerate(self.maze): if self.maze[index] in types: result.append(index) return result def findEntrance(self): for index, val in np.ndenumerate(self.maze): if val == 2: ...
This function checks if all cells of a specified type (default: "path") in a grid are connected starting from the entrance, using a recursive algorithm to traverse and mark visited cells.
def allAreConnected(self, cell_type="path"): visited = np.zeros(self.dimensions) cell_pos = [1,2,3] if cell_type == "path": cell_pos = [0,2,3] allPos = self.getAllCoordsOf(cell_pos) entrance = self.findEntrance() visitedPaths = [] return self.__allAreC...
def checkerboardMaze(self): for index, x in np.ndenumerate(self.maze): if sum(index) % 2 == 0: self.maze[index] = 1 else: self.maze[index] = 0 def fillBorders(maze): for index, val in np.ndenumerate(maze.maze): for i, dim in enumerate(i...
This function generates a solvable maze by randomly toggling cell values (0/1) in a checkerboard pattern until the maze meets solvability criteria. It initializes the maze structure, removes border cells, adds entrances/exits, and iteratively modifies internal cells to ensure a valid path exists. The process continues ...
def bruteForceStep(self, low_threshold=0, high_threshold=1, paths_connect = True, walls_connect = True): self.checkerboardMaze() self.fillBorders() self.addEntranceAndExit() cell_indexes = set(self.getAllCoordsOf([0,1])) - set(self.getAllBorderCells()) cell_indexes = list(cell_in...
def fillBorders(maze): for index, val in np.ndenumerate(maze.maze): for i, dim in enumerate(index): if dim == maze.dimensions[i] - 1 or dim == 0 : maze.maze[index] = 1 def addEntranceAndExit(self): self.addEntrance() self.addExit() def isSolvable(s...
This function repeatedly fills borders and adds entrance/exit points until the maze becomes solvable, using a brute-force approach to ensure a valid path exists.
def bruteForceAssignEntraceAndExit(self): self.fillBorders() self.addEntranceAndExit() while self.isSolvable() == False: self.fillBorders() self.addEntranceAndExit()
def monteCarloMaze(self, density=.1): for index, x in np.ndenumerate(self.maze): rnd = randint(0,0) if rnd < 0*density: self.maze[index] = 1 else: self.maze[index] = 0 def fillBorders(maze): for index, val in np.ndenumerate(maze.maze): ...
The code generates a maze using Monte Carlo methods, repeatedly regenerating it until it meets criteria: solvable, density within thresholds, and all paths/walls connected. It employs brute-force iteration to satisfy these conditions.
def bruteForceMonteCarlo(self, low_threshold=0, high_threshold=1, paths_connect = True, walls_connect = True): self.monteCarloMaze() self.fillBorders() self.addEntranceAndExit() while self.isSolvable() == False or (self.getDensity() < low_threshold or self.getDensity() > high_threshold) ...
def printSolvability(self): if self.isSolvable(): print("Solvable!") else: print("NOT solvable!") def printConnectedness(self): if self.allAreConnected("path"): print("All paths are connected!") else: print("NOT all paths are connected!") ...
The code's main task is to analyze and display key properties of a maze by calling three methods: checking solvability (path existence), assessing connectedness (reachability of all cells), and calculating density (wall-to-space ratio). It provides a comprehensive overview of the maze's structure, complexity, and navig...
def printMazeInfo(self): self.printSolvability() self.printConnectedness() self.printDensity()
def canWin(self): for i in range(self.length): for j in range(self.length): if self.board[i][j] == 0: self.board[i][j] = self.player if self.checkWin() == self.player: self.setAiMove(3 * i + j) return True else: self.board[i][j] = 0 def canBlock(self): for i in range(self.len...
This function determines an AI's move in a game by incrementing the move count, prioritizing a winning move if possible, then blocking the opponent if necessary, and defaulting to a random move if neither option is available.
def aiMove(self): self.numMoves += 1 if self.canWin(): return elif self.canBlock(): return else: self.randomMove() return
def canWin(self): for i in range(self.length): for j in range(self.length): if self.board[i][j] == 0: self.board[i][j] = self.player if self.checkWin() == self.player: return True else: self.board[i][j] = 0 def canBlock(self): for i in range(self.length): for j in range(self.len...
The code implements an AI's move in a game by incrementing the move counter, checking if the AI can win or block the opponent, and making a random move if neither is possible. It returns the updated board state after each action.
def aiMove(self): self.numMoves += 1 if self.canWin(): return self.board elif self.canBlock(): return self.board else: self.randomMove() return self.board
def printBoard(self): print('') for i in range(self.length): row = [] for j in self.board[i]: if j == 0: row.append(' ') elif j == 1: row.append('O') elif j == -1: row.append('X') if i != 0: print(' ---------') print(' ' + ' | '.join(row)) print('') def makeMove(self): ...
The code initiates a TicTacToe game, asking the user if they want to play and against whom (AI or human). It manages the game loop, alternating moves between players or AI, checks for win/draw conditions, displays the board, and announces results. If the user declines, it exits with a message.
def startGame(self): answer = input(' Hello, do you want to play a game of TicTacToe? yes/no: ') if answer == 'yes': answer2 = input(" Great! Do you want to play against the computer? yes/no: ") print(" Let's start!") if answer2 == 'yes': ai = True else: ai = False while True: self.printB...
def _choose_transactions_from_mempool(self, block_num): processed_transactions = {} contract_states = {} while len(processed_transactions) < 10 and len(self.mempool) > 0: transaction_id = random.choice(list(self.mempool)) transaction = copy.deepcopy(self.mempool[transacti...
The main task of the code is to mine a block by selecting transactions and contract states from the mempool, computing Merkle roots for transactions and contract states, generating a valid nonce through proof-of-work (hashing until the hash meets difficulty requirements), and appending the validated block to the blockc...
def _mine_block(self, block): block['transactions'], block['contract_states'] = self._choose_transactions_from_mempool(block['header']['number']) block['header']['merkle_root'] = \ self._calculate_merkle_root(list(block['transactions'])) #print(list(block['contract_states'])) ...
def parse_levels(levels_txt): #: parse the levels parameter text into an array of scales min, max = list(map(int, levels_txt.split('-'))) return settings.SCALES[min:max + 1] def cache_test_extent(self): print('caching test extent') cache_scales = intersect_scales(settings.SCALES, self.restr...
The main task of the code is to initialize and configure a map caching process for a specified basemap service. It sets up parameters like cache modes (recreate all tiles or only empty tiles), handles data updates and test cache validation, manages progress tracking, and executes caching operations either comprehensive...
def __init__(self, basemap, missing_only=False, skip_update=False, skip_test=False, spot_path=False, levels=False): print('caching {}'.format(basemap)) self.errors = [] self.start_time = time.time() self.service_name = basemap if not levels: self.restrict_scales = se...
def demonstrateHelpers(trainDF): print("Attributes with missing values:", getAttrsWithMissingValues(trainDF), sep='\n') numericAttrs = getNumericAttrs(trainDF) print("Numeric attributes:", numericAttrs, sep='\n') nonnumericAttrs = getNonNumericAttrs(trainDF) print("Non-numeric attributes:"...
The main task of the code is to process training and test datasets for a predictive modeling task. It reads CSV files, demonstrates helper functions, transforms data into input/output formats, trains a model via experiments, and applies the model to the test set for Kaggle-style predictions, outputting results with tes...
def main(): # Read the original data files trainDF = pd.read_csv("train.csv") testDF = pd.read_csv("test.csv") demonstrateHelpers(trainDF) trainInput, testInput, trainOutput, testIDs, predictors = transformData(trainDF, testDF) doExperiment(trainInput, trainOutput, predictors) ...
def demonstrateHelpers(trainDF): print("Attributes with missing values:", getAttrsWithMissingValues(trainDF), sep='\n') numericAttrs = getNumericAttrs(trainDF) print("Numeric attributes:", numericAttrs, sep='\n') nonnumericAttrs = getNonNumericAttrs(trainDF) print("Non-numeric attributes:"...
The main task of the code is to load training and test datasets, preprocess them, demonstrate helper functions, train a model using transformed features, evaluate performance, and generate Kaggle competition predictions. It follows a machine learning pipeline from data loading to model experimentation and final test su...
def main(): # Read the original data files trainDF = pd.read_csv("train.csv") testDF = pd.read_csv("test.csv") demonstrateHelpers(trainDF) trainInput, testInput, trainOutput, testIDs, predictors = transformData(trainDF, testDF) doExperiment(trainInput, trainOutput, predictors) do...
def demonstrateHelpers(trainDF): print("Attributes with missing values:", getAttrsWithMissingValues(trainDF), sep='\n') numericAttrs = getNumericAttrs(trainDF) print("Numeric attributes:", numericAttrs, sep='\n') nonnumericAttrs = getNonNumericAttrs(trainDF) print("Non-numeric attributes:"...
The code's main task is to load training and test datasets, demonstrate helper functions, preprocess data, conduct experiments, and generate Kaggle competition predictions using transformed inputs and outputs. It orchestrates data handling, model evaluation, and submission preparation for machine learning tasks.
def main(): # Read the original data files trainDF = pd.read_csv("train.csv") testDF = pd.read_csv("test.csv") demonstrateHelpers(trainDF) trainInput, testInput, trainOutput, testIDs, predictors = transformData(trainDF, testDF) doExperiment(trainInput, trainOutput, predictors) do...
def reset_agent(self): self.agent.set_state(self.init_state) def is_terminal(self, state, next_state): if not self.env.is_valid(next_state[0:2]): return True if self.env.is_obstacle(next_state[0:2]): return True if self.is_final(next_state): return Tru...
The code simulates one episode of an agent's interaction with an environment. It initializes variables, iteratively selects actions via epsilon-greedy policy, transitions states, computes rewards, updates Q-values, and accumulates total reward. The episode ends when the state becomes terminal, returning the state seque...
def run_episode(self): self.reset_agent() path = [] aseq = [] er = 0 last_state = self.agent.get_state() state = self.agent.get_state() while not self.is_terminal(last_state, state): action = self.epsilon_greedy_policy(state) ...
def run_episode(self): self.reset_agent() path = [] aseq = [] er = 0 last_state = self.agent.get_state() state = self.agent.get_state() while not self.is_terminal(last_state, state): action = self.epsilon_greedy_policy(state) ...
The code trains an agent over multiple episodes, tracking convergence metrics and cumulative rewards. It runs episodes, updates convergence values and rewards, logs progress when reaching goals or at intervals, and optionally visualizes learning paths. The function returns arrays of convergence data and rewards for ana...
def learn(self, logger): if self.plot: self.fig.show() convg = [] rew = [] best = -10e99 try: for i in range(1, self.ep + 1): path, terminal_state, _, er = self.run_episode() convg.append(self.convergence()[self.agent.fin...