dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def create_spreadsheet(self): print("Method ran") #book = openpyxl.load_workbook(self.file_name) # Get the first sheet and give it a name #self.sheet_1 = self.book.active #self.sheet_1.title = "Sheet1" self.sheet_1["A2"].value = "Date" self.sheet_1["B2"].value = ...
The main task of the code is to update multiple sheets in a spreadsheet by creating a new spreadsheet, updating specific sheets (sheet_1 and sheet_2), clearing empty fields, and saving the modified workbook with the specified file name.
def update_sheets(self): self.create_spreadsheet() self.updatesheet_1() self.updateSheet_2() self.emptyFeilds() self.book.save(self.file_name)
def _create_buttons(self): start_game_button = Button(None,None,"START",RED,BLACK,centered=True,font=self.menu_font) start_game_button = Button(None,None,"START",RED,BLACK,centered=True,font=self.menu_font) difficulty_buttons = pygame.sprite.Group() sample_text = self.menu_...
The code initializes a game UI by rendering the title "MASTERMIND", positioning it at the top center, creating buttons, loading resources, and preparing the display for gameplay. It sets up visual elements and initializes necessary components for the game's interface and functionality.
def __init__(self): self.title_text = self.menu_font.render("MASTERMIND",True,BLACK) top_gap = 50 self.title_text_rect = self.title_text.get_rect(center=(SCREEN_WIDTH//2,top_gap + self.title_text.get_height()//2)) self._create_buttons() self._load_a...
def resetColours(grid, node): positions = generatePotentialMoves(node, grid)[0] positions.append(node) for colouredNodes in positions: nodeX, nodeY = colouredNodes grid[nodeX][nodeY].colour = WHITE if abs(nodeX - nodeY) % 2 == 0 else BLACK def generatePotentialMoves(nodePosition, grid): ...
The function moves a piece on a grid from an old position to a new position, updates piece attributes (e.g., promoting to 'KING' if reaching specific columns), removes jumped-over pieces if applicable, and returns the winning team based on move validity and potential moves.
def move(grid, piecePosition, newPosition): resetColours(grid, piecePosition) newColumn, newRow = newPosition oldColumn, oldRow = piecePosition piece = grid[oldColumn][oldRow].piece grid[newColumn][newRow].piece = piece grid[oldColumn][oldRow].piece = None if newColumn == 7 and grid[newCol...
def make_grid(rows, width): grid = [] gap = width // rows count = 0 for i in range(rows): grid.append([]) for j in range(rows): node = Node(j, i, gap) if abs(i - j) % 2 == 0: node.colour = WHITE if (abs(i + j) % 2 == 0) and (i < 3): ...
The code implements a checkers game loop using Pygame. It handles mouse clicks to select and move pieces, checks for valid moves, tracks the current player's turn, detects game end conditions (no remaining pieces), and displays the appropriate game-over screen. The loop updates the game state, renders the board, and ex...
def checkers(WIDTH, ROWS, curmove): grid = make_grid(ROWS, WIDTH) highlightedPiece = None currMove = curmove while True: for event in pygame.event.get(): if event.type == pygame.QUIT: print('EXIT SUCCESSFUL') pygame.quit() sys.exit() ...
def mastery(self, usr_info): if usr_info == '27': drops = (range(1, 4), range(1), range(1), range(1)) elif usr_info == '28 to 35': drops = (range(1, 4), range(1, 3), range(1), range(1)) elif usr_info == '36 to 44': drops = (range(1, 4), range(1, 4), range(1), ...
This code processes POST requests by determining the activity type (Domain of Mastery, Domain of Forgery, or Boss), generating corresponding "drops" using specific methods, and returning a JSON response with processed results or None if no drops are generated.
def post(self, request): data = json.loads(request.POST.get('data', None)) activity = request.POST.get('activity', None) if activity == 'Domain of Mastery': drops = self.mastery(request.POST.get('usr_info', None)) elif activity == 'Domain of Forgery': drops = self...
def get_storage_client(conn: Union[str, dict]): """ Returns an S3 client object """ conn = safe_conn(conn) uri = conn['BUCKET_URI'] _, _, scheme = parse_cloud_storage_uri(uri) if scheme == 's3': aws_access_key_id, aws_secret_access_key = get_credentials(conn) return boto3.cl...
The main task of the code is to write data to cloud storage (AWS, Azure, or Google) using a connection object and a key. It identifies the storage type, constructs the appropriate URI, and uses specific methods (e.g., `put_object` for AWS, `upload_blob` for Azure) to store the data. The function includes error handling...
def write_file(conn: Union[str, dict], key: str, data) -> None: """ Writes a file to cloud storage """ storage_client = get_storage_client(conn) try: storage_type = get_storage_client_type(conn) full_uri = safe_uri(conn, key) # handle the aws case if storage_type == ...
def safe_conn(conn: Union[str, dict]) -> dict: """ Returns a safe connection object """ if isinstance(conn, str): return json.loads(conn) elif isinstance(conn, dict): return conn else: raise Exception('Invalid connection object') def get_storage_client(conn: Union[str, di...
The main task of the code is to read a file from cloud storage (AWS S3 or Azure Blob Storage) using a connection and key, handling different storage types, decoding content if necessary, and returning the data or None on error. It supports JSON/CSV/TXT file decoding and handles URI parsing for AWS and Azure, with a pla...
def read_file(conn: Union[str, dict], key: str) -> Union[str, bytes]: """ Reads a file from an S3 bucket """ conn = safe_conn(conn) storage_client = get_storage_client(conn) try: full_uri = safe_uri(conn, key) storage_type = get_storage_client_type(conn) # handle the aws ...
def safe_conn(conn: Union[str, dict]) -> dict: """ Returns a safe connection object """ if isinstance(conn, str): return json.loads(conn) elif isinstance(conn, dict): return conn else: raise Exception('Invalid connection object') def get_storage_client(conn: Union[str, di...
This function deletes a file from cloud storage (AWS/Azure) using a provided connection. It identifies the storage type, constructs the correct URI, and invokes the appropriate client method to delete the file. AWS uses `delete_object`, Azure uses `delete_blob`, while Google is unimplemented. Exceptions are caught sile...
def delete_file(conn: Union[str, dict], key: str) -> None: """ Deletes a file """ conn = safe_conn(conn) storage_client = get_storage_client(conn) try: full_uri = safe_uri(conn, key) storage_type = get_storage_client_type(conn) # handle the aws case if storage_ty...
def safe_conn(conn: Union[str, dict]) -> dict: """ Returns a safe connection object """ if isinstance(conn, str): return json.loads(conn) elif isinstance(conn, dict): return conn else: raise Exception('Invalid connection object') def get_storage_client(conn: Union[str, di...
The code deletes a specified folder and its contents from cloud storage (AWS, Azure, or Google) using a connection object. It handles AWS by listing and deleting objects with a prefix, Azure by deleting blobs recursively (twice to handle empty folders), and raises an error for unsupported storage types.
def delete_folder(conn: Union[str, dict], folder_to_delete: str) -> None: """ Deletes a folder """ try: conn = safe_conn(conn) storage_client = get_storage_client(conn) if not folder_to_delete.endswith('/'): folder_to_delete = folder_to_delete + '/' full_uri ...
def get_storage_client(conn: Union[str, dict]): """ Returns an S3 client object """ conn = safe_conn(conn) uri = conn['BUCKET_URI'] _, _, scheme = parse_cloud_storage_uri(uri) if scheme == 's3': aws_access_key_id, aws_secret_access_key = get_credentials(conn) return boto3.cl...
The main task of the code is to check if a file exists in cloud storage (AWS S3 or Azure) using the provided connection and key. It constructs a full URI, identifies the storage type, and uses corresponding methods (AWS: `head_object`, Azure: `blob_client.exists()`) to verify existence, returning `True` if the file exi...
def check_if_file_exists(conn: Union[str, dict], key: str) -> bool: """ Checks if a file exists """ storage_client = get_storage_client(conn) full_uri = safe_uri(conn, key) storage_type = get_storage_client_type(conn) # handle the aws case if storage_type == 'aws': try: ...
def safe_conn(conn: Union[str, dict]) -> dict: """ Returns a safe connection object """ if isinstance(conn, str): return json.loads(conn) elif isinstance(conn, dict): return conn else: raise Exception('Invalid connection object') def get_storage_client(conn: Union[str, di...
The function copies a file from cloud storage (AWS/Azure) to a local path. It validates the connection, creates necessary directories, identifies the storage type, and uses corresponding SDKs to download the file. AWS uses `download_file`, Azure uses blob clients for download, while Google is unimplemented.
def copy_file_to_local(conn: Union[str, dict], key: str, local_file_path: str) -> None: """ Copies a file from the cloud storage to the local file system """ conn = safe_conn(conn) storage_client = get_storage_client(conn) full_uri = safe_uri(conn, key) # ensure that the path to local_file_...
def safe_conn(conn: Union[str, dict]) -> dict: """ Returns a safe connection object """ if isinstance(conn, str): return json.loads(conn) elif isinstance(conn, dict): return conn else: raise Exception('Invalid connection object') def get_storage_client(conn: Union[str, di...
This function copies a local file to cloud storage using a provided connection, handling AWS, Azure, and Google (unimplemented) storage services. It determines the storage type, parses the target URI, and uploads the file via the appropriate client (S3 for AWS, Blob for Azure). The function raises an error if the stora...
def copy_file_from_local(conn: Union[str, dict], local_file_path: str, key: str) -> None: """ Copies a file from the local file system to the cloud storage """ conn = safe_conn(conn) storage_client = get_storage_client(conn) full_uri = safe_uri(conn, key) storage_type = get_storage_client_ty...
def safe_conn(conn: Union[str, dict]) -> dict: """ Returns a safe connection object """ if isinstance(conn, str): return json.loads(conn) elif isinstance(conn, dict): return conn else: raise Exception('Invalid connection object') def get_storage_client(conn: Union[str, di...
This function copies a folder from cloud storage (AWS/Azure) to a local directory. It validates the connection, ensures the local path exists, and downloads all files within the specified remote folder. AWS uses list_objects_v2 and download_file, while Azure uses walk_blobs and download_blob. The Google Cloud case is u...
def copy_folder_to_local(conn: Union[str, dict], folder_key: str, local_folder_path: str) -> None: """ Copies a folder from the cloud storage to the local file system """ conn = safe_conn(conn) storage_client = get_storage_client(conn) full_uri = safe_uri(conn, folder_key) # ensure that loc...
def safe_conn(conn: Union[str, dict]) -> dict: """ Returns a safe connection object """ if isinstance(conn, str): return json.loads(conn) elif isinstance(conn, dict): return conn else: raise Exception('Invalid connection object') def get_storage_client(conn: Union[str, di...
This function copies a local folder to cloud storage (AWS/Azure) by recursively uploading each file. It ensures proper path formatting, identifies the storage type, and uses provider-specific clients to upload files to the specified remote directory. Google Cloud is not yet supported.
def copy_folder_from_local(conn: Union[str, dict], local_folder_path: str, folder_key: str) -> None: """ Copies a folder from the local file system to the cloud storage """ conn = safe_conn(conn) storage_client = get_storage_client(conn) full_uri = safe_uri(conn, folder_key) # ensure that lo...
def safe_conn(conn: Union[str, dict]) -> dict: """ Returns a safe connection object """ if isinstance(conn, str): return json.loads(conn) elif isinstance(conn, dict): return conn else: raise Exception('Invalid connection object') def get_storage_client(conn: Union[str, di...
The main task of the code is to copy all files from a specified cloud storage folder (AWS/Azure) to a local directory. It ensures the local path exists, handles cloud-specific operations (e.g., listing objects/blobs), and downloads each file individually while preserving their relative structure. The function currently...
def copy_folder_to_local_v2(conn: Union[str, dict], folder_key: str, local_folder_path: str) -> None: """ Copies a folder from the cloud storage to the local file system """ conn = safe_conn(conn) storage_client = get_storage_client(conn) full_uri = safe_uri(conn, folder_key) # ensure that ...
def safe_conn(conn: Union[str, dict]) -> dict: """ Returns a safe connection object """ if isinstance(conn, str): return json.loads(conn) elif isinstance(conn, dict): return conn else: raise Exception('Invalid connection object') def get_storage_client(conn: Union[str, di...
This function recursively copies a local folder to cloud storage (AWS/Azure) using a provided connection. It ensures proper path formatting, walks through local files, and uploads them to the specified cloud bucket/container with the given folder key. AWS uses S3 upload logic, Azure uses blob storage with recursive glo...
def copy_folder_from_local_v2(conn: Union[str, dict], local_folder_path: str, folder_key: str) -> None: """ Copies a folder from the local file system to the cloud storage """ conn = safe_conn(conn) storage_client = get_storage_client(conn) full_uri = safe_uri(conn, folder_key) # ensure that...
def safe_conn(conn: Union[str, dict]) -> dict: """ Returns a safe connection object """ if isinstance(conn, str): return json.loads(conn) elif isinstance(conn, dict): return conn else: raise Exception('Invalid connection object') def get_storage_client(conn: Union[str, di...
The function lists files in a cloud storage bucket (AWS/Azure) matching a specified prefix, optionally returning metadata like size and timestamps. It handles different storage types, cleans file paths by removing the bucket prefix, and excludes exact prefix matches from results.
def list_files(conn: Union[str, dict], prefix: str, return_details: bool = False): """ Returns a list of files in bucket matching the prefix """ conn = safe_conn(conn) storage_client = get_storage_client(conn) # get the storage type (one of azure, aws, google) storage_type = get_storage_clie...
def safe_conn(conn: Union[str, dict]) -> dict: """ Returns a safe connection object """ if isinstance(conn, str): return json.loads(conn) elif isinstance(conn, dict): return conn else: raise Exception('Invalid connection object') def get_storage_client(conn: Union[str, di...
The function creates an Azure Blob Storage container with the specified name, generates a SAS token for access, and returns the container's URI along with the token. It validates the storage type is Azure, raises an error if the container already exists, and handles connection parameters to ensure proper resource creat...
def create_container(conn: Union[str, dict], container_name: str) -> str: """ Creates a new container with container_name in the storage account and returns SAS token. Raises Exception if container with container_name already exists """ conn = safe_conn(conn) storage_client = get_storage_client(...
def safe_conn(conn: Union[str, dict]) -> dict: """ Returns a safe connection object """ if isinstance(conn, str): return json.loads(conn) elif isinstance(conn, dict): return conn else: raise Exception('Invalid connection object') def delete_file(conn: Union[str, dict], ke...
This function renames a file in cloud storage by copying it from the old key to the new key, then deleting the original. It supports AWS S3 and Azure Blob Storage, handling URI parsing, client initialization, and asynchronous copy operations. The process includes deleting the target file first, performing the copy, and...
def rename_file(conn: Union[str, dict], old_file_key: str, new_file_key: str) -> None: """ Renames a file """ try: conn = safe_conn(conn) delete_file(conn, new_file_key) storage_client = get_storage_client(conn) full_old_uri = safe_uri(conn, old_file_key) full_ne...
def safe_conn(conn: Union[str, dict]) -> dict: """ Returns a safe connection object """ if isinstance(conn, str): return json.loads(conn) elif isinstance(conn, dict): return conn else: raise Exception('Invalid connection object') def delete_folder(conn: Union[str, dict], ...
This function renames a cloud storage folder by moving all its contents to a new folder path, then deleting the original. It trims trailing slashes from folder keys, deletes the target folder if it exists, lists files in the old folder, renames each file to the new path, and finally deletes the empty original folder.
def rename_folder(conn: Union[str, dict], old_folder_key: str, new_folder_key: str) -> None: """ Renames a folder in cloud storage """ conn = safe_conn(conn) if old_folder_key.endswith('/'): old_folder_key = old_folder_key[:1] if new_folder_key.endswith('/'): new_folder_key = new...
def verify_future_date(customer_info): customer_dd = customer_info.get(KEY_DELIVERY_DATE) verified = True if not date_verify(customer_dd): return not verified, NOTHING delivery_doy, delivery_year = date_to_doy(customer_dd) current_doy = months.get(str(TODAY_DATE.month)) + TODAY_DATE.day ...
The function allows users to edit specific fields in a customer dictionary (e.g., name, package details, delivery date) via a menu. It validates input, updates the dictionary with new values, and ensures only future delivery dates are accepted. If invalid, it prompts retries. Selection 8 ("DONE") exits and returns the ...
def edit_menu(customer_dictionary): """ Print the menu for the user and return the choice :return: <int> """ if not verify_future_date(customer_dictionary)[0]: print(f"Sorry, only shipments with future delivery dates can be edited.") return customer_dictionary while True: ...
def _debug(self, *args, **kwargs): print((self._indent + kwargs.get('incr', 0)) * ' ' + ' '.join(['{}'] * len(args)).format(*args)) def _tn(self): """Return a temporary variable name.""" self._ti += 1 return '__temp__' + str(self._ti) def ast_name(id, ctx=Load()): n...
This function processes a comparison operation in an AST node. It handles multiple comparison operators by iteratively evaluating each pair of operands, storing intermediate results, and combining them using a logical AND operation. If there's only one comparison, it falls back to the default visitor method. The result...
def visit_Compare(self, node): self._debug('Compare', node.ops, incr=1) if len(node.ops) > 1: values = [] left = self[node.left] for op, right in zip(node.ops, node.comparators): right = self[right] tn = self._tn() valu...
def processTitle(self, data): #print("TITLE - ", data) data = data.lower() processedTitle = self.basicProcessing(data) return processedTitle def removeUnnessaryDetails(self, data): data = data.lower() data = re.sub(self.removeLinksPattern, ' ', data)#, flags = re.DOTALL) data = re.sub(r'{\|(.*?)\|}', ' ',...
The code processes input data based on flags. If `titleFlag` is True, it handles titles via `processTitle`. If `textFlag` is True, it cleans data, extracts categories, references, info boxes, external links, and body content, then returns multiple structured dictionaries containing processed information.
def processData(self, data, titleFlag, textFlag): if(titleFlag==True): return self.processTitle(data) elif(textFlag == True): data = self.removeUnnessaryDetails(data) self.processCategoryData(data) self.processReferences(data) self.processInfoBoxData(data) self.processExternalLinksData(data) ...
def getNumberOfEtf(amount): num_portfolios = { (1, 5000):5, (5001, 20000):10, (20000, math.inf): 15 } no_etfs = 0 for k in num_portfolios: if amount>=k[0] and amount<=k[1]: no_etfs = num_portfolios[k] return no_etfs def getPortfolios(number, etfs): if len(etfs) <= number: return [e...
This function determines an optimal ETF portfolio by converting GBP to USD, filtering feasible ETFs, generating portfolios, calculating Sharpe ratios and VaR, and selecting the portfolio with the highest Sharpe ratio while adhering to risk constraints. If no valid portfolios exist, it returns the lowest VaR option.
def getOptPortfolio(amount, years, risk_level): cr = CurrencyRates() amount = cr.convert('GBP', 'USD', amount) no_etfs = getNumberOfEtf(amount) data = df.loc[df["adj_close"]<=amount] etfs = list(data['symbol']) portfolios = getPortfolios(no_etfs, etfs) sharpRatioAndVaRs = [] for portfolio in portfolios:...
def getKilled(self, isWhite, mType, legalMove): if mType != "passant": killed = self.board.state[legalMove[0]][legalMove[1]] else: if isWhite: killed = self.board.state[legalMove[0] + 1][legalMove[1]] else: killed = self.board.state[leg...
The function `bestMove` determines the optimal move for a player (White or Black) in a board game using a minimax algorithm with alpha-beta pruning. It evaluates all legal moves, recursively assesses their outcomes, and selects the move with the highest (for White) or lowest (for Black) score, considering check conditi...
def bestMove(self, isWhite, branchBest, nRep=0): incumbent = [0, 0, 0, 0] if isWhite: color = "W" KC = self.board.white_moves else: color = "B" KC = self.board.black_moves if isWhite: incumbentScore = -1000 else: ...
def print_tests_list(tests, f): """Print the list of available tests, with their descriptions.""" log("\n" + '-' * 60) for t in tests: desc = get_test_description(t)[1] log(t.ljust(20) + "\t" + desc) log('-' * 60) def print_banner(string, f=None): """Print a banner with the result of...
The main task of the code is to run a test suite for the "vim-visual-multi" project, allowing users to execute specific tests, choose between Vim/Neovim, list available tests, and log results. It processes command-line arguments, configures test execution, runs tests, records failures, and outputs a summary. If any tes...
def main(): """Main function.""" # arg parsing parser = argparse.ArgumentParser(description='Run test suite. See README.') parser.add_argument('test', nargs='?', help='run <test> only instead of running all tests') parser.add_argument('-n', '--nvim', action='store_true', help='run in neovim instead ...
def welcome_messages(game, gametype, high_score): num_targs = game["targs"] num_dists = game["dists"] total = num_targs + num_dists if gametype == 'guide': guide_screen("start", [], [], num_targs, total) wait_key() # == Fixation cross screen == guide_screen("focus", [], ...
The code runs a game trial where participants select targets under time constraints, records their performance (hit rates, d-primes), updates game difficulty, and handles feedback, breaks, and data logging for experimental or practice sessions. It manages user input, animations, timing, and LSL data transmission for ne...
def trials(game, recorder, gametype, time_or_trials, high_score, audio_path, participant_number, user_number, name, outlet, tag_dict): #outlet.resync() # == Messages to user based on gametype == welcome_messages(game, gametype, high_score) # == Generates the game == dt = 0 hit_rates = [] ...
def tag_dicts(): # still need miss and fixation tags tags = ['TMUP', 'STOP', 'ESCP', 'SPCE', 'CLCK', 'UCLK', 'MVE1', 'CRCT', 'STRT', 'FLSH', 'MVE0', 'OPN0', 'OPN1', 'OPN2', 'OPN3', 'CLS0', 'CLS1', 'CLS2', 'CLS3'] incorrect_codes = [] tag_dict = {} rev_tag_dict = {} for index, tag in enumera...
The code runs a game with phases (guide, practice, real trials), collects user responses, logs data, updates high scores, and streams events via LSL/NetStation. It uses Pygame for visuals/audio, handles user input, and allows replay. If `unified` is True, it returns a boolean based on user choice; else, it exits. Key t...
def main(unified): mot_play_again = True while mot_play_again == True: tag_dict, rev_tag_dict = tag_dicts() # == Initiate pygame and collect user information == #consent_screens() pg.init() pg.mixer.init() log, highscore_path, high_score, user_number, name, date_s...
def load_data(self): self.train = pd.read_csv(self.train_data_path, header=None) self.train.columns = ['open', 'high', 'low', 'close'] self.test = pd.read_csv(self.test_data_path, header=None) self.test.columns = ['open', 'high', 'low', 'close'] self.combine = pd.concat([self.tra...
The code's main task is to execute a specified machine learning model (XGBoost or LSTM) after loading data. It checks the `model_type` parameter, runs the corresponding method (`xgb()` or `lstm()`), and exits if the model is unsupported.
def execute(self, model_type = "lstm"): self.load_data() if model_type == "xgboost": self.xgb() elif model_type == "lstm": self.lstm() else: sys.exit("Model Not found")
def getposition(row): if(row[18]!=''and row[17]!=''and row!=rows[0]): return [float(row[18]),float(row[17])] def haversine(a,b): # [longitude, latitude] lat1=a[1] lon1=a[0] lat2=b[1] lon2=b[0] R = 6371 # earth radius in kilometers dlat = math.radians(lat2 - lat1) dlon = ma...
This function identifies the species with the highest repopulation score within a specified geographic range of given coordinates. It filters species within a distance limit using the Haversine formula, calculates their scores, and returns the species with the maximum score.
def best_tree(long,lat,acceptable_range=10000): y = lat x = long best=[0,""] # score, species species_array=[] for row in rows: if(getposition(row)!=None): if(haversine([x,y],getposition(row))<=acceptable_range and row[7]not in species_array): species_array.a...
def update_mini_batch(self, mini_batch, eta, mu, cost_fun = 'CE', reg_parameter = 0, activ_funct = 'Sigmoid'): """Update the network's weights and biases by applying gradient descent using backpropagation to a single mini batch. The <<mini_batch>> is a list of tuples (x, y), and <<eta>...
The code implements mini-batch Stochastic Gradient Descent (SGD) to train a neural network, supporting momentum, L2 regularization, learning rate scheduling, and early stopping. It processes training data in epochs, using either vectorized or matrix-based backpropagation. If test data is provided, it evaluates accuracy...
def SGD(self, training_data, epochs, mini_batch_size, eta, eta_schedule = (5, 2, 4), mu = 0, test_data = None, method = 'M', cost_fun = 'CE', reg_parameter = 0, early_stop = 999, activ_funct = 'Sigmoid'): """Train the neural network using mini-batch Stochastic Gradient Descent. - The <<tra...
def generate_empty_grid(self): self.grid = [[0 for _ in range(0, self.VALUE_MAX)] for _ in range(0, self.VALUE_MAX)] def fill_diagonals(self): for i in range(0, self.VALUE_MAX, self.SIZE): possible_values = list(range(1, self.VALUE_MAX+1)) random.shuffle(possible_values) ...
The main task of the code is to generate a fully solved Sudoku grid by first creating an empty grid, filling its main diagonals with initial values, and then solving the puzzle using a Sudoku-solving algorithm.
def generate_full_grid(self): self.generate_empty_grid() self.fill_diagonals() self.solve_sudoku()
def init_rng(self): """ Initialize random generator for training. """ if hasattr(self.env, "rng"): return if self.train: worker_id = self.get_worker_id() self.env.worker_id = worker_id self.env.rng = np.random.RandomState( ...
The `__getitem__` method retrieves a training sample by either generating it or reading from a file, depending on whether `self.path` is `None`. It initializes a random number generator, uses `generate_sample()` if no file path is provided, or `read_sample(index)` otherwise, ensuring flexibility in data loading for tra...
def __getitem__(self, index): """ Return a training sample. Either generate it, or read it from file. """ self.init_rng() if self.path is None: return self.generate_sample() else: return self.read_sample(index)
def combine_reused_samples(self, rng, idx, currN): ''' Combines the reused samples depending on the K level. ''' A_s = np.zeros(shape=(self.K, self.N, self.N), dtype=np.int64) B_s = np.zeros(shape=(self.K, self.N), dtype=np.int64) for i in range(self.K): a,b =...
This code generates samples based on reuse settings. If `reuse` is enabled, it either combines existing samples (if `K > 1`) or retrieves a single reused sample. If `reuse` is disabled, it generates a new sample. The method selects between reuse strategies or fresh generation, depending on configuration parameters.
def generate(self, rng, idx, currN=-1): if self.reuse: if self.K > 1: return self.combine_reused_samples(rng, idx, currN) else: return self.get_reused_sample(rng, idx, currN) else: return self.get_sample(rng, idx, currN)
def _check_calc_done(self, name: str): if self.calc_data.get(name) is None: return False expected_shapes = { "train_emb": self.train_data.shape[0], "test_emb": self.test_data.shape[0], "tsne": self.train_data.shape[0] + self.test_data.shape[0], } ...
This function computes nearest neighbors for test embeddings using a specified distance metric. It checks if embeddings are generated, reruns calculations if needed, fits a NearestNeighbors model on training embeddings, calculates distances for test embeddings, normalizes these distances with MinMaxScaler, and stores r...
def get_neighbors( self, n: int = 30, distance_metric: str = "euclidean", force_rerun: bool = False ): knn = NearestNeighbors(metric=distance_metric) if (not self._check_calc_done("train_emb")) or (not self._check_calc_done("test_emb")): self.generate_embeddings() if ( ...
def _check_calc_done(self, name: str): if self.calc_data.get(name) is None: return False expected_shapes = { "train_emb": self.train_data.shape[0], "test_emb": self.test_data.shape[0], "tsne": self.train_data.shape[0] + self.test_data.shape[0], } ...
The code performs t-SNE dimensionality reduction on combined train/test embeddings, visualizing results. It checks if TSNE is already computed, generates embeddings if needed, merges train/test data with metadata, applies PCA for dimensionality reduction, runs t-SNE on PCA components, adds results to a dataframe, saves...
def tsne(self, species: Optional[str] = None): if self._check_calc_done("tsne"): return self._plot_tsne(species) if (not self._check_calc_done("train_emb")) or (not self._check_calc_done("test_emb")): self.generate_embeddings() df_combined = pd.concat( [self...
def generate_embeddings(self, force_rerun: bool = False): if force_rerun: self.continue_previous = False self._set_start_idx() self._get_embeddings("train") self._get_embeddings("test") def tsne(self, species: Optional[str] = None): if self._check_calc_done("tsne"):...
This method performs an end-to-end pipeline for embedding generation, visualization, neighbor identification, threshold tuning, and submission creation. It generates embeddings (with optional recalculation), applies t-SNE for visualization, identifies neighbors (with optional recalculation), tunes thresholds, creates t...
def end_to_end( self, recalc_emb: bool = False, recalc_neigh: bool = False, ): self.generate_embeddings(force_rerun=recalc_emb) self.tsne() self.get_neighbors(force_rerun=(recalc_neigh or recalc_emb)) self.tune_threshold(force_rerun=(recalc_neigh or recalc_emb...
def glClearColor(self, r, g, b): self.clearcolor = color(r, g, b) def glClear(self): self.pixels = [[self.clearcolor for y in range(self.height)] for x in range(self.width)] self.zBuffer = [[float('inf') for y in range(self.height)] for x ...
This code initializes an OpenGL rendering context by setting up clear color, viewport, camera, and projection matrices. It configures shaders, vertex buffers, and rendering parameters for 3D graphics rendering, preparing the environment to draw objects using specified primitive types and textures.
def __init__(self, width, height): self.width = width self.height = height self.glClearColor(0, 0, 0) self.glClear() self.glColor(1, 1, 1) self.vertexShader = None self.fragmentShader = None self.primitiveType = triangles self.vertexBuffer = [] ...
def xyz(): cset = CoordSet() cset.add("positions", (687071.44,), 0, "easting") cset.add("positions", (6210141.33,), 1, "northing") cset.add("positions", (10,), 2, "elevation") expected = "687071.44\t6210141.33\t10.0\t# \n" return cset, expected def xyzt(): cset, _ = xyz() cset.add("ep...
This function tests if the 'write_and_read' function correctly processes input data ('proj' and 'cset') by asserting that its output matches the expected result. It verifies the function's behavior for writing and reading operations, ensuring accuracy against predefined test cases.
def test_proj_write_to_file(write_and_read, data): """Test writing to file """ cset, expected = data assert write_and_read("proj", cset) == expected
def xyz(): cset = CoordSet() cset.add("positions", (687071.44,), 0, "easting") cset.add("positions", (6210141.33,), 1, "northing") cset.add("positions", (10,), 2, "elevation") expected = "687071.44\t6210141.33\t10.0\t# \n" return cset, expected def xyzt(): cset, _ = xyz() cset.add("ep...
This test verifies that writing a 'proj' stream to stdout using the writers module produces the expected output. It captures stdout/stderr, checks if stdout matches the expected value, and confirms stderr is empty.
def test_proj_write_to_stdout(capsys, data): cset, expected = data writers.write_stream(sys.stdout.buffer, "proj", cset) stdout, stderr = capsys.readouterr() assert stdout == expected assert stderr == ""
def setup_pygame(self): screen = pygame.display.set_mode((cp.width , cp.height)) pygame.display.set_caption(cp.title) pygame.init() return screen def menu(self,screen,font): global game_state play_text = font.render("Play", True, cp.White) play_text_y_offset = 0 ...
The code initializes a game loop that runs while `game_state` is not 2, setting up Pygame, fonts, and key inputs. It handles different game states (0-5) by rendering corresponding screens: a menu for state 0, the main game for state 1, and specific regions (Roma, Eygpt, China) for states 3-5, using state-specific logic...
def __init__(self) -> None: while game_state != 2: screen = self.setup_pygame() font = pygame.font.Font("Inter.ttf",32) font_small = pygame.font.Font("Inter.ttf",20) # A D W S 1 2 3 keys = [False, False, False, Fals...
def unpack_oru_r01(m_payload, remove_none=False): #unpack hl7 message segment_MSH = parse_msh_segment(m_payload.msh) segment_PID = parse_pid_segment(m_payload.pid) segment_OBR = parse_obr_segment(m_payload.obr) segment_OBXs = parse_obx_segments(m_payload.obx) combined_dict = { "MSH": seg...
The code processes HL7 messages to generate acknowledgment responses by identifying message types (ORU^R01 or QRY^Q02), extracting structured data, modifying key-value mappings, combining with default templates, and creating ACK payloads. It handles unsupported messages with a fallback unpacking method, returns parsed ...
def process_hl7_message(hl7_message, remove_none = False): message_payload = parse_message(hl7_message.replace("\n", "\r"), find_groups=False) message_type = message_payload.msh.msh_9.value print(message_type) message_dict_R = {} message_dict_S = {} response_payload = Message() if message_ty...
def _reset_metrics(self): for metric in self.metrics.values(): metric.reset() def test_step(self, data): ### config input data ### data = self._convert_cuda_data(data) x, y = data ######################### with self.autocast(): with torch.no_grad(...
The code evaluates a model on a validation dataset, computes metrics, and optionally displays progress and metrics in real-time. It configures the model for evaluation, iterates through validation batches, resets metrics, and updates them using `test_step`. If `verbose` is True, it shows progress with `tqdm` and update...
def evaluate(self, val_loader, verbose=True): ### model setting ### if self.use_cuda: self.model.cuda() self.criterion.cuda() self.model.eval() ##################### val_iter = iter(val_loader) if verbose: val_iter = tqdm(val_iter, tot...
def get_facet_label(line_label, roof, df): labels = [] for key, value in roof.facet_segment_ids.items(): if line_label in value: labels.append(key) return sorted(labels, key=lambda label: get_facet_pitch(label, df))[-1] def get_facet_pitch(facet_label, df): for i, row in df.iterrows...
The main task of the code is to predict missing roof line lengths using linear regression based on provided data, adjust for 3D geometry and pitch angles, calculate facet areas considering scale factors, and save results to a CSV file. It also generates a report.
def main(roof, manual=False): if not manual: df = pd.read_csv(os.path.join(roof.folder, "data_sheet.csv")) assert "-" not in list(df["Pitch"].values), "All pitch values must be given" value_counts = df["Length (ft.)"].value_counts() if "-" in value_counts: assert value...
def avPattern(self, dat, pmap): """ Average together elements that have the same label. Args ---- dat: array of data values pmap: mapping from unique array elements to pooling indices Returns ---- dat: array of pooled data (changes dat in place) ...
The code fits a probabilistic model using the EM algorithm to estimate parameters (mean, covariance) from multivariate data, supporting regularization and Markov order constraints. It initializes parameters, iterates between E-step (expectation) and M-step (maximization), and computes statistical properties (correlatio...
def fit(self, dfX, pattern=None, paramsInit=None, MLEalgo='ortho_select', alpha=0.0, Morder=1, gl_maxIter=500, gl_verbose=False): """ Fit the model using EM with data X. Args ---- dfX : DataFrame, [nExamples, dataDim] df of training data, where nExam...
def initializeParameterNode(self): """ Ensure parameter node exists and observed. """ # Parameter node stores all user choices in parameter values, node selections, etc. # so that when the scene is saved and reloaded, these settings are restored. self.setParameterNode(self.logic.getParameterNode...
The main task of the code is to initialize a Slicer module's UI, connect it to MRML scene data, create a logic class for backend processing, and establish signal-slot connections for user interactions like node selection, file input, parameter adjustments, and data collection. It sets up GUI elements, initializes param...
def setup(self): ScriptedLoadableModuleWidget.setup(self) # Load widget from .ui file (created by Qt Designer). # Additional widgets can be instantiated manually and added to self.layout. uiWidget = slicer.util.loadUI(self.resourcePath('UI/BroadbandSpecModule.ui')) self.layout.addWidget(uiWidget) ...
def removeObservers(self): for nodeTagPair in self.observerTags: nodeTagPair[0].RemoveObserver(nodeTagPair[1]) def addObservers(self): parameterNode = self.getParameterNode() spectrumImageNode = parameterNode.GetNodeReference(self.INPUT_VOLUME) if spectrumImageNode: # print("Add observer to ...
The main task of the code is to initialize a plotting layout in Slicer by setting a conventional plot view arrangement, removing existing observers to avoid conflicts, adding new observers for updates, and triggering an initial modification event on the spectrum image node to start data visualization.
def startPlotting(self): print("Start plotting") # Change the layout to one that has a chart. ln = slicer.util.getNode(pattern='vtkMRMLLayoutNode*') ln.SetViewArrangement(slicer.vtkMRMLLayoutNode.SlicerLayoutConventionalPlotView) # Make sure there aren't already observers self.remove...
def process(image): image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image.flags.writeable = False results = pose.process(image) return results def repetitions(image, results = None): global reps global last_angle if not results: results = process(image) if not results.pose_landmar...
The code processes an image by first analyzing it with the 'process' function, then applying repetition effects using 'repetitions' and modifying it with 'dog_feeding' based on the analysis results, finally returning the transformed image.
def gather_functions(image): results = process(image) image = repetitions(image, results) image = dog_feeding(image, results) return image
def print_welcome_message(): # Prints Welcome message print("Welcome to Kpoll") print_options() def register_new_user_loop(): # Provides I/O for adding a new user and calls register_user print("Please enter username") username = input() print("Please enter password") password = input() ...
The main task of the code is to provide a menu-driven interface for managing poll-related operations. It continuously accepts user commands to register new users, view previous polls, vote on polls, start new polls, or exit. The loop processes inputs, executes corresponding functions, and terminates when the user selec...
def main(): print_welcome_message() cmd = "" off = False while not off: cmd = input() if cmd == "Q": print("Thank-you") off = True elif cmd == "N": register_new_user_loop() elif cmd == "S": see_prev_poll_loop() elif ...
def manhattan(self): #this obtains the manhattan distances between tiles total = 0 currTile = None; goalTile = None flat = self.flatten() for i in range(len(flat)): for tile in flat: if (tile.val == i): currTile = tile #find the location of...
This code initializes a node for a pathfinding algorithm, storing board state, parent reference, cost (g), heuristic (h), and total cost (f). It handles initial state setup and subsequent state generation by copying previous states, updating position, calculating Manhattan heuristic, and tracking blank tile availabilit...
def __init__(self, board, position=None): if position == None: #determine whether this is the first instance. if it is, then we self.pre = board #this stores the contents of the board on the first iteration self.parent = None # the parent is set to none by default if it is the first ...
def const_date_checker(start_date,end_date,request): if start_date == end_date: messages.error(request, "Please provide different dates in order to book holidays") return False return True def past_dates(start,end,request): present = datetime.now().date() if (start < present or end < ...
This function calculates requested holidays between dates, checks against remaining holidays for different staff levels, validates date constraints, and prevents duplicate requests, returning True if all conditions are met.
def holidays_left(start,end,request,username,first_name,last_name,staff_note): #Formatting date coming from HTML form to date type in python. formatted_start_date = datetime.strptime(start, '%Y-%m-%d').date() formatted_end_date = datetime.strptime(end, '%Y-%m-%d').date() holidays_requested = ...
def getSubjectNames(dataPath, sim): ### dataPath: str --> path to directory with wavelet files ### sim: bool --> to decide which prefix to use for sorting dataDirContents = os.listdir(dataPath) # print('dataDirContents: ' + str(dataDirContents)) subjects = [] if sim: prefix = 'v34_batch57_' else: prefix ...
The code processes wavelet statistics from simulated and NHP datasets, extracting duration, peak frequency, and cycle count across brain regions and frequency bands. It generates boxplots to compare these metrics between the two datasets, enabling visual analysis of neural oscillation patterns in different regions and ...
def plotStats(): simPath = dataPathPrefix + 'v34_batch57/' # print('simPath: ' + str(simPath)) nhpPath = dataPathPrefix + 'NHP_data/spont/' # print('nhpPath: ' + str(nhpPath)) simSubjects = getSubjectNames(dataPath=simPath, sim=1) nhpSubjects = getSubjectNames(dataPath=nhpPath, sim=0) # print('simSubjects: ' +...
def generate_grid(self): self.grid = [[1 if i == 0 or i == 21 or j == 0 or j == 31 else 0 for j in range(32)] for i in range(22)] for figure in self.figures: for width in range(figure['width']): for height in range(figure['height']): self.grid[figure['poin...
The main task of the code is to simulate a movement algorithm on a grid-based map. It generates a grid, initializes a tile map, and iteratively updates the position based on direction, checking for obstacles or boundaries. If movement is blocked, it adjusts direction; otherwise, it progresses. The loop continuously upd...
def run(self): self.generate_grid() self.grid_map = [[Tile() for j in range(32)] for i in range(22)] row, column = self.start_point[1] + 1, self.start_point[0] + 1 distance = 4 movement_direction = Direction.DOWN while True: self.__update_grid_map(column, dist...
def accuracy(preds, correct_labels): confusion = confusion_matrix(preds, correct_labels) if np.sum(confusion) > 0: return np.sum(np.diagonal(confusion)) / np.sum(confusion) else: return 0. def confusion_matrix(preds, correct_labels): labels = np.sort(np.unique(np.concatenate((preds, corr...
The code calculates evaluation metrics for classification tasks, including mean accuracy, confusion matrix, precision, recall, and F1-score, using predicted labels (preds) and true labels (correct_labels). It returns these metrics as a tuple to assess model performance.
def generate_evaluation(preds, correct_labels): mean_accuracy = accuracy(preds, correct_labels) confusions = confusion_matrix(preds, correct_labels) precisions = precision(preds, correct_labels) recalls = recall(preds, correct_labels) f1s = f1(preds, correct_labels) return (mean_accuracy, confus...
def find_goal(map,width): the_flateen=np.asarray(map) the_flateen=the_flateen.flatten() for m in range(len(the_flateen)): if the_flateen[m] == 2: theFirstIndixVal=m//width theSecondIndixVal=m-(width*theFirstIndixVal) print("the First Indix Val",theFirstIndixVal,"t...
The main task of the code is to plan a path from a given start position to a goal on a grid map. It validates the start position, adjusts it if invalid, finds the goal, modifies a value map to mark paths, and traces back a trajectory from the start to the goal. The function returns the modified map and the generated pa...
def planner(map,start_row,start_col): try: if start_col>=map.shape[0] or start_row>=map.shape[1]: print('forbidden place the program will start at 4,4') start_col = 45 start_row = 4 if map[start_col,start_row] == 1: print('forbidden place the p...
def readFile(filename): """ Reads the provided file with exception handling Parameters --------- filename : str File name to be open in read mode Returns ------- list List of lines from the file """ try: readOnlyFile = open(filename, "r") # open file in read mode listOfLine...
The code reads the /etc/passwd file, splits each line by colons to extract user details, and appends formatted user and group information to an output file. It prints dashed lines before and after each entry for visual separation.
def print_user_details(): lines = readFile("/etc/passwd"); # calling readFile function to get all the linse in file as list for line in lines: print_dash_line() splittedLine = line.split(":") # splitting string based on colon : as a seperator # example line variable is root:1:1:1:root:/root:/root/bi...
def parse_cmdline_kwargs(args): ''' convert a list of '='-spaced command-line arguments to a dictionary, evaluating python objects when possible ''' def parse(v): assert isinstance(v, str) try: return eval(v) except (NameError, SyntaxError): return v ...
The main task of the code is to configure logging, parse command-line arguments, train a reinforcement learning model, save the trained model if specified, and optionally run the trained model in an environment for playback. It handles distributed training with MPI, manages argument parsing for priority settings, and e...
def main(main_args): # configure logger, disable logging in child MPI processes (with rank > 0) print(main_args) arg_parser = common_arg_parser() args, unknown_args = arg_parser.parse_known_args(main_args) extra_args = parse_cmdline_kwargs(unknown_args) prio_parser = prio_arg_parser() prio_...
def get_action(self, x): if np.random.random() < self.epsilon: return np.random.randint(self.num_actions) # random action else: q_val = self.predict(x, self.train_network)[0] # greedy action return np.argmax(q_val) def add_experience(self, exp, step_number): ...
The main task of the code is to execute a single episode in a reinforcement learning environment. It initializes variables, interacts with the environment by selecting actions, accumulating rewards, and logging experiences. The episode ends when the environment signals completion or the maximum step limit is reached. A...
def run_episode(self): rewards = 0 steps = 0 done = False state = self.env.reset() while not done: action = self.get_action(state) new_state, reward, done, _ = self.env.step(action) steps += 1 rewards += reward self.step...
def build_pyramid( self, I: tf.Tensor ): def conv_with_pad(x: tf.Tensor, h: tf.Tensor) -> tf.Tensor: k_ = h.get_shape()[0] // 2 x = tf.pad(x, tf.constant([[0, 0], [k_, k_], [k_, k_], [0, 0]], tf.int32), 'SYMMETRIC') return tf.nn.convolution(x, h, p...
This function extracts key points and their descriptors from an input image using a multi-scale pyramid approach. It builds a pyramid, detects extrema, assigns orientations, accumulates key points across octaves, computes descriptors, and optionally stores them as a template. The output includes detected key points and...
def keypoints_with_descriptors( self, inputs: tf.Tensor, keep_as_templet: bool = False ) -> tuple[KeyPoints, tf.Tensor]: if keep_as_templet and self.templet_capture: raise Warning('prev templet will be removed') self.build_pyramid(inputs) key_points = KeyP...
def get_satdc(repo_path): comments = find_comments(repo_path) satd_comments = {} for file_name in comments.keys(): satd = [] for comment in comments[file_name]: if is_satdc(comment.text()): satd.append(comment) if(len(satd) > 0): satd_co...
The code clones a GitHub repository, extracts SATDC comments, identifies their references to issues, and saves the results. It returns the count of SATDC comments and their associated references.
def run(repo_owner, repo_name, label): g = Github("", "") github_user = g.get_user() original_repo = g.get_repo(repo_owner + "/" + repo_name) #clone repository repo_path = Path(__file__).parent / "./temp/" / original_repo.name cloned_repo = Repo.clone_from(original_repo.clone_url, repo_path) ...
def find_winning_move(self, game, player_id): possible_moves = self.get_possible_moves(game, player_id) for moves in possible_moves: x, y = moves[0] direction = moves[1] if self.is_winning_move(game, x, y, direction, player_id): return moves ...
The code determines the optimal move for a player in a game by following three rules: first, it checks for an immediate winning move; if none, it avoids moves that allow the opponent to win; finally, it selects the best move improving the player's position. If no optimal moves exist, it randomly chooses from available ...
def make_move(self, game: Game) -> "tuple[tuple[int, int], Move]": # Get the current state of the board board = game.get_board() player_id = game.get_current_player() # print("Player_id: ", player_id) # Rule 1: Check for a winning move winning_move = self.find_winning_mo...
def contains(self, x, y, epsilon=0, ignore_last_line=True): """ Checks whether a given point is already in the trail :return: True if point occurs in the trail/False otherwise """ temp_lines = deepcopy(self.lines) if ignore_last_line: temp_lines = temp_lines[:...
The main task of the code is to add a list of points to a trail, checking for backtracking by verifying if a point already exists in the trail. If so, it backtracks to that point before adding the new endpoint. Each valid point (non-None) is processed to update the trail, ensuring proper line connections. The method co...
def add_endpoints(self, points): """ Adds a list of points to the trail (ex. for initializing a trail via points) :param points: list of tuples """ for point in points: if point is not None: x = point[0] y = point[1] if ...
def get_distance(self): """ :return: sum of trail line lengths (float) """ distance = 0 for line in self.get_lines(): distance += line.get_distance() return distance def get_first_point(self): return self.lines[0].endpoint1 def get_lines(self): ...
The code modifies a trail by removing invalid lines. It checks if the trail's distance is too short, then filters valid endpoints from lines, ignoring invalid ones. If fewer than two valid points remain, it returns False. Otherwise, it clears the existing trail and reconstructs it using the valid points in reversed ord...
def fix_trail(self): """ Modifies trail lines to remove invalid lines :return: False if trail cannot be fixed; True if it was fixed """ if self.get_distance() < 4: return False true_points = [self.get_first_point()] for line in self.get_lines(): ...
def create_dataset_dir(): if not os.path.exists(dir): os.mkdir(dir) if not os.path.exists(query_dir): os.mkdir(query_dir) if not os.path.exists(ref_dir): os.mkdir(ref_dir) def load_csv(): print('RGB mode') file_path = glob.glob(csv_path) print('GPS file count: {}'.format(...
The main task of the code is to process datasets by loading CSV files, compute ground truth data, move associated images, and save the results in compatible formats. It measures and prints the time taken for these operations, including directory creation, data manipulation, and file conversion.
def main(): start = time() ####################################################################### create_dataset_dir() df, dfq = load_csv() # df.to_csv('df.csv', index=True, header=True) # dfq.to_csv('dfq.csv', index=True, header=True) gt = compute_ground_truth(df, dfq) # pd.DataFrame(g...
def validMultiNeighbors(kenken: Kenken, cells: set[Cell]) -> set[Cell]: neighs = multiNeighbors(cells, len(kenken.board)) avail = availableCells(kenken) validNeighs = neighs.intersection(avail) return validNeighs def validOperations(board: list[list[int]], cells: set[Cell]) -> set[str]: n = len(cell...
This function generates a random Kenken cage starting from a free cell. It selects a target size (2-4), expands by adding valid neighboring cells, checks feasible operations, calculates the target value, and returns a Cage object with the chosen cells, operation, and target value.
def makeCage(kenken: Kenken, freeCell: Cell) -> Cage: maxSize = 4 targetSize = random.randint(2, maxSize) cageNeighbors: set[Cell] = validMultiNeighbors(kenken, set([freeCell])) cells: set[Cell] = set([freeCell]) while len(cells) < targetSize and len(cageNeighbors) > 0: chosen = random.choi...
def twoDimensionalShuffle(board: list[list[int]]): random.shuffle(board) shuffleCoords = list(range(0, len(board[0]))) random.shuffle(shuffleCoords) copy = deepcopy(board) for x in range(len(board)): for y in range(len(board)): copy[y][shuffleCoords[x]] = board[y][x] return...
The code generates a Kenken puzzle by initializing a size×size board with shuffled numbers, adding specified freebie cells, and populating remaining cells with cages. It returns the completed Kenken grid with structured constraints for puzzle-solving.
def generate(size, freebies) -> Kenken: # initialise board kenken = Kenken( [[((x + i) % size) + 1 for x in range(0, size)] for i in range(0, size)], [] ) # shuffle board kenken.board = twoDimensionalShuffle(kenken.board) # add freebie cages addFreeCells(kenken, freebies, size, siz...
def queue_file(self): ''' Initialize a file for analysis using the load_data.py scripts. Collects all information and assumes it exists in the file. NOTE: queue_file will include all timestamps within the range of the user's start & stop, but not exceed it. e.g. if the user asks ...
The main task of the code is to execute all analysis steps for all nodes during initialization by sequentially calling `queue_file`, `run_cache`, and `iterate` methods. It aggregates results into a structured numpy array with node keys as the first column, then optionally applies post-analysis processing if `post_analy...
def run_all(self): ''' Run all analysis for all nodes in initialization. This serves as an easy way to run the whole analysis rather than individually executing class methods. Although either way is valid and manual execution may be better for debugging and development. '...
def _srtm_tile(self) -> str | None: """Determines SRTM tile name from coordinates downloads it if necessary, and decompresses. Returns: str: Path to decompressed tile or None if download failed. """ latitude_band, tile_name = self._tile_info(*self.coordinates) self.l...
The code processes a Digital Elevation Model (DEM) by reading an SRTM file, cropping it to a specified geographic area, normalizing the data, resampling it to a target resolution, applying Gaussian blur, and saving the processed DEM to a designated directory.
def process(self) -> None: """Reads SRTM file, crops it to map size, normalizes and blurs it, saves to map directory.""" north, south, east, west = ox.utils_geo.bbox_from_point( # pylint: disable=W0632 self.coordinates, dist=self.distance ) self.logger.debug( ...
def is_valid_row(self, row_index): row = self.get_row(row_index) row.sort() return row == default_candidates def is_valid_column(self, column_index): column = self.get_column(column_index) column.sort() return column == default_candidates def is_valid_block(self, block_in...
This function checks if a solved Sudoku grid is valid by verifying all rows, columns, and 3x3 blocks for duplicates. It raises an error if the grid isn't solved first. If invalid sections are found, it returns a report listing them. The result is a dictionary with 'valid' status and 'invalid_parts' list.
def get_validity_report(self): if self.solved == False: raise Exception('Puzzle not solved yet. Call <Grid>.solve() first.') invalid_parts = [] valid = True for i in range(9): valid_row = self.is_valid_row(i) valid_column = self.is_valid_colum...
def dump_if_over_time(certificate, target_directory, name_of_instance): if time()- global_support.STARTING_TIME >= global_support.TIME_LIMIT: logging.debug("too slow") certificate["finished"] = "time_kill" # Certificate Output """ with open(os.path.join(target_directory, ...
The function creates box constraints around variables in a master optimization problem, iteratively solves subproblems (feasible/infeasible) via callbacks, generates cutting planes (cuts) to refine the solution, and removes the box constraints once the optimal solution meets a termination condition.
def box_loop(target_directory, name_of_instance,master, feasible_sub, infeasible_sub, expr_terms, certificate, distance=1.): """Create constraints around optimal solutions of master. Call one optimize with callback.""" logging.debug('Creating box') box_constraints = [] for vari...
def post_notes() : data = get_user_note() response = requests.post(base_url, data) if response.status_code == 201 : print("Note created successfully") else : print(f"Failed to create note. Status code: {response.status_code}") def get_notes() : try : response = requests.get(b...
The main task of the code is to provide a CLI client for a daily notes application. It connects to a server, displays a welcome menu with options to create notes, list all notes, or view a note by ID, and processes user input to execute corresponding actions while handling connection errors gracefully.
def welcome() : try : response = requests.get(base_url) except ConnectionError as e : print("Failed to connect to the server. Try again later!") return print("Welcome to the cli client of the daily notes application.") print("") print("1) To create a new note.") print...
def forward(self, X): # Input to hidden layer self.z1 = np.dot(X, self.W1) + self.b1 self.a1 = self.relu(self.z1) # Hidden to output layer self.z2 = np.dot(self.a1, self.W2) + self.b2 self.a2 = self.sigmoid(self.z2) return self.a2 def backward(self, X, y, output...
This code trains a neural network model by performing forward and backward propagation over multiple epochs, updating weights via gradient descent. It calculates mean squared error loss every 100 epochs to monitor training progress.
def train(self, X, y, learning_rate=0.01, num_epochs=1000): for epoch in range(num_epochs): # Forward propagation output = self.forward(X) # Backward propagation self.backward(X, y, output) # Gradient descent self.optimize(learning_rate) ...
def getPassband(self, passbandFile='model_passbands.npz'): tmp = np.load(datapath.joinpath(passbandFile)) self.f_GHz = tmp['f_GHz'][:50000] if (self.band==1.1): self.passband = tmp['band_280'][:50000]+1.0e-10 self.fmin = 245. self.fmax = 310. elif(self...
The code updates telescope and atmospheric parameters, calculates optical and system efficiency, determines thermal characteristics (optics and detector temperatures), and computes noise performance metrics (P0, net, nefd, nep) along with mapping speed for astronomical instrumentation analysis.
def update(self): #fetch the passband self.getPassband() #telescope and atmosphere self.telAtm = LMTAtmosphere(elevation=self.elevation, \ quartile=self.atmQuartile, \ path=datapath) self.telEffici...
def _write(self, data): if self._verbose: alog.info(f"WRITE: {repr(data)}") for c in data: self._tty_w.write(c) time.sleep(0.01) def _expect_ok(self, expect_empty_line_before_ok=True): return self._expect_str('OK', expect_empty_line_before_ok) def _expect_empt...
This function checks if a modem is connected to a network by sending AT commands to set text mode and query registration status. It parses the response to determine if the modem is registered on a home or roaming network, returning a boolean indicating connectivity.
def is_connected(self): if self._verbose: alog.info('Change to text mode') self._write('AT+CMGF=1\r\n') self._expect_ok() if self._verbose: alog.info('Query connection state') self._write('AT+CREG?\r\n') self._expect_empty_line() res = self...
def _write(self, data): if self._verbose: alog.info(f"WRITE: {repr(data)}") for c in data: self._tty_w.write(c) time.sleep(0.01) def _expect_empty_line(self): line = self._read_line() if line != '': raise Exception(f'Expected an empty line,...
This function checks if a PIN is ready on a device by sending the AT+CPIN? command, reading the response, and verifying if it matches '+CPIN: READY'. It logs status if verbose, returns a boolean indicating PIN readiness, and ensures expected responses like OK are received.
def is_pin_ready(self): if self._verbose: alog.info("Check if PIN is ready") self._write('AT+CPIN?\r\n') self._expect_empty_line() ready = self._read_line() == '+CPIN: READY' self._expect_ok() if self._verbose: alog.info(f'PIN is ready: {ready}') ...
def _write(self, data): if self._verbose: alog.info(f"WRITE: {repr(data)}") for c in data: self._tty_w.write(c) time.sleep(0.01) def _expect_ok(self, expect_empty_line_before_ok=True): return self._expect_str('OK', expect_empty_line_before_ok) def _expect_empt...
This function sends an SMS message in PDU format using AT commands. It sets the SMS mode to PDU, calculates the required message length, transmits the PDU data, handles response validation, checks for error codes, and ensures successful command execution. The function includes verbose logging and error handling for SMS...
def _send_pdu_cmd(self, pdu_msg): if self._verbose: alog.info('Change to PDU mode') self._write(f'AT+CMGF=0\r\n') self._expect_ok() if self._verbose: alog.info('Send PDU message') self._write(f'AT+CMGS={(len(pdu_msg) - 1) // 2}\r') self._expect_emp...
def is_pin_ready(self): if self._verbose: alog.info("Check if PIN is ready") self._write('AT+CPIN?\r\n') self._expect_empty_line() ready = self._read_line() == '+CPIN: READY' self._expect_ok() if self._verbose: alog.info(f'PIN is ready: {ready}') ...
This code sends an SMS message via a PDU (Protocol Data Unit) after validating input constraints, including message length, PIN readiness, and network connectivity. It constructs a PDU with parameters like recipient number, message type, flash setting, and GSM-encoded text, then transmits it using `_send_pdu_cmd`.
def send(self, receiver, text='', type=SmsType.DEFAULT, flash=False, delivery_report=False): if len(text) > SmsGateway.MAX_SMS_LEN: raise Exception(f'The maximum length for a SMS is {SmsGateway.MAX_SMS_LEN}, but the given SMS has a length of {len(text)}!') if not self.is_pin_ready(): ...
def _send_start_paste(self): self._send_character("\5") def _send_line(self, line_text: str, ending: str = "\r\n"): assert isinstance(line_text, str) assert isinstance(ending, str) serial_connection = self._serial_connection serial_connection.write((line_text + ending).encode('ut...
The code executes a specified file on a controller by reading its contents and executing them using `exec()`, with an optional global initialization string. It sends commands to start/paste code, initializes globals if provided, opens the file, executes its content in the global namespace, then ends the paste process.
def run_file(self, file_name: str, globals_init: str = ""): """ Execute a file on the controller Args: file_name (str): The file name to be executed which is stored on the controller globals_init (str): Initializier prior to script execution """ self._send...
def _send_start_paste(self): self._send_character("\5") def _send_line(self, line_text: str, ending: str = "\r\n"): assert isinstance(line_text, str) assert isinstance(ending, str) serial_connection = self._serial_connection serial_connection.write((line_text + ending).encode('ut...
This function pastes multiple lines of text by sending each line with a carriage return, enclosed by start/end paste commands, then flushes input. It handles line-by-line transmission for operations like pasting code or text blocks.
def __paste_lines(self, lines: List[str]): self._send_start_paste() for line in lines: self._send_line(line, "\r") self._send_end_paste() self._flush_input()
def run_file(self, file_name: str, globals_init: str = ""): """ Execute a file on the controller Args: file_name (str): The file name to be executed which is stored on the controller globals_init (str): Initializier prior to script execution """ self._send...
The main task of the code is to create a file on the controller using UTF-8 encoded content. It initializes the file creation process by calling `run_file` with a predefined command, flushes input, and transmits the content via `_send_file` to store the data in the specified file named `file_name`.)
def create_file(self, content: bytes, file_name: str): """ Create a file from an utf-8 encoded data buffer Args: content (byte): utf-8 encoded data which will be stored in the file file_name (str): The filename for the newly created file on the controller """ ...
def _read_to_next_prompt(self, timeout: float = 5.0): serial_connection = self._serial_connection received_data = b"" start_time = time.time() while len(received_data) < 4 or received_data[-4:] != b">>> ": if (time.time() - start_time) >= timeout: raise Timeou...
The code establishes a serial connection, waits for the device to boot by reading prompts with timeout handling, sends a control character if needed, and initiates file upload. It configures the context manager to handle device communication and data transfer preparation.
def __enter__(self): self.__serial_connection = SerialTransmitter.__open_serial_connection(self.__port) # Give board time to boot for _ in range(20): try: self._read_to_next_prompt(2) except TimeoutError: self.send_control_character("c") ...
def advance(self): c = self.source[self.current] self.current = self.current + 1 return c def addToken(self, type, literal): text = self.source[(self.start):(self.current)] self.tokens.append(Token(type, text, literal, self.line)) def match(self, expected): if self.isAtEn...
The `scanToken` method processes a character from the input stream, identifying and tokenizing it based on its type. It adds tokens for parentheses, braces, punctuation, operators, and keywords. Special handling includes checking for multi-character operators (e.g., `>=`, `<=`), comments (`//`), and strings (`"`). Whit...
def scanToken(self): c = self.advance() if c == '(': self.addToken(TokenType.LEFT_PAREN, None) elif c == ")": self.addToken(TokenType.RIGHT_PAREN, None) elif c == "{": self.addToken(TokenType.LEFT_BRACE, None) elif c == "}": sel...
def set_configurations(self): self.configurations = configparser.ConfigParser() loc = os.path.dirname(os.path.abspath(__file__)) self.configurations.read(loc+'\config.ini') self.city = self.configurations["configs"]["city"] self.interval = int(self.configurations["configs"]["inte...
The code initializes a GUI application using Tkinter, configures settings, fetches weather data, sets up a timer, and terminates the GUI. Its main task is to create a weather and timer display interface.
def __init__(self): self.set_configurations() self.setup_tkinter() self.fetch_weather() self.setup_time_config() self.setup_timer() self.end_tkinter()
def __is_filter_changed(self) -> bool: changed = False with open(self._ua_filters_path, 'r') as file: filters = json.load(file) if (filters['device'] != self._device): changed = True if (filters['os_name'] != self._device): changed = T...
The function checks if the filter has changed. If so, it refreshes the data; otherwise, it loads the UA database. The main task is to conditionally refresh or load UA data based on filter status.
def __load_or_download_ua(self): if (self.__is_filter_changed()): self.refresh() else: self.__load_ua_db()
def __is_local_db_exist(self) -> bool: return os.path.exists(self._ua_path) def refresh(self): self._ua_list = self.__download_ua() # # Unescaping user-agents # for index, ua in enumerate(self._ua_list): # if ('\"' in ua): # self._ua_list[index] = ast...
The main task of the code is to initialize a database by checking if a local database exists. If not, it refreshes the database; otherwise, it loads or downloads user agents. This ensures the system either updates data or uses existing local data for user agent handling.
def __initialize(self): if (not self.__is_local_db_exist()): self.refresh() else: self.__load_or_download_ua()
def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings,apply_rp,pruning_mask): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pyli...
The code trains and evaluates a BERT model for multiple NLP tasks (e.g., GLUE benchmarks), with a focus on training and applying **sample-specific pruning masks**. It supports training masks for individual samples by freezing BERT weights and learning mask layers, then uses these masks for prediction. The script handle...
def main(_): tf.logging.set_verbosity(tf.logging.ERROR) processors = { "cola": ColaProcessor, "mnli": MnliProcessor, "mrpc": MrpcProcessor, "xnli": XnliProcessor, "news": NewsProcessor, "rte" : RteProcessor, "ag_news" : AGNewsProcessor } tokenization.validate_case_mat...
def check_events(self): for event in pygame.event.get(): self.exit(event) self.key_down(event) self.key_up(event) def bul_upd(self): self.bullets.update() for bullet in self.bullets.copy(): if bullet.rect.bottom <= 0: self.b...
The main task of the code is to run a game loop that continuously updates game elements: checking events, updating the ship, bullets, aliens, and refreshing the screen to create dynamic gameplay. It maintains real-time interaction and visual rendering until the game ends.
def run_game(self): while True: self.check_events() self.ship.update() self.bul_upd() self.alien_upd() self.upd_screen()
def set_board(self, board): self.board = board def set_tetromino(self, tetromino, tetromino_x, tetromino_y): self.tetromino = tetromino self.tetromino_x = tetromino_x self.tetromino_y = tetromino_y def _get_board_props(self): cum_height = self.get_cumulative_height(self.board) rows_cleared = sel...
This code trains a Deep Q-Network (DQN) agent for Tetris using reinforcement learning. It runs episodes, logs scores, trains the model periodically with experience replay, saves checkpoints, and uses TensorBoard for monitoring. The agent selects actions based on predicted next states, updates memory, and adapts to game...
def start_dql(self, training = True, episodes = 5000): pbar = tqdm(total = 10000+1) n_neurons = [32, 32] mem_size = 20000 batch_size = 512 log_dir = f'logs/tetris-nn={str(n_neurons)}-mem={mem_size}-bs={batch_size}-e={1}-{datetime.now().strftime("%Y%m%d-%H%M%S")}' log = CustomTensorBoard(log_dir=...
def load_board(self): cur_state = self.tetris_app.get_state() self.set_board(cur_state["board"]) self.set_tetromino(cur_state["tetromino"], cur_state["tetromino_x"], cur_state["tetromino_y"]) return cur_state def set_board(self, board): self.board = board def set_tetromino(self, tetromino, tetromino...
This function tests a Deep Q-Learning (DQL) agent in a Tetris game by simulating gameplay. It loads game states, identifies optimal actions using the agent's best_state method, executes those actions, and records scores when the game ends. The loop continues until testing completes, evaluating the agent's decision-maki...
def test_dql(self, testing = True): scores = [] while testing: cur_state = self.load_board() cur_state = self.tetris_app.get_state() self.set_board(cur_state["board"]) self.set_tetromino(cur_state["tetromino"], cur_state["tetromino_x"], cur_state["tetromino_y"]) if not cur_stat...
def check_size(eval_segm, gt_segm): h_e, w_e = segm_size(eval_segm) h_g, w_g = segm_size(gt_segm) if (h_e != h_g) or (w_e != w_g): raise ValueError('Uneuqal image and mask size') def union_classes(eval_segm, gt_segm): eval_cl, _ = extract_classes(eval_segm) gt_cl, _ = extract_classes(gt_s...
The function `mean_IU` calculates the **mean Intersection over Union (IoU)** between an evaluated segmentation map (`eval_segm`) and a ground-truth segmentation map (`gt_segm`). It computes per-class IoU values by comparing overlapping regions (true positives) with the union of predicted and ground-truth areas, then av...
def mean_IU(eval_segm, gt_segm): ''' (1/n_cl) * sum_i(n_ii / (t_i + sum_j(n_ji) - n_ii)) ''' check_size(eval_segm, gt_segm) cl, n_cl = union_classes(eval_segm, gt_segm) _, n_cl_gt = extract_classes(gt_segm) eval_mask, gt_mask = extract_both_masks(eval_segm, gt_segm, cl, n_cl) IU = l...
def get_conic_and_bb(self, camera: Camera, thresh:float=3., optimal:bool=False, bboxsize_cam:np.ndarray=None): """Get conic and other bounding boxes. Is this implementation sound?""" conic = self.get_conic(camera) if not optimal: bboxsize_cam = self.get_fast_bb(thresh) else: ...
This code renders high-resolution images by efficiently calculating Gaussian distributions' contributions using binning. It updates the bitmap and alpha channels by applying opacity and color values from Gaussians, optimizing performance through spatial partitioning and exponential blending.
def render_old(self, bitmap: np.ndarray, alphas: np.ndarray, camera: Camera=None, depths=None, depth_map=None): # Kept because it is actually faster than new rendering when rendering high resolution images if camera is None: camera = self.camera else: GaussianModel._update_camera(ca...
def remove_ionic_from_react_file(self, root: str, file: str, dst_root: str): src_path = path.join(root, file) with open(src_path, "rt") as fin: content = fin.read() dst_path = path.join(dst_root, file) with open(dst_path, "wt") as fout: content = self.remove_impo...
This function removes Ionic-specific code from a React project by processing files in the source directory, copying or converting them to the destination directory, and generating React components or classes. It ensures directories are structured correctly, avoids overwriting, and reports the number of processed files ...
def remove_ionic_from_react_project(self, ionic_dir: str, dst_dir: str): ionic_dir = path.abspath(ionic_dir) dst_dir = path.abspath(dst_dir) if ionic_dir == dst_dir: raise ValueError("Ionic source directory and destination directory must not be the same.") n_files = 0 ...
def open_povinator(args): if platform.system() == 'Windows': return open_povinator_windows(args) else: return open_povinator_linux(args) def wait_and_read(proc, timeout=60): start = time.time() r = read(proc) while r == '' and (time.time()-start < timeout): time.sleep(.2) ...
The function interacts with a program (povinator) to process a URL, handle sheet selections, download presentations, and manage zip file options, returning the result of the interaction.
def go(url, sheets, download, zip): povinator = open_povinator(['go']) init = wait_and_read(povinator) if init != POV3K_WELCOME: raise RuntimeError if not url.endswith('\n'): url = url + '\n' write(povinator, url) got = wait_and_read(povinator) while got.endswith(POV3K_RESPON...
def open_povinator(args): if platform.system() == 'Windows': return open_povinator_windows(args) else: return open_povinator_linux(args) def wait_and_read(proc, timeout=60): start = time.time() r = read(proc) while r == '' and (time.time()-start < timeout): time.sleep(.2) ...
This function interacts with a process to extract sheet names from a URL. It sends the URL, reads responses, and collects sheet identifiers until no more are found. It validates initial responses, handles communication, and returns a list of sheet names extracted from the process's output.
def get_sheets(url): povinator = open_povinator(['go']) init = wait_and_read(povinator) if init != POV3K_WELCOME: raise RuntimeError if not url.endswith('\n'): url = url + '\n' write(povinator, url) got = wait_and_read(povinator) sheets = [] while got.endswith(POV3K_RESPO...
def get_db_cursor(commit=False): '''use commit = true to make lasting changes. Call this function in a with statement''' with get_db_connection() as connection: cursor = connection.cursor(cursor_factory=RealDictCursor) try: yield cursor if commit: connection.commit(...
This function updates a user's media list by moving items between status categories (e.g., from 'will_watch' to 'watching') or deleting them. It deletes the media_id from the source table (e.g., 'will_watch') and inserts it into the destination table (e.g., 'watching') based on start/end parameters. If 'delete' is spec...
def update_list_db(user, media_id, start, end): with get_db_cursor(True) as cur: if start == "will_watch" and end == "watching": cur.execute("DELETE FROM will_watch where user_id = %s and media_id = %s", (user, media_id,)) add_item_to_watching(user, media_id) elif start == "w...
def load_config(self): with open('config.yml', 'r') as config: self.config = yaml.load(config, Loader=yaml.SafeLoader) def init_firebase(self): self.firebase = pyrebase.initialize_app(self.config) def init_dashboard_ui(self): dashboard_layout = QVBoxLayout() # Tank photo cont...
This code initializes a GUI application for an aquarium log system, setting up a window with buttons for user authentication, data/upload management, and graphical displays. It creates a table to display log data (PH, SG, etc.), initializes Firebase connection, loads configurations, and prepares components for photo/sl...
def __init__(self): super().__init__() self.setWindowTitle('Aquarium Log') self.setFixedWidth(900) self.setFixedHeight(780) # Define image container self.tank_image_container = QLabel('') # Define buttons self.sign_in_btn = QPushButton('Sign In') s...
def sendPassengerUnsafe(self): self.passenger_safe_pub.publish(False) def analyze(self): rate = rospy.Rate(5) while self.image_ready == False and not rospy.is_shutdown(): rate.sleep() final_image = self.image_raw final_image = self.edit_video(final_image) ...
The code monitors passenger safety by analyzing predictions to adjust a safety counter. It initializes unsafe status, runs a loop to increment/decrement the counter based on prediction results, exits on ESC, logs safety confirmation, marks the passenger as safe, plays a sound, and triggers further safety analysis.
def initial_safety(self, data): safety_counter = 0 # Send unsafe message if self.passenger_unsafe == False: self.sendPassengerUnsafe() self.passenger_unsafe = True while safety_counter < 30 and not rospy.is_shutdown(): pred, frame, op_outp...
def classeNome(self, data): return list(set([x[-1] for x in data])) def classeDominante(self, data): frequencia = [0] * len(self.classes) for linha in data: index = self.classes.index(linha[-1]) frequencia[index] += 1 return self.classes[frequencia.index(max(fre...
The code generates a decision tree by recursively splitting data based on the best attribute and threshold, creating nodes with attributes as tests and children as subsequent splits or leaf nodes with class labels, stopping when data is empty, only one class exists, or no attributes remain.
def gerarArvore(self, data, atributos): if len(data) == 0: return No(True, "Error", None) classe_nome = self.classeNome(data) if len(classe_nome) == 1: return No(True, classe_nome[0], None) elif len(atributos) == 0: return No(True, self.classeDominan...
def wait_component(self, component, max_retries=3): for _ in range(max_retries): try: self.wait_title_to_be_visible(url=component['url'], locator=component['title']) self.wait_frame_to_be_visible(*component['frame']) if 'element' in component: ...
This code retrieves device information for a user by locating web elements, extracting device details from HTML, associating each device with the provided email, and returning a list of device data. It waits for specific UI components, checks for device presence, processes each device row, and enriches entries with the...
def get_device_info(self, email, user_id): device_info = [] component = { 'url': f'#view/Microsoft_AAD_UsersAndTenants/UserProfileMenuBlade/~/Devices/userId/{user_id}/hidePreviewBanner~/true', 'title': self.locator.device_title, 'frame': self.locator.devices_list, ...
def _read_data(self): assert isinstance(self.data, list) and all(isinstance(X,list) for X in self.data), \ 'Expected data as a list of lists' self._data_stats = { 'n_sessions': len(self.data), 'n_conditions': len(self.data[0]), 'n_units_per_session': [X[0]...
This code initializes an object with provided data and parameters, processes the data using helper methods, prepares a dataset, performs cleanup, and resets the dataset. It assigns attributes like data, unit IDs, condition details, and sample rate, then executes methods to read and structure the data for further analys...
def __init__( self, data: List[list], unit_ids: List[list]=None, condition_ids: list=None, condition_times: list=None, data_name: str='data', sample_rate: int=1, ): self.data = data self.unit_ids = unit_ids self.condition_ids = cond...