dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _update_all_sha(self): """ Re caches all tree information :return: """ self.__cache = self._api_req(f"/repos/{self._login}/{self._name}/git/trees/main?recursive=1").json() if "tree" not in self.__cache: self._create_readme() self._update_all_sh...
The main task of the code is to retrieve a file or directory from a Git repository by path or SHA, returning a Response if found. It checks local cache first, updates it if needed, and falls back to GitHub API if cache misses. The FORCE_UPDATE flag triggers a full cache refresh. It handles both path-based and SHA-based...
def get(self, path: str, FORCE_UPDATE=False) -> Union[Response, None]: """ Give it a path or sha, and it'll return a Response if found else just None :param path: the PATH or SHA of the thing you want e.g. path: test/test.json sha: f1a84e92cdfcdb32d2ebd94b015094e4d8b13c3...
def __upload_blob(self, _data) -> Tuple[str, int]: """ uploads blob to github and return sha and size :param _data: :return: Tuple(sha, size) """ body = { "content": _data, "encoding": "base64" } # to avoid empty rep errors ...
This function updates a file in a GitHub repository by converting the input data (dict, string, bytes, or list) to base64, uploading it as a blob, creating a new commit with the updated file, and updating the main branch reference to point to this commit. It handles data serialization, encoding, Git tree/commit operati...
def set(self, path: str, value: Union[dict, str, bytes, list]): """ Update a file with either a dict, string or bytes :param path: The path of the file to be updates :param value: This can be a DICT, STRING or BYTES (useful for images), Size should be lower than 100MB """ ...
def validate_path(path) -> str: """ Fixes path e.g. an empty path to ".", "test\\test2" -> "test/test2" :param path: :return: """ _out = "/".join(Path(path).parts) # If path is highest if not _out: _out = "." return _out def get(self, path: str, FORCE_UPDATE=False) -> Unio...
This function removes a specified file or directory from both GitHub and the local cache. For files, it directly deletes them from GitHub and the cache. For directories, it recursively deletes all child files and subdirectories from GitHub and the cache, then removes the directory itself from the cache (if not the root...
def remove(self, path: str): """ Removes a given file or directory :param path: The path to delete """ _path = validate_path(path) item = self.get(_path) # get the item information if item.type == "file": self._remove_from_github(item.path, ite...
def generate_custom(self): # * Generates the matrix, size depending on 'MAX' var # TODO: Make it user interactive self.createMatrix() # * Places the words in the matrix in random starting point and direction self.generate_words() # * Fills other spaces with random letters...
The code's main task is to select an option based on the provided index, update the instance's word list using `ALL_WORDS`, generate custom content, and display updated options and actions. It processes user input, modifies internal state, and triggers UI updates for interactive word-based functionality.
def choose_option(self, chosen_indx): print(chosen_indx) self.words = ALL_WORDS[chosen_indx] self.generate_custom() self.show_options_words() self.show_actions()
def gen_conf_matrix(self, actual): fig = Figure(figsize = (5, 5), dpi = 100) predictions = [] for image in os.listdir("Network/metrics_images"): image = "Network/metrics_images/" + image prediction = self.make_prediction(cv2.imread(image), "metric") predicti...
The code generates evaluation metrics for a classification model based on the specified metric type. It uses a predefined list of actual labels and delegates to helper methods to compute metrics like Confusion Matrix, Normalized Confusion Matrix, F-Score, Precision, Recall, MAE, and MSE.
def generate_metrics(self, metric): actual = ["Sad", "Disgust", "Angry", "Fear", "Happy", "Surprise", "Angry", "Surprise", "Sad", "Surprise"] if metric == "Confusion Matrix": return self.gen_conf_matrix(actual) elif metric == "Normalized Confusion Matrix": return self.gen...
def undbus(v): if isinstance(v, dbus.Boolean): return bool(v) if isinstance(v, int): return int(v) if isinstance(v, str): return str(v) if isinstance(v, bytes): return bytes(v) if isinstance(v, dict): return dict((undbus(k), undbus(v)) for k, v in v.items()) if isinstance(v, list): return list(undbus(v) for v in ...
This function creates and displays a desktop notification with customizable content, handling timeouts, icons, and user interactions. It processes input parameters, generates a unique notification ID, sets up a Gtk window for rendering, manages timeout logic, and returns the assigned ID for reference.
def Notify(self, app_name, id, icon, summary, body, actions, hints, timeout): # -> (id) app_name = undbus(app_name) id = undbus(id) icon = undbus(icon) summary = undbus(summary) body = undbus(body) actions = undbus(actions) hints = undbus(hints) timeout = undbus(timeout) try: if id == 0: self....
def ArnoldCatEncryption(img, key): """ Encrypts the image using the Arnaud-Cat algorithm Args: img: The image to be encrypted key: The key to be used for encryption Returns: The encrypted image """ for i in range (0,key): img = ArnoldCatTransform(img) r...
The function encrypts an image using chaos-based algorithms (Arnold Cat, Henon Map, or Logistic Map) based on the specified key and algorithm choice, returning the encrypted image.
def chaosEncryption(img,key,algorithm=0): """ Encrypt the image using the chaos encryption algorithms with the given key Args: img: The image to be encrypted key: The key to be used for encryption algorithm: The algorithm to be used for encryption. 0 for ArnoldCat , 1 for HenonMap, ...
def ArnoldCatDecryption(img, key): """ Decrypts the image using the Arnaud-Cat algorithm Args: img: The image to be decrypted key: The key to be used for decryption Returns: The decrypted image """ rows, cols, ch = img.shape dimension = rows decrypt_it = dim...
The main task of the code is to decrypt an encrypted image using chaos-based encryption algorithms (Arnold Cat, Henon Map, or Logistic Map) based on the specified algorithm parameter and key. It selects the appropriate decryption method, applies it to the input image, and returns the decrypted image.
def chaosDecryption(img,key,algorithm=0): """ Decrypt the image using the chaos encryption algorithms with the given key Args: img: The image to be decrypted key: The key to be used for decryption algorithm: The algorithm to be used for decryption. 0 for ArnoldCat , 1 for HenonMap, ...
def load_datasets(data_dir: Path): train_data = torch.load(data_dir / "train.pt") val_data = torch.load(data_dir / "test.pt") return train_data, val_data def train( fabric: L.Fabric, model: torch.nn.Module, optimizer: torch.optim.Optimizer, train_data: np.ndarray, val_data: np.ndarray, ...
The main task of the code is to fine-tune a pre-trained model's adapter using a specified dataset. It loads a model checkpoint, configures training parameters, sets up an optimizer, trains the model, and saves the final adapter weights. The process includes initializing the model, marking only the adapter layers as tra...
def main( fabric: L.Fabric = None, data_dir: Path = Path("data/alpaca"), checkpoint_dir: Path = Path("checkpoints/stabilityai/stablelm-base-alpha-3b"), out_dir: Path = Path("out/adapter/alpaca"), ): check_valid_checkpoint_dir(checkpoint_dir) fabric.seed_everything(1337 + fabric.global_rank) ...
def setBeadShape(self): # suppose we put a particle at the center of the grid, # where it's (hopefully) far from any annoying edges that might obscure its beautiful round shape x0 = int(self.gridSize[0]/2) y0 = int(self.gridSize[1]/2) # find px included in this bead by starting...
The main task of the code is to randomly place a specified number of beads on a grid while avoiding overlaps. It initializes grid parameters, checks for available positions, updates occupied pixel data, and terminates if placement exceeds a one-minute timeout. The function ensures beads are placed within bounds and tra...
def populateGridRandomly(self,numBeads,gridX,gridY,rad): self.gridSize = [gridX,gridY] self.xmin = 0 self.ymin = 0 self.beadRad = rad self.particleCenters = [] self.occupiedPx = [] self.resolution = 1 self.setBeadShape() self.setExclShape() ...
def freeSpacePoly(self,particleID): particleCenter = self.particleCenters[particleID] pxToCheck = [particleCenter] freePx = [] for (x,y) in pxToCheck: if self.isAvailPoly(particleCenter,(x,y)): freePx.append((x,y)) neighbors = self.getNeighbors...
The function calculates the entropy of a particle arrangement by evaluating free space around each particle using three methods (freeSpacePoly, freeSpace, freeSpaceMC). It optionally generates visualizations of the grid with occupied/free pixels and writes results to a CSV. The entropy value, number of particles, and c...
def entropy(self,makeImg=False,imgFile=None,sbeadFile=None,method=1): tic = time.time() # generate an Sbead file name, if none provided i = self.crystalFile.rfind('/') # chop off any part of the name before a slash nameRoot = self.crystalFile[i+1:-4] if sbeadFile == None: ...
def setBeadShape(self): # suppose we put a particle at the center of the grid, # where it's (hopefully) far from any annoying edges that might obscure its beautiful round shape x0 = int(self.gridSize[0]/2) y0 = int(self.gridSize[1]/2) # find px included in this bead by starting...
This code initializes a crystal structure by reading particle data from a CSV file, setting up bead and exclusion shapes, tracking occupied pixels, and optionally processing neighbor relationships and psi6 values for each particle. It configures grid parameters, processes particle coordinates, and prepares data structu...
def __init__(self,fname,rad=0,usePsi6=False,useNeighbs=False): self.crystalFile = fname self.particleCenters = [] self.psi6dict = {} self.occupiedPx = [] self.exclShape = [] self.beadShape = [] self.snowflakeShape = [] self.usePsi6 = usePsi6 self....
def reset(): for i in range(2,10): Pin(i, Pin.OUT, value=0) def Count(): # Counter, speed and tick variables counter = 0 countspeed = 1000 varTick = 1 # Interrupt flags global interrupt_flagL, interrupt_flagR while True: varTick = varTick + 1 if varTick > 2**15...
The code defines a menu function that presents three tasks: counting numbers, single-player LED pong, and multi-player LED pong. It takes user input to select a task, initializes necessary flags, and calls corresponding functions like Count(), LEDPong(), or KnowYourNeighbor() based on the input. It also handles button ...
def Menu(): # Global variables global interrupt_flagL, interrupt_flagR, start_flag_xor, start_flag_bcs # Call Menu with reseting PINs reset() # Menu instructions print("Tasks are given below, please enter one of the numbers on the left.") print(" 1: Count - Starts to count numbers from 0 to...
def reset(): # Define every pin again for i in range(2,10): Pin(i, Pin.OUT, value=0) def ByteDisplay(val=0): # Setting off all the LEDs. reset() # Setting the limiting values to the 0 - 255 as we have 8 bits. if 0 <= val <= 255: # Converting the input to binary. # I...
This code defines a menu-driven interface for controlling LED displays and sensor interactions. It resets hardware, displays task options, and executes corresponding functions based on user input, such as displaying numbers on LEDs, animating lights, counting button presses, measuring potentiometer values, and displayi...
def Menu(): # Call Menu with reseting PINs reset() # Menu instructions print("Tasks are given below, please enter one of the numbers on the left.") print(" 2: Byte Display - Number you enter will be displayed on the LEDs") print(" 3: Walking Lights") print(" 4: Walking & Fading Lights") ...
def _loadAdmin(self): return self._loadUser(self._adminEmail) def getWorkspaceID(self, workspaceName): wsId = None workspaces = self.getWorkspaces() for ws in workspaces: if ws["name"] == workspaceName: wsId = ws["id"] if wsId == None: rais...
This method adds a client to a specified workspace by sending a POST request. It retrieves the workspace ID, constructs the API URL, and submits the client name. If the request fails (e.g., 400 status), it returns EXISTS if the client already exists or ERR for other issues, logging errors. On success, it returns OK and...
def addClient(self, name, workspace): curUser = self._loadedUserEmail self._loadAdmin() wsId = self.getWorkspaceID(workspace) url = self.url + "/workspaces/%s/clients"%wsId params = {"name":name} rv = self._request(url, body=params, typ="POST") ...
def _loadAdmin(self): return self._loadUser(self._adminEmail) def getWorkspaceID(self, workspaceName): wsId = None workspaces = self.getWorkspaces() for ws in workspaces: if ws["name"] == workspaceName: wsId = ws["id"] if wsId == None: rais...
The main task of the code is to synchronize and retrieve client data from a Clockify workspace. If synchronization is enabled, it fetches client information via an API request, saves the results to a JSON file, and returns the client data. The process involves loading administrative privileges, identifying the workspac...
def getClients(self, workspace): if self._syncClients == True: curUser = self._loadedUserEmail self._loadAdmin() wsId = self.getWorkspaceID(workspace) url = self.url + "/workspaces/%s/clients"%wsId self.clients = self.multiGetRequest(url) ...
def _loadAdmin(self): return self._loadUser(self._adminEmail) def getWorkspaceID(self, workspaceName): wsId = None workspaces = self.getWorkspaces() for ws in workspaces: if ws["name"] == workspaceName: wsId = ws["id"] if wsId == None: rais...
The code retrieves user data from Clockify's API for a specified workspace, saves the results to a JSON file, and returns the user list. It checks if synchronization is needed, fetches users via a GET request, updates internal storage, and logs the process.
def getUsers(self, workspace): if self._syncUsers == True: curUser = self._loadedUserEmail self._loadAdmin() wsId = self.getWorkspaceID(workspace) url = self.url + "/workspace/%s/users"%wsId rv = self._request(url, typ="GET") ...
def _loadAdmin(self): return self._loadUser(self._adminEmail) def getWorkspaceID(self, workspaceName): wsId = None workspaces = self.getWorkspaces() for ws in workspaces: if ws["name"] == workspaceName: wsId = ws["id"] if wsId == None: rais...
The code retrieves user groups from a Clockify workspace API, saves them to a JSON file, and returns the list. It checks if synchronization is enabled, fetches data via an API request, logs the action, and stores results locally for later use.
def getUserGroups(self, workspace): if self._syncGroups == True: curUser = self._loadedUserEmail self._loadAdmin() self.userGroups = [] wsId = self.getWorkspaceID(workspace) url = self.urlWorking + "/workspaces/%s/userGroups"%wsId ...
def _loadAdmin(self): return self._loadUser(self._adminEmail) def getWorkspaceID(self, workspaceName): wsId = None workspaces = self.getWorkspaces() for ws in workspaces: if ws["name"] == workspaceName: wsId = ws["id"] if wsId == None: rais...
The code adds a user group to a specified workspace by making a POST request to an API endpoint. It checks the response status code: returning OK for success (201), EXISTS if the group already exists (400), or logging an error otherwise. The function also reloads the user data post-operation and returns the result.
def addUserGroup(self, groupName, workspace): curUser = self._loadedUserEmail self._loadAdmin() wsId = self.getWorkspaceID(workspace) url = self.urlWorking + "/workspaces/%s/userGroups/"%wsId params = {"name": groupName} rv = self._request(url, body=params, typ="...
def _loadAdmin(self): return self._loadUser(self._adminEmail) def getWorkspaceID(self, workspaceName): wsId = None workspaces = self.getWorkspaces() for ws in workspaces: if ws["name"] == workspaceName: wsId = ws["id"] if wsId == None: rais...
The code synchronizes and retrieves tags from a specified Clockify workspace by making an API request. If synchronization is enabled, it fetches tags, stores them in a JSON file, and returns the list. It also handles user context switching and logging.
def getTags(self, workspace): if self._syncTags == True: curUser = self._loadedUserEmail self._loadAdmin() self.tags = [] wsId = self.getWorkspaceID(workspace) url = self.url + "/workspaces/%s/tags"%wsId self.tags = self.multiG...
def _loadAdmin(self): return self._loadUser(self._adminEmail) def getWorkspaceID(self, workspaceName): wsId = None workspaces = self.getWorkspaces() for ws in workspaces: if ws["name"] == workspaceName: wsId = ws["id"] if wsId == None: rais...
The main task of the code is to add a tag to a specified workspace by sending a POST request to an API endpoint. It retrieves the workspace ID, constructs the request URL, and handles the response: returning OK on success (201), EXISTS if the tag already exists (400), or an error otherwise. It also updates tag synchron...
def addTag(self, tagName, workspace): curUser = self._loadedUserEmail self._loadAdmin() wsId = self.getWorkspaceID(workspace) url = self.url + "/workspaces/%s/tags"%wsId params = {"name": tagName} rv = self._request(url, body=params, typ="POST") if rv.sta...
def _loadAdmin(self): return self._loadUser(self._adminEmail) def _request(self, url, body=None, typ="GET"): headers={ 'X-Api-Key': self.apiToken} if typ == "GET": response=requests.get(url,headers=headers, params=body) elif typ == "POST": response=req...
The code adds a task to a specified project within a workspace by sending a POST request. It handles responses: returns OK on success (201), EXISTS if the task already exists (400), or logs an error otherwise. It also updates sync status and reloads the user after the operation.
def addTask(self, wsId, name, projectId, estimate): curUser = self._loadedUserEmail self._loadAdmin() #wsId = self.getWorkspaceID(workspace) url = self.url + "/workspaces/%s/projects/%s/tasks/"%(wsId, projectId) params = { "name": name, "projectId...
def _loadAdmin(self): return self._loadUser(self._adminEmail) def getWorkspaceID(self, workspaceName): wsId = None workspaces = self.getWorkspaces() for ws in workspaces: if ws["name"] == workspaceName: wsId = ws["id"] if wsId == None: rais...
The main task of the code is to retrieve tasks associated with a specific project in a given workspace by constructing an API URL using workspace and project IDs, then fetching the data via a multi-get request and returning the result.
def getTasksOnProject(self, workspace, projectName): curUser = self._loadedUserEmail self._loadAdmin() wsId = self.getWorkspaceID(workspace) pId = self.getProjectID(projectName, workspace) url = self.url + "/workspaces/%s/projects/%s/tasks"%(wsId, pId) self.pTasks = sel...
def _loadUser(self, userMail): mailChk = self._loadedUserEmail if mailChk == None: mailChk = "" if userMail.lower() == mailChk.lower(): return RetVal.OK userLoaded = False for user in self._APIusers: if user["email"].lower() == userM...
The main task of the code is to retrieve time entries for a specified user in a workspace, optionally filtered by project name and start time. It constructs a request URL with user and workspace identifiers, prepares query parameters, and executes a GET request. The function returns the retrieved data or an error statu...
def getTimeEntryForUser(self, userMail, workspace, description, projectName, start, timeZone="Z"): data = None rv = self._loadUser(userMail) if rv == RetVal.OK: wsId = self.getWorkspaceID(workspace) uId = self.userID ...
def getWorkspaceID(self, workspaceName): wsId = None workspaces = self.getWorkspaces() for ws in workspaces: if ws["name"] == workspaceName: wsId = ws["id"] if wsId == None: raise RuntimeError("Workspace %s not found. Available workspaces: %s"%(wor...
The main task of the code is to archive a project in Clockify via its API. It retrieves the workspace and project IDs, constructs an API URL, sends a GET request to archive the project, and returns a success status (OK) if the request succeeds (status code 200) or an error (ERR) with logging if it fails.
def archiveProject(self, projectName, workspace, skipPrjQuery=False): wsId = self.getWorkspaceID(workspace) pID = self.getProjectID(projectName, workspace, skipPrjQuery=skipPrjQuery) url = "https://api.clockify.me/api/workspaces/%s/projects/%s/archive"%(wsId, pID) rv = self._request(url,...
def getWorkspaceID(self, workspaceName): wsId = None workspaces = self.getWorkspaces() for ws in workspaces: if ws["name"] == workspaceName: wsId = ws["id"] if wsId == None: raise RuntimeError("Workspace %s not found. Available workspaces: %s"%(wor...
This method deletes a project by its name and workspace. It retrieves the workspace and project IDs, constructs a URL, sends a DELETE request, and returns OK if successful or ERR with a warning if failed.
def deleteProject(self, projectName, workspace, skipPrjQuery=False): wsId = self.getWorkspaceID(workspace) projectID = self.getProjectID(projectName, workspace, skipPrjQuery) url = self.url +"/workspaces/%s/projects/%s"%(wsId, projectID) rv = self._request(url, typ="DELETE") if r...
def _loadAdmin(self): return self._loadUser(self._adminEmail) def _loadUser(self, userMail): mailChk = self._loadedUserEmail if mailChk == None: mailChk = "" if userMail.lower() == mailChk.lower(): return RetVal.OK userLoaded = False for...
This code creates a project in a specified workspace with parameters like name, client, visibility, and billing settings. It handles user permissions, retrieves necessary IDs, sends a POST request to an API endpoint, and processes responses (success, existence conflict, forbidden, or error). It logs warnings for missin...
def addProject(self, name, client, workspace, isPublic=False, billable=False, color="#f44336", memberships=None, hourlyRate=None, manager=""): curUser = self._loadedUserEmail if manager == "": if isPublic == False: admin = self._adminEm...
def getWorkspaceID(self, workspaceName): wsId = None workspaces = self.getWorkspaces() for ws in workspaces: if ws["name"] == workspaceName: wsId = ws["id"] if wsId == None: raise RuntimeError("Workspace %s not found. Available workspaces: %s"%(wor...
This function deletes a client from a specified workspace in the Clockify API by retrieving the workspace and client IDs, sending a DELETE request to the API endpoint, and returning success or error status. It updates a sync flag on success and logs warnings for errors.
def deleteClient(self, clientName, workspace, skipCliQuery=False): wsId = self.getWorkspaceID(workspace) clId = self.getClientID(clientName, workspace, skipCliQuery) url = "https://api.clockify.me/api/workspaces/%s/clients/%s"%(wsId, clId) rv = self._request(url, typ="DELETE") if...
def getUsersInProject(self, wsId, pId): userIds = [] url = self.urlWorking + "/workspaces/%s/projects/%s/users"%(wsId, pId) rv = self._request(url, typ="GET") userIds = rv.json() self.logger.info("Finished getting users already assigned to the project.") return userIds ...
This function adds user groups to a project in a Clockify workspace by retrieving existing project users, validating group IDs, collecting user group IDs, and sending a POST request with user and group IDs. It handles API responses, returning status codes like OK, EXISTS, FORBIDDEN, or ERR based on the result.
def addGroupsToProject(self, wsName, wsId, pId, wsGroupIds, pGroups): # API fields to POST: {userIds = [], userGroupIds = []} # From: https://clockify.github.io/clockify_api_docs/#operation--workspaces--workspaceId--projects--projectId--team-post url = self.urlWorking + "/workspaces/%s/project...
def _loadUser(self, userMail): mailChk = self._loadedUserEmail if mailChk == None: mailChk = "" if userMail.lower() == mailChk.lower(): return RetVal.OK userLoaded = False for user in self._APIusers: if user["email"].lower() == userM...
This function adds a time entry to a workspace by converting project/task names to IDs, checking for existing entries with similar parameters, and sending a POST request if no duplicates are found. It handles user authentication, time formatting, tag mappings, and returns success/failure status along with response data...
def addEntry(self, start, description, projectName, userMail, workspace, timeZone="Z", end=None, billable=False, tagNames=None, taskName=None): rv = self._loadUser(userMail) data = None if rv == RetVal.OK: wsId = self.getWorkspaceID(workspace) u...
def getTimeEntryForUser(self, userMail, workspace, description, projectName, start, timeZone="Z"): data = None rv = self._loadUser(userMail) if rv == RetVal.OK: wsId = self.getWorkspaceID(workspace) uId = self.userID ...
The main task of the code is to delete all time entries for a specified user in a given workspace. It repeatedly retrieves entries, logs each deletion, and removes them one by one until no more entries remain. The function returns the total number of entries processed, ensuring all associated records are removed while ...
def deleteEntriesOfUser(self, userMail, workspace): while True: rv, entries = self.getTimeEntryForUser(userMail, workspace, "", None, None, "") numEntries = 0 if rv == RetVal.OK: curUser = self._loadedUserEmail rv = self._loadAdmin() ...
def _loadUser(self, userMail): mailChk = self._loadedUserEmail if mailChk == None: mailChk = "" if userMail.lower() == mailChk.lower(): return RetVal.OK userLoaded = False for user in self._APIusers: if user["email"].lower() == userM...
The main task of the code is to delete all projects from every user in the `self._APIusers` list for a specified workspace. It iterates through each user, loads their data, retrieves their projects, logs each deletion step, and removes projects one by one using `deleteProject()`. After processing all users, it restores...
def deleteAllProjects(self, workspace): curUser = self._loadedUserEmail for user in self._APIusers: self._loadUser(user["email"]) self.logger.info("Deleting all project from user %s"%user["email"]) prjs = self.getProjects(workspace) idx = 0 num...
def _loadUser(self, userMail): mailChk = self._loadedUserEmail if mailChk == None: mailChk = "" if userMail.lower() == mailChk.lower(): return RetVal.OK userLoaded = False for user in self._APIusers: if user["email"].lower() == userM...
The method deletes all clients associated with each user in the API users list for a specified workspace. It iterates through each user, loads their data, retrieves their clients, and sequentially deletes each client while logging progress. After processing all users, it restores the original user context.
def deleteAllClients(self, workspace): curUser = self._loadedUserEmail for user in self._APIusers: self._loadUser(user["email"]) self.logger.info("Deleting all clients from user %s"%user["email"]) clis = self.getClients(workspace) idx = 0 numCl...
def getIPclass(ip_str): first_byte = int(ip_str.split(".")[0]) if first_byte < 128: return ['255', 24] elif first_byte < 192: return ['255.255', 16] else: return ['255.255.255', 8] def calculate_borrow_bits(custom_host_bit_len, class_host_bit_len): borrowed_bit_len = class_ho...
The code calculates subnet masks and network addresses based on user-provided IP addresses and subnet requirements. It determines the IP class, computes borrowed bits for subnetting, constructs the subnet mask, and calculates required subnets with host ranges. The main task involves IP subnetting, mask generation, and ...
def main(): ip = input("Enter IP address (Ex: 192.168.100.0/25): ") ip = ip.split("/") ip_class_info = getIPclass(ip[0]) borrowed_bits_info = calculate_borrow_bits(32 - int(ip[1]), ip_class_info[1]) subnet_mask = ip_class_info[0] + calculate_borrow_dec(borrowed_bits_info[0], borrowed_bits_info[1], b...
def contestant_ratings(before): if before == "before": handles = get_perf_handles() else: handles = get_reg_handles() for handle in handles: if handle not in rating_store or "score" not in rating_store[handle]: sleep(0.01) try: j = get_user_sta...
The code predicts and updates contestant ratings based on performance in a competition. It calculates average ratings, volatility, expected performance using normal distributions, and adjusts ratings by comparing actual performance against expectations. It dynamically updates scores, ranks, and volatility with weighted...
def predictor(handle, extra, before): _ = contestant_ratings(before) # ave rating rave = 0 for k in rating_store: rave += int(rating_store[k]["rating"]) rave /= len(rating_store) # cf rtemp = 0 vtemp = 0 for k in rating_store: vtemp += float(ra...
def _parse_command_line(): # parse the command line arguments args_parser = argparse.ArgumentParser() args_parser.add_argument( "--base_dir", type=str, required=True, help="path to the base output directory", ) args_parser.add_argument( "--labels", ty...
This function downloads a dataset, either with or without segmentation data, based on command-line arguments. It validates the required '--format' parameter and delegates to 'download_segmentation_dataset' or 'download_dataset' using specified parameters like base directory, labels, exclusions, format, metadata directo...
def _entrypoint_download_dataset(): args = _parse_command_line() # we must have an annotation format specified if args["format"] is None: raise argparse.ArgumentError(None, f"Missing the required '--format' argument") if args["include_segmentation"]: download_segmentation_dataset( ...
def _read_variable(name: str) -> str: if name in os.environ: val = os.environ[name] logger.info("Took from environment {}".format(val)) return val return input("Enter your {}:".format(name)) def _init_dashboard_list(uid_list, base_url, r_headers): dashboards_list = [] for uid in ...
The main task of the code is to migrate Grafana dashboards to Logz.io by reading environment variables, validating inputs, fetching dashboards from Grafana, processing their structure, and uploading them to Logz.io with error handling. It includes input validation, folder creation in Logz.io, schema checks, and logging...
def main(): logger.info('Configure your environment variables') logger.info('Your grafana host without protocol specification (e.g. localhost:3000). ') GRAFANA_HOST = _read_variable('GRAFANA_HOST') logger.info('Your grafana editor/admin API key, find or create one under Configuration -> API keys.') ...
def get_constraint_batch_labels(self, input_ids, labels): batch_size = input_ids.size(0) res_text = [] for i in range(batch_size): constraint_output = self.gen_constraint_label(input_ids[i], labels[i]) res_text.append(constraint_output) return res_text def pad_lab...
The code computes multiple loss components during a forward and backward pass of a neural network model. It generates constraint-based labels, calculates forward and backward losses using modified inputs/labels, and adds contrastive losses. The total loss combines these terms for training, likely for a task involving c...
def forward(self, input_ids, labels): constraint_labels = self.get_constraint_batch_labels(input_ids, labels) self.model.train() constraint_labels_pad = torch.tensor(self.pad_labels(constraint_labels)).cuda() forward_outputs = self.model(input_ids=input_ids, labels=constraint_labels_pad)...
def initialize_with_random(dim): w = np.random.randn(dim,1 ) * 0.01 print("Shape of initialized w:", w.shape) b = 0 assert(w.shape == (dim,1)) assert(isinstance(b,float) or isinstance(b,int)) return w,b def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): co...
The code trains a linear model using gradient descent on training data, evaluates it on test data, and returns parameters, predictions, costs, and accuracy metrics for both training and testing sets.
def model(features_train, label_train, features_test, label_test, num_iterations=3000, learning_rate=0.5, print_cost=False): w, b = initialize_with_random(features_train.shape[0]) params, grads, costs = optimize(w, b, features_train, label_train, num_iterations, learning_rate, print_cost=False) w = params...
def createGame(nrows = NROWS, ncols = NCOLS): NROWS = nrows NCOLS = ncols game = np.zeros((nrows, ncols), dtype = int) return game def MCTS(game, player, iter, root = None, lastMove = [-1, -1]): for it in range(iter): # print("MCTS iter : ", it) node = root state = copy...
This code simulates a two-player game using Monte Carlo Tree Search (MCTS), where players alternate turns to make moves based on MCTS strategies with different iteration counts (iter1/iter2) and exploration parameter C. The function determines the winner or draw, returning +1, -1, or 0 based on which player (MC40/MC200...
def playGame(numGame, iter1, iter2, C = sqrt(2)): game = createGame() node1 = Node(game, 1, C = C) node2 = Node(game, -1, C = C) col1 = -1 col2 = -1 lastMove1 = [-1, -1] lastMove2 = [-1. -1] playername1, playername2 = None, None player = 1 if(numGame >= 50): playername1 =...
def ElongationInit(self,logfile): l='\n\n*****************\n\nExtensionRound '+str(self.roundNum)+'\n' logfile.writelines(l) print (l) self.roundDir=self.base.outfile+'/round'+str(self.roundNum) if not os.path.exists(self.roundDir): os.makedirs(self.roundDir) self.lastRoundDir=self.base.outfile+'/round'+...
This code performs iterative sequence elongation by extending contigs using reads, logging results, and generating output files. It initializes parameters, processes extension rounds, checks for valid extensions, updates lengths, and writes final sequences to a FASTA file. Depending on extension outcomes, it handles ca...
def __init__(self,base): self.base=base self.roundNum=1 self.usedReads=[] self.extensionLen=0 self.endSignal=False logfile=open(self.base.log,'w') summaryfile=open(self.base.summary,'w') while self.endSignal==False: self.ElongationInit(logfile) self.lastRoundUsedReads=self.ElongateSeq(logfile,sum...
def readlog(self): logfilet=open(self.log,'r') self.selectContigNote='' for row in logfilet: row1=row.rstrip().split('\t') if row1[0]=='hifiasmDir': self.hifiasmDir=row1[1] elif row1[0]=='hifiasmCommand': self.hifiasmCommand=row1[1] elif row1[0]=='hifiasmResult': self.hifiasmResult=row1[1]...
The code processes extension reads to generate or retrieve contigs using Hifiasm, logs detailed parameters (e.g., command, results, alignment data), and handles fallback methods if Hifiasm fails. It manages contig selection, alignment validation, and writes structured logs for tracking assembly outcomes and extension m...
def __init__(self,ExtensionReads): self.extensionReads=ExtensionReads self.log=self.extensionReads.roundInput.elongation.roundDir+"/extensionConthgs.log" self.extensionSequence=self.extensionReads.roundInput.elongation.roundDir+"/extensionSequence."+self.extensionReads.roundInput.elongation.base.tag+".fa" self....
def roundInit(self): self.projectOut=self.project+"/DG"+str(self.projectID) if not os.path.exists(self.projectOut): os.makedirs(self.projectOut) self.projectData=self.projectOut+"/data" if not os.path.exists(self.projectData): os.makedirs(self.projectData) self.projectTerminalCtg=self.projectOut+"/data/...
This function processes genomic scaffolds iteratively. It initializes parameters, runs rounds until all scaffolds are placed or the last round completes. Each round checks for existing data; if absent, it extends scaffolds via elongation. After processing, it increments the project ID and removes temporary files to man...
def CtgLinkerPipline(self): self.scaffoldID=1 self.projectID=1 self.Lastround=False while self.unplacednum >0 or self.Lastround==False: self.roundInit() if os.path.exists(self.projectfasta)==True and os.path.getsize(self.projectfasta)!=0: self.skipRound() else: self.elongationDG() self.proje...
def readlog(self): logfilet=open(self.log,'r') for row in logfilet: row1=row.rstrip().split('\t') if row1[0]=='potentialExtensionReadsAln': self.potentialExtensionReadsAln=row1[1] elif row1[0]=='minimap2Command': self.minimap2Command=row1[1] elif row1[0]=='minimap2Output': self.minimap2Outpu...
This code processes biological sequencing reads by aligning them using Minimap2, filtering based on alignment quality and length thresholds, and selecting valid extension reads. It adjusts parameters iteratively if no valid reads are found, logs detailed outputs, and stores results for downstream analysis in a round-ba...
def __init__(self,roundInput,lastRoundUsedReads,usedReads): self.roundInput=roundInput self.lastRoundUsedReads=lastRoundUsedReads self.usedReads=usedReads self.note='' self.extensionReads=self.roundInput.elongation.roundDir+"/extensionReads."+self.roundInput.elongation.base.tag+".fa" self.log=self.roundInpu...
def _get_I_vol_4(self): #---------------------------------------------------------------- # the fourth order volumetric-identity tensor #---------------------------------------------------------------- delta = identity(3) I_vol_ijkl = (1.0 / 3.0) * einsum('ij,kl -> ijkl', delta,...
This function computes the fourth-order secant stiffness tensor $ S_{ijkl} $ for nonlinear elasticity using the initial elastic tensor $ S_0 $, state variables $ d_n $, and material parameters. It constructs correction terms $ D_{ijkl} $ via projection operators and material weight functions, then combines them with $ ...
def _get_S_3_tns(self, sctx, eps_app_eng, sigma_kk): #---------------------------------------------------------------------- # Returns the fourth order secant stiffness tensor (cf. [Wu.2009], Eq.(34)) #---------------------------------------------------------------------- K0 = self.E / (...
def _get_phi_arr(self, sctx, eps_app_eng, sigma_kk): #------------------------------------------------------------- # Returns a list of the integrity factors for all microplanes. #------------------------------------------------------------- phi_arr = 1. - \ self._get_state_v...
The function computes the fourth-order secant stiffness tensor $ S_{1}^{ijkl} $ using a combination of volumetric and deviatoric components. It calculates bulk modulus $ K_0 $ and shear modulus $ G_0 $ from material properties, retrieves state variables $ \phi_n $, and combines them with precomputed fourth-order tensor...
def _get_S_1_tns(self, sctx, eps_app_eng, sigma_kk): #---------------------------------------------------------------------- # Returns the fourth order secant stiffness tensor (cf. [Wu.2009], Eq.(29)) #---------------------------------------------------------------------- K0 = self.E / (...
def _get_I_vol_4(self): #---------------------------------------------------------------- # the fourth order volumetric-identity tensor #---------------------------------------------------------------- delta = identity(3) I_vol_ijkl = (1.0 / 3.0) * einsum('ij,kl -> ijkl', delta,...
This function computes the fourth-order secant stiffness tensor (S_4_ijkl) for double orthotropic materials. It combines bulk modulus (K0), shear modulus (G0), volumetric/deviatoric identity tensors, and a modified strain-dependent tensor (D_bar_ij) through a weighted sum involving Einsum operations. The result represe...
def _get_S_4_tns(self, sctx, eps_app_eng, sigma_kk): #---------------------------------------------------------------------- # Returns the fourth order secant stiffness tensor (double orthotropic) #---------------------------------------------------------------------- K0 = self.E / (1. ...
def _get_I_vol_4(self): #---------------------------------------------------------------- # the fourth order volumetric-identity tensor #---------------------------------------------------------------- delta = identity(3) I_vol_ijkl = (1.0 / 3.0) * einsum('ij,kl -> ijkl', delta,...
This function computes the fourth-order secant stiffness tensor for a double orthotropic N-T split model, combining volumetric and deviatoric components scaled by effective moduli $E_N$ and $E_T$. It uses tensor operations involving identity tensors, stress-strain relationships, and anisotropic corrections derived from...
def _get_S_5_tns(self, sctx, eps_app_eng, sigma_kk): #---------------------------------------------------------------------- # Returns the fourth order secant stiffness tensor (double orthotropic N-T split) #---------------------------------------------------------------------- E_N = se...
def _get_I_vol_4(self): #---------------------------------------------------------------- # the fourth order volumetric-identity tensor #---------------------------------------------------------------- delta = identity(3) I_vol_ijkl = (1.0 / 3.0) * einsum('ij,kl -> ijkl', delta,...
The main task of the code is to compute the fourth-order secant stiffness tensor $ S_{2} $ using the given material parameters $ E $, $ \nu $, and input variables $ sctx $, $ \varepsilon_{\text{app\_eng}} $, $ \sigma_{kk} $. It combines volumetric and deviatoric components via tensor operations involving the bulk modul...
def _get_S_2_tns(self, sctx, eps_app_eng, sigma_kk): #---------------------------------------------------------------------- # Returns the fourth order secant stiffness tensor (cf. [Wu.2009], Eq.(31)) #---------------------------------------------------------------------- K0 = self.E / (...
def parseargs(): """Parse our command line arguments, returns a Namespace of results.""" parser = argparse.ArgumentParser() parser.add_argument("yaml", help="Path to YAML file to load") args = parser.parse_args() return args def abspath(frompath, relpath): """Gets the absolute path of relpath fr...
The code's main task is to load a YAML configuration file, locate and parse an SVD file using the YAML's specifications, apply included YAML files, process device data from the SVD, and output the modified SVD with a ".patched" suffix. It ensures the YAML contains an "_svd" key, constructs the SVD path, and updates the...
def main(): # Load the specified YAML root file args = parseargs() with open(args.yaml, encoding='utf-8') as f: root = yaml.safe_load(f) root["_path"] = args.yaml # Load the specified SVD file if "_svd" not in root: raise RuntimeError("You must have an svd key in the root YA...
def spec_ind(spec): """ Find left and right indices of enumeration token in specification string. """ li1 = spec.find("*") li2 = spec.find("?") li3 = spec.find("[") li = li1 if li1 > -1 else li2 if li2 > -1 else li3 if li3 > -1 else None ri1 = spec[::-1].find("*") ri2 = spec[::-1].fi...
This code collects registers with similar properties into an array by validating their offsets and bitmasks, then configures array parameters like dim, dimIndex, and dimIncrement in the XML structure while removing redundant register entries.
def collect_in_array(self, rspec, rmod): """Collect same registers in peripheral into register array.""" registers = [] li, ri = spec_ind(rspec) for rtag in list(self.iter_registers(rspec)): rname = rtag.findtext('name') registers.append([rtag, rname[li:len(rname)...
def spec_ind(spec): """ Find left and right indices of enumeration token in specification string. """ li1 = spec.find("*") li2 = spec.find("?") li3 = spec.find("[") li = li1 if li1 > -1 else li2 if li2 > -1 else li3 if li3 > -1 else None ri1 = spec[::-1].find("*") ri2 = spec[::-1].fi...
The code groups registers into clusters by validating their offsets and bitmasks for consistency. It constructs XML clusters, adjusts register names and addresses, and raises errors if checks fail. Registers are moved under the cluster, with parameters like dim, dimIndex, and dimIncrement set. The task ensures proper h...
def collect_in_cluster(self, cname, cmod): """Collect registers in peripheral into clusters.""" rdict = {} first = True check = True rspecs = [r for r in cmod if r != "description"] for rspec in rspecs: registers = [] li, ri = spec_ind(rspec) ...
def consensus(score, offset, sequence1, sequence2): return ( sequence2[0 : max(0, offset)] + sequence1 + sequence2[len(sequence1) + offset :] ) def find_best_match(sequence, others): return max( [ find_best_offset(sequence, sequence2) for sequence2 in others ...
The code recursively assembles a consensus sequence by iteratively finding the best match between the input sequence and a list of alternatives, then repeating the process with the remaining alternatives until all are processed. It uses consensus results from matches to build a final sequence through recursive calls.
def assemble(sequence, others): return ( consensus(*find_best_match(sequence, others)) if len(others) == 1 else assemble( consensus(*find_best_match(sequence, others)), [y for y in others if y != find_best_match(sequence, others)[2]], ) )
def find_command(command: str, msg: Optional[str] = None) -> str: return run_pipe("which", command, msg=msg).read().strip() def run_pipe(*args: str, msg: Optional[str] = None, verbose: bool = False, **kwargs: Any) -> TextIO: p = run(*args, msg=msg, verbose=verbose, stdout=PIPE, universal_newlines=True, **kwargs...
The main task of the code is to configure and build Kvrocks and its components using CMake, with options to set compiler, proxy, build type, and parallelism. It checks dependencies, validates CMake version, applies build configurations, and executes the build process, skipping it if specified.
def build(dir: str, jobs: Optional[int], ghproxy: bool, ninja: bool, unittest: bool, compiler: str, cmake_path: str, D: List[str], skip_build: bool) -> None: basedir = Path(__file__).parent.absolute() find_command("autoconf", msg="autoconf is required to build jemalloc") cmake = find_command(cmak...
def find_command(command: str, msg: Optional[str] = None) -> str: return run_pipe("which", command, msg=msg).read().strip() def run_pipe(*args: str, msg: Optional[str] = None, verbose: bool = False, **kwargs: Any) -> TextIO: p = run(*args, msg=msg, verbose=verbose, stdout=PIPE, universal_newlines=True, **kwargs...
This function uses clang-format to either fix code formatting issues or check for inconsistencies. It verifies the clang-format version, issues a warning if the version exceeds 12 (recommending version 12 for CI consistency), and executes the tool on source files with options for fixing (-i) or dry-run validation (--dr...
def clang_format(clang_format_path: str, fix: bool = False) -> None: command = find_command(clang_format_path, msg="clang-format is required") version_res = run_pipe(command, '--version').read().strip() version_str = re.search(r'version\s+((?:\w|\.)+)', version_res).group(1) version = check_version(ve...
def find_command(command: str, msg: Optional[str] = None) -> str: return run_pipe("which", command, msg=msg).read().strip() def run_pipe(*args: str, msg: Optional[str] = None, verbose: bool = False, **kwargs: Any) -> TextIO: p = run(*args, msg=msg, verbose=verbose, stdout=PIPE, universal_newlines=True, **kwargs...
This function executes clang-tidy on a specified directory using LLVM's run-clang-tidy script. It verifies required tools exist, checks clang-tidy version, ensures compile_commands.json is present, and runs analysis on 'kvrocks/src/'. Options include parallel jobs and specifies the clang-tidy binary path.
def clang_tidy(dir: str, jobs: Optional[int], clang_tidy_path: str, run_clang_tidy_path: str) -> None: # use the run-clang-tidy Python script provided by LLVM Clang run_command = find_command(run_clang_tidy_path, msg="run-clang-tidy is required") tidy_command = find_command(clang_tidy_path, msg="clang-tidy ...
def find_command(command: str, msg: Optional[str] = None) -> str: return run_pipe("which", command, msg=msg).read().strip() def run_pipe(*args: str, msg: Optional[str] = None, verbose: bool = False, **kwargs: Any) -> TextIO: p = run(*args, msg=msg, verbose=verbose, stdout=PIPE, universal_newlines=True, **kwargs...
This function installs and runs golangci-lint for Go code testing. It locates the GOPATH, checks for the golangci-lint binary in $GOPATH/bin, downloads and installs it if missing, then executes it on Go test cases in the 'tests/gocase' directory with verbose output.
def golangci_lint() -> None: go = find_command('go', msg='go is required for testing') gopath = run_pipe(go, 'env', 'GOPATH').read().strip() bindir = Path(gopath).absolute() / 'bin' binpath = bindir / 'golangci-lint' if not binpath.exists(): output = run_pipe('curl', '-sfL', 'https://raw.git...
def write_version(release_version: str) -> str: version = release_version.strip() if SEMVER_REGEX.match(version) is None: raise RuntimeError(f"Kvrocks version should follow semver spec, got: {version}") with open('src/VERSION.txt', 'w+') as f: f.write(version) return version def find_c...
The main task of the code is to automate the preparation of a source package for a software release. It writes the version to a file, commits and tags the code with Git, creates a compressed source tarball, signs it with GPG for authenticity, and generates a SHA512 checksum for integrity verification. This ensures a se...
def package_source(release_version: str) -> None: # 0. Write input version to VERSION file version = write_version(release_version) # 1. Git commit and tag git = find_command('git', msg='git is required for source packaging') run(git, 'commit', '-a', '-m', f'[source-release] prepare release apache-...
def find_command(command: str, msg: Optional[str] = None) -> str: return run_pipe("which", command, msg=msg).read().strip() def write_version(release_version: str) -> str: version = release_version.strip() if SEMVER_REGEX.match(version) is None: raise RuntimeError(f"Kvrocks version should follow sem...
(The main task of the code is to generate a software package using `fpm` by building the project, organizing binaries and configurations into a directory structure, and invoking `fpm` with specified parameters like package type, version, prefixes, and metadata to create a distributable package.)
def package_fpm(package_type: str, release_version: str, dir: str, jobs: Optional[int]) -> None: fpm = find_command('fpm', msg=f'fpm is required for {package_type} packaging') version = write_version(release_version) build(dir=dir, jobs=jobs, ghproxy=False, ninja=False, unittest=False, skip_build=False, c...
def FindingScreenSize_(self): app = QtWidgets.QApplication(sys.argv) screen = app.primaryScreen() size = screen.size() Screensize = (size.width()/96, size.height()/96) return Screensize def Hist(self): final_size = self.FindingScreenSize_() self.data.hist(figsize=...
This code initializes a plotter class to generate visualizations (histograms, line/scatter plots) based on input data and parameters. It validates column names and plot types, raises errors for missing inputs, and sets figure size dynamically.
def __init__(self, data = None,type_of_plot = "", column_values_for_x = None, column_values_for_y = None,alpha = None): self.data = data self.alpha = alpha self.x = column_values_for_x self.y = column_values_for_y self.type_of_plot = type_of_plot plt.rcParams["figure.figs...
def __receive_message(self, client_socket): try: message_header = client_socket.recv(self.HEADER_LENGTH) if not len(message_header): return False message_length = int(message_header.decode('utf-8').strip()) return {'header': message_header, 'data':...
This code runs a server that uses asynchronous I/O with `select.select()` to monitor multiple client sockets. It accepts new connections, receives messages, and broadcasts them to relevant chat rooms. It handles commands like 'send' and 'exit', manages user data, and cleans up disconnected clients or errors. The server...
def run_server(self): while True: # Calls Unix select() system call or Windows select() WinSock call with three parameters: # - rlist - sockets to be monitored for incoming data # - wlist - sockets for data to be send to (checks if for example buffers are not full and soc...
def __start_server(self): try: self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((self.IP, self.PORT)) self.server_socket.listen() sel...
This code initializes a server node in a distributed system, setting up communication parameters, starting a server and broadcast listener, broadcasting a 'join-server' message, and assuming leadership if no other servers are detected within 3 seconds.
def __init__(self, header_len, ip, port, broadcast_port) -> None: self.HEADER_LENGTH = header_len self.IP = ip self.PORT = int(port) self.BROADCAST_PORT = int(broadcast_port) self.leader = False self.participant = False self.leader_id = "" self.servers= {...
def create_sudoku_board(root_n, n, difficulty, random_board=False): """ returns the sudoku board of size x by y, and this will only work if the sizes are legit sudoku board size the "ran" variable stands for random and indicates if it should return a randomized board or the default board """ ...
The main task of the code is to generate and solve Sudoku puzzles by creating an empty board, using either an exact cover algorithm or backtracking. It allows user interaction to view the board, control solution limits, and check for unique solutions, while displaying results visually via images and console output.
def main(): # modifiable parameters root_n, n = 3, 9 randomize, print_bool = False, True limit, sol_counter = 100, 0 #making a filled sudoku board and removing values to get a empty board to be solved board = create_sudoku_board(root_n, n, random.randint(1,6), random_board=randomize) if inpu...
def fetch_candidate_keys(file_name): folder = file_name.replace(' ','_').replace('-','_').replace(".pdf","") with open(f'./textbox_working_textract/{folder}/tagged_margins_output.json', 'rb') as f: outputj = j.load(f) key_set = [] found_keys = [] page_cnt = 0 for page in outputj: ...
The main task of the code is to extract and process key-value pairs from a PDF document by matching candidate keys against extracted text items, cleansing duplicates/page numbers, and saving structured JSON outputs. It uses exact matching, filtering, and post-processing to organize results, returning item counts and me...
def build_extractor(file_name): folder = file_name.replace(' ','_').replace('-','_').replace(".pdf","") find_method = 'n/a' keys = fetch_candidate_keys(file_name=file_name) item_list = gen_item_list_output(file_name=file_name) found_keys = [] kvset = [] for candidate_key_set in keys: ...
def del_working_files(folder_name): folder = folder_name for filename in os.listdir(folder): file_path = os.path.join(folder, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): ...
The function processes a PDF file using AWS Textract to extract text and bounding boxes, handling both regular and bold text variants. It creates directories, parallelizes processing with ThreadPoolExecutor, cleans output, merges results, and saves structured JSON outputs for text analysis.
def collect_textract_all_pages(file_name,bold=None): tclient = boto3.client('textract') if bold is None: img_folder = './pdf_images/'+file_name.replace(' ','_').replace('-','_').replace(".pdf","") textbox_folder = './textbox_working_textract/'+file_name.replace(' ','_').replace('-','_').replac...
def checkForPinsAndChecks(self): pins = [] checks = [] inCheck = False if self.whiteToMove: enemyColor = 'b' allyColor = 'w' startRow = self.whiteKingLocation[0] startCol = self.whiteKingLocation[1] else: enemyColor = 'w...
This function generates valid chess moves by checking for pins and checks, filtering moves to ensure the king isn't exposed. If in check, it handles single/double checks by blocking or moving the king. It includes castling moves and determines checkmate/stalemate if no valid moves exist.
def getValidMovesAdvanced(self): moves = [] self.inCheck, self.pins, self.checks = self.checkForPinsAndChecks() if self.whiteToMove: kingRow = self.whiteKingLocation[0] kingCol = self.whiteKingLocation[1] else: kingRow = self.blackKingLocation[0] ...
def retranslateUi(self, Dialog): # _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "pyRotateDisplay Settings")) self.displayLabel.setText(_translate("Dialog", "Display:")) self.currentModeLabel.setText(_translate("Dialog", "CurrentMode:")) ...
This code sets up a dialog UI with form elements for selecting display settings, COM ports, and handshake configurations. It creates a window with OK/Cancel buttons, a form layout containing labels and input fields, and connects UI interactions to handler functions. The dialog initializes and refreshes combo boxes for ...
def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(402, 163) self.buttonBox = QtWidgets.QDialogButtonBox(Dialog) self.buttonBox.setGeometry(QtCore.QRect(50, 130, 341, 32)) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardB...
def setButtonsEnabled(self,flag): for button in self.buttonBox.buttons(): button.setEnabled(flag) def refreshDisplayCombo(self): selected = self.display.selected self.displayComboBox.clear() devList = self.display.getDeviceList() devList = list(map(lambda dic : \ ...
This method handles user acceptance in a GUI, validates a handshake input, manages Arduino connection states, and updates UI elements. It warns if the handshake field is empty, initiates a handshake thread if disconnected, or disables/re-enables buttons and refreshes device/COM port selections when connected, adjusting...
def accept(self): print("accepted!") if str(self.handShakeLineEdit.text())=="": QtWidgets.QMessageBox.warning( self.Dialog, "HandShake string empty.", "Put HandShake string." ) elif not self.arduino.connected: se...
def path_is_hidden(self, path): parts = Path(path).parts path = '' for part in parts: path = os.path.join(path, part) if self.os_path.is_hidden(path): return True return False def update_paths_dict(self, file_path, update_value): if not sel...
This function recursively updates two dictionaries with directory and file paths from a base directory, excluding hidden directories. It traverses the directory tree using os.walk, checks for non-hidden directories, updates the paths dictionary with directory paths, and adds each file's full path to the files dictionar...
def update_files_paths_dict(self, base_directory, update_value): for (dir_path, dir_names, file_names) in os.walk(base_directory): if not self.path_is_hidden(dir_path): self.update_paths_dict(dir_path, update_value) for filename in file_names: file...
def update_files_paths_dict(self, base_directory, update_value): for (dir_path, dir_names, file_names) in os.walk(base_directory): if not self.path_is_hidden(dir_path): self.update_paths_dict(dir_path, update_value) for filename in file_names: file...
This code initializes a synchronization process between a source and destination directory. It sets up parameters, scans both locations to build mappings of files and paths, and then executes synchronization of files and directories, logging progress. The task involves preparing for data synchronization, tracking files...
def __init__(self, source, destination, dry_run, can_delete, logger, os_path): self.source = source self.destination = destination self.dry_run = dry_run self.can_delete = can_delete self.logger = logger self.os_path = os_path self.pathsDict = dict() self....
def handle_process(dir,processed_dir,name): if not os.path.exists(processed_dir): valid_id_arr,rgbpcds_arr,poses_arr = preprocess(name,1024) np.savez(processed_dir,valid_id=valid_id_arr, rgbpcd=rgbpcds_arr,pose=poses_arr) if len(os.listdir(dir)) == 0: unpack_DATA(processed_dir,dir) ...
The main task of the code is to process training and validation datasets, train a PoseNet model for pose estimation, and evaluate its performance. It loads preprocessed data, initializes the model with optional weight loading, sets up training parameters (optimizer, scheduler), and iterates over epochs to train the mod...
def mainprocess(debug:bool): processed_val_dir = '../HW2DATA/processed_val.npz' val_dir = '../HW2DATA/val' handle_process(val_dir,processed_val_dir,'val') processed_train_dir = '../HW2DATA/processed_train.npz' train_dir = '../HW2DATA/train' handle_process(train_dir,processed_train_dir,'train') ...
def handle_process(dir,processed_dir,name): if not os.path.exists(processed_dir): valid_id_arr,rgbpcds_arr,poses_arr = preprocess(name,1024) np.savez(processed_dir,valid_id=valid_id_arr, rgbpcd=rgbpcds_arr,pose=poses_arr) if len(os.listdir(dir)) == 0: unpack_DATA(processed_dir,dir) ...
The code processes training and validation data, initializes a PoseNet model for pose estimation, loads pre-trained weights if available, trains the model with Adam optimizer and exponential learning rate decay, evaluates on validation/test sets, and saves checkpoints. Debug mode uses a subset of data for faster testin...
def mainprocess(debug:bool): processed_val_dir = '../HW2DATA/processed_val.npz' val_dir = '../HW2DATA/val' handle_process(val_dir,processed_val_dir,'val') processed_train_dir = '../HW2DATA/processed_train.npz' train_dir = '../HW2DATA/train' handle_process(train_dir,processed_train_dir,'train') ...
def loadModelMatrix(self, translate=(0,0,0),scale=(1,1,1),rotate=(0,0,0)): translate_matrix = [ [1,0,0,translate[0]], [0,1,0,translate[1]], [0,0,1,translate[2]], [0,0,0,1] ] scale_matrix = [ [scale[0],0,0,0], [0,sca...
This function loads an .obj 3D model, applies transformations (translate, scale, rotate), processes vertices/faces with material/textures, calculates lighting intensity using normals, and renders triangles with shading. It handles material colors, texture mapping, and lighting effects to display the model.
def glLoadObjModel(self, file_name, mtl=None, texture=None, translate=(0,0, 0), scale=(1,1, 1), rotate =(0,0,0)): '''Load and Render .obj file''' #Reads .obj file self.loadModelMatrix(translate, scale, rotate) self.glPipelineMatrix() if not mtl: model = ObjRe...
def run_auxiliary_command(): parent_conn, child_conn = Pipe() command = Process(target = cmd.run_command, args = (configuration.get_auxiliary_command(), child_conn, )) command.start() pid = parent_conn.recv() return pid def measure_baseline_wattage(): check_seconds = configuration.get_base_check...
The code's main task is to measure CPU, GPU, and power usage during a process, log data to files, and generate reports. It initializes configurations, runs auxiliary processes, captures baseline wattage, collects real-time metrics via threads, combines dataframes, and outputs visualizations and results. The script also...
def main(): aux_pid = run_auxiliary_command() configuration.initialize_files() measure_baseline_wattage() powerlog_filename = configuration.get_powerlog_filename() nvidia_smi_filename = configuration.get_nvidia_smi_filename() process_filename = configuration.get_process_filename() ...
def web_url(self): """ Returns the url for use in the web interface """ if self.is_app(): return f"apps/{self.name}/" else: return f"pkgs/{self.name}/" def is_app(self) -> bool: """ Heuristic to detect whether this is a graphical app that u...
This method converts an object's attributes and computed properties into a structured dictionary, primarily for search indexing or data representation. It aggregates fields like name, title, URL, icon, summary, version details, and status flags into a standardized format for external use.
def to_search_dict(self): return { "name": self.name, "title": self.title, "url": self.web_url(), "icon": self.icon.remote_url if self.icon else None, "summary": self.summary, "description": self.description, "version": self.ver...
def get_account_counters(): """ Get and save all counters in current account """ user_domains = DomainData.objects.all() account_counters_dict = {} try: get_response_from_api = create_get_request("https://api-metrika.yandex.net/management/v1/counters") for counter_info in range...
The code retrieves and processes Yandex API metrics by sequentially fetching account counters, visits, hits, and user data, then calculates a total goal counter. It sets a success message and returns the processed user metrics dictionary.
def start_yandex_api(request): counter_dict = get_account_counters() visits_dict = get_any_metrics(counter_dict, 'visits') hits_dict = get_any_metrics(visits_dict, 'hits') users_dict = get_any_metrics(hits_dict, 'users') get_total_goal_counter(users_dict) messages.success(request, 'Actual info...
def check_if_one_wins(start,target,size): for i in start[0]: if i == 'b': if target == 'b': return size else: return -size length = len(start) for i in start[length-1]: if i == 'w': if target == 'w': return s...
This function implements a minimax algorithm with depth limitation to determine the optimal game state. It evaluates if the current state is a terminal win, then recursively explores possible moves (generating new states) based on player turn (MIN/MAX). At maximum depth, it returns evaluated values; otherwise, it aggre...
def find_desire_state(start,size,target,depth,layer): rc = check_if_one_wins(start,target,size) if rc != False: return rc result_val = 0 if layer % 2 == 1: mode = "MIN" else: mode = "MAX" new_states = generate_new(start,size,target,mode) if layer >= (depth-1): ...
def arr_conv(start): arr = [] for i in range(len(start)): arr.append(list(start[i])) return arr def check_if_one_wins(start,target,size): for i in start[0]: if i == 'b': if target == 'b': return size else: return -size length = ...
The code implements a game-playing algorithm for Hexapawn, determining the optimal move by evaluating possible next states. It checks for an immediate win, generates valid moves, evaluates their desirability recursively, sorts them, and returns the best move as a formatted string grid.
def hexapawn(input,size,target,depth): start = arr_conv(input) rc = check_if_one_wins(start,target,size) if rc != False: return start layer = 1 next_moves = generate_new(start,size,target,"MAX") if next_moves == []: return start values = [] for x in next_moves: va...
def plotRangeBands(self, fig): nSamplesPerCircle = 100 hoursAway = [4, 12, 24, 48] prototypeSwellPeriodInSeconds = 15 minSwellPeriod = 12 maxSwellPeriod = 18 bearings = np.linspace(0, 2*np.pi, nSamplesPerCircle) #bearings = np.concatenate((bearings, np.array([0]...
This code generates an interactive geographical map visualizing buoy data using Plotly. It initializes a Scattergeo plot, configures map projections and features (coastlines, land, oceans), adds wave height/period markers, swell direction indicators, range bands, and the current location. It customizes the legend layou...
def mapBuoys(self): fig = go.Figure(go.Scattergeo()) fig.update_geos(projection_type="orthographic", showcoastlines = True, showland = True, showocean = True, showlakes = True, resolution = 50, fitbounds = ...
def _get(self, url, *args, **kwargs) -> requests.Response: """Wraps the session.get command to handle login state management""" r = self._request("GET", url, *args, **kwargs) while not self._check_logged_in(r): self._do_login() r = self._request("GET", url, *args, **kwarg...
This code retrieves and returns the current repository mirror configurations for a specified repository by fetching its settings page, handling re-authentication if needed, parsing HTML content, and extracting the relevant mirror settings section.
def list_repository_mirrors(self, repo_name: str): """List the current repository mirror configurations""" request_url = str(self.base_url) + "/" + repo_name + "/settings/repository" r = self._get(request_url) while not self._check_logged_in(r): self._do_login() ...
def move_snake(self): head = self.snake[0] new_head = None if self.direction == "Right": new_head = (head[0] + 20, head[1]) elif self.direction == "Left": new_head = (head[0] - 20, head[1]) elif self.direction == "Up": new_head = (head[0], head...
The main task of the code is to update the game state by moving both the user-controlled and AI-controlled snakes, checking for collisions, redrawing their positions on the canvas, and handling food consumption. It runs repeatedly via `self.master.after(200, self.update)`, ensuring game mechanics like movement, collisi...
def update(self): if self.is_game_over: return self.move_snake() self.check_collision() head = self.snake[0] food_coords = tuple(self.canvas.coords(self.food)[:2]) obstacle_coords = [tuple(self.canvas.coords(obstacle)[:2]) for obstacle in self.obstacles] ...
def setup_score_board(self): self.canvas.delete("user_points") self.canvas.delete("ai_points") self.canvas.create_text( WIDTH - 80, 30, font=('consolas', 12), text="Score: {}".format(self.score), fill="green", tags="score", ...
This code initializes a Snake Game window with settings, sets up score tracking, game time, obstacles, food, and initializes the snake and AI components. It binds key presses for direction control and starts the game loop with `self.update()` to handle game logic and rendering.
def __init__(self, master): # Initialising Game Window settings self.master = master self.master.title("Snake Game") self.master.geometry("{w}x{h}".format(h=HEIGHT, w=WIDTH)) self.master.resizable(False, False) self.score_label = None self.score = 0 self....
def step(self, state, is_test=False): """Select an action (randomly or from policy), perform the action on the environment, and add the newly observed information to the replay buffer. """ action = self.select_action(state, is_test) next_state, reward, done, _ = self.env.step(act...
The main task of the code is to train a reinforcement learning agent over a specified number of episodes. It interacts with the environment, stores experiences in a replay buffer, and periodically trains the agent using random batches from the buffer. Training occurs after a minimum number of steps and repeats at set i...
def train(self): """Train the agent for a given number of episodes. """ self.current_episode_number = 0 self.current_step_number = 0 for episode_i in range(1, self.num_episodes+1): print('Starting training for episode {}...'.format(episode_i)) self.curren...
def _input_data_validate(self,feature_df): if isinstance(feature_df,np.ndarray): if feature_df.ndim != 2: raise ValueError('The dimesion of the input %d is not 2!'%feature_df.ndim) else: raise ValueError('The input type is not np.array') # check t...
This code performs k-fold cross-validation by splitting data into nfold subsets, training on n-1 subsets, and testing on the remaining subset for each fold. It handles different score_df formats, iteratively builds training data, trains the model for specified epochs, and evaluates test accuracy for each fold, logging ...
def cross_validation(self,feature_df,score_df,nfold=5, train_epoches=1000): nSamples,nDims = self._input_data_validate(feature_df) nfoldist = self._random_split(nSamples,nfold) for n in range(nfold): self._printlog('Starting the %d-...
def branch(inputs, output, size_dict, memory_limit=None, nbranch=None): """ Explores possible pair contractions in a depth-first recursive manner like the ``optimal`` approach, but with extra heuristic early pruning of branches as well sieving by ``memory_limit`` and the best path found so far. Retu...
The function `greedy` computes an optimal contraction path for einsum operations using a three-stage algorithm: (1) eagerly calculating Hadamard products, (2) greedily selecting contractions to maximize removed data size, and (3) greedily computing outer products. It takes input dimensions, output dimensions, index siz...
def greedy(inputs, output, size_dict, memory_limit=None): """ Finds the path by a three stage algorithm: 1. Eagerly compute Hadamard products. 2. Greedily compute contractions to maximize ``removed_size`` 3. Greedily compute outer products. This algorithm scales quadratically with respect to t...
def extract_validator_info()->list: """ extract and return important validator info into a list ie. (validator_address, moniker, jailed, tokens) """ validator_dict = convert_validator_data_to_dict() validators = validator_dict["validators"] validator_info_list = [] for validator in valid...
The main task of the code is to process validator data by aggregating commission and reward details. It extracts raw validator information, calculates total outstanding and withdrawn commissions/rewards, and compiles all fields into a structured list of tuples containing validator addresses, monikers, status, token amo...
def build_validator_info(): """ [('f2oqixz9k4pxxji162oel2ccdan46wf6', 'Cogni🧠', False, 4915426.917313896, 591.8402775296655, 4.2337591781656325, 4665.656907786245, 34.94493206874103)] returns a list of validator info """ data = extract_validator_info() validator_info = [] for d in data: validator_ad...
def dead(self, enemy_group, traps_group): for trap in traps_group: if self.rect.colliderect(trap.rect): self.lives -= 1 if self.lives == 0: print("Mori") for enemy in enemy_group: if self.rect.colliderect(enemy.rect_left_collition) ...
This code updates a game object's state by handling collisions with enemies/traps, recharging resources, updating bullet behavior, enforcing border collisions, applying movement based on platforms and input, and advancing animations over time.
def update(self, delta_ms, list_platforms, borders, keys, enemy_group, traps_group): self.dead(enemy_group, traps_group) self.recharge() self.bullet_group.update(enemy_group, borders) self.collition_borders(borders, keys) self.do_movement(delta_ms, list_platforms) self.do...
def get_input(): # filename = "sample" filename = "input" with open(filename, 'r') as file: return list(map(json.loads, file.read().splitlines())) def magnitude(x): if isinstance(x, int): return x return 3 * magnitude(x[0]) + 2 * magnitude(x[1]) def add(a, b): x = [a, b] whil...
This code computes the maximum magnitude of the sum of all possible pairs from the input data. It uses permutations to generate pairs, adds them with the 'add' function, calculates their magnitude, and returns the highest value.
def test_star_2(self): data = get_input() print("Part 2:", max(magnitude(add(a, b)) for a, b in itertools.permutations(data, 2)))
def get_corrected_charging_pattern(prob,x): g_star = [0]*len(prob.N) for i in prob.N: installed = False for w in range(len(prob.W)): if x[i*len(prob.W)+w] > 0.8: installed = True g_star[i] = w break if not installed: ...
This function iteratively solves a master optimization problem with time limits, generating cuts from sub-problems to refine solutions. It tracks bounds, gaps, and computational times, adding constraints to the master problem until the solution gap falls below 1e-3 or the time limit expires. Key tasks include solving s...
def solve_master_iterative(self, time_limit=3600): len_path = [sum([len(self.paths[k]) for k in self.prob.K.keys()])] self.time_limit = time_limit while True: if time.time() - self.start_time > self.time_limit: self.master.solve() bound = 0 ...
def get_corrected_charging_pattern(prob,x): g_star = [0]*len(prob.N) for i in prob.N: installed = False for w in range(len(prob.W)): if x[i*len(prob.W)+w] > 0.8: installed = True g_star[i] = w break if not installed: ...
This code performs iterative cut generation for an optimization problem, monitoring time limits. It updates the model with new cuts derived from corrected charging patterns, tracks timing metrics (LP solving, labeling, cut generation), and increments counters for calls and cuts. The process involves recalculating param...
def __call__(self): if time.time() - self.start_time > self.time_limit: self.abort() else: self.num_called += 1 g_star = get_corrected_charging_pattern(self.prob, self.get_values()) alpha_k, beta_k, cut_gen_time, labeling_time, lp_solve_time ...
def validate_query(query: str) -> str: """ Check that query is an accepted accession type and return the accession type. Current accepted types are: Projects - PRJEB, PRJNA, PRJDA Studies - ERP, DRP, SRP BioSamples - SAMD, SAME, SAMN Samples - ERS, DRS, SRS Experimen...
The function downloads FASTQ files from ENA/SRA based on an accession query, handles duplicates, groups runs by experiment/sample, merges paired/single-end files, and outputs metadata and merged FASTQs in specified directories with TSV logs.
def get_fastqs( accession, group_by_experiment, group_by_sample, outdir, max_attempts, sleep, force, prefix, ): """Download FASTQ files from ENA or SRA.""" query = validate_query(accession) data_from, ena_data = get_run_info( query, max_attempts=max_attempts, ...
def parse_deck(deck_str): lines = deck_str.strip().split('\n') hero = '' weapons = [] equipment = [] cards = defaultdict(int) last_pitch = None for line in lines: if 'Class:' in line: continue elif 'Hero:' in line: hero = line.split('Hero:', 1)[1]...
This function processes a user-submitted decklist by parsing card data, querying database records, and structuring them into a session-stored format for display in a custom deck table. It maps descriptors to card names, retrieves weapon/equipment cards, processes card details, and stores structured data including hero,...
def prepare_custom_table(): if request.method == 'POST': user_id = session.get("_user_id") deck_str = request.form.get('decklist') deck_data = parse_deck(deck_str) descriptor_to_name = {card.descriptor: card.name for card in Card.query.filter(Card.des...
def sendToDevice(self, command): if self.debug: print("Sending: " + command) if self.ser != None: try: self.ser.write((command + "\n").encode()) except serial.SerialException as e: self.disconnect() else: self.discon...
This function updates a device's display by sending refresh commands (full or partial) and image data, ensuring proper device responses within a timeout. It acquires a lock to prevent concurrent updates, waits for "ok" confirmation after each command, and retries if responses are delayed or missing. If timeout occurs, ...
def updateDisplay(self, fullRefresh=False, timeout=5): with self.awaitingResponseLock: start = time.time() self.sendToDevice(CommandCode.REFRESH.value + " " + (RefreshTypeCode.FULL.value if fullRefresh else RefreshTypeCode.PARTIAL.value)) line = self.readFromDevice() ...
def render_file_select_sidebar(): st.sidebar.title("File Selection") uploaded_file = st.sidebar.file_uploader("Upload a PDF Containing Text",type=['pdf']) st.set_option('deprecation.showfileUploaderEncoding', False) # Disabling warning st.sidebar.subheader("Enter Page Range") col1, col2 = st.sidebar.columns(2) s...
The code provides an OCR processing interface using Streamlit, allowing users to upload documents, apply preprocessing (thresholding, denoising), and extract text with Tesseract. It displays OCR results, evaluates quality via metrics like garbageness score, language confidence, word confidence, dictionary checks, and e...
def main(): # Wide mode st.set_page_config(layout="centered") st.title(MAIN_TITLE_TEXT) st.write(TITLE_DESCRIPTION) # File selection UI start, end, uploaded_file = render_file_select_sidebar() st.sidebar.title("Preprocessing Methods") thresh_method = st.sidebar.radio("Thresholding Method", THRESHOLDING_METHO...
def __endStream(self): return self.__index >= self.__len def __getCurrentChar(self): return self.__s[self.__index] def __toNextChar(self): self.__index += 1 def __isCharDigit(self): if self.__endStream(): return False curChar = self.__getCurrentChar() return '...
This function tokenizes input characters into valid tokens (e.g., integers, floats, identifiers, operators) by checking current characters against predefined token types. It handles numeric values (including decimal parsing), letters (as identifiers), spaces (skipped), and invalid characters. If no valid token is found...
def nextToken(self): while not self.__endStream(): #Check if character is operator, comma, or EOI current = self.__getCurrentChar() for tokenType in self.__singleCharTypes: if tokenType.valid(current): if isinstance(tokenType,...
def __endStream(self): return self.__index >= self.__len def __getCurrentChar(self): return self.__s[self.__index] def __toNextChar(self): self.__index += 1 def __isCharDigit(self): if self.__endStream(): return False curChar = self.__getCurrentChar() return '...
The main task of the code is to parse an input stream into tokens by identifying operators, numbers (integers/floats), identifiers, keywords, spaces, and invalid characters. It processes each character sequentially, returning the corresponding token type, and handles edge cases like incomplete floats or unexpected char...
def nextToken(self): while not self.__endStream(): #Check if character is operator, comma, or EOI current = self.__getCurrentChar() for tokenType in self.__singleCharTypes: if tokenType.valid(current): if isinstance(tokenType,...
def get_body_data(body_hash, body_type): attribute_name = body_type + '_type' choice_hash = get_attribute_hash(body_hash, attribute_name) all_bodies = ALL_BODIES[body_type] body = weighed_choice(all_bodies, choice_hash, choice_key='odds') return dict(all_bodies[body]) def get_attribute_hash(parent_h...
The code generates a star object with its type and a list of planets. It retrieves star data, determines the number of planets using a range from the star's attributes, and iteratively creates each planet by fetching its specific attributes and generating it. The final star dictionary includes the star type and the gen...
def generate_star(star_hash): star_data = get_body_data(star_hash, 'star') planet_count_hash = get_attribute_hash(star_hash, 'star_planet_count') min_planets, max_planets = star_data['min_planets'], star_data['max_planets'] planet_count = generation_types.get_range(planet_count_hash, min_planets, max_pl...
def get_body_data(body_hash, body_type): attribute_name = body_type + '_type' choice_hash = get_attribute_hash(body_hash, attribute_name) all_bodies = ALL_BODIES[body_type] body = weighed_choice(all_bodies, choice_hash, choice_key='odds') return dict(all_bodies[body]) def get_attribute_hash(parent_h...
The main task of the code is to generate a galaxy object containing a list of stars. It retrieves galaxy parameters, determines the number of stars using a hash, and iteratively creates each star by fetching their individual hashes and generating star data, compiling them into a structured galaxy dictionary with a 'sta...
def generate_galaxy(galaxy_hash): galaxy_data = get_body_data(galaxy_hash, 'galaxy') star_count_hash = get_attribute_hash(galaxy_hash, 'galaxy_star_count') min_stars, max_stars = galaxy_data['min_stars'], galaxy_data['max_stars'] star_count = generation_types.get_range(star_count_hash, min_stars, max_st...
def integral_intensity(image: np.ndarray): """ Get image of integral intensity from original image. """ integral_image = image.copy() integral_image = np.cumsum(integral_image, 0) integral_image = np.cumsum(integral_image, 1) return integral_image def make_fe...
The main task of the code is to prepare a dataset for AdaBoost by computing integral images from input images, generating Haar-like features, and constructing a feature matrix X. It either loads a precomputed X from a file or calculates it by applying features to integral images. The resulting dataset is saved if speci...
def fit(self, images, y, filename='mit_face_X', save_dataset=True): print('Computing integral images') iis = [self.integral_intensity(i) for i in images] self.height_training, self.width_training = iis[0].shape print('Complete integral images') print('Making features') fe...
def integral_intensity(image: np.ndarray): """ Get image of integral intensity from original image. """ integral_image = image.copy() integral_image = np.cumsum(integral_image, 0) integral_image = np.cumsum(integral_image, 1) return integral_image def make_fe...
The code trains a cascade of AdaBoost classifiers using Haar-like features for face detection, iteratively applying integral images to compute feature responses, pruning training data based on classifier performance, and adjusting thresholds to meet target false positive/negative rates while saving computed datasets fo...
def fit(self, images, y, filename='mit_face_X', save_dataset=True): t_start_overall = datetime.datetime.now() print('Computing integral images') iis = [self.integral_intensity(i) for i in images] self.height_training, self.width_training = iis[0].shape print('Making features') ...