dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def is_mine(board, x, y): """return if the coordinate has a mine or not""" return board[x, y] == MINE def count_neighbour_mines(self, x, y): """return number of mines in neighbour cells given an x-y coordinate Cell -->Current Cell(row, col) N --> North(row - 1, col) ...
The function updates the visible board state based on a player's move at coordinates (x,y). If the cell contains a mine, it marks it and ends the game. Otherwise, it reveals the number of adjacent mines. If the count is zero, neighboring cells are recursively opened. The updated board and game status are returned.
def get_next_state(self, state, x, y): """ Get the next state. Parameters ---- state : (np.array) visible board x : int location y : int location Returns ---- next_state : (np.array) next visible board game_over : (bool) ...
def is_new_move(my_board, x, y): """ return true if this is not an already clicked place""" return my_board[x, y] == CLOSED def get_next_state(self, state, x, y): """ Get the next state. Parameters ---- state : (np.array) visible board x : int location ...
The function determines the next game state and reward after a move at (x,y). It checks if the move is valid; if invalid, it returns a penalty. If valid, it updates the state, checks for win/loss, and returns the new state, reward (1000 for win, 5 for progress, -1000 for loss), and game status.
def next_step(self, state, x, y): """ Get the next observation, reward, done, and info. Parameters ---- state : (np.array) visible board x : int location y : int location Returns ---- next_state : (np.array) next visible board ...
def detect_python_version(packages: List[Dict]): for package in packages: if package['name'] == "python": return package['version'] return None def copy_package(package_cache_directory: pathlib.Path, install_directory: pathlib.Path, package: Dict): package_directory = package_cache_direc...
This function installs Python packages by copying them to designated directories. It first detects the Python version from the packages and creates a version-specific directory structure. For each package, it determines the target installation path based on whether the package is noarch for Python. It then copies the p...
def install_packages(package_cache_directory: pathlib.Path, install_directory: pathlib.Path, packages: List[Dict]): python_version = detect_python_version(packages) if python_version is not None: major_minor = '.'.join(python_version.split('.')[:2]) noarch_python_directory = install_directory / ...
def set_name(): temp_name = input("Input your name:\n\tmax chars- 12.\n\tmin chars- 1.\n") new_player.name = temp_name if temp_name == 'admin': if input("Password?") == 'sagiv': new_player.balance = 999999 def check_if_name_in_data_and_replace(): var = None x = 0 name = new_p...
The main task of the code is to manage a game menu where a player selects from various games (War, Roulette, Blackjack, Tic Tac Toe), view high scores, save/load progress, or exit. It initializes the player, displays their balance, processes game selections, executes chosen games, handles invalid inputs, and exits with...
def main_menu(): set_name() check_if_name_in_data_and_replace() print(f"Hello {new_player.name}\nYour starting balance is {new_player.balance}.\nGood Luck!\n") game_picked_by_player = game_pick() playing_deck = Deck() while game_picked_by_player != 9: while game_picked_by_player in [1,...
def get_running_hsm(): hsms = get_hsm() return [hsm for hsm in hsms if hsm["State"]=='ACTIVE'] def debug_print(*args, **kwargs): if DEBUG: print(*args, **kwargs) def get_removable_hsm(): return [hsm['HsmId'] for hsm in get_running_hsm() if hsm['HsmId'] not in main_hsms]
The function `remove_hsm` checks if the number of running HSMs exceeds a minimum threshold. If so, it randomly selects and removes one HSM node from the cluster using `cloudhsm.delete_hsm`, ensuring the cluster retains at least the minimum required HSMs. Debug logs track the action and result.
def remove_hsm(): hsms = get_running_hsm() if len(hsms) <= MIN_HSM_NUMBER: debug_print("min running hsm number reached, will not remove hsm.") return else: available_hsm_ids = get_removable_hsm() debug_print(f"randomly remove 1 HSM node") res = cloudhsm.delete_hsm(Clu...
def in_alarm_state(alarm_arn): alarm_name = alarm_arn.split(':')[-1] response = cloudwatch.describe_alarms(AlarmNames=[alarm_name]) debug_print(f"alarm name: {alarm_name}, alarm_state: {response['MetricAlarms'][0]['StateValue']}") if response['MetricAlarms'][0]['StateValue'] == 'ALARM': return T...
This Lambda function handles scaling events for Hardware Security Modules (HSMs) by adjusting their count based on alarm states. It checks triggers from CloudWatch alarms, enables/disables scheduler rules, and adds/removes HSMs to maintain predefined limits (MAX_HSM_NUMBER/MIN_HSM_NUMBER), ensuring system stability dur...
def lambda_handler(event, context): trigger = event["resources"][0] detail = event["detail"] if trigger == high_scheduler_arn: if in_alarm_state(high_response_alarm_arn): debug_print("receive high_scheduler event") running_hsms_number = len(get_running_hsm()) ...
def get_sql_data_night_select(_measure,table,node_id,start_date,end_date): """ returns values between 12AM and 3 AM :param _measure: :param table: :param node_id: :param start_date: :param end_date: :return: an sql string """ return get_data_time_selection(_measure,table,node_id,...
The function calculates the 10th percentile of nighttime sensor data over a specified period, using minute-resolution data from a database. It groups data by day, computes daily percentiles, applies a 30-day rolling window to derive monthly trends, and saves the result to a hourly-resolution table for offset calibratio...
def calculate_night_percentile(node_id,start_date,end_date ,_measure,_dest_var, verbose=False): """ load the data for the period and generate an offset variable saved with the node called automatically when trying to generate an offset slope calibration Note: this works based on the minute data having a...
def check_high_score(stats, sb): """Check to see if there's a new high score""" if stats.score > stats.high_score: stats.high_score = stats.score sb.prep_high_score() def ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets, bunkers): # Need to pass in Timer class in here for 8 fr...
The code checks bullet collisions with aliens, updating the score and handling special cases like a random alien (Alien4). It also processes collisions between bullets/alien bullets and bunkers, repairing or removing bunkers based on damage. If alien bullets hit the ship, it triggers a ship hit response. Finally, when ...
def check_bullet_collisions(ai_settings, screen, stats, sb, ship, aliens, bullets, alien_bullets, bunkers): if ai_settings.rand_alien_alive: rand = Group() random_alien = Alien4(ai_settings, screen) rand.add(random_alien) rand_collision = pygame.sprite.groupcollide(bullets, rand, Tru...
def check_keydown_events(event, ai_settings, screen, ship, bullets, stats, sb): """Respond to keypresses.""" if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = True elif event.key == pygame.K_SPACE: fire_bullet(ai_settings...
This function processes user inputs by handling keyboard and mouse events in a Pygame game. It responds to quitting, key presses (e.g., movement/shooting), and mouse clicks on buttons (play, high scores, quit, back). Events trigger actions like starting gameplay, accessing high scores, exiting, or returning to menus, w...
def check_events(ai_settings, screen, stats, sb, play_button, high_score_button, quit_button, back_button, ship, aliens, bullets, bunkers): """Respond to keypresses and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif eve...
def check_fleet_edges(ai_settings, aliens): """Respond appropriately if any aliens have reached an edge""" for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def alien_fire_bullets(ai_settings, screen, aliens, alien_bullets): ...
The function updates alien positions, checks for edge collisions, triggers alien shooting, detects ship-alien collisions, and checks if aliens reach the screen bottom, handling game state changes like ship hits and game over conditions.
def update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets, alien_bullets, bunkers): """Update the positions of all aliens in the fleet.""" check_fleet_edges(ai_settings, aliens) aliens.update() alien_fire_bullets(ai_settings, screen, aliens, alien_bullets) if pygame.sprite.spritecolli...
def move(self): # check if all the waypoints have been reached yet if self.target_waypoints < len(self.waypoints): self.target = Vector2(self.waypoints[self.target_waypoints]) # the difference between two points self.movement = self.target - self.pos # represents the distance ...
The code updates an object's state by moving it, rendering it on the screen, and deleting it if marked as dead. The move() method handles motion, draw() renders the object, and self.delete() removes it when self.dead is True. A commented-out health decrement suggests potential future functionality for damage logic.
def update(self): self.move() # self.decreaseHealth(1) self.draw() if self.dead: self.delete()
def maya_main_window(): main_window_ptr = omui.MQtUtil.mainWindow() return wrapInstance(long(main_window_ptr), QtWidgets.QWidget) def create_widgets(self): self.title_frm = QtWidgets.QFrame() self.title_frm.setFrameShape(QtWidgets.QFrame.HLine) self.title_frm.setFrameShadow(QtW...
This code initializes a custom GUI window for an Animation Exporter plugin in Maya. It sets the window title, minimum size, removes the context help button, and prepares the interface by creating widgets, layout, and connections to handle user interactions for exporting animations.
def __init__(self, parent=maya_main_window()): super(AnimationExporter, self).__init__(parent) minWidth = 650 minHeight = 500 self.setWindowTitle("Animation Exporter") self.setMinimumSize(minWidth, minHeight) self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowCont...
def getTransformBone(self): if self.xform_bn_le.text() != "": transformBone = self.xform_bn_le.text() else: transformBone = self.xform_bn_le.placeholderText() return self.checkObjExists(transformBone) def getValuesFromLineEdit(self, layout): ...
This code applies an offset and scale transformation to a selected object's animation, cutting existing keyframes for translate/scale attributes, then setting new keyframes across a specified timeline range. It retrieves UI values for offset and scale, applies them via move/scale commands, and generates keyframes for e...
def setOffsetAndScale(self): self.getTransformBone() sel = ls(sl=True) cutKey( sel[0], cl=True, t=":", hi="none", at="translate" ) cutKey( sel[0], cl=True, t=":", hi="none", at="scale" ) offsetValue = map(float, self.getValuesFromLineEdit(self.offset_la...
def getTransformBone(self): if self.xform_bn_le.text() != "": transformBone = self.xform_bn_le.text() else: transformBone = self.xform_bn_le.placeholderText() return self.checkObjExists(transformBone) def checkForEmptyLineEdit(self, txtField): ...
This function exports animation clips to an FBX file by configuring FBX export settings, validating user input for file paths and names, and executing the FBXExport command with the specified file path. It ensures animation-only export, deletes original takes when splitting, retrieves bone transforms, and handles user ...
def exportAnimClipsFBX(self): mel.eval( "FBXExportAnimationOnly -v true;" ) mel.eval( "FBXExportDeleteOriginalTakeOnSplitAnimation -v true;") self.getTransformBone() if not self.checkForEmptyLineEdit(self.filepath_le): self.getFolderPath() ...
def getTransformBone(self): if self.xform_bn_le.text() != "": transformBone = self.xform_bn_le.text() else: transformBone = self.xform_bn_le.placeholderText() return self.checkObjExists(transformBone) def getTimelineMinMax(self): minTime...
The main task of the code is to bake animation keys for a transform bone's timeline and, if enabled, cut translate/rotate keys for a plane bone. It selects the active object, retrieves timeline ranges, applies baking, checks a checkbox for plane bone processing, and uses Maya's `cutKey` to remove specified attributes' ...
def bakeKeys(self): if self.getTransformBone(): sel = ls( sl=True ) timeline = self.getTimelineMinMax() bakeResults(sel[0], sm=True, hi="below", t=( timeline )) if self.pln_bn_chk.isChecked(): if self.getPlaneBone(): ...
def show_folder_select_dialog(self): self.launch_libfolder_sel_window() self.img_path = os.path.join(self.folder_path, "images") self.img_path = os.path.normpath(self.img_path) isDir = os.path.isdir(self.img_path) if not isDir: os.makedirs(self.img_path) def create_fi...
The code exports selected mesh objects to a library directory, creating thumbnails. It checks for existing files, centers objects for export, handles overwrites via a dialog, and updates or adds cells in a grid with thumbnails. If no selection or folder path is provided, warnings are issued.
def export_geo(self): # Export selected object to library directory, creating thumbnail image # Prompt to overwrite if same name exists already. objSel = cmds.ls(sl=True) sel = cmds.ls(sl=True, type='transform', dag=True, ni=True) if sel: if self.fol...
def clearCreateAnimClip(self, arg_string): mel.eval( 'FBXExportSplitAnimationIntoTakes -clear;' ) mel.eval( 'FBXExportSplitAnimationIntoTakes -v ' + arg_string ) def exportAnimClipsFBX(self): mel.eval( "FBXExportAnimationOnly -v true;" ) mel.eval( "FBXExportDel...
The code exports animation clips as FBX files by processing user inputs from a UI layout. It iterates through line edit widgets, converts numeric inputs to floats, and collects clip names. Depending on a checkbox state, it either creates multiple FBX files or a single clip, then triggers the FBX export process with col...
def startExport(self): mel.eval( "FBXExportSplitAnimationIntoTakes -clear;" ) layout = self.clip_main_layout rows = (layout.itemAt(i).layout() for i in range(layout.count() -1)) for row in rows: clipArgs = [] ...
def open_file(name): ''' Opens a .bff file and creates a new list of strings from it to be used for other functions **Parameters** name: *str* name of a file **Returns** fptr_lines: *list, str* a list of strings separated by lines for identifying d...
The code solves a lazor puzzle from a `.bff` file by generating permutations of block placements in a grid. It identifies the grid layout, block types, laser origins, and target points. It replaces open spaces (`'o'`) with block types (A, B, C) and iterates through all permutations. For each arrangement, it simulates l...
def solver(fptr): ''' Solves a lazor .bff file using sympy **Parameters** fptr: *str* name of a file to open, read, and solve **Returns** solved: *boolean* whether the puzzle is solved ''' if '.bff' in fptr: filename = fptr.split('.bff')[0] fil...
def increase_counter(self): self.counter+=1 def ADD(self, destination, source1, source2): if self.cache_on: self.search_value(destination) self.search_value(source1) self.search_value(source2) self.write_memory(reg_inx(destination), int(self.se...
This code processes input instructions by splitting them into components, increments a counter, and executes corresponding methods (ADD, ADDI, J, CACHE) based on the instruction type.
def instruction(self, instructions): print("Instruction: " +instructions) self.increase_counter() inst = instructions.split(',') if inst[0] == 'ADD': self.ADD(inst[1], inst[2], inst[3]) if inst[0] == 'ADDI': self.ADDI(inst[1], inst[2], inst...
def add_junk(notes): junk = int(20 * notes['speed']) notes['notes'].extend([[] for i in range(junk - len(notes))]) notes['notes'].append([440]) return notes def get_wav_blob(notes): notes_response = convert_notes_to_midi(notes) app.logger.info("Notes converter response:" + str(notes_response.sta...
The code processes a JSON request to generate a mood analysis by converting input notes into a WAV audio file, then detecting the mood from the audio. It handles errors in data retrieval, WAV generation, and mood detection, returning a JSON response with the detected mood or defaulting to "happy" on failure.
def generate_mood(): notes = add_junk(request.get_json()) if not notes: app.logger.error('Notes could not be obtained from post request') return 'Error: make sure the post request is formatted right.', 422 wav_blob = get_wav_blob(add_junk(notes)) if 'Error' in wav_blob: app.logg...
def _set_decimal_precision(self, decimal_precision: int) -> bool: # store precision value (if it is valid) self._decimal_precision = decimal_precision if decimal_precision > 0 else 0 return True def _coco_images(self, path_to_files: Union[str, pl.Path] = None) -> List[dict]: coco_images ...
The main task of the code is to aggregate COCO dataset components—images, categories, and annotations—into a structured dictionary format. It retrieves image data, category mappings, and annotations, combines them with metadata, and returns a COCO-compliant dictionary containing "images," "categories," "annotations," a...
def get_coco_data(self, path_to_files: Union[str, pl.Path] = None, decimal_precision: int = 0) -> dict: self._set_decimal_precision(decimal_precision) data_coco_images = self._coco_images(path_to_files=path_to_files) data_coco_categories = self._coco_categories() data_coco_annotations =...
def _fill_by_suit(cards): out = {} for suit in Card.suits: out[suit] = [] for card in cards: out[card.suit].append(card) return out def _fill_by_value(cards): out = {} for value in Card.values: out[value] = [] for card in cards: out[card.value].append(card) ...
The code initializes a class to process a set of playing cards, organizing them by suit and value using helper functions. It sets up attributes for the cards, an empty hand, a title, and calculated score via the _eval() method, which likely determines the hand's value based on card groupings.
def __init__(self, cards): self.cards = cards self.hand = [] self.title = '' self.cards_by_suit = _fill_by_suit(cards) self.cards_by_value = _fill_by_value(cards) self.score = self._eval()
def log(msg, level=INFO): _LEVELS = ["ERROR", "WARN", "INFO", "DEBUG"] if loglevel >= level: print("%s:\t%s" % (_LEVELS[level], msg)) def sync_time(self): ts = self._get_timestamp_as_array() ts_string = "%02d%02d-%02d-%02d %02d:%02d:%02d" % (ts[0], ts[1], ...
The code connects to a device via Bluetooth using a MAC address or a serial port based on the input address. It initializes a Bluetooth socket for MAC addresses, sets a timeout, and identifies the device. For "COM" addresses, it uses a serial connection. Errors log a failure message. On success, it logs the connection,...
def connect(self, address): try: if re.match(self._MAC_PATTERN, address): log("Connnect via Bluetooth to %s" % address, DEBUG) self._client_socket = socket.socket( socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) sel...
def is_stop_signal(self): return os.path.isfile(self._stop_file_path()) def _get_timestamp_as_array(self): dt_now = datetime.datetime.now() cc = dt_now.year // 100 yy = dt_now.year % 100 mm = dt_now.month - 1 dd = dt_now.day h24 = dt_now.hour m = dt_now...
This function decrements a given number of seconds, formats the current timestamp into a specific string format, updates device time data, sends time-related requests, and logs progress. It runs in a loop until secs reaches 0 or a stop signal is received, ensuring approximately 1-second intervals between updates while ...
def display_mins_n_secs(self, secs): while (secs >= 0 and not self.is_stop_signal()): before = time.time() ts = self._get_timestamp_as_array() ts_string = "%02d%02d-%02d-%02d %02d:%02d:%02d" % (ts[0], ts[1], ts...
def _get_timestamp_as_array(self): dt_now = datetime.datetime.now() cc = dt_now.year // 100 yy = dt_now.year % 100 mm = dt_now.month - 1 dd = dt_now.day h24 = dt_now.hour m = dt_now.minute s = dt_now.second return [cc, yy, mm, dd, h24, m, s] def...
This function implements a countdown timer that decrements from a specified duration (minutes:seconds), updates a timestamp array with elapsed time, logs progress, sends control signals to a device, and maintains a 1-second interval. It adjusts for step direction, handles stop signals, and manages interruptions with lo...
def countdown(self, minutes, seconds, step=-1): step = 1 if step > 0 else -1 ts = self._get_timestamp_as_array() total = minutes * 60 + seconds remain = total while (remain >= 0 and not self.is_stop_signal()): before = time.time() if step == -1: ...
def log(msg, level=INFO): _LEVELS = ["ERROR", "WARN", "INFO", "DEBUG"] if loglevel >= level: print("%s:\t%s" % (_LEVELS[level], msg)) def is_stop_signal(self): return os.path.isfile(self._stop_file_path()) def _send(self, data, lresponse=32): try: log(">>> %s" % (" ".join(...
This function blinks an alarm LED for a specified duration by sending toggle commands. It logs the action, doubles the input time, and alternates LED states (on/off) every 0.5 seconds for the calculated duration. It checks for stop signals and handles interruptions, logging completion or warnings accordingly.
def blink_alarm_led(self, secs): log("Blink alarm led for %i seconds" % secs, INFO) secs *= 2 while (secs >= 0 and not self.is_stop_signal()): self._send(self._get_request(17, [24, secs % 2]), lresponse=6) try: time.sleep(.5) secs -= ...
def _exec_run(self, command, **kwargs): # Set pyenv dir, otherwise it will detect the original pyenv which is inaccessible command = 'PYENV_DIR={} {}'.format(self.path, command) # Wrap with firejail if settings.VirtualEnv.USE_FIREJAIL: network = '' if self.network else ' --ne...
The main task of the code is to set up a Python virtual environment using pyenv, create a working directory, configure volume mounts (via symlink or copy based on firejail settings), and ensure pip is updated. It handles environment isolation, dependency management, and file binding for a specified Python image and pro...
def start(self): # Create working folder and cd os.makedirs(self.path, exist_ok=True) os.chdir(self.path) # Provide pyenv for firejail if settings.VirtualEnv.USE_FIREJAIL: self._exec_run('curl https://pyenv.run | bash') self._exec_run('pyenv install {}'.fo...
def log(self, message, log_type='info'): getattr(logger, log_type)("[TS={}, A={}, R={}, M={}] {}".format(self.ts_id, self.agent_id, self.runner_type, self.metadata, message)) def pull_image(self): self.log('Pulling image: {}'.format(self.image)) client.images.pull(self.image) def run_container(self): self.log('...
This code runs a containerized application by pulling an image, setting up dependencies, executing a runner script within time limits, capturing output, handling errors, and cleaning up resources. It logs progress, enforces size and time constraints, installs required packages, and returns results or errors while ensur...
def run(self, interactive=False): self.log('Running container: TS.{}, A.{}, RT.{}, RTL.{}'.format(self.ts_id, self.agent_id, self.runner_type, self.run_time_limit)) output = (None, None) # (error, data) try: with utils.time_limit(self.pull_time_limit, 'Image pull time limit exceeded'): self.pull_image() ...
def generate_new_columns(df, plant_name, plant_data): t_values, h_values, l_values, w_values = get_ideal_values(df, plant_name) t_first_element = t_values[0] t_last_element = t_first_element try: t_last_element = t_values[-1] exc...
This function processes plant deviation data by reading a CSV file, generating an ideal care package for a specified plant, applying user-defined deviations to the package parameters, logging the changes, and executing the adjusted package settings on a device with the given ID.
def send_deviated_package(id_device: str, plant_name: str, deviations: dict): file_path = 'resources/plants_dataset.csv' df = pd.read_csv(file_path) df['Botanical_Name'] = df['Botanical_Name'].str.lower() plant_name = plant_name.lower() new_df = df.copy() plant_data = df[df['Botanical_Name'] =...
def zero_low_density(rho,cut=1e-10): rho[rho<cut]=0 return rho def vwn_epsp(x): return vwn_eps(x,0.0310907,-0.10498,3.72744,12.9352) def vwn_epsf(x): return vwn_eps(x,0.01554535,-0.32500,7.06042,18.0578) def vwn_g(z): return 1.125*(np.power(1+z,4./3.)+np.power(1-z,4./3.)-2) def vwn_depsp(x): return vwn_deps(x,0...
The function `cvwn5` computes the VWN5 correlation energy (`ec`) and its derivatives (`vcrhoa`, `vcrhob`) for electron densities `rhoa` and `rhob`. It first filters out negligible densities using `zero_low_density`. For each density pair, it calculates the total density `rho`, the spin polarization `zeta`, and derives ...
def cvwn5(rhoa,rhob,tol=1e-10): rhoa = zero_low_density(rhoa) rhob = zero_low_density(rhob) ecs = [] vcrhoas = [] vcrhobs = [] for na,nb in zip(rhoa,rhob): rho = na+nb ec = vcrhoa = vcrhob = 0 if rho>tol: zeta=(na-nb)/rho x = pow(3./4./np.pi/rho,1...
def load_ip_addresses(self): path = self.select_file() try: with open(path, "r") as file: self.ips = file.read().splitlines() # Read IP addresses from a file and store them in the list return path print("IPs loaded successfully.") except F...
The main task of the code is to manage a list of IP addresses through a menu-driven interface. It allows users to start connections, view, add, remove, edit, or clear IP addresses, and save changes to a file. The menu loops until the user exits, handling each choice by calling corresponding methods and ensuring updates...
def main_menu(self): path = self.load_ip_addresses() # Load IP addresses from a file self.clear_screen() while True: print("\n=== Config Menu ===\ \n1. Start Connection\ \n2. Print IPs\ \n3. Add IP\ \n4....
def player_moves(self, player, i=range(64)): result = [] for tile in i: if self.board.get_player(tile) == player: piece = self.board.board[tile] rays = self.EVERY_MOVE.get(piece) for ray in rays[tile]: move...
This function generates legal moves for a chess player by filtering out moves that leave the king in check. It simulates each move on a test board, checks if the opponent can attack the king's position, and excludes invalid moves. Special handling for castling ensures the king isn't exposed to attacks during or after t...
def get_moves(self, player, i=range(64)): if not self.check: return self.player_moves(player, i=i) result = [] testBoard = Game(fen=str(self), check=False) for move in self.player_moves(player, i=i): kingColor = 'K' if player == 'w' else 'k' ...
def notation_to_index(self, notation): return (8 - int(notation[1])) * 8 + ord(notation[0]) - 97 def get_moves(self, player, i=range(64)): if not self.check: return self.player_moves(player, i=i) result = [] testBoard = Game(fen=str(self), check=False) for move in s...
The code updates the game state after a move by processing indices, validating the move, modifying turn, castling rights, en passant, and special moves like castling or en passant captures. It adjusts the board, tracks move history, and updates the FEN notation to reflect the new state, including turn switches, castlin...
def make_move(self, move): # Updates Board states as well as making the move # Indicies start = self.notation_to_index(move[0:2]) end = self.notation_to_index(move[2:4]) # Names piece = self.board.board[start] target = self.board.board[end] temp = self.get_moves...
def verify_str_arg(value, arg=None, valid_values=None, custom_msg=None): if not isinstance(value, torch._six.string_classes): if arg is None: msg = "Expected type str, but got type {type}." else: msg = "Expected type str for argument {arg}, but got type {type}." msg =...
This code initializes a dataset class (SubImageNet) by setting up directories, verifying the data split (train/val), handling downloads, loading metadata to map class identifiers (wnids) to human-readable labels, and constructing class-to-index mappings for use in training/validation. It prepares the dataset structure ...
def __init__(self, root, split='train', download=False, **kwargs): root = self.root = os.path.expanduser(root) self.split = verify_str_arg(split, "split", ("train", "val")) if download: self.download() wnid_to_classes = self._load_meta_file()[0] super(SubImageNet, s...
def restart(self): '''setup the environment''' self.setup_state_space() self.setup_action_space() self.setup_reward_function() def observe(self, num=1): '''sample observed states''' self.state = self.rng_s.uniform(self.low_s, self.high_s, (num,self.dim_s)) return ...
The code computes the distribution of optimal actions by sampling states, calculating rewards, and generating a histogram of the most frequent optimal actions, then printing them in descending order.
def print_action_histogram(self, num_s=100000): '''compute the average/minimum/maximum reward values and optimal actions''' self.restart() S = self.observe(num=num_s) R = self.compute_reward_raw(S, self.actions) hist = np.histogram(R.argmax(axis=1), bins=np.arange(self.num_a+1), ...
def restart(self): '''setup the environment''' self.setup_state_space() self.setup_action_space() self.setup_reward_function() def observe(self, num=1): '''sample observed states''' self.state = self.rng_s.uniform(self.low_s, self.high_s, (num,self.dim_s)) return ...
The code evaluates an agent's performance by sampling states, predicting actions via the agent's policy, calculating average rewards, and analyzing action distribution using a histogram. It restarts the environment, observes states, computes rewards for agent's actions, and prints the mean reward and sorted action freq...
def evaluate_agent(self, agent, num_s=100000): '''evaluate the agent's performance on the randomly sampled states''' self.restart() S = self.observe(num=num_s) A = agent(S).numpy().argmax(axis=1) R = self.compute_reward(S,A) hist = np.histogram(A, bins=np.arange(self.num_...
def load_ingredient_mapper(self): path = os.path.join(self.directory, 'ingredient_mapper.pkl') self.ingredient_mapper = pickle.load(open(path, 'rb')) def load_embeddings(self): embeddings_path = os.path.join(self.directory, 'embeddings.pkl') self.embeddings = pickle.load(open(embeddings_...
The code initializes a class to handle recipe data by loading ingredient mappings, embeddings, and recipe embeddings. It sets up attributes for directory storage, ingredient mapping, embedding models, and recipe vectors, preparing the object for tasks like recipe similarity or ingredient analysis.
def __init__(self, directory): self.directory = directory self.ingredient_mapper = None self.embeddings = None self.model = None self.recipe_embeddings = None self.load_ingredient_mapper() self.load_embeddings() self.get_recipe_embeddings()
def stopCheck(self,x,y): stopped = False kx = 0 ky = 0 if self.board.board[x][y].team: kx = self.blackKingX ky = self.blackKingY else: kx = self.whitekingX ky = self.whitekingY # checking if the king can capture the piece...
The code determines if a king is in checkmate by checking if any adjacent square allows the king to escape capture, considering valid moves, non-ally pieces, and capture possibilities. It sets `checkMate` to False if an escape exists, returning whether checkmate is achieved.
def checkMate(self,x,y): checkMate = True kx = 0 ky = 0 if self.stopCheck(x,y): checkMate = False if self.board.board[x][y].team: kx = self.blackKingX ky = self.blackKingY else: kx = self.whitekingX ky = self....
def enemyKinginCheck(self,x2,y2): kx = 0 ky = 0 if self.board.board[x2][y2].team: kx = self.blackKingX ky = self.blackKingY else: kx = self.whitekingX ky = self.whitekingY if self.Capture(kx,ky,self.board.board[kx][ky].team,False...
This function checks if a move results in checkmate. It verifies if the enemy king is in check, identifies checking pieces, and determines if any of these pieces can deliver checkmate. If so, it sets `check_mate` to True and returns `mate = True`, otherwise returns False.
def enemyChecks(self,x2,y2,moveInfo): mate = False if self.enemyKinginCheck(x2,y2,): moveInfo.check = True self.checkPieces.clear() self.FindCheckPieces(self.board.board[x2][y2].team) for point in self.checkPieces: if self.checkMate(poin...
def get_users(token=bottoken,bigslack=bigslack): '''gets the users list''' if bigslack: cursor="" url = ( 'https://slack.com/api/users.list?token=' +token+'&limit=1000&presence=false' ) result={'members':[]} result1= create_request(url) if...
The code sends reminder messages to all users by retrieving user data, iterating through user IDs, and using a bot to dispatch each reminder, with status updates logged at the start and end of the process.
def sendreminders(): results1['users.list'] = get_users(bottoken) allusersids = gather_allusers(results1) do_send_botmessage("INFO: Start of reminders Sending") for i in allusersids[1]: do_send_reminder(remindertxt, i, 1) do_send_botmessage("INFO: End of reminders Sending")
def gather_admins(results): admin_names , admin_ids = [],[] for i in range(len(results['users.list']['members'])): if results['users.list']['members'][i]['deleted']==False and ( results['users.list']['members'][i]['is_admin']==True or results['users.list']['members'][i]['is_...
The code establishes a real-time WebSocket connection to process events, using configuration data (admins, commands, security rules) to validate and handle incoming messages. It continuously listens for updates, applies security checks, and logs activity, ensuring persistent monitoring through an infinite loop.
def realtime_run(): lograte=Lograte(6) results1['users.list'] = get_users(bottoken) admins = gather_admins(results1) results1['channels.list'] = get_channels(bottoken) channels=gather_channels(results1) for i in admins[1]: alloweduserids.append(i) simplecommands = get_config_sim...
def _get_image_from_source(src_image): if isinstance(src_image, str): # Daca sursa este calea catre imagine # vom incarca intai imaginea return cv.imread(src_image) else: return src_image def _find_faces(self, img, image_path=''): # assert self._model is not None or self....
The main task of the code is to blur detected faces in an input image. It retrieves the image, identifies face regions using detection, and applies blurring to those specific areas before returning the modified image with faces obscured.
def blur_image(self, src_image): current_image = _get_image_from_source(src_image) # Gasim detectiile pentru imaginea data detections = self._find_faces(current_image, src_image) # Cenzuram portiunile detectate blurred_image = self._blur_image_portions(current_image, detections...
def updateMeasurementInputs(self): """ Update the measurement inputs based on user input and configuration parameters. """ try: self.entry7.state([]) self.saveUserInput(self.entryrev,'stepperRev_mm') self.saveUserInput(self.entry5,'measu...
This code creates a calibration GUI frame with input fields for displacement, stepper, and sensor positions. It binds an entry field to update measurement inputs and includes a 'Calibrate' button that triggers calibration, saves user input, converts units, runs the calibration process, updates the console, and disables...
def createCalibrationFrame(self): frame = tk.ttk.LabelFrame(self.root, text="Calibration") frame.place(x=50, y=600, width=265, height=190) label = tk.ttk.Label(frame, text="Displacement (mm / rev):") label.place(x=5, y=10) self.entryrev = tk.ttk.Entry(frame, width=6) sel...
def saveUserInput(self, entry, param_name): """ Save the user input value for a parameter and update the cache file. """ value = entry.get() if self.arcon.userInput[param_name]: self.arcon.userInput[param_name] = (value) entry.unbind('<Retur...
This function creates a GUI frame for measurement settings, including input fields for coil current, sample count, measurement parameters, and buttons to initiate Coil or Permanent Mode measurements. It binds entries to save user inputs, updates measurement configurations, disables buttons during execution, and trigger...
def createMeasurementFrame(self): frame = tk.ttk.LabelFrame(self.root, text="Measurement") frame.place(x=320, y=600, width=225, height=281) label2 = tk.ttk.Label(frame, text='Coil Current (A):') label2.place(x=5, y=10) entry2 = tk.ttk.Entry(frame, width=8) entry2.place(x...
def toggleRealTimeMeasurement(self): """ Toggle the real-time measurement on or off. """ self.varRealTimeMeasurement.set(not self.varRealTimeMeasurement.get()) if self.varRealTimeMeasurement.get() == True: try: self.measureLiveButton.config(imag...
This code creates a GUI frame for manual control of a stepper motor and sensor data display. It includes input fields for absolute/relative movement, buttons to trigger motion, real-time measurement toggles, and labels to show magnetic field readings (x, y, z, R). It integrates with hardware control via `arcon` and all...
def createManualOperationFrame(self): frame = tk.ttk.LabelFrame(self.root, text="Manual Operation") frame.place(x=550, y=600, width=1000, height=95) label8 = tk.ttk.Label(frame, text='Stepper move to (mm):') label8.place(x=5, y=7) self.entry8 = tk.ttk.Entry(frame, width=5) ...
def createMainWindow(self): self.root = ThemedTk() self.my_font = font.Font(size=12) Style().configure("TButton", font=self.my_font) self.root.option_add("*font", self.my_font) self.root.title('Automated Magnetometer GUI') self.root.set_theme('arc') self.root.wm_g...
The main task of the code is to initialize a graphical user interface (GUI) by creating and configuring multiple UI components such as the main window, information console, toolbar, data plots, calibration/measurement frames, and manual operation sections. It disables all buttons initially, enables the initialization b...
def initializeUI(self): self.createMainWindow() self.createInformationConsole() self.createToolbar() self.createDataPlots() self.createCalibrationFrame() self.createMeasurementFrame() self.createGroupLogo() self.createManualOperationFrame() self.d...
def get_Q(model): def Q(states, actions): inputs = np.empty((len(states), 3)) inputs[:, :-1] = states inputs[:, -1] = actions ret = model(inputs) if len(ret.shape) > 1: ret = ret[:, 0].numpy() return ret return Q def get_policy(Q, epsilon): de...
The code trains a neural network using reinforcement learning, iteratively improving a Q-function model via episodes of simulated interactions. It initializes a Keras model, generates state-action samples with an epsilon-greedy policy, computes target Q-values, and trains the model on these data. Epsilon decays over it...
def train(_model=None, epsilon=1): if _model is None: _model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(3,)), tf.keras.layers.Dense(10, activation='relu'), tf.keras.layers.Dense(10, activation='relu'), tf.keras.layers.Dense(1) ...
def train_dataloader(self): # logging.info('training data loader called') loader = torch.utils.data.DataLoader(self.data_train, batch_size=self.batch_size, collate_fn=self.collate_fn, shuffle=True) return loader def val_dataloader(self): # ...
This method executes one training or validation epoch. It initializes data loaders and model modes (train/eval), iterates through batches with progress tracking, performs training/validation steps, aggregates outputs, schedules learning rate, and finalizes results via train_end/validation_end. The core task is to manag...
def run_epoch(self, validation=False): if not validation: loader = self.train_dataloader() pbar = tqdm(loader, desc='Epoch: [%d]/[%d] Training'%(self.count, self.epochs), leave=True) self.model.train() else: loader = self.val_dataloader() pbar ...
def proc_openNewWindow(self): self.dlg = addChunksDlg() def proc_displayInfo(self): self.dlg2 = promptReflCalibDlg() self.dlg2.show() def openDrtkFileDlg(self): filename = QFileDialog.getOpenFileName(self, '(If Blockshift enabled) Choose tex...
This code creates a GUI for Metashape processing, collecting user inputs for calibration checks, coordinate systems, smoothing settings, and file selections. It includes buttons to add images, display info, run processing, and quit, along with checkboxes and input fields to configure workflow parameters like EPSG codes...
def __init__(self): super().__init__() self.setWindowTitle("Metashape processing menu") layout = QVBoxLayout() clickAddImages = QPushButton("Add images") self.label = QLabel("User input required to Locate panel and select calibration images") info = QPushButton("Info o...
def build_sample_graph(model, model_hparams): placeholders = model.set_inputs() log_prob, out, edge_feat = model.setup(is_training=False, sample=True) loss = tf.reduce_mean(log_prob) loss_string = tf.summary.scalar('sample_log_prob', loss) z, omega = out z_string = t...
The code generates synthetic graph structures using a trained GraphGenerator model by sampling random inputs (z_in, edge_in, omega_in), passing them through the model to produce adjacency matrices and node features, and logging the generated outputs along with their log probabilities for analysis and visualization.
def sample(model_hparams, train_data, valid_data, eval_every, exp_dir="", summary_writer=None, n_node_types=None, n_edge_types=None): assert n_node_types is not None assert n_edge_types is not None with tf.Graph().as_default(): params = dict() params['is_...
def get_config(): base_path = get_base_path() config_file = str(get_base_path() / 'SNScrapeAPI/config.json') with open(config_file) as json_file: config = json.load(json_file) return config def overwrite_config_with_args(config, args): ### overwrite config with args is provided if args....
The main task of the code is to load and configure settings, conditionally execute data collection and reporting based on configuration flags, and finalize the process. It overrides default config with command-line arguments, skips data collection or reporting if flags are inactive, logs skipped steps, and prints "done...
def main(args): # experts = ['BITCOINTRAPPER', 'j0hnnyw00'] # screen name config = get_config() config = overwrite_config_with_args(config, args) is_collect_data_flag_active = bool(config['is_collect_data']['is_flag_active']) is_report_flag_active = bool(config['is_report']['is_flag_active']) ...
def losses_for_idealized_participants(): import statistics ret = {} for evaluation in shared_task_evaluations(): if not(is_evaluation_for_idealized_participants(evaluation)): continue evaluationMeasure = evaluation['EvaluationMeasure'] if evaluationMeasure not in ret: ...
The function generates a formatted table row by combining idealized loss values and evaluation results from two deduplication strategies ('remove' and 'duplicatesMarkedIrrelevant') for a given shared task and measure. It retrieves precomputed losses, calculates metrics like average scores, deltas, and Kendall Tau value...
def table_3_row(shared_task: SharedTasks, measure: Measure, qrel_deduplication: QrelDeduplication): losses_for_idealized = losses_for_idealized_participants()[measure.name][shared_task.name] remove_duplicates = evaluation_for( shared_task=shared_task, dedup='remove', measure=measure, ...
def get_resource_by_uri(self, uri): """Resolve remote path by mediafire uri uri -- One of: mf:(quickkey|folderkey[/path/to/resource]|/path/to/resource) /path/to/resource """ tokens = urlparse(uri) if tokens.path.startswith("/"): # Use path lo...
The code defines a method to delete a file or folder from MediaFire based on the provided URI. It identifies the resource type (File/Folder), calls the appropriate deletion method, and handles unsupported types by raising an error. The 'purge' parameter determines if the deletion is permanent.
def delete_resource(self, uri, purge=False): """Remove file or folder uri -- mediafire URI """ resource = self.get_resource_by_uri(uri) if type(resource) is File: result = self.delete_file(uri, purge) elif type(resource) is Folder: result = self....
def _Vclean(m, t, D, Vs, Ve): d = util.phi(m) return t**2 * d * Ve * (Vs + Ve) def _Vlevel(V, ops, Bargs, kswargs, sdist): model = ops['model'] sums = ops['sums'] rots = ops['rots'] const = ops['const'] Vconst = _Vconst(const, **Bargs) Vswitch = _Vswitch(**Bargs, **kswargs) return ...
The code computes a logarithmic value based on iteratively transformed variables. It initializes V using _Vclean, then applies _Vlevel and _Vmul/_Vswitch operations multiple times (defined by 'muls'). The result is a log2 of D multiplied by sqrt(8*V), where V evolves through the iterations. This likely calculates a com...
def _logq(ops, Bargs, kswargs, sdist): muls = ops['muls'] D = Bargs['D'] V = _Vclean(**Bargs) for _ in range(muls): V = _Vlevel(V, ops, Bargs, kswargs, sdist) V = _Vmul(V, sdist, **Bargs) + _Vswitch(**Bargs, **kswargs) return util.clog2(D * math.sqrt(8 * V))
def _B(ops, Bargs, kswargs): model = ops['model'] sums = ops['sums'] rots = ops['rots'] const = ops['const'] Bconst = _Bconst(const, **Bargs) Bscale = _Bscale(**Bargs) Bswitch = _Bswitch(**Bargs, **kswargs) fscale = _fscale(**kswargs) B = var('B') f = { 'Base': ((sums *...
The main task of the code is to compute a sequence of log probabilities (`logq`) for a probabilistic model, starting with an initial state (`_logp0`), followed by intermediate steps (`_logpi`), and ending with a final state (`_logpM`). These values are aggregated into a list, and a total log probability (`logP`) is cal...
def logqP(ops, Bargs, kswargs, sdist): B = _B(ops, Bargs, kswargs) B0 = _B0(ops, B, Bargs, kswargs) logq = [_logp0(B0)] for _ in range(ops['muls'] - 1): logq.append(_logpi(B)) logq.append(_logpM(B, Bargs)) logP = _logP(logq, kswargs) return logq, logP
def find_all_routes(self,town1,town2,maxStops): graph = self.return_graph_as_dict_of_neighbours() #dfs on graph to find all routes initial_stop = 0 #list_with_path path = [] all_paths = list(self.dfs_find_all_routes( graph,town1,town2,path,initial_stop,maxStops)) return all_paths def find_min_distance(s...
This function finds the shortest path from a source to a target node in a graph by evaluating all possible paths, calculating their total distances, and returning the path with the minimum distance along with the distance value.
def find_min_distance_with_path(self,src,target): all_paths = self.find_all_routes(src,target,float("inf")) min_distance = self.find_min_distance(src,target) graph = self.return_graph_as_dict_of_neighbours() #determines if path is the min path min_path = None for path in all_paths: summ = 0 for i in r...
def create_minibatches(self, X, Y, batch_size): """ Create minibatches from input features and labels. Args: X: Input features matrix. Y: Labels matrix. batch_size: Size of each minibatch. Returns: List of tuples, each containing a miniba...
The code trains a multi-class logistic regression model using mini-batch gradient descent with L2 regularization. It initializes weights and bias, iteratively updates them via softmax-predicted gradients, and evaluates accuracy/F1 score per epoch. Regularization (self.C) is directly added to weight updates, while bias ...
def train(self, X, Y, ): """ Train the Logistic Regression model. Args: X: Feature matrix Y: Label matrix Returns: None """ #################### STUDENT SOLUTION ################### # Initialize weights and bias self...
def lpc(self, frame_no: int, lpc_type="iac", p: int = 20) -> np.array: """ -> Q. 4 Calculate LPC coefficients. We calculate them in three ways (as in requested in exercise's questions) First way to calculate LPC coefficients is to use auto correlation matrix and solve it using inv(R) * r...
The main task of this code is to plot the spectral envelope of a specific audio frame using Linear Predictive Coding (LPC) coefficients. It calculates the envelope from LPC coefficients, optionally overlays the frame's spectrum, identifies formant frequencies, and visualizes them as dashed lines. The plot includes freq...
def plot_spectral_envelope(self, frame_no: int, p: int = 20, frame_spec_plot: bool = True, show_formants: int = 3): """ Plot Spectral envelope of a specific frame :param frame_no: Signal's frame number :param p: LPC coefficients count :param frame_spec_plot: Whether Plot frame sp...
def pre_processing(self): """ Apply all the pre-processing steps on the signal. First we calculate signal frames. Hyper-parameters are: self.frame_length, HOP_LENGTH, self.window which we define as class parameters. The values are from exercise. I check if pre-processing appl...
The code computes MFCC features from audio signals, applying pre-processing, FFT, filter banks, and DCT. It replaces the first MFCC coefficient with short-time energy, optionally applies cepstral mean normalization (CMVN) using VAD, and appends first/second-order derivatives if enabled. The result is a normalized, deri...
def mfcc(self, cmvn: bool = True, derivatives: bool = True): self.pre_processing() self.frames_fft() filter_bank = self.filter_bank(plot=False) log_filter_bank = self.log_frame_filter_bank(filter_bank) MFCC = self.frames_dct(log_filter_bank) MFCC[:, 0] = self.short_time_...
def init_clusters(k): clusters = [] for i in range(k): clusters.append([]) return clusters def assign_points(x, clusters, centroids): for point in x: centroid_index = closest_centroid(point, centroids) if centroid_index != -1: clusters[centroid_index].append(point) ...
The code implements the K-means clustering algorithm, iterating up to 30 times to assign data points to clusters and update centroids until convergence (no centroid changes). It tracks iteration details in a string, returning the log of centroid states at each step.
def k_means(k, x, centroids): output_string = "" iter_count = 0 iter_max = 30 convergence = False while not convergence and iter_count < iter_max: clusters = init_clusters(k) clusters = assign_points(x, clusters, centroids) old_centroids = centroids.copy() update_cent...
def shuffle(arr): np.random.shuffle(arr) return arr def split_training_set(training_set, split_k): parts = np.array(np.array_split(training_set.copy(), split_k), dtype=object) validation = parts[0].copy() train = np.concatenate(np.delete(parts.copy(), 0, axis=0)) return train, validation def get...
The function `get_all_results` trains a machine learning model over multiple epochs, evaluating its performance on training and validation sets each epoch. It shuffles the training data, splits it into train/validation subsets, and iteratively trains the model while recording accuracy and loss metrics. After training, ...
def get_all_results(training_set, batch_size, model, split_k): validation_accuracies = [] train_accuracies = [] validation_losses = [] train_losses = [] training_set = shuffle(training_set) train_set, validation_set = split_training_set(training_set, split_k) train_loader = get_data_loader(t...
def shuffle(arr): np.random.shuffle(arr) return arr def split_training_set(training_set, split_k): parts = np.array(np.array_split(training_set.copy(), split_k), dtype=object) validation = parts[0].copy() train = np.concatenate(np.delete(parts.copy(), 0, axis=0)) return train, validation def get...
The code trains a model using a shuffled and split training set, then predicts on test data. It shuffles the training set, splits it into training and validation, trains the model, converts test data to tensors, creates a test loader, generates predictions, and writes them to a file.
def train_and_predict_test_x(training_set, test_x, model, batch_size, split_k): training_set = shuffle(training_set) train_set, validation_set = split_training_set(training_set, split_k) train_loader = get_data_loader(train_set, batch_size, True) training_process(model, train_loader) test_tensor = c...
def calc_fc0_size(self): return self.calc_size(self.data_height) * self.calc_size(self.data_width) * self.conv4_out_chs def get_cnn_layer(self, in_chs, out_chs): return nn.Sequential( nn.Conv2d(in_chs, out_chs, self.kernel_size, self.stride, self.padding), nn.BatchNorm2d(out_chs)...
The code initializes a CNN model with five convolutional layers (32→64→128→64→32 channels) and three fully connected layers (480→256→128), using max pooling and Adam optimizer for training.
def __init__(self, data_height, data_width, labels_count): super(Model, self).__init__() self.data_height = data_height self.data_width = data_width self.labels_count = labels_count # the parameters for all the cnn layers self.kernel_size = 5 self.stride = 1 ...
def make_x_array(file_name): return np.loadtxt(file_name, delimiter=",", converters={11: convert_nominal}) def make_y_array(file_name): return np.loadtxt(file_name, dtype=int) def z_score_normalization(train_x, test_x, feature_count): mean_v = np.mean(train_x, axis=0) std_v = np.std(train_x, axis=0) ...
The code performs multi-class classification using KNN, Perceptron, and PA algorithms on normalized data. It loads training/test data, applies z-score normalization, adds bias terms, and trains models with specified hyperparameters. Predictions from all three methods are generated for test samples and printed. Key step...
def main(): # data parameters feature_count = 12 label_count = 3 # hyper-parameters knn_k = 7 perceptron_eta = 0.0003 perceptron_epochs = 80 # get the data from the given files train_x, train_y, test_x = sys.argv[1], sys.argv[2], sys.argv[3] train_x = make_x_array(train_x) tr...
def normalize(arr): arr /= PIXEL_RANGE return arr def merge_examples_and_predictions(examples, predictions): return np.array(list(zip(examples, predictions)), dtype=object) def train_and_predict_test_x(training_set, test_x, model, batch_size, split_k): training_set = shuffle(training_set) train_set,...
The main task of the code is to configure hyperparameters for multiple models, load and normalize training/test data, select Model B as the optimal model, train it using cross-validation (split_k=5), and generate predictions on test data, saving results to a file.
def main(): # all models hyper-parameters # model A model_a_batch_size = 4 model_a_lr = 0.012 # model B model_b_batch_size = 32 model_b_lr = 0.001 model_b_beta0 = 0.9 model_b_beta1 = 0.99 # model C model_c_batch_size = 8 model_c_lr = 0.045 model_c_p0 = 0.2 model_c...
def shuffle(arr): np.random.shuffle(arr) def np_arr(arr): return np.array(arr, dtype=object) def init_w1_and_w2(feature_count, label_count, hid_layer_dim): w1 = rand(hid_layer_dim, feature_count) / feature_count w2 = rand(label_count, hid_layer_dim) / hid_layer_dim return w1, w2 def forward_propagat...
The code trains a neural network using backpropagation on a shuffled training set, splitting it into training and validation subsets. It iterates over epochs, updating weights with gradient descent, and tracks the best weights based on validation accuracy. The function returns the optimal weights after training.
def training_process(training_set, feature_count, label_count, hid_layer_dim, epochs, eta): shuffle(training_set) # train size will be 50000, validation size will be 5000 sub_arrays = np_arr(np.array_split(training_set, 11)) # get a validation set to check accuracy on validation = sub_arrays[0].copy...
def add_bias_column(arr): return np.append(arr, np.ones([len(arr), 1]), axis=1) def combine_arrays(arr1, arr2): return np_arr(list(zip(arr1, arr2))) def training_process(training_set, feature_count, label_count, hid_layer_dim, epochs, eta): shuffle(training_set) # train size will be 50000, validation si...
The code trains a two-layer neural network on normalized MNIST-like data (785 features, 10 labels) using specified hyperparameters (100 hidden units, 50 epochs, 0.01 learning rate). It loads training/test data, adds bias terms, normalizes pixel values, trains the model, predicts test labels, and writes results to a fil...
def main(): # exercise parameters feature_count = 785 label_count = 10 pixel_range = 255 # hyper-parameters hid_layer_dim = 100 epochs = 50 eta = 0.01 # files arguments train_x, train_y, test_x = sys.argv[1], sys.argv[2], sys.argv[3] # load all the files data train_x = np...
def _gen_batch(self) -> Generator[Tuple[np.ndarray, np.ndarray], None, None]: size = self._target.size while True: X, y = shuffle(self._features, self._target) step_size = int(size * self._batch_size) or 1 for i in range(0, size, step_size): yield X[i:...
The code trains a logistic regression model using gradient descent by splitting input data into training and validation sets, initializing coefficients, iterating through batches to minimize validation loss, and returning the best coefficients found during training.
def fit(self, features: np.ndarray, target: np.ndarray) -> np.ndarray: self._num_of_losses = 0 features, target = shuffle(features, target) size: int = int(self._validation_size * target.size) self._validation_features: np.ndarray = features[:size] self._validation_target: np.nd...
def get_backfilled_ts(ts_before: str): return [dt_ for dt_ in generate_datetimes(parser.parse(ts_before), datetime.utcnow(), timedelta(minutes=5))] def fetch_opensea_events( collection_slug: str, ts_before: datetime, ts_after: datetime, event_type: str = "successful", limit: str = 50, ) -> Dict:...
The function `parse_opensea_event` retrieves and processes OpenSea NFT sales data for a specified collection. It fetches events either in "backfill" mode (historical data across timestamp intervals) or recent events (last 10 minutes). After cleaning the data, it optionally tweets sales details using Twitter API, loggin...
def parse_opensea_event( collection: str, ts_before: str = str(datetime.utcnow()), mode: str = "backfill", is_tweet: bool = False ) -> List[VandulSaleDetail]: timestamp_list = None sales_list = [] if mode == "backfill": logger.log(f"[orange] Starting backfill from {ts_before}") timestamp...
def get_number_of_passenger_today(self): month = self.get_month() return self.passenger_flow_monthly_sum[month - 1] def generate_passenger_path(self): path = self.get_random_path() while path[0] == path[1]: path = self.get_random_path() return path def get_skewed_data...
This code generates synthetic passenger booking data over a specified number of days, creating flight paths, categorizing passengers as personal/business, applying booking skew distributions, and saving structured data (with prebooking days, flight dates, etc.) as CSV files monthly. It logs progress and manages data cl...
def build_passenger_booking_pattern(self, number_of_days): timestamp = datetime.now().timestamp() logger.info("Started building passenger booking pattern...") day_data = [] normalised_max_value = 1 total_passenger_count = 0 logger.info("Started creating passenger source a...
def build_service(json_file="google_service_account.json"): credentials = get_credentials_gsheets(json_file=json_file) http = credentials.authorize(httplib2.Http()) discoveryUrl = "https://sheets.googleapis.com/$discovery/rest?" "version=v4" service = discovery.build( "sheets", "v4", http=http, ...
This function writes a pandas DataFrame to a Google Sheet, handling column headers, data formatting, and optional sheet cleaning. It uses the Google Sheets API to build a service, determines the target cell range, converts data to strings, and writes values while allowing adjustments for starting rows and sheet cleanup...
def write_spreadsheet( df, sheet_id, tab_name, columns=True, tab_id=0, clean_sheet_bool=True, clean_sheet_start_row=1, write_row_start=-1, json_file="google_service_account.json", ): service = build_service(json_file=json_file) tab_range = find_a_z(len(df.columns.values.toli...
def classify_pixels(self): self.bgd_indexes = np.where(np.logical_or( self.mask == DRAW_BG['val'], self.mask == DRAW_PR_BG['val'])) self.fgd_indexes = np.where(np.logical_or( self.mask == DRAW_FG['val'], self.mask == DRAW_PR_FG['val'])) assert self.bgd_indexes[0].size > ...
This code initializes an image segmentation model using graph cuts and Gaussian Mixture Models (GMM). It sets up image and mask data, configures foreground/background regions, initializes GMM parameters, creates data structures for energy calculations, and prepares for segmentation by setting up graph cut terminals and...
def __init__(self, img, mask, rect=None, gmm_components=5): self.img = np.asarray(img, dtype=np.float64) self.rows, self.cols, _ = img.shape self.edge_to_capacity = dict() self.mask = mask if rect is not None: self.mask[rect[1]:rect[1] + rect[3], ...
def load_vcf(vcf): # load vcf print(datetime.datetime.now(), "Loading " + vcf + "...") callset = allel.read_vcf(vcf) # parse out different components gt = callset['calldata/GT'] chrom = callset['variants/CHROM'] pos = callset['variants/POS'] samples = callset['samples'] # combine a...
The code processes a VCF file to analyze genetic diversity statistics around a focal genomic site. It loads genotype data, isolates SNPs within a specified window near the focus, calculates metrics like nucleotide diversity (π), Watterson’s θ, Tajima’s D, Garud’s statistics, and others, then saves results to a TSV file...
def main(vcf, window_length, focus, output_prefix): print(datetime.datetime.now(), "input options: vcf =", vcf, "window length =", window_length, "focus =", focus, "output prefix =", output_prefix) # load VCF and extract components print(datetime.datetime.now(),"Loading VCF...") gt, chrom, pos, samples...
def resolve_night(self): if self.interactions: self.print_dead() for agent in self.agents: if agent.is_alive() and agent.role == Role.LOOKOUT and agent.visiting != None: self.resolve_lookout(agent) if agent.is_alive() and agent.role == Role.MAYOR and ...
This method advances the game's night phase by allowing agents to perform actions, resolving those actions' outcomes, resetting temporary states, updating knowledge if inference is enabled, and initiating a vote among surviving villagers and mafia members based on the specified strategy.
def step(self): self.schedule.step() # Allow agents to do their night actions self.resolve_night() # Resolve the actions of the agents self.end_night() # Reset visited_by, statuses etc if self.infer: self.infer_knowledge() if len(self.get_alive_villagers(...
def _forward_pass(self, x): """Perform a forward pass through the network.""" activations = [x.reshape(-1, 1)] # Input layer activation # Forward propagate through the layers for l in range(1, self.L): z = np.dot(self.w[l], activations[l - 1]) + self.theta[l] # A...
The code trains a neural network by splitting data into training and validation sets, performing forward and backward passes for each sample in each epoch, and recording training and validation errors after each epoch to monitor model performance.
def fit(self, X, y): """Train the network on the dataset for the specified number of epochs.""" # Split data into training and validation sets split_at = int(len(X) * (1 - self.validation_split)) X_train, X_val = X[:split_at], X[split_at:] y_train, y_val = y[:split_at], y[split_a...
def log_initialize(logfile,logappend): global optLogfile # Determine log file name logfileDefault = "{:s}/{:s}.{:s}.log".format(logfolderDefault,progName,lognameTS()) optLogfile = logfile if logfile else logfileDefault optLogfile = optLogfile.replace('"','') # Create log f...
This function parses command-line arguments for a script, configuring global variables like Google file ID, output path, credentials, and logging settings. It validates required parameters, sets defaults, initializes logging if enabled, and ensures necessary files exist. The parsed arguments control output handling, de...
def command_args_get(): global optOutput global optLogfile global optLog global optLogAppend global optStdOut global optGoogleId global optCredentials global optPickle # global optProgressInterval global optDebug global optVerbose # Create a parser object, define argumen...
def make_connection(dotenv_path_string): """ Creates link to the data lake """ dotenv_path = Path(dotenv_path_string) load_dotenv(dotenv_path=dotenv_path) if dotenv_path_string.endswith('development'): details = pull_secrets() conn = pg8000.connect( database=details['...
The code connects to AWS RDS, retrieves table names, checks each table for updates, and compiles necessary updates into a pandas DataFrame. If updates exist, it exports them as parquet files to an S3 bucket; if none, it exits. The process involves database connection, metadata retrieval, data comparison, and cloud stor...
def index(dotenv_path_string): """ Integrates all subfunctions to connect to AWS RDS, find a list of table names, iterate through them to evaluate whether there any updates to make. if so, return a list of all neccessary updates in pandas parquet format, if not exit the programme. """ ...
def get_arrival_times(): arrival_rate = {} for key, value in arrival_times.items(): if (value == None): arrival_rate[key] = None else: arrival_rate[key] = [] for day in value: arr = [] for time in day: if tim...
The main task of the code is to simulate a clinic's operations by dynamically scheduling patient arrivals based on time intervals, managing staff shift changes (registration, ED, imaging, lab), and processing patients through the system. It handles timeouts, prioritization, and reopens the clinic after a 12-hour closur...
def setup(env): """Keep creating workers approx. every ``IAT`` minutes +-1 IAT_range .""" global patients_arrived patient_timeouts = { "em_ser": None, "em_mod": None, "img_in": None, "img_out": None, "lab_in": None, "lab_out": None, } iat = get_arriva...
def findServiceById(service_id): res = None for u in urls: u2 = preapareCacheUrl(u, 'services') with open(u2) as f: services_json = json.load(f) for s in services_json: if s['id'] == service_id: if not res: s['from'] = u ...
The main task of the code is to install a service by validating its name, downloading its files, setting up checker and service directories, and updating configurations. It checks the service name format, verifies service existence, downloads files if missing, copies checker and service components to designated directo...
def cmd_install(): name_ = name.lower() pattern = re.compile("^([a-z0-9_]+)$") if not pattern.match(name_): print("Service name invalid") exit(0) if not findServiceById(name_): print("Service not found") exit(0) dirto = './.ctf01d-store/downloads/service_' + name_ ...
def load_list(path): if isinstance(path, str) or isinstance(path, Path): with open(path, mode="rt", newline="") as f: return [ line.strip() for line in f if len(line.strip()) > 0 ] assert hasattr(path, "__iter__") return path def GetDataRoot(self): return self._data_root def Ge...
The code trains a medical image segmentation model using a deep learning framework (likely MONAI). It loads training/validation data, applies preprocessing/augmentation transforms, initializes optimizer/scheduler, performs multi-epoch training with cross-entropy and dice loss, and saves model checkpoints. The model pro...
def Train(self, train_list, snapshot_dir, val_perc=0.0, val_list=None): train_list = load_list(train_list) window = self._model.extra_outputs num_epochs = 1000 if val_list is not None: val_list = load_list(val_list) print(f"Info: Loaded {len(val_list)} validation...
def get_db(id, type): """Use database url to pull json dictionary. Args: ID: TMDb movie ID Type: Select database requested (moive or trailer) Behavior: Call get_db_url to generate database url. Pull data through json request. Returns: Requested data. """ ...
The function `get_tmdb` retrieves movie data using a TMDb ID, processes it into structured variables (title, year, summary, poster, trailer), and appends these to the input list `movie_info` for class object creation. It uses helper functions to fetch poster and trailer URLs, formats data, and returns the updated list.
def get_tmdb(movie_info): """Compile list used to generate moive class object. Args: movie_info: list containing TMDb movie ID Behavior: Use movie ID found in movie_info to call get_db and get movie data. Use moive data to start building & formating class variables. Call ge...
def naivniAlgoritam(src,dst): g = preslikajBazne(src) h = preslikajBazne(dst) inverz_g = np.linalg.inv(g) return np.dot(h,inverz_g) def dlt(src,dst): A = [] for i in range(len(src)): tacka = src[i] slika_tacke = dst[i] prvi_red = np.array([0, 0, 0, -slika_tacke[2]...
The code compares transformation matrices computed via a naive algorithm, DLT (Direct Linear Transformation), and normalized DLT. It calculates matrices for point mappings, normalizes coordinates, and verifies proportionality between results. The process includes rounding, normalization matrices, and converting normali...
def primer1(): p = naivniAlgoritam([(-3,-1,1), (3,-1,1), (1,1,1), (-1,1,1)], [(-2,-1,1), (2,-1,1), (2,1,1), (-2,1,1)]) print(f"Matrica preslikavanja dobijena naivnim algoritmom:\n {p}") pdlt = dlt([(-3,-1,1), (3,-1,1), (1,1,1), (-1,1,1), (1,2,3), (-8,-2,1)], [(-2,-1,1), (2,-1,1), (2,1,1), (-2,1,1), preslik...
def naivniAlgoritam(src,dst): g = preslikajBazne(src) h = preslikajBazne(dst) inverz_g = np.linalg.inv(g) return np.dot(h,inverz_g) def dlt(src,dst): A = [] for i in range(len(src)): tacka = src[i] slika_tacke = dst[i] prvi_red = np.array([0, 0, 0, -slika_tacke[2]...
The main task of the code is to compare the results of a naive algorithm, DLT, and a modified DLT in computing transformation matrices using different numbers of correspondences (4 and 6 points). It verifies proportionality between matrices and tests invariance under coordinate transformations by applying transformatio...
def primer2(): a = (1, 1, 1) b = (5, 1, 1) c = (5, 3, 1) d = (1, 5, 1) tacke = [a,b,c,d] slika_a = (-1, -2, 1) slika_b = (3, -2, 1) slika_c = (3, 2, 1) slika_d = (1, 2, 1) slike_tacaka = [slika_a, slika_b, slika_c, slika_d] p = naivniAlgoritam(tacke, slike_tacaka) p...
def naivniAlgoritam(src,dst): g = preslikajBazne(src) h = preslikajBazne(dst) inverz_g = np.linalg.inv(g) return np.dot(h,inverz_g) def dlt(src,dst): A = [] for i in range(len(src)): tacka = src[i] slika_tacke = dst[i] prvi_red = np.array([0, 0, 0, -slika_tacke[2]...
The code compares three methods (naive, DLT, and normalized DLT) for computing transformation matrices using corresponding 2D point pairs. It tests these algorithms with 4 and 5 point pairs, normalizes the resulting matrices, and prints them to evaluate their performance in geometric transformations like homography est...
def primer4(): print("1)") y1 = (2,1,1) y2 = (1,2,1) y3 = (3,4,1) y4 = (-1,-3,1) tacke = [y1,y2,y3,y4] y1p = (0,1,1) y2p = (5,0,1) y3p = (2,-5,1) y4p = (-1,-1,1) slike_tacaka = [y1p,y2p,y3p,y4p] p = naivniAlgoritam(tacke,slike_tacaka) p = (p / p[0][0]) * 1.0 pr...
def setup(self): if self.schema.gradient_checkpointing: self.unet.enable_gradient_checkpointing() if self.schema.train_text_encoder: self.text_encoder.gradient_checkpointing_enable() if self.schema.scale_learning_rate: self.schema.learning_rate = ( ...
The main task of the code is to train a diffusion model (e.g., UNet) with optional text encoder using a diffusion process that predicts noise residuals. It includes gradient accumulation, checkpointing, prior preservation loss, and validation. The code handles noise scheduling, text embedding generation, loss calculati...
def train(self): ( train_dataloader, optimizer, learning_rate_scheduler, num_update_steps_per_epoch, validation_prompt_negative_prompt_embeds, validation_prompt_encoder_hidden_states, ) = self.setup() total_batch_size = ( ...
def getInput(varName): boothIn = input('Please enter your ' + varName + ": ") while int(boothIn)>127 or int(boothIn)<-128: print("Absolute value too big, please try again") boothIn = input('Please enter your ' + varName + ": ") return boothIn def convertDec(dec): if int(dec)<0: ...
The code implements Booth's algorithm for binary multiplication. It converts decimal inputs to binary, applies Booth's method via `boothsTriumph()`, and outputs the decimal result of the multiplication. The main task is to multiply two numbers using Booth's algorithm, which efficiently handles both positive and negativ...
def booths_algorithm(): multiplicand_dec = getInput("Mutiplicand") multiplier_dec = getInput("Multiplier") multiplicand_bin = convertDec(multiplicand_dec) multiplier_bin = convertDec(multiplier_dec) boothsTriumph(multiplicand_bin,multiplier_bin) print("Decimal Result: " + str(int(multiplie...
def delete_hostname(self, hostname, index): # Check exist hostname if self.check_exits_host(hostname): self.element_click(self.button_delete_host(index)) time.sleep(self.time_deplay) self.button_click(self.xpath_button_comfirm_delete) print("Delete hostname: {} complete!".format(hostname...
The function manually updates a domain's DNS entry with a provided IP address, overriding existing configurations regardless of time remaining. It deletes the old hostname, introduces a delay, creates a new hostname with the new IP, and grants a fresh 30-day license. Returns True on success, False if deletion fails.
def update_domain_manual(self, hostname, ip): """ Need provide ip manual Update domain when ipv4 diffirent with server. And provide new lienses (30 days) again. This action will force update hostname and no care of time left noip """ hostname_dns = f"{hostname}.ddns.net" if self.delet...
def delete_hostname(self, hostname, index): # Check exist hostname if self.check_exits_host(hostname): self.element_click(self.button_delete_host(index)) time.sleep(self.time_deplay) self.button_click(self.xpath_button_comfirm_delete) print("Delete hostname: {} complete!".format(hostname...
The main task of the code is to automatically update a domain's hostname with the current public IP address, renewing its 30-day license, by deleting the existing record and creating a new one. It forces an update regardless of the remaining time on the previous license, ensuring the hostname always reflects the latest...
def update_domain_auto(self, hostname): """ Don't need provide ip manual, ip will set by ip public. Noice: If you use this function, the ip auto get from on local Update domain when ipv4 diffirent with server. And provide new lienses (30 days) again. This action will force update hostname an...
def get_masses(atoms): with open("POTCAR", "r") as f: potcar = f.read() elements = np.array(re.findall("VRHFIN\s*=\s*(\w+)\s*:", potcar)) mass_elem = np.array([float(a) for a in re.findall("POMASS\s*=\s*([0-9\.]+)\s*", potcar)]) masses = np.zeros(len(atoms)) for i, a in enumerate(atoms)...
This code calculates the rotational partition function $ Z $, energy $ E $, and entropy $ S $ for a molecule using the rigid rotor approximation. It computes moments of inertia, symmetry number $ \sigma $, and distinguishes between symmetric (3D) and asymmetric (simplified) cases based on the inertia tensor determinant...
def __init__(self, T, cell, atoms, tol=Itol): # Rigid rotor approximation, only applies to smaller molecules if len(atoms) == 1: self.Z = 1 self.S = 0 self.E = 0 self.sigma = 1 self.I = [0,0,0] return masses = g...
def getBoundsGermany(): ger = readGeojsonToShapely('./data/germany_outline.geojson') west, south, east, north = ger.bounds return shg.box(west, south, east, north) def getLkRaster(height, width): bbox = getBoundsGermany() west, south, east, north = bbox.bounds affineTransform = riot.from_bounds(...
This code generates batches of normalized input-output pairs for training a machine learning model using satellite NO2 data and ground truth raster data. It loads and masks NetCDF data over Germany, creates training windows with specified image sizes and time spans, normalizes input (s5Window) and target (gtWindow) val...
def trainingDataGenerator(batchSize, imageSize, timeSpan): bboxGermany = getBoundsGermany() s5dataSet = rio.open('netcdf:./downloads/data_2020_feb.nc:tcno2', 'r') s5data, transf = riom.mask(s5dataSet, [bboxGermany], crop=True) T, R, C = s5data.shape print(f"Study area: {T} * {R} * {C}") _, _, gt...
def randomImage(size, nrNodes): m = np.zeros((size, size)) centers = [(np.random.randint(size), np.random.randint(size)) for i in range(nrNodes)] for center in centers: m += point(size, size, center[0], center[1], np.random.randint(10)) for i in range(nrNodes-1): c1 = centers[i] ...
The main task of the code is to generate a training pair consisting of a base image and a modified image. It creates a random base image with specified node count, applies a Gaussian kernel with randomized spread and covariance, rotates the kernel by a random angle, convolves it with the base image, and returns both th...
def createTrainingPair(size, maxSpread=10, maxNodes=10): nrNodes = np.random.randint(maxNodes) + 1 s1 = np.random.randint(maxSpread) + 1 s2 = np.random.randint(maxSpread) + 1 cv = np.random.rand() angle = np.random.randint(180) base = randomImage(size, nrNodes) k = gaussianKernel(maxSpread*...
def tree(label, branches=[]): for branch in branches: assert is_tree(branch), "branches must be trees" return [label] + list(branches) def label(tree): return tree[0]
The function constructs a binary tree representing the Fibonacci sequence recursively. For n ≥ 2, it builds a tree where each node's value is the sum of its left (fib_tree(n-2)) and right (fib_tree(n-1)) children's values, mirroring the Fibonacci recurrence relation. Base cases return single-node trees with values 0 or...
def fib_tree(n): if n == 0 or n == 1: return tree(n) else: left, right = fib_tree(n-2), fib_tree(n-1) fib_n = label(left) + label(right) return tree(fib_n, [left, right])
def validate_line_mappings(line_mappings): """ raises if the supplied mappings are non-sensical: * checks all standard mappings exist * checks all priorities are unique within a field """ priorities = {} for column_mapping in line_mappings: if column_mapping.get('standard_ma...
The main task of the code is to transform a line of input data according to specified column mappings. It decodes raw values, applies field-specific transformations and validations, aggregates results into structured output, and returns a dictionary of processed attributes along with raw text. The function handles dyna...
def mapped_line(line, line_mappings): """ applies mapping to the given line. """ validate_line_mappings(line_mappings) rawtext = {} data = {} for col, raw_value in enumerate(line): column_mapping = line_mappings[col] if not column_mapping: raise Exception('Wrong...
def tree_ok(claims): """ Given a list of claims corresponding to the leaves of a nonordering proof tree, checks that the data really defines a directed trivalent tree with a unique root vertex. """ T, leaves = build_graph(claims) # A branching is a directed forest where every vertex has in-...
The `check_proof` function rigorously verifies the validity of a nonordering proof tree. It parses the input proof, constructs a manifold and word problem solver, and checks structural consistency (generators/relators), non-trivial edge labels, and individual claim correctness. It returns `True` only if all components ...
def check_proof(proof, bits_prec=100): """ This is the main function for rigorously verifying that a nonordering proof tree is valid. """ if isinstance(proof, str): proof = json.loads(proof) M = snappy.Manifold(proof['name']) solver = word_problem.WordProblemSolver(M, bits_prec=bit...
def readtext(filename): log_dependency(filename) return filename.read_text(encoding='utf-8-sig') def multi_line(text): return ('\n' + text).replace('\\', r'\\').replace('\n', '\\\n').replace("'", r"\'") def load_image(filename): mtype, _ = guess_type(str(filename)) # todo: after Python 3.8 mimetypes ac...
The function `expand_template` processes template placeholders by including content from files based on keywords. It retrieves settings or file content, formats it (e.g., wrapping in quotes, handling multi-line text, or replacing image URLs in CSS), and returns the processed content. Different keywords trigger specific...
def expand_template(match, path=None): quote = "'%s'" kw, filename = match.groups() if not filename: return quote % getattr(settings, kw) fullname = path / filename if kw == 'include_raw': return """// *** included: {filename} *** {content} """.format(filename=filename, content=rea...
def create_grading_dir(d2l_archive): global grading_dir if not os.path.isdir(grading_dir): unpack_file(d2l_archive, grading_dir) return grading_dir def prune_grading_dir(grading_dir): global archive_types all_files = os.listdir(grading_dir) file_paths = list(map(lambda x: "grading_dir/" ...
The code processes student submissions by either interactively grading selected Python scripts or detecting potential cheaters by analyzing all scripts when the -c flag is used. It unpacks student archives, identifies Python files, and uses selection handling for grading or cheating detection, outputting results accord...
def main(): global grading_dir parser = argparse.ArgumentParser() parser.add_argument("file") parser.add_argument('-c', '--cheating', required=False, action='store_true') args = parser.parse_args() create_grading_dir(args.file) prune_grading_dir(grading_dir) students = generate_students...
def formatGradingDirectory(grading_file): ts = str(time.time()) grading_dir = "grading_dir_" + ts + "/" if os.path.isfile(grading_file): file_ext = os.path.splitext(grading_file)[1] #1. Zip file straight from D2L if file_ext == ".zip": unpackFile(grading_file, grading_dir...
This code processes student submissions by grading files in a directory. It parses command-line arguments, checks existing grades, skips already graded students if specified, and interactsively handles each student's files. After grading, it removes processed folders and the main grading directory, ensuring clean-up of...
def main(): parser = argparse.ArgumentParser() parser.add_argument("file") args = parser.parse_args() cwd = os.getcwd() grades_file = cwd + "/grades.txt" grading_dir = formatGradingDirectory(args.file) gradeable_folders = getGradeableFolders(grading_dir) curr_graded, skip_already_gr...
def setup(fair): driver.get(fair['url']) wait_and_find_elements(By.XPATH, '//*[@id="root"]/div/div/div[1]/header/div/div[2]/button')[0].click() driver.find_element_by_xpath("//*[contains(text(), 'Event Info')]").click() fair_title = wait_and_find_elements(By.TAG_NAME, 'h2')[0].text driver.find_eleme...
The code scrapes job fair data using Selenium, extracting company names, job positions, meeting details, and availability from web pages. It handles dynamic content, retries on errors, and stores structured data in a dictionary. The function iterates through fairs, companies, and positions, managing browser navigation,...
def scrape_fairs(fair_list): global driver driver = webdriver.Chrome() for fair_index, fair in enumerate(fair_list): fair_title = setup(fair) # Iterate through the companies in the fair companies = wait_and_find_elements(By.CLASS_NAME, 'employer-list-item-container') current_...
def stap1(): print('Welkom bij Papi Gelato je mag alle smaken kiezen zolang het maar vanille ijs is.') try: global bolletjes bolletjes = (int)(input('Hoeveel bolletjes wilt u?: ')) except ValueError: print('Voer alstublieft een nummber in') stap1() if bolletjes > 8: ...
The code defines a function `kopen()` that sequentially executes steps for an ice cream ordering process. It first calls `stap1()` (likely initializing order details), then checks if the number of scoops (`bolletjes`) is less than 4 to trigger `stap2()` (possibly handling small orders). If `bolletjes` exceeds 3, it set...
def kopen(): stap1() if bolletjes < 4: stap2() elif bolletjes > 3: global ijs ijs = 'bakje' stap3()
def stap1(): print('Welkom bij Papi Gelato.') global bolletjes bolletjes = (int)(input('Hoeveel bolletjes wilt u?: ')) if bolletjes > 8: print('Sorry, zulke grote bakken hebben we niet.') stap1() return def stap2(): print('Wilt u deze ' + (str)(bolletjes) + ' in A) een hoorntje o...
The code defines a function `kopen()` that handles an ice cream ordering process. It validates user input (ensuring a number is entered), processes scoop quantity (`bolletjes`), selects a container (`bakje` for >3 scoops), applies toppings, and generates a receipt. It sequentially calls functions for order steps, error...
def kopen(): try: stap1() except ValueError: print('please enter a number') stap1() if bolletjes < 4: stap2() elif bolletjes > 3: global ijs ijs = 'bakje' topping() stap4() stap3() bon() return