dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def pieceatsqr(num): if num > 63 or num < 0: return None s = boardlist[num] return getPiece(s) def ChangeVar(start, end): j = pieceatsqr(start) boardlist[start] = 0 boardlist[end] = id(j) def pawnPromoted(end): s = numtocoord(end) pce = pieceatsqr(end) if (s[1] == '8' and pce...
The function `MovePiece` handles chess piece movement, including castling (adjusting rook positions), pawn promotion (replacing pawns with queens), and en passant rules. It updates the game state, tracks last move data for the 50-move rule, and manages piece captures. If `update=True`, it applies changes to the board a...
def MovePiece(start, end, update=True): j = pieceatsqr(start) m = pieceatsqr(end) curState.prevState = copy.copy(curState) curState.prevBoard = copy.copy(boardlist) ChangeVar(start, end) toUpdate = {id(j):[start,end]} # Move the rook if the king castled if j.name == KING and (end - st...
def pieceatsqr(num): if num > 63 or num < 0: return None s = boardlist[num] return getPiece(s) def numtocoord(num): return chr(num%8 + 97) + str((num/8)+1) def kingMovement(sqr, i): m, n = sqr[0], sqr[1] p = [] if m != 'a': p.append(i - 1) if n != '1': p.a...
This function generates legal moves for a chess piece at position `i` based on its type (king, pawn, knight, etc.), considering rules like castling, en passant, and non-attacking moves. It filters out invalid moves by checking if they leave the king in check or involve friendly fire, returning a list of valid target sq...
def PieceMovement(i): j = pieceatsqr(i) sqr = numtocoord(i) m, n = sqr[0], sqr[1] p = [] if not j: return p # King Movement if j.name == KING: p = kingMovement(sqr, i) # Castling if (j.colour == WHITE and curState.ws) or (j.colour == BLACK and curState.bs): ...
def EvaluatePosition(colour): evalu = 0.01 BL = pm.boardlist # Check for draw if isDraw(): return 0 # Calculate material imbalances for y in whitepieces: evalu += y.value * len(y.piecelist) for y in blackpieces: evalu -= y.value * len(y.piecelist) if colour == ...
This function finds the best move for a given chess color using a recursive minimax algorithm with depth and width constraints. It evaluates positions, explores possible moves, checks for checkmates, and considers opponent responses to determine optimal moves, returning the top move with evaluation and coordinates.
def FindBest(colour, depth=DEPTH, width=maxWidth, first=True): time0 = current_time_millis() if width <= 0: width = 1 if colour == WHITE: pieces = whitepieces opp = BLACK elif colour == BLACK: pieces = blackpieces opp = WHITE topMoves = [] e = lambda po...
def checkForDead(start, end): piece = pm.pieceatsqr(end) if piece: if piece.colour == WHITE: mainState.deadWhite.append(piece) elif piece.colour == BLACK: mainState.deadBlack.append(piece) elif abs(start-end) == 7 or abs(start-end) == 9: if pm.pieceatsqr(start...
The function `DoCompTurn` handles a computer's turn in a chess game. It selects a move based on the game state: using predefined opening moves for the first 5 moves or finding the optimal move otherwise. It then updates the game state by moving the piece, checks for captures, redraws the board, and switches the turn to...
def DoCompTurn(turn): if mainState.END: return if mainState.movenumber <= 5: start, end = ChessEngine.OpeningMoves(turn, mainState.movenumber, mainState.randmove) else: mv = ChessEngine.FindBest(turn) start, end = mv.movestart, mv.moveend checkForDead(start, end) pm.MovePiece...
def pieceatsqr(num): if num > 63 or num < 0: return None s = boardlist[num] return getPiece(s) def isInCheck(colour): if colour == WHITE: kingsqr = wk.piecelist[0] elif colour == BLACK: kingsqr = bk.piecelist[0] return not(isSafe(kingsqr, colour)) def MovePiece(start, end...
This function checks if a move is legal by verifying: 1) No friendly fire (same color piece at target square), 2) King cannot castle out of check, 3) Simulates the move to check if it results in the king being in check. Returns True if legal, False otherwise.
def MoveFilterer(x): # Make sure we don't have friendly fire if boardlist[x] and (pieceatsqr(x)).colour == j.colour: return False # Cannot castle out of check if j.name == KING and abs(x-i) == 2 and isInCheck(j.colour): return False legalMove = True ...
def resetState(): global mainState mainState = GameState() pm.resetgame() drawStuff() def UndoStuff(): if mainState.END: mainState.END = False pm.UndoMove() pm.UndoMove() reviveDead() drawStuff() if mainState.movenumber == 1: mainState.turn = WHITE if mainState.movenu...
This function handles Pygame events: checks for quit requests, detects mouse clicks on three buttons (reset, undo, flip), triggers corresponding actions (resetState, UndoStuff, toggling FLIP state), and returns True after processing valid button clicks.
def checkType(event): # Check for quit if event.type == pygame.QUIT: pygame.quit(); sys.exit(); # Reset the game if 'new game' selected if event.type == pygame.MOUSEBUTTONUP: mousex, mousey = event.pos if buttonx < mousex < buttonx + buttonWidth and buttony < mousey < buttony + b...
def checkType(event): # Check for quit if event.type == pygame.QUIT: pygame.quit(); sys.exit(); # Reset the game if 'new game' selected if event.type == pygame.MOUSEBUTTONUP: mousex, mousey = event.pos if buttonx < mousex < buttonx + buttonWidth and buttony < mousey < buttony + b...
The function `DoPlayerTurn` handles a player's turn in a board game by processing mouse events to select and move pieces. It checks for valid moves, updates the board state, and switches turns. When a piece is clicked, it highlights valid moves; if a valid target square is clicked, the piece moves, and the turn ends. T...
def DoPlayerTurn(turn): temp = -1 while (True): for event in pygame.event.get(): if checkType(event): return if event.type == pygame.MOUSEBUTTONUP: mousex, mousey = event.pos msqr = squareClicked(mousex, mousey) if m...
def drawStuff(sqr=-1): screen.fill(backcolour) drawButtons() drawBoard() if sqr != -1: drawHighlight(sqr) drawDead() drawPieces() def checkType(event): # Check for quit if event.type == pygame.QUIT: pygame.quit(); sys.exit(); # Reset the game if 'new game' selected if eve...
This code initializes a chess game interface using Pygame, handling player vs. computer gameplay. It checks for checkmate or draw conditions, alternates turns between the player (WHITE) and AI (BLACK), and updates the game state. The loop processes events, displays messages for game outcomes, and renders the board, ena...
def main(): # Initialize things pygame.display.set_caption('Can you beat Shallow Blue in chess?') pm.updateCastlingRights() drawStuff() # Main game loop: while (True): for event in pygame.event.get(): checkType(event) # Checks for mate if not mainState.END: ...
def hand_id(cardlist): """return card IDs of a list of cards""" hand_id_list = [] for card in cardlist: hand_id_list.append(card_id(card)) return hand_id_list def card_value_check(cardlist, value): """check if a cardlist has a card of that specific value""" for card in cardlist: ...
The function handles a turn in a card game by prompting the current player to ask another player for a specific card. It checks if the target player has the card, allowing the current player to steal it and check for four-of-a-kind. If the card isn't found, the player "goes fish," draws a card from the deck, and checks...
def turn(game_deck, player_list, hand_list, current_player, score_list): """prompt for another player and a card value. perform card value check. if true, grab card and go again if false, deal 1 card from deck check deck to see if no cards left. """ z = 1 while z == 1: if len(game_deck) == 0: ...
def get_images(tag='', image_sha1='', image_uuid='', limit=10, offset=0): time_start = time.time() client = get_db() txn = client.txn(read_only=True) query = """{{ count(func: type(Image)){{ count(uid) }} images(func: type(Image), first:{0}, offset: {1}, orderdesc: up...
This function handles image retrieval and upload via HTTP methods. For GET, it fetches images by SHA1 hash, tag, or default list, logging time taken. For PUT, it validates new uploads, generates unique IDs, creates temporary upload URLs, and stores metadata if the image isn't already uploaded. It returns URLs for uploa...
def images(): if request.method == 'GET': time_start = time.time() image_sha1 = None human_readable_name = None offset = 0 limit = 10 #request_payload = request.get_json() # if request_payload: image_sha1 = request.args.get("image_sha1", "") of...
def get_image_by_id(image_uuid): if image_uuid: db = get_db() txn = db.txn(read_only=True) # Run query. query = """query image_detail($a: string) { image_detail(func: eq(image_uuid, $a)) { expand(_all_){ expand(_all_){ ...
The main task of the code is to handle HTTP requests for an image resource, specifically retrieving image details via GET and deleting an image via DELETE. For GET, it fetches image data using helper functions and returns it as JSON, or raises an error if not found. For DELETE, it deletes the image and returns a succes...
def image_detail(image_id): if request.method == 'GET': image = get_image_by_id(image_id) image = get_image_view(image) if image: return jsonify(image) else: raise ImagePutError('Image not found'.format()) image = get_images(image_sha1, offset=offset, ...
def get_image_tags(image_id): client = get_db() txn = client.txn(read_only=True) query = """{{ result(func: eq(image_uuid,"{0}")){{ stored_at{{ tagged_with{{ tag_name }} }} }} }}""".format(image_id) res = txn...
The code updates an image's tags in a Dgraph database by adding new tags and removing outdated ones. It calculates differences between current and new tags, then uses Dgraph transactions to add new tag relationships or create new tags if needed, and deletes existing tag associations for removed tags.
def update_image_tags(image_uuid, tags): current_tags = get_image_tags(image_uuid) to_add_tags = set(tags).difference(current_tags) to_del_tags = set(current_tags).difference(tags) add_tags(to_add_tags) client = get_db() for tag_name in to_add_tags: txn = client.txn(read_only=False) ...
def _read_data(self) -> bytearray: return self._read_register(b"\x00") def _joystick_l(self, do_read: bool = True) -> _Joystick_L: if do_read: self._read_data() return self._Joystick_L((self.buffer[0] & 0x3F), (self.buffer[1] & 0x3F)) def _joystick_r(self, do_read: bool = True) -> _J...
The main task of the code is to return the current state of all input values (joysticks, shoulders, d-pad, buttons) by creating a `_Values` object with pre-existing data, without triggering new reads. It first ensures data is read via `_read_data()` and then aggregates the latest states using internal methods with `do_...
def values(self) -> _Values: """The current state of all values.""" self._read_data() return self._Values( self._joystick_l(do_read=False), self._joystick_r(do_read=False), self._l_shoulder(do_read=False), self._r_shoulder(do_read=False), ...
def from_normjoint_to_cropspace(joint3d): joint3d[:,:,:2] = (joint3d[:,:,:2] + 0.5 )*256.0 return joint3d def invPoseToCamSpacePlus(cropPose3d,jointRoot,camID,trans): # convert normalized 3d joints to camera space 3d joints fullPose2d = cropPoseToFullPose(cropPose3d[:,0:2],trans) j3d = restore_cam...
The function evaluates 3D pose estimation accuracy using MPJPE metrics by blending original and flipped predictions, converting joints to camera space, and returning protocol-specific errors, action IDs, and video metadata. It processes input joints through normalization, flipping, and coordinate transformations to com...
def eval_metric(pred_joint3d_numpy,pred_joint3d_filp_numpy,gt_joint3d_numpy,camid_numpy,\ trans_numpy,joint_root_numpy,gt_joint3d_j18_numpy,seqJsonDict=None,debug = False,return_viz_joints=False): pred_joint3d_numpy_crop = from_normjoint_to_cropspace(pred_joint3d_numpy) gt_joint3d_numpy_crop = from...
def set_k_sigma(self, sigma_penalty=1e7): n = 1 + len(self.x) G = sigma_penalty * np.eye(n) G[0, 0] = 1.0 C, b = self.get_constraints() a = np.zeros(n) qp_soln = qp.solve_qp(G=G, a=a, C=C, b=b, meq=0) x = qp_soln[0] self.k = float(x[0]) self.sigma = x[1:] def exploit(self, size=1): ...
The main task of the code is to perform iterative optimization by alternating between exploration and exploitation phases. It runs for `niter` iterations, updating parameters (`x`, `y`) and tracking the best solution found. The algorithm prints progress if enabled, validates inputs, and returns final results after comp...
def fit(self, niter=60, iter_start=0): self._validate_fit_inputs(niter=niter, iter_start=iter_start) # increment end iterations niter += iter_start for j in range(iter_start, niter): msg = "" self.set_k_sigma() if j % 2 == 1: new_x, new_y = self.exploit() else: ne...
def create_signals(max_signals, store_signals): num_signals = random.randint(0, max_signals) sigs = [] mods = [] if random.randint(1, 2) == 1: sig, mod, rate = generate_signal() notcher = create_notcher(len(sig)) sig *= notcher env = np.copy(sig) if store_signa...
The main task of the code is to generate annotated spectrogram images from synthetic signals, incorporating noise, and save them to a specified directory. It creates signals and modulations, prepares spectrograms with noise, and annotates them with labels, modulations, and image parameters. The function handles both an...
def generate_example(directory, max_signals, noise_intensity, image_size, sub_labels, threshold=False): env, sigs, mods = create_signals(max_signals=max_signals, store_signals=sub_labels) env = prepare_spectrogram(signal=env, noise_intensity=noise_intensity) sigs = [prepare_spectrogram(signal=sig, noise_i...
def open_no_file(self): # write data to test file self.set_file(None) if core._attributes != []: return False elif core._fds != []: return False elif core._cover != []: return False return True def open_bad_file(self): # write d...
The code defines a test method `test_open_save_file` that verifies the functionality of multiple file-handling methods (`open_no_file`, `open_bad_file`, etc.) by asserting their return values are `True`. It checks if the system correctly handles scenarios like missing files, invalid file descriptors, and incorrect cove...
def test_open_save_file(self): self.assertTrue(self.open_no_file()) self.assertTrue(self.open_no_file()) self.assertTrue(self.open_bad_file()) self.assertTrue(self.open_bad_fds()) self.assertTrue(self.open_bad_cover()) self.assertTrue(self.open_false_cover()) ...
def split_rhs (DEPS): """Splits FDs with multiple attributes on the RHS to multiple FDs with a single attribute on the RHS""" FDS = [] for dep in DEPS: for let in dep[1]: if not [dep[0],let] in FDS: FDS.append([dep[0],let]) return FDS def find_...
The code computes a minimal cover of functional dependencies by splitting right-hand sides, calculating attribute closures, removing redundant dependencies, and minimizing left-hand sides to produce an equivalent, simplified set of FDs.
def mincover(dependencies): """Computes and returns a minimal cover made from the set of FDs""" fds = split_rhs(dependencies) closures = find_closures(fds) fds = remove_redundant(fds, closures) fds = minimize_lhs(fds) return fds
def parse_setup(self, filename): """ Read config from config.json See config.json for comments on the settings """ with open(filename) as file: data = json.load(file)['experiment'] self.user_id = data['userId'] self.shape_width = data['shapeWi...
The code initializes a class instance by parsing setup parameters, configuring participant tracking (current repetitions, Latin square conditions), setting up graphical elements (shapes, coordinates, timer), and initializing a DataFrame for data storage. It prepares the object for managing experimental conditions and p...
def __init__(self): self.helper = () self.parse_setup(sys.argv[1]) self.init_shapes() self.init_shape_coords() self.timer = QtCore.QTime() self.mouse_moving = False self.current_participant_repetitions = 1 # counts how many conditions the participant has alread...
def Extract_Contours(img): """"" extracts contours from the input image and store its cordinates (x,y) into cords[] using boundingrect function also exports some params that are needed down the pipeline (main_pipeline function) """"" img = resize(img) gray = cv.cvtColor(img, cv.COLOR_BGR...
The main task of the code is to process an input image to detect and organize alphabets (a-z) by extracting contours, grouping nearby characters, and storing their detected images along with dimensions. It also identifies missing alphabets that couldn't be detected. The function returns arrays of detected alphabets, th...
def Main_Pipeline(img,STATE): """ takes an image as input and return ALP_arr : an array consisting of detected alphabets images in a-z order Dimn_arr : an array consiting of dimention of the corresponding image missing_Alpha : an array of missing alpbaets that are unable to detect by model ...
def appendRollCourses(slots, roll, courseCode): new_list=[] for i in arr: if i in slots: new_list.append(courseCode) else: new_list.append('') return new_list def getCourseSlots(courseCode): slotsString = ServerGETSLOTS(courseCode) # slotsString = "+CS304+G1...
The function `ServerFETCH` processes incoming requests to manage a timetable system. It handles three commands: 'N' (create a new entry by parsing roll numbers and courses, updating a CSV file), 'C' (check if a roll number has courses), and default (fetch a course code for a specific slot). It uses CSV operations, stri...
def ServerFETCH(req): """handle a request to the function Args: req (str): request body """ command = req[0] if(command == 'N'): # Call function to create new entry flag = 0 for i in range(len(req)): if (req[i] == '$'): flag = i ...
def load_media() -> Tuple[Optional[Media], Optional[str]]: """Load the media from the file system.""" images_dir = PACKAGE_DIR / "media/images" ground_tile_pths = sorted(images_dir.glob("ground*.png")) ground_tiles = [ pygame.image.load(str(pth)).convert_alpha() for pth in ground_tile_pths ...
The main task of the code is to run a game using Pygame, handling input via keyboard and pose recognition, updating the game state, rendering scenes, and maintaining a 30 FPS loop, with version checking and error handling for media loading.
def main(prog: str) -> int: """ Execute the main routine. :param prog: name of the program to be displayed in the help :return: exit code """ parser = argparse.ArgumentParser(prog=prog, description=__doc__) parser.add_argument( "--version", help="show the current version and exit", ...
def get_secret(): secret_name = "INSERT_SECRET_NAME" region_name = "INSERT_REGION" # Create a Secrets Manager client session = boto3.session.Session() client = session.client( service_name='secretsmanager', region_name=region_name ) get_secret_value_response = client.get_secr...
The code executes Salesforce queries (query_more or query_all) based on q_type, processes results into DataFrames, removes metadata columns, and uploads the output as tab-separated CSV files to an S3 bucket. It handles pagination for large datasets, logging progress and errors, with the primary task being automated dat...
def query_loop(query_list, q_type): private_key = get_secret() sf = jwt_login(consumer_id, username, private_key, sandbox=False) for sub_list in query_list: start = time.time() print() print(">> Running %s at %s" % (sub_list[0],now())) ### Run the Normal query for the FULL ...
def query_full_list(): query_account = "" query_user = "" query_contact = "" ### Define the query's Array and the filename query_list = [ ['query_contact', query_contact], ['query_user', query_user], ['query_account', query_account] ] return (query_list) def query_l...
The function `runit` processes queries based on the input `period` and `Qtype`. If `period` is 'FULL', it retrieves all queries using `query_full_list()`; otherwise, it fetches custom-period queries via `query_custom_list(period)`. Both cases pass the generated query list and `Qtype` to `query_loop` for further process...
def runit(period, Qtype): if period == 'FULL': # FULL QUERY, WILL TAKES TIME. query_list = query_full_list() varsloop = query_loop(query_list, Qtype) else: # CUSTOM QUERY LIKE YESTERDAY, LAST_MONTH query_list = query_custom_list(period) varsloop = query_loop(query_list, Qtype ...
def readDigitData(filename): counter = 0 index = 0 digitsData = [[]] with open("digitdata/" + filename, 'r') as f: for line in f: data_str = line[:28] digitsData[index].append(data_str) counter += 1 if(counter == 28): digitsData.app...
The code evaluates a digit recognition model's performance by training on varying percentages of data (10% to 100%) with different feature extraction parameters (n). It measures training time, validation accuracy, and test accuracy statistics (mean/std dev) for each configuration, using two feature types ('+' and '#') ...
def getDigitStats(iters, n): trainingData = readDigitData("trainingimages") trainingLabels = readDigitLabels("traininglabels") validationData = readDigitData("validationimages") validationLabels = readDigitLabels("validationlabels") testData = readDigitData("testimages") testLabels = readDigitLa...
def readFaceData(filename): counter = 0 index = 0 facesData = [[]] with open("facedata/" + filename, 'r') as f: for line in f: data_str = line[:60] facesData[index].append(data_str) counter += 1 if(counter == 70): facesData.append([...
The code evaluates a face recognition model's performance by training on varying percentages of the dataset (10% to 100%), measuring training time, and testing accuracy on validation and test sets. It extracts features from face images, trains classifiers with different iterations, and computes mean accuracy and standa...
def getFaceStats(iters, n): trainingData = readFaceData("facedatatrain") trainingLabels = readFaceLabels("facedatatrainlabels") validationData = readFaceData("facedatavalidation") validationLabels = readFaceLabels("facedatavalidationlabels") testData = readFaceData("facedatatest") testLabels = r...
def readDigitData(filename): counter = 0 index = 0 digitsData = [[]] with open("digitdata/" + filename, 'r') as f: for line in f: data_str = line[:28] digitsData[index].append(data_str) counter += 1 if(counter == 28): digitsData.app...
The code evaluates a digit recognition model's performance by training on varying percentages (10% to 100%) of the training data, testing on validation and test sets, and reporting accuracy and prediction error statistics for each subset. It measures training time, validation accuracy, and test error mean/standard devi...
def digitStatistics(): trainingData = readDigitData("trainingimages") trainingLabels = readDigitLabels("traininglabels") validationData = readDigitData("validationimages") validationLabels = readDigitLabels("validationlabels") testData = readDigitData("testimages") testLabels = readDigitLabels("...
def readFaceData(filename): counter = 0 index = 0 facesData = [[]] with open("facedata/" + filename, 'r') as f: for line in f: data_str = line[:60] facesData[index].append(data_str) counter += 1 if(counter == 70): facesData.append([...
The code evaluates a face detection model's performance by training on varying fractions of the dataset (10% to 100%), testing on validation and test sets, and calculating accuracy, mean accuracy, and standard deviation for each fraction to assess model reliability and training efficiency.
def faceStatistics(): trainingData = readFaceData("facedatatrain") trainingLabels = readFaceLabels("facedatatrainlabels") validationData = readFaceData("facedatavalidation") validationLabels = readFaceLabels("facedatavalidationlabels") testData = readFaceData("facedatatest") testLabels = readFac...
def get_bases(definition_dict: Dict[str, Any], loader: "Loader") -> Dict[str, Any]: """Collect inherited behaviors.""" bases = definition_dict.get("bases", ()) if bases: # FIXME this currently does not work raise NotImplementedError bases = ( loader.get_comp_dict(required...
The main task of the code is to construct and return a `Device` object by initializing it with parameters from `device_dict`, incorporating error handlers, end-of-message (EOM) configurations, and channels. It uses a `Loader` for dependencies and `resource_dict` for resource attachment, recursively building device comp...
def get_device( name: str, device_dict: Dict[str, Any], loader: "Loader", resource_dict: Dict[str, str], ) -> Device: """Get a device from a device dictionary. Parameters ---------- name : str Name identifying the device. device_dict : Dict[str, Any] Dictionary descr...
def verify_env_file(self): """ Check if the env file is okay and contain the correct data. Exit the program if not. """ if not os.path.exists(".env"): self.log.critical(".env file not found. Make sure to copy ") exit(1) if not self.api_key: se...
The main task of the code is to automatically execute recommended stock trades to rebalance portfolios. It retrieves portfolio data, identifies calculated trades, logs trade details, and sends API requests to place orders, updating the portfolio allocation by executing trades with specified units, prices, and commissio...
def activ_passiv(self): """ Executes the routine to automatically buy the recommended stocks. """ self.log.info("Starting ActivPassiv") self.verify_env_file() self.test_api_connectivity() portfolio_ids: list = self.get_portfolio_ids() for portfolio_id ...
def checkForIndirect(gramA, a, ai): if ai not in gramA: return False if a == ai: return True for i in gramA[ai]: if i[0] == ai: return False if i[0] in gramA: return checkForIndirect(gramA, a, i[0]) return False def rep(gramA, A): temp = gramA[...
The code converts a grammar into a form without left recursion by renaming non-terminals, parsing expressions with operators (+, *, -), eliminating indirect and direct left recursion, and mapping symbols back to original identifiers. It processes each rule, replaces symbols with temporary labels, checks for recursion, ...
def rem(gram): c = 1 conv = {} gramA = {} revconv = {} for j in gram: conv[j] = "A"+str(c) gramA["A"+str(c)] = [] c+=1 for i in gram: check = "" check2=[] for k in gram[i]: temp = [] if re.match('\+',...
def parse_config(self): general = 'general' arch_sec = 'architecture_presets' net_sec = 'network_presets' # config_filename = "./scale.cfg" config_filename = FLAGS.arch_config print("Using Architechture from ",config_filename) config = cp.ConfigParser() c...
The code's main task is to execute either a single run or a sweep of operations based on the 'sweep' configuration flag. It first parses the configuration, then calls `run_once()` if sweeping is disabled, or `run_sweep()` if enabled, determining the execution mode for the scale process.
def run_scale(self): self.parse_config() if self.sweep == False: self.run_once() else: self.run_sweep()
def build_laplacian_pyramid(im, max_levels, filter_size): ''' constructs a Gaussian pyramid of a given image. :param im: a grayscale image with float values in [0, 1]. :param max_levels: the maximal number of levels in the resulting pyramid. :param filter_size: the size of the Gaussian filter (an od...
The function performs pyramid blending of two grayscale images (im1 and im2) using a boolean mask. It constructs Laplacian pyramids for both images and a Gaussian pyramid for the mask. At each pyramid level, the mask blends corresponding Laplacian layers of im1 and im2, then reconstructs the final image via inverse pyr...
def pyramid_blending(im1, im2, mask, max_levels, filter_size_im, filter_size_mask): ''' pyramid blends the two images according to the mask. im1, im2 and mask should all have the same dimensions that are multiples of 2**(max_levels−1) . :param im1: input grayscale image to be blended. :param im2: in...
def spread_out_corners(im, m, n, radius): """ Splits the image im to m by n rectangles and uses harris_corner_detector on each. :param im: A 2D array representing an image. :param m: Vertical number of rectangles. :param n: Horizontal number of rectangles. :param radius: Minimal distance of corn...
The function `find_features` detects and extracts feature points from a 3-level Gaussian pyramid. It identifies corners in the base level (`pyr[0]`), translates their positions to a higher pyramid level (`pyr[2]`), and samples descriptors using a fixed radius (`DESC_RAD`). The output includes corner coordinates at the ...
def find_features(pyr): """ Detects and extracts feature points from a pyramid. :param pyr: Gaussian pyramid of a grayscale image having 3 levels. :return: A list containing: 1) An array with shape (N,2) of [x,y] feature location per row found in the image. These coord...
def build_laplacian_pyramid(im, max_levels, filter_size): ''' constructs a Gaussian pyramid of a given image. :param im: a grayscale image with float values in [0, 1]. :param max_levels: the maximal number of levels in the resulting pyramid. :param filter_size: the size of the Gaussian filter (an od...
The function performs pyramid blending of two input images using a mask. It constructs Gaussian and Laplacian pyramids for both images and the mask, then combines the Laplacian layers weighted by the Gaussian mask pyramid. The result is a blended image where regions from im1 and im2 are merged according to the mask, en...
def pyramid_blending(im1, im2, mask, max_levels, filter_size_im, filter_size_mask): ''' pyramid blends the two images according to the mask. im1, im2 and mask should all have the same dimensions that are multiples of 2**(max_levels−1) . :param im1: input grayscale image to be blended. :param im2: in...
def compute_bounding_box(homography, w, h): """ computes bounding box of warped image under homography, without actually warping the image :param homography: homography :param w: width of the image :param h: height of the image :return: 2x2 array, where the first row is [x,y] of the top left cor...
The code generates panoramic images by warping and stitching input images using homographies. It calculates bounding boxes, adjusts coordinate systems, determines slice positions, and combines image strips. For the bonus, it creates dual panoramas with barcode blending, handling even/odd frames and pyramid blending. No...
def generate_panoramic_images(self, number_of_panoramas): """ combine slices from input images to panoramas. :param number_of_panoramas: how many different slices to take from each input image """ assert self.homographies is not None # compute bounding boxes of all warpe...
def find_features(pyr): """ Detects and extracts feature points from a pyramid. :param pyr: Gaussian pyramid of a grayscale image having 3 levels. :return: A list containing: 1) An array with shape (N,2) of [x,y] feature location per row found in the image. These coord...
The code aligns a sequence of images into a common coordinate system by computing homographies between consecutive pairs using feature matching and RANSAC. It accumulates these homographies to create composite transformations, filters them for translation consistency, and stores valid homographies for panorama generati...
def align_images(self, translation_only=False): """ compute homographies between all images to a common coordinate system :param translation_only: see estimte_rigid_transform """ # Extract feature point locations and descriptors. points_and_descriptors = [] for fi...
def read_image(filename, representation): ''' reads an image file and converts it into a given representation. :param filename: string containing the image filename to read. :param representation: representation code, either 1 or 2 defining whether the output should be a grayscale image (1) or an RG...
This code demonstrates image blending using a mask. It reads two images and a binary mask, processes the mask, applies pyramid blending with specified parameters, and displays the original images, mask, and blended result. The main task is to combine two images based on a mask using multi-scale blending techniques.
def blending_example1(): im1 = read_image('externals/example1/kimono.jpg', 2) im2 = read_image('externals/example1/dog.jpg', 2) mask = read_image('externals/example1/mask.jpg', 1) mask[mask < 0.5] = 0 mask = mask.astype(np.bool) im_blend = pyramid_blending_rpg(im1, im2, mask, max_levels=7, ...
def isMulti(soup): try: if("multiple commitments" in soup.findAll('p')[1].contents[0]): return True except(IndexError): return False return False def extractMulti(browser, soup, hash_from_birthdays_to_used_names): listOfTables = soup.findAll("table") recordTable = listOfT...
This code extracts data from a web page by clicking a dynamically named element, parsing the HTML, determining if the page contains multiple or single records, and processing it with either `extractMulti` or `extractFirst` functions. It then navigates back in the browser.
def extract(browser, rowNum, hash_from_birthdays_to_used_names): browser.find_element_by_name('din' + str(rowNum)).click() # din info click source = browser.page_source soupMainPage = BeautifulSoup(source, 'html.parser') # check if a multi-record or single if isMulti(soupMainPage): extractM...
def repair_odim_source(obj): import re source = obj.source # France - Falaise if obj.source == 'WMO:07027': return odim_source.SOURCE["frcae"].encode(UTF8) # France - Nancy elif obj.source == 'WMO:07180': return odim_source.SOURCE["frnan"].encode(UTF8) # France - Nimes e...
The code validates and harmonizes radar data (ODIM) files by checking for payload presence, correcting PVOL/SCAN metadata inconsistencies, repairing source attributes, converting BUFR data to uint8 for efficiency, and addressing data-metadata mismatches (e.g., renaming TH to DBZH). It ensures compatibility with downstr...
def Validate(rio): # Zero check: do we have a payload? if not rio.object: raise IOError("Failed to read file.") # First ODIM violation fix: ODIM_BUFR cannot tell the difference between # a SCAN and a PVOL. ODIM_H5 can. if rio.objectType == _raveio.Rave_ObjectType_PVOL and rio.object.getNumb...
def send_chat_action(self, update, context, action): """Send a chat action to indicate the bot's status.""" try: context.bot.send_chat_action(chat_id=update.effective_chat.id, action=action) except telegram.error.TimedOut: logging.error("Timed out while sending chat actio...
This method handles Telegram button clicks by retrieving user data based on callback queries. It processes actions like text-to-speech (TTS) generation, summarization, paraphrasing, and elaboration. It logs interactions, uses a database manager to fetch data, and sends appropriate responses via audio/text, with error h...
def button_click(self, update, context): query = update.callback_query user_id = query.from_user.id if query.from_user else None if user_id is not None: callback_data_parts = query.data.split("_") if len(callback_data_parts) == 2 : data_id = int(callback_...
def pick_word(self, file): self.target = "default" try: with open(file, "r") as f: # First line of file is source of word list f.readline() # Second line of file is number of words count = int(f.readline().strip()) ...
This code initializes a Hangman-style game by setting up the screen, loading a target word from a file, tracking game state variables (correct letters, guesses remaining), and creating UI buttons for letter guessing, difficulty selection, and restarting the game. It prepares the game environment for player interaction.
def __init__(self, screen): self.screen = screen self.font = pygame.font.SysFont("Ariel", 50) self.target = "default" self.file = "easy.txt" self.pick_word(self.file) # Boolean array of which letters have been correctly guessed self.correct_letters = [False] * le...
def handle_get(): get() def handle_update(): print ("Please choose which entry to update.") update() def handle_add(): # obtain details for our new entry from the user print() print ("Please enter details of your new entry.") album = input("Album Title: ") print() artist = input("Arti...
This code defines a menu-driven application that allows users to interact with a data set through options like looking up, updating, adding, deleting entries, or displaying all entries. It repeatedly prompts the user for input, executes the corresponding function based on their choice, and exits when the user selects o...
def main(): print() print ("1. Lookup an entry \n2. Update an entry \n3. Add an entry \n4. Delete Entry \n5. Show All \n0. Exit") response = int(input("Please choose an option: ")) while response != 0: if response == 1: handle_get() elif response == 2: handle_update()...
def compute_parameters(self, code_block): parameters = [] app.logger.debug("Compute parameters for %s" % code_block) try: for line in code_block: app.logger.debug("Scan line for parameters: %s" % line) if line.type == "assignment": ...
The main task of the code is to generate a modular code package from a given code block. It creates a dictionary with a randomly named part, extracts required imports, computes parameters/return variables, generates a 'main' method, and compiles dependencies into app.py, requirements.txt, and a polling agent script. Th...
def gen_part_from_block(self, code_block): part = {'name': "part_" + ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))} # TODO only import the needed packages preamble = self.all_imports[:] # Compute list of parameters parameters = self.compute_parameters(cod...
def which_code_block(node, code_blocks): for i in range(len(code_blocks)): if node in code_blocks[i]: return i return -1 def gen_iterator(self, list): iterator_name = "it_" + ''.join(random.choices(string.ascii_uppercase + string.digits, k=5)) iterator_template_path = os.pat...
This function processes a list of nodes to generate script parts and update a workflow structure. It handles control flow constructs like loops (while/for) and if-else blocks, adding corresponding workflow markers (start_while, start_for, start_if, etc.) and recursively processing nested nodes. It integrates standalone...
def build_base_script(self, nodes, code_blocks, result_workflow): script_parts = [] for node in nodes: # if node is not in any code block if which_code_block(node, code_blocks) == -1: if node in self.SPLITTING_LABELS and self.SPLITTING_LABELS[node] == Labels.LOOP:...
def get_initial_labels(self, script): labels = {} for baron_node in script: app.logger.debug('Label code line: %s...' % repr(baron_node.dumps())) # Handle imports if baron_node.type in ['import', 'from_import']: app.logger.debug('Found import --> IMP...
The main task of the code is to generate and refine labels for code blocks by initializing labels, iteratively relabeling non-hybrid blocks (e.g., ifs, whiles) to "QUANTUM/CLASSICAL," applying thresholds to adjust labels, and repeating until convergence or max iterations (10), finally returning the refined labels for a...
def get_labels(self): # Get Initial labels labels = self.get_initial_labels(self.ROOT_SCRIPT) app.logger.debug("Initial Labels:") for key, value in labels.items(): app.logger.debug("LABEL: %s - %s" % (value, repr(key.dumps()))) # If code blocks (ifs, whiles, etc.) a...
def cards_iterate(step=1): """ Iterates through coach profile cards on a web page, extracting data using `get_data_from_tab`. Parameters: - step: The index of the coach profile card to start iterating from. """ try: element = browser.find_element(By.XPATH, f"//div[@class='{div_cards_cla...
The main task of the code is to iterate through pages of coach profiles on a web page, extract data from each page's cards using `cards_iterate()`, save the extracted data to a CSV file, and recursively navigate to the next page until no more pages are available. The function handles pagination by clicking "next page" ...
def iterate_page(page=1): """ Iterates through pages of coach profiles on a web page, calling `cards_iterate` for each page. Parameters: - page: The page number to start iterating from. """ global csv_data try: if page > 1: # If on a page greater than 1, click the next ...
def init_sim(self): self._captured_frames_since_restart=0 self._agent_location_on_last_capture = None self._frames_since_last_capture = 0 #####reset stuff ######## if self.world: if self.display_manager: self.display_manager.destroy() sel...
This code runs a CARLA simulation loop using PyGame, handling rendering, event input, data saving, and cleanup. It initializes the simulation, continuously updates the world state, renders visuals, checks for reset conditions, and exits upon user input or reaching 10,000 frames. Finally, it destroys CARLA actors and th...
def run(self): """Launch the PyGame.""" #Simulation loop call_exit = False self.init_sim() try: while True: time.sleep(0.01) self.world.tick() #world.wait_for_tick() # Render received dat...
def load_wallets() -> list[Account]: """Load private keys from private.json.""" with open("private.json", "r", encoding="utf8") as file: wallets = json.load(file) wallets = [Account.load_key(key) for key in wallets] logger.info(f"Load {len(wallets)} wallets from file") return wallets def ge...
The main task of the code is to load or generate wallets, disperse APT cryptocurrency to them using a main account, execute multi-mint operations, and log progress. It initializes wallet handling, transfers funds, performs minting actions, and confirms completion with logging.
def main(): logger.info("Start abuz") if EXIST_WALLETS: wallets = load_wallets() else: wallets = generate_wallets(WALLETS_AMOUNT) disperse_apt_to_wallets(main_acc=main_acc, target_wallets=wallets) multi_mint(wallets) logger.success("All done")
def parse_cl_args(): argParser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawTextHelpFormatter, ) argParser._action_groups.pop() required = argParser.add_argument_group('Required arguments') required.add_argument( 'file_or_dir', nargs='*', ...
The main task of the code is to parse command-line arguments, configure printing and progress settings, retrieve file/directory contents, and execute tokenization using parallel workers. It returns a success status after processing input content with configurable print options and worker count.
def run_main(): args = parse_cl_args() do_print = not args.dont_print print_progress_int = { None: 100, False: -1, }.get(args.print_progress, args.print_progress) content_generator = get_file_or_dir_contents(args.file_or_dir) run_tokenize( args.file_or_dir, proc...
def print_card(selected_card, all_cards): children = get_children_of_selected(selected_card, all_cards) print("\n") print(selected_card['title'].upper()) print(selected_card['text']) if selected_card.get('text_exceeds_500'): print(f"!!WARNING: Text length is {len(selected_card['text'])}!!") ...
This function handles user actions on a card system, allowing navigation (view, browse children, go to parent), creation, editing, and deletion of cards. It updates the selected card and action state based on user input, returning both for further processing.
def perform_action(action, selected_card, all_cards): if action == 'View this card': print_card(selected_card, all_cards) action = ask_for_next_action() if action == 'Browse children': children = get_children_of_selected(selected_card, all_cards) if not children: pr...
def select_square(turn,pos): piece_selected=False #is a piece selected while not piece_selected: #print(pos) #pos of click x=int(pos[0]/square_size) y=int(pos[1]/square_size) try: if board.board[x][y].get_piece() and board.board[x][y].get_piece_color()==turn: ...
This code implements a turn-based game loop for a chess-like game using Pygame. It handles player turns (WHITE/BLACK), selects pieces, validates moves, highlights possible moves, processes mouse input for piece selection/movement, and updates the board state. The loop ensures valid moves, checks for check conditions, a...
def game(): turn=WHITE while True: move_completed=False #if true, give control to other player #king_in_check=Piece.King.kingCheck(turn) #is the king currently in check while not move_completed: valid_square_selection=False valid_move_selection=False ...
def normalize(X): mean =X.mean(axis=0) std = X.std(axis=0) X = (X - mean)/std return X, mean, std def encode(y): y_en = [] y_en = [1 if i == 'M' else 0 for i in y] return np.array(y_en) def fit_LogisticRegression(X, y, epochs, lr=0.01): w, X = initializ...
The function performs leave-one-out cross-validation for a logistic regression model. It iterates through each data point, trains the model on all but one sample, predicts the left-out sample, and calculates the overall accuracy by comparing all predictions to true labels.
def leave_one_out_evaluation(X, y): predictions = [] for i in range(len(X)): test_X = [X[i]] train_X = np.delete(X, i, axis=0) train_y = np.delete(y, i, axis=0) train_X_std, mean, std = normalize(train_X) train_y_en = encode(train_y) ...
def get_optimal_split(self, dataset, num_samples, num_features): # the best splitss in a blank dictionary optimal_split = {} maximum_info_gain = -np.inf # loop through each feature for feature_index in range(num_features): feature_values = data...
This function recursively constructs a decision tree by splitting the dataset based on optimal information gain. It checks stopping conditions (minimum samples and maximum depth), selects the best split, and creates internal nodes with left/right subtrees. If splitting isn't possible, it returns a leaf node with calcul...
def constructing_trees(self, dataset, curr_depth=0): X, y = dataset[:, :-1], dataset[:, -1] num_samples, num_features = np.shape(X) # dividing the data until the required conditions for pruning are met if num_samples>=self.min_samples_split and curr_depth<=self.max_depth:...
def increase_by_one(matrix): for i, row in enumerate(matrix): for j, value in enumerate(row): matrix[i][j]['level'] += 1 def flash(matrix) -> int: flashes = 0 for i, row in enumerate(matrix): for j, octopus in enumerate(row): if octopus['level'] > 9 and not octopus['f...
The code reads a matrix from a file, simulates an iterative process where each element increments and flashes when reaching a threshold, counts total flashes, and stops when all elements flash simultaneously, printing the iteration count and total flashes.
def main(): with open('data.txt', 'r') as f: data = f.readlines() matrix = [] for line in data: row = line.strip() row_numbers = [{'level': int(n), 'flashed': False} for n in row] matrix.append(row_numbers) flash_counter = 0 iteration = 0 ...
def check_neighbour(x, y, value, locations): if x < 0 or y < 0: return True try: if locations[x][y] > value: return True else: return False except IndexError: return True def traverse(x, y, locations): # TRY UP result = 1 locations[x][y] = ...
The code reads a grid of integers from 'input.txt', identifies cells with all four adjacent neighbors (up, down, left, right), traverses from those cells, and computes a result from the collected values. It processes the grid to find valid starting points, explores their paths, and aggregates outcomes using `get_result...
def main(): with open('input.txt', 'r') as f: data = f.readlines() locations = [] for line in data: row = line.strip() row_numbers = [int(n) for n in row] locations.append(row_numbers) numbers = [] for i, row in enumerate(locations): ...
def list_asset_generator(): for asset_model in list_asset_model_generator(): token = None first_execution = True while first_execution or token is not None: first_execution = False asset_list_result = list_assets_from_sitewise(asset_model["id"], next_token=token) ...
The code processes assets by generating files in NDJSON format for each asset's properties and uploading them to an S3 bucket. It retrieves asset details, extracts property information, formats the data, and stores it in S3 with a structured key. The task is triggered by an event containing bucket and prefix parameters...
def lambda_handler(event, context): bucket_name = event['bucket_name'] key_name_prefix = event['key_name_prefix'] for asset in list_asset_generator(): asset_summary = describe_asset_from_sitewise(asset["id"]) asset_property_list = extract_asset_property_details( asset_summary, a...
def parts_for(ty): st = syntax[ty] parts = [] for ps in st: if random.random() < ps[0]: if type(ps[1]) == type(None): parts.append(ps[2]) elif type(ps[1]) == type(""): parts.extend(parts_for(ps[1])) else: parts.appen...
The code converts a given type (ty) into a naming format: camelCase for "class" types and snake_case for others, by splitting, processing, and joining parts derived from the input.
def single_name(ty): parts = [] for x in parts_for(ty): parts.extend(x.split("_")) parts = post_processs_parts(parts) if ty == "class": return camelCase(parts) return "_".join(parts)
def stopCriteria(dataSet): ''' Criteria to stop splitting: 1) if all the classe labels are the same, then return the class label; 2) if there are no more features to split, then return the majority label of the subset. Parameters ----------------- dataSet: 2-D list [n_sampels, m_fe...
The code constructs a decision tree recursively by selecting the best feature to split the dataset, creating nested dictionaries to represent the tree structure, and applying stopping criteria to assign class labels. It partitions data based on unique feature values and repeats the process for each subset until all sam...
def buildTree(dataSet, featNames): ''' Build the decision tree Parameters ----------------- dataSet: 2-D list [n'_sampels, m'_features + 1] the last column is class label Returns ------------------ myTree: nested dictionary ''' assignedLabel = stopCriteria(d...
def _create_application(self): """To create the Vortex application""" setup_file_str = str(self._setup_file_path) self.app = vxatp3.VxATPConfig.createApplication(self, self.application_name, setup_file_str) self.set_app_mode(AppMode.EDITING) def _load_scene(self): """To load the ...
This code initializes a Vortex simulation environment by configuring parameters, loading scene files from specified directories, validating simulation time steps, setting up rendering displays based on viewpoints, and advancing the simulation by one step. It handles asset paths, application creation, and display initia...
def __init__( self, assets_dir: Path, config_file: str, content_file: str, h=0.01, viewpoints: list = [], # Name of the viewpoints to render. '' for default render: bool = True, ) -> None: self.sim_time = 0.0 self.step_count = 0 # Step counte...
def _wrap_dataloader(self, dataloader): if self.verbose: dataloader = tqdm(dataloader) return dataloader def process_one_pair(self, ru_vector, eng_vector): """ ru_vector shape [batch_size, seq_len_1, fast_text_vect] eng_vector shape [batch_size, seq_len_2, vocab_size]...
The main task of the code is to train a model over multiple epochs using a dataloader, compute loss metrics for each batch, log training and validation performance, and save the model if the validation loss improves. It processes Russian and English input vectors, validates periodically, and retains the best model base...
def train(self, dataloader, validation_dataloader): dataloader = self._wrap_dataloader(dataloader) for current_epoch in range(1, self.epoch + 1): if self.verbose: print(f"Epoch {current_epoch}") metric_dict = {LOSS_VAL: 0} for batch in dataloader: ...
def reload_config(self): try: with open(self.runtime_config_path, mode="r") as file: new_config = json.load(file) self.runtime_config_dict = new_config except Exception: traceback.print_exc() def _wrap_dataloader(self, dataloader): if self.verb...
This code trains a model over multiple epochs using a training dataloader, computes loss metrics, normalizes cumulative loss, logs training statistics, validates the model with a validation dataloader, saves the best model based on loss improvement, creates periodic checkpoints, and terminates training if a stop comman...
def train(self, dataloader, validation_dataloader): for current_epoch in range(self.start_epoch, self.epoch + 1): self.reload_config() epoch_dataloader = self._wrap_dataloader(dataloader) if self.verbose: print(f"Epoch {current_epoch}") metric_dic...
def bitwise(self, raw_data, m, b, rb): M_raw = ((int(m, 16) * 0xC0) << 2) + (int(m, 16) >> 8) B_raw = ((int(b, 16) & 0xC0) << 2) + (int(b, 16) >> 8) Km_raw = int(rb, 16) >> 4 Kb_raw = int(rb, 16) & 0x0F M_data = self.toSigned(M_raw, 10) B_data = self.toSigned(B_raw, 10...
The function `sensorValueResolve` processes sensor data by parsing attributes (e.g., `STYPE`, `L`, `READING`) to determine the sensor type and apply specific conversion logic. It calculates a processed value using bitwise operations or mathematical functions (e.g., squaring), scales it, and checks thresholds to assign ...
def sensorValueResolve(self, sensor): SensorReadingScale = 1000 _L = sensor.getAttribute("L") _STYPE = sensor.getAttribute("STYPE") _M = sensor.getAttribute("M") _B = sensor.getAttribute("B") _RB = sensor.getAttribute("RB") _READING = sensor.getAttribute("READIN...
def sensorType(self, id): sensorDef = { "01": "temperature", "02": "voltage", "04": "fanspeed", "05": "chassis", "08": "psu", "c0": "OEM Sensor", "0d": "hdd", "c1": "wattage", } try: ret...
The main task of the code is to parse XML sensor data from `_data`, extract sensor attributes, categorize them by type, resolve values and states, and store structured sensor information in `self.sensorDB`. It handles parsing errors by logging them, processes sensor-specific data (e.g., temperature, voltage, PSU status...
def sensorProcess(self, _data): self.sensorDB = {} try: doc = minidom.parseString(str(_data)) except Exception as e: if self.LOG: with open("ipmi_poller_err", "a+") as fo: fo.write( str(datetime.datetime.n...
def search_image(url): try: params = { 'image_url': url, 'hl': 'es', } query = BASE_SEARCH_URL % urllib.parse.urlencode(params) f = opener.open(query) url = f.url f = opener.open(url) html = f.read() set_referer(f.url) return html except: pass def get_simi...
The main task of the code is to analyze tweets' images for authenticity by comparing them with web search results, checking metadata, dates, and image similarity. It updates a database with findings, marks images as fake/real, and logs results into text files. The process involves cleaning directories, parsing CSV data...
def main(): global URLFAKE with open("config.json") as json_data_file: data = json.load(json_data_file) mydb= cnx.database_connection() if (os.path.isdir("./"+sys.argv[1])): shutil.rmtree("./"+sys.argv[1]) if os.path.exists("./"+sys.argv[1]+"/reales.txt"): os.remove("./"...
def split_expression(expression): result = [] number = '' for char in expression: if char.isdigit() or char == '.': number += char else: if number: result.append(number) number = '' if char in get_operator_dict().keys(): ...
The code evaluates a mathematical expression string using a stack-based approach, adhering to operator precedence and parentheses. It tokenizes the input, processes numbers and operators, handles unary and binary operations, and computes the result by resolving operations in correct order. The final value is rounded to...
def evaluate_exp(exp: str, op_dict: dict) -> float: vld.validate_exp(exp) exp = exp_manipulation.manipulate_string(exp) tokens = split_expression(exp) values = [] operators = [] for token in tokens: if is_number(token): values.append(token) elif token == '(': ...
def get_metadata(self, filepath): """ Gets metadata from epub files with 3 possible parsers ebooklib, epub_meta, lector """ full_metadata = {} # Read using ebooklib if "ebooklib" in self.parsers: try: metadata_1 = epub.read_epub(filepath) ...
The main task of the code is to sort books by extracting EPUB metadata (author, title) from each file in `file_list`, generating a structured path (e.g., "Author/Title/book.epub"), and either copying or moving the file to this new location based on the `copy_files` flag. It skips files with invalid metadata and logs pr...
def start_book_sorter(self): """ takes every file in file_list and gets the epub metadata and creates a new path for it based on author and book title Terry Goodkind / Wizards First Rule / book.epub author title file """ print("(+) stari...
def nearest(self, goal): """ Finds the nearest neigbour to the goal """ min_dist = 99999999 for vertex in self.nodes: dist = self.duration(vertex.pose, goal) if dist < min_dist: min_dist = dist nearest = vertex retur...
The code implements the RRT* algorithm to expand a tree for path planning in configuration spaces (R², R³, SE(2), SE(3)). It generates random samples, connects them to the nearest tree node via steering, checks collision-free paths, and optimizes by rewiring nearby nodes within a radius. The tree is built with nodes an...
def expand_tree(self, start, space, number_of_samples, neighborhood_radius, collision_step, isrrtstar, steer_step): """Expand the RRT(*) tree for finding the shortest path Args: start: Pose - start configuration of the robot in SE(3) coordinates space: String - configuration ...
def parse_lbl_def(tokens, symbols, code, line): er = ["<error>"] if not tokens: return 0 if(tokens[0][0] == "<lbl_def>"): lbl = tokens[0][1] if lbl[:-1] in symbols.labelDefs: error("Label already in use!",line) return er elif lbl[:-1] in table.reserved...
The main task of the code is to parse a line of code into labeled definitions, directives, or code segments. It checks for exactly one valid component (label, directive, or code) without leftover tokens. If invalid, it returns an error; otherwise, it compiles the parsed elements into a list with a "<line>" tag.
def parse_line(tokens, symbols, code, line): data = ["<line>"] er = ["<error>"] if(len(tokens) == 0): return 0 ################################ # [lbl_def] lbl_def = parse_lbl_def(tokens, symbols, code, line) if(lbl_def): if(lbl_def == er): return er data....
def lexer(lines): tokens = [] code_lines = [x for x in lines if len(x[1])] for line in code_lines: tl = [] for word in line[1]: word = word.strip() if word in table.mnm_0: tl.append(["<mnm_0>", word]) elif(re.match(r'^(0[Xx])?[0-9A-Fa-f]{2}...
The code parses input lines into an abstract syntax tree (AST) using a lexer and parser. It processes each line, checks for errors during parsing, and constructs a tree structure. After parsing, it performs a second pass on symbols and code for validation. If any step fails (e.g., errors in parsing or validation), the ...
def parse(lines, symbols, code): code_lines, tokenLines = lexer(lines) if(code_lines == 0): sys.exit(1) tree = [] for tokens, line in zip(tokenLines, code_lines): parsed_line = parse_line(tokens, symbols, code, line) if(parsed_line[0] == "<error>"): sys.exit(1) ...
def parse(s): return [i.splitlines() for i in s.split("\n\n")] def hor_mirror2(grid): rows, cols = grid2bin(grid) m, n = len(rows), len(cols) for r in range(1, m): sec1 = rows[r - 1 :: -1] sec2 = rows[r:] valid = min(len(sec1), len(sec2)) if (join_bins(sec1[:valid], n) ^ ...
The code processes grids by checking for horizontal and vertical mirrors. For each grid, it adds 100 times the horizontal mirror position to the result if found; otherwise, it adds the vertical mirror position. The main task is to compute a weighted sum of mirror positions in multiple grids for a given input.
def part2(inp): grids = parse(inp) res = 0 for grid in grids: if (h := hor_mirror2(grid)) is not None: res += 100 * h elif (v := ver_mirror2(grid)) is not None: res += v return res
def set_size(self, event, size: tuple = (5,5)): ''' Sets the size of the sliders to specific values ''' self.scale_x.set(size[0]) self.scale_y.set(size[1]) self.resize(None) def GetContrast(self, event): return self.contrast_slider.get() def GetColor(self, event):...
This code initializes a GUI for a Pixel Art Generator using Tkinter. It sets up a window with buttons for image selection, size adjustments, contrast/saturation sliders, and text output. The interface allows users to load images, modify their dimensions, apply enhancements, and save results, with two image panels for d...
def __init__( self, window_width: int = 1600, window_height: int = 900) -> None: self.root = tk.Tk() self.root.title('Pixel Art Generator') self.raw_image = None self.raw_scaled = None self.im1 = None self.im2 = None # Set x and y coordin...
def GetScaleX(self, event): return self.scale_x.get() def GetScaleY(self, event): return self.scale_y.get() def GetPixelArtDisplayImage(self, img: Image, i_size: tuple, o_size: tuple): ''' Takes an image and resamples it twice to get a pixelated version ...
The code selects an image file, resizes it to fit within a dynamic scale (max 500x900), generates a pixel-art version, and updates display elements. It stores raw/resized images, calculates scaling factors, and triggers drawing/enhancement updates.
def PickImageFile(self): f = fd.askopenfilename() # Check if a file was selected if f == '': return 1 im1 = Image.open(f) # Raw image for whatever purpose self.raw_image = Image.open(f) # Current size of the image size = (im1.width, im1.hei...
def is_armed(self): """ Specifies if the vehicle is armed. """ return self.is_connected() and self.__state_sub.data.armed def set_mode(self, new_mode, wait_for_new_mode = False): """ Sends a request to set the vehicle in a new mode. """ resp = self.__set_m...
The code requests the vehicle to land by setting its mode to PX4_MODE_LAND if armed. If 'block' is True, it waits until the vehicle disarms (indicating landing completion). If not armed, it logs an error.
def land(self, block = False): """ Requests that the vehicle land. """ if self.is_armed(): self.set_mode(px4_modes.PX4_MODE_LAND) if block: self.wait_for_status(self.is_armed, False, 1) else: rospy.logerr("Vehicle is not armed."...
def is_armed(self): """ Specifies if the vehicle is armed. """ return self.is_connected() and self.__state_sub.data.armed def set_mode(self, new_mode, wait_for_new_mode = False): """ Sends a request to set the vehicle in a new mode. """ resp = self.__set_m...
The function initiates a takeoff by setting the vehicle's mode to PX4 takeoff if armed. If 'block' is True, it waits for the vehicle to enter hovering mode (timeout 2s). If the vehicle is not armed, it logs an error.
def takeoff(self, block = False): """ Requests that the vehicle takeoff is possible. """ if self.is_armed(): self.set_mode(px4_modes.PX4_MODE_TAKEOFF) if block: self.wait_for_status(self.in_hovering_mode, True, 2) else: rospy.lo...
def add_visited_dir(self, loc, goal, route): self.visited_dir[(loc, goal)] = route def choose_transportation(self, route): pos_in_route = 0 for i in range(len(route)): if(route[i] == self.current_location): pos_in_route = i pair = (route[pos_...
The code's main task is to determine a route from the current location to a desired destination using A* algorithm if not previously stored, then select appropriate transportation and proceed. It checks if a precomputed route exists in 'visited_dir'; if not, it calculates the route, converts it to node values, stores i...
def move(self): if (self.current_location, self.desired_destiny) in self.visited_dir.keys(): route = self.visited_dir[(self.current_location, self.desired_destiny)] else: current,destiny=get_nodes_by_value(self.current_location, self.desired_destiny, self.obs_bus_stops) ...
def ask_file_save_exit(self): """(Mainframe) -> None If a filesave is pending on close, ask the user to save or drop the changes, or to cancel the close. If no filesave is pending, close. """ if self.get_file_changed(): # Create the dial...
The main task of the code is to handle window closure by prompting the user to save, discard, or cancel exiting. If not cancelled, it saves changes if confirmed, performs an automatic backup, and closes the window. The function checks the response to determine actions, ensuring data persistence before termination.
def on_exit(self, event, response = None): """(Mainframe, Event) -> None Close the window. First ask the user whether they want to save or scrap their work or cancel the close. This response is provided in advance if called by an OS window close. """ ...
def set_preferences(self, prefs): """(Mainframe, str) -> None Read the given string and set the preference variables. """ lines = prefs.split('\n') default_sort = lines[0] # This is saved as a string... if lines[1] == 'False': ...
(The main task of the code is to initialize a GUI application window using wxPython, setting up menus, UI elements (like coupon lists, input fields, and buttons), event handlers, and preferences. It creates a coupon management interface with features for adding, editing, sorting, and searching coupons, along with menu ...
def __init__(self, parent, title): """(Mainframe, Frame, str) -> Mainframe Construct the Mainframe. """ #------------------------------------------- # Initialize #------------------------------------------- # No-resize style ...
def requires_update(metrics, mode, name, best_value): """Returns True if a metric needs to be updated.""" assert mode in ["min", "max"] current_value = metrics[name] if mode == "min" and current_value < best_value: return True if mode == "max" and current_value > best...
This function updates the best hyperparameter metrics after a validation epoch by checking if current metrics (loss, precision, recall, f1) are better than the stored best value. If so, it logs new metrics, updates the best metric value, and saves results using the trainer's logger.
def update_best_metric(self, trainer, pl_module, split): """Updates the best hparams metrics after validation epoch.""" val_metrics = pl_module.val_metrics # the latest combined metrics best_value = pl_module.val_best_metric # the best value (so far) mode = pl_module.cfg.monitor.mode ...
def findAllDaysAcrossYears(year,year1,month,month1): count_days_in_year = 0 for actualYear in range(year+1,year1): # print (actualYear) if leapyr(actualYear): count_days_in_year+=366 else: count_days_in_year+=365 count_days_in_year+=findAllDaysInYear(month,yea...
The code calculates the number of days between two given dates by splitting the dates into day, month, and year components, then handling different scenarios based on year and month differences. It uses helper functions to compute days across years, between months, and additional days, summing them to return the total ...
def datediff(date, date1): day,month,year = date.split("/") ## split the date into 3 separate variables. day1,month1,year1 = date1.split("/") ## split the date into 3 separate variables. year = int(year) year1 = int(year1) month = int(month) month1 = int(month1) day = int (day...
def heapify(self,array): """ Put elements of array in heap order. """ start = self.parentIdx(array.size - 1) while start >= 0: array = self.siftDown(array, start, array.size-1) start = start - 1 return array def swap(self, array, idx1, idx2): ...
The code implements the Heap Sort algorithm to sort an array and measures the elapsed time. It first checks if the array is empty, then initializes a timer. The array is heapified, followed by repeatedly swapping the root with the last element and sifting down to maintain the heap property. The sorted array is stored i...
def sortArray(self): """ Sorts array using Heap Sort https://en.wikipedia.org/wiki/Heapsort Returns: - time (float): elapsed time to sort the array Updates: - self.output: the sorted array """ if (self.arraySize == 0): print("Pl...
def create_population(self): population = [] indices = list(range(len(self.coords))) for i in range(self.pop_size): tour = random.sample(indices, len(self.coords)) population.append(tour) self.population = population return population def fitness(self, tou...
The code implements a genetic algorithm to evolve a population of tours over multiple generations, tracking the best tour and its fitness. It iteratively evaluates each generation's fitness, updates the best solution found, and prepares for the next generation. The main task is to optimize tour solutions by selecting, ...
def solve(self): self.create_population() best_tour = None best_fitness = 0 fitness_values = [] for i in range(self.generations): fitness_scores = [self.fitness(tour) for tour in self.population] max_fitness = max(fitness_scores) fitness_values...
def getFocusDb(): retVal = None if not path.exists(focusDbFilePath): setupFocusDb() with open(focusDbFilePath, 'r') as dbf: retVal = json.loads(''.join(dbf.readlines())) return retVal def workspaceExists(name): db = getFocusDb() return name in db['workspaces'].keys() def publishF...
The main task of the code is to add a new workspace to a database if it does not already exist. It retrieves the database, checks for the workspace's existence, creates an empty entry for it if absent, and then updates the database with the new workspace.
def addWorkspace(name): db = getFocusDb() if not workspaceExists(name): db['workspaces'][name] = {} publishFocusDb(db)
def getCurrentWorkspace(): db = getFocusDb() if db['cws'] == '': print(f'No workspace has been activated, activate one with \'ws\' command first') sys.exit() return db['cws'] def workspaceExists(name): db = getFocusDb() return name in db['workspaces'].keys() def getFocusDb(): ret...
The function checks if a specified name exists in the focus database for a given or current workspace. It first validates the workspace existence, retrieves the focus database, and returns whether the name is a key in the workspace's entry.
def focusExists(name, ws=None): ''' THIS ASSUMES ws EXISTS WHEN SPECIFIED''' if not ws: ws = getCurrentWorkspace() elif not workspaceExists(ws): print(f'Error: specified workspace {ws} not found.') sys.exit() db = getFocusDb() return name in db['workspaces'][ws].keys()
def getCurrentWorkspace(): db = getFocusDb() if db['cws'] == '': print(f'No workspace has been activated, activate one with \'ws\' command first') sys.exit() return db['cws'] def workspaceExists(name): db = getFocusDb() return name in db['workspaces'].keys() def addWorkspace(name): ...
The function verifies the existence of a workspace. If not provided, it retrieves the current workspace. If the specified workspace doesn't exist, it either creates it (if `create=True`) or exits with an error message. It ensures a valid workspace is returned, handling cases where the workspace is missing or needs crea...
def verifyWorkspace(ws, create=False): if not ws: ws = getCurrentWorkspace() elif not workspaceExists(ws): if create: addWorkspace(ws) else: print(f'Workspace {ws} does not exist.') print(f'Specify -c/--create when registering or cr...
def workspaceExists(name): db = getFocusDb() return name in db['workspaces'].keys() def addWorkspace(name): db = getFocusDb() if not workspaceExists(name): db['workspaces'][name] = {} publishFocusDb(db) def getFocusDb(): retVal = None if not path.exists(focusDbFilePath): setu...
This function sets or unsets the current workspace. If no name is provided, it unsets the workspace. If a name is given, it checks if the workspace exists, creates it if allowed, or exits with an error. It then updates the database's 'cws' field with the specified name and publishes the updated database.
def setCurrentWorkspace(name=None, create=False): ''' Call without specifying any arguments to unset the current workspace ''' if not name: name = '' elif not workspaceExists(name): if create: addWorkspace(name) else: print(f'No registered workspac...
def getCurrentWorkspace(): db = getFocusDb() if db['cws'] == '': print(f'No workspace has been activated, activate one with \'ws\' command first') sys.exit() return db['cws'] def workspaceExists(name): db = getFocusDb() return name in db['workspaces'].keys() def focusExists(name, ws=...
The main task of the code is to remove a specified entry from the focus database under a given workspace. If no workspace is provided, it uses the current workspace. It validates the workspace existence, deletes the entry from the database if it exists, and updates the focus database with the changes.
def removeFocus(name, ws=None): if not ws: ws = getCurrentWorkspace() elif not workspaceExists(ws): print (f'no namespace \'{ws}\' found') if focusExists(): db = getFocusDb() del(db['workspaces'][ws][name]) publishFocusDb(db)
def verifyFocusPath(path, create=False): if not focusPath: focusPath = path.abspath(path.curdir) else: if not path.exists(focusPath): if create: os.mkdir(focusPath) else: print(f'Focus path {focusPath} does not exist.') prin...
This function adds or updates a focus entry in a database by validating the focus path and workspace, then storing the specified path under the given name and workspace. If the focus doesn't exist or an update is requested, it updates the database and publishes the changes.
def addFocus(name, ws=None, focusPath=None, create=False, update=False): focusPath = verifyFocusPath(focusPath, create) ws = verifyWorkspace(ws, create) if update or not focusExists(name, ws): db = getFocusDb() db['workspaces'][ws][name] = focusPath publishFocusDb(db)
def workspaceExists(name): db = getFocusDb() return name in db['workspaces'].keys() def getCurrentWorkspace(): db = getFocusDb() if db['cws'] == '': print(f'No workspace has been activated, activate one with \'ws\' command first') sys.exit() return db['cws'] def setCurrentWorkspace(n...
The main task of the code is to remove a specified workspace from the database. It first checks if the workspace exists, then ensures it is not the current workspace (if so, it sets a new current workspace). Finally, it deletes the workspace entry from the database and updates the focus database with the changes.
def removeWorkspace(name): if workspaceExists(name): if getCurrentWorkspace() == name: setCurrentWorkspace() db = getFocusDb() del(db['workspaces'][name]) publishFocusDb(db)
def getFocusDb(): retVal = None if not path.exists(focusDbFilePath): setupFocusDb() with open(focusDbFilePath, 'r') as dbf: retVal = json.loads(''.join(dbf.readlines())) return retVal def getCurrentWorkspace(): db = getFocusDb() if db['cws'] == '': print(f'No workspace ha...
This function retrieves or creates a focus path entry in a specified workspace. It checks if a focus exists by name; if not and 'create' is True, it adds the focus with the given path. The function returns the database entry for the focus in the workspace, handling workspace creation if needed.
def getFocusPath(name, ws=None, focusPath=None, create=False): db = getFocusDb() if not ws: ws = getCurrentWorkspace() else: setCurrentWorkspace(ws, create) if not focusExists(name, ws): if create: addFocus(name, ws, focusPath, create) return db['workspaces'][ws...
def openLoggingFile(self): self.file_hanlder = FileHandler(filename="log.txt", encoding='utf-8', mode="a") self.file_hanlder.setFormatter(self.formatter) self.logger.addHandler(self.file_hanlder) def closeLoggingFile(self): handler = self.logger.handlers[:] for h in handler: ...
The code captures and processes video frames from a camera, handling both Raspberry Pi and standard camera inputs. It manages logging, FTP uploads, and conditional storage of images/videos based on settings. It also performs periodic checks, triggers data analysis at intervals, and allows real-time frame display with e...
def collect(self): cv2.namedWindow("Execute", cv2.WINDOW_NORMAL) cv2.resizeWindow("Execute", 640, 480) if self.os == 'pi': for image in self.camera.capture_continuous(self.PiRGBArray, format="rgb", use_video_port=self.video_port): self.openLoggingFile...
def encode_file(self, file, part_size, end_of_file: WrapValue, pbar: tqdm) -> bitarray: bit_arr = bitarray() num_bytes = 0 for line in file: for ch in line: bit_arr += self.table_of_codes[ch] update_pbar(len(line), pbar) b = line.encode('utf-8'...
This function encodes a source file into a compressed format by processing it in 64KB chunks, splitting bit arrays for writing, adding padding, and writing a header with metadata. It handles large files efficiently, tracks encoding progress, and ensures proper file structure for decompression by combining encoded data ...
def encode_and_write(self, source, dest) -> None: input_file_size = os.path.getsize(source) / 1024 / 1024 print(f'Size of input file: {str(input_file_size)} Mb') with open(file=source, mode='r') as f_in, open(file=dest, mode='wb') as f_out: # if file is large then we must split it an...
def define_freq(self, path: str) -> None: with open(path, "r") as f: pbar = tqdm(total=float(os.path.getsize(path) / 1024 / 1024), unit="Mb", unit_scale=True, desc="Read to define frequency") for line in f: for ch in list(li...
This code compresses a source string using Huffman coding by calculating character frequencies, building a Huffman tree, generating binary codes, validating the code table, and writing the encoded data to a destination file.
def compress(self, source: str, dest: str) -> None: self.define_freq(source) self.nodes = [Node(letter=k, freq=v) for k, v in self.char_freq.items()] self.create_huffman_tree() if len(self.char_freq.keys()) == 1: self.create_table_of_codes(self.nodes[0], '0') else: ...
def read_from_file(self, f) -> int: header, header_bytes = self.read_header(f) header = WrapValue(header) root_node = Node(left=None, right=None) self.nodes.append(root_node) if len(header.val) == 2: self.restore_tree(root_node, header, '0') else: ...
This code decompresses a file by reading header data, processing blocks in 64KB chunks, and decoding them while updating a progress bar. It handles padding bits, checks for encryption, and writes decompressed data to the destination. The loop processes blocks until the file ends, ensuring proper decompression and progr...
def decompress(self, source: str, dest: str) -> None: with open(source, "rb") as f: partition_size = 1024 * 64 header_bytes = self.read_from_file(f) pbar = tqdm(total=float(os.path.getsize(source) / 1024 / 1024), unit="Mb", unit_scale=True, ...
def move_east(mat): return move_south(mat.T).T def move_south(mat): return np.flip( move_north( np.flip( mat, 0 ) ), 0 ) def move_west(mat): return move_north(mat.T).T def move_north(mat): mat2 = np.copy(mat) mat2[ma...
The code defines a function `cycle` that applies four sequential directional shifts to a matrix: first moving north, then west, followed by south, and finally east. The main task is to perform a cyclic permutation of the matrix elements through these four movements, effectively rearranging the matrix's contents in a sp...
def cycle(mat): return move_east(move_south(move_west(move_north(mat))))
def vehicles_menu(self): """ CRUD ops for vehicles """ questions = [ inquirer.List( "opts", message="Vehicle menu", choices=[ ("Stats", "s"), ("Add", "a"), ("Edit", "e"...
This function displays a main menu with options to navigate to Vehicles, Records, Plots, or exit. It uses the `inquirer` library to prompt user selection, then triggers corresponding methods (`vehicles_menu`, `records_menu`, `plot_menu`) or terminates the application by setting `is_running` to False when "Exit" is chos...
def show_main_menu(self): """ Main menu """ questions = [ inquirer.List( "opts", message="Things to do", choices=[ ("Vehicles", "v"), ("Records", "r"), ("Plots", "p"), ...
def connect_to_database(): cnx = pymysql.connect( user='root', password='test123!', host='172.26.105.1', port=3306, database='projecthosting' ) return cnx def get_user_id(email:str): # connect to the database db_connection = connect_to_database() # creat...
The function updates the admin of a specified project by modifying the 'projects' table to set a new admin ID derived from an email, then removes the previous admin's participation and adds the new admin's role in the 'participations' table.
def change_admin_of_project(projectname:str, email:str): # make connection with the database db_connection = connect_to_database() # create a cursor cursor = db_connection.cursor() # create query and execute it (table projects) query = "UPDATE projects SET admin_id = " + str(get_user_id(email)...
def and_(a: bool, b: bool) -> bool: """ >>> and_(False, False) False >>> and_(True, False) False >>> and_(False, True) False >>> and_(True, True) True """ return not_(nand(a, b)) def or_(a: bool, b: bool) -> bool: """ >>> or_(False, False) False >>> or_(True, ...
The code implements an XOR function using logical operations. It returns `True` when exactly one of the boolean inputs (`a` or `b`) is `True`, aligning with standard XOR behavior. The function combines `or_` (logical OR) and `nand` (NOT AND) operations via `and_` (logical AND) to achieve this. Test cases validate all f...
def xor(a: bool, b: bool) -> bool: """ >>> xor(False, False) False >>> xor(True, False) True >>> xor(False, True) True >>> xor(True, True) False """ return and_(or_(a, b), nand(a, b))
def retrieve(data): client = pymongo.MongoClient('mongodb+srv://darren_zhao:Hu8FZR8edfh2b0eP@cluster0.x5znh.mongodb.net/myFirstDatabase?retryWrites=true&w=majority') the_db = client[data] cursor = the_db.data.find_one() # print(cursor['Date']) dic_output = {} for thekey in cursor.keys(): ...
The code's main task is to explore Apple (AAPL) stock data by retrieving the dataset, performing time series analysis, analyzing yearly trends, examining feature correlations, and testing hypotheses. This comprehensive exploration aims to uncover patterns, relationships, and statistical significance in the financial da...
def explore(): AAPL_df = retrieve('AAPL_DATA') time_series_analysis(AAPL_df) time_series_analysis_by_year(AAPL_df) Feature_Correlation(AAPL_df) test_hypothesis(AAPL_df)
def acquire(): aapl_data = get_historical_data('AAPL') aapl_data.to_csv('AAPL.csv',index = False) get_news() news_cleaning() get_cleaning_cov_data() get_cleaning_carbon_data() get_cleaning_other_data() def store(): # Implement me, and remove the exception below. # Make sure...
The main task of the code is to execute a sequential data pipeline: acquiring data, storing it, processing it, exploring insights, and performing data inference. Each function likely handles a distinct stage in the data lifecycle, from collection to analysis and prediction.
def main(): acquire() store() process() explore() data_inference()