dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def update(self): """Sends update packets to all neighbouring routers""" self.router.print_forwarding_table() logger("Sending routing update to neighbouring routers...", 1) for neighbour in self.router.config.outputs.keys(): packet = RipPacket(self.router.config.router_id, ...
This code initializes a RIP (Routing Information Protocol) daemon by setting the router instance, sending initial updates to neighbors, configuring timers for periodic and triggered updates, and starting an event loop to manage routing processes. It logs the initialization and begins the routing loop for dynamic networ...
def __init__(self, router): """Sets self.router to router, sets other attributes to default, sends update to neighbours, start event loop""" self.router = router self.update() self.last_update = timer_refresh(1) self.triggered_update = -1 # timer for triggered updates lo...
def set_up(self, car=None): """resets the game""" self._first_choice = None self._second_choice = None self._reveal = None self._doors = [0, 0, 0] if car is None: car = random.randint(0, 2) self._doors[car] = 1 def first_pick(self, pick=None): ...
The code simulates the Monty Hall problem, where a player either switches or stays with their initial door choice based on the given strategy (0: always switch, 1: never switch, 2: random switch). It sets up the game, lets the player pick a door, reveals a goat, applies the strategy for the second choice, and returns w...
def play(self, strategy=0): """Strategy is how one plays the game 0 is always switch to the other door 1 is never switch (first choice is second choice) 2 is sometimes switch (random choice on second choice) Any other value will give the 0 strategy""" self.set_up() ...
def _init_golist(self): godag = GODag(obo_file=self.infile, optional_attrs="relationship") golist = list(set(godag.values())) # golist = [val for val in godag.values if val.namespace == "biological_process"] self.golist = golist def _extract_relationship(self): self.relationships...
The main task of the code is to initialize file paths for entity, relation, and training data, extract relationships, build entity and relation mappings, and construct a knowledge graph dataset for training. It prepares necessary files and structures data for downstream tasks like knowledge graph embedding or relation ...
def build(self): self.ent_file = self.outdir + "/entity2id.txt" self.rel_file = self.outdir + "/relation2id.txt" self.train_file = self.outdir + "/train2id.txt" # self.valid_file = self.outdir + "/valid2id.txt" # self.test_file = self.outdir + "/test2id.txt" self._init_g...
def selection(self, node): while not node.terminate: # expand the node if the node is not fully expanded if not node.isFullyExpanded: # return the selected node return node # if the current node is fully expanded, apply UCT to find next node t...
This code defines a thread task that repeatedly selects, expands, simulates, and backpropagates a node in a concurrent environment. It uses a lock to ensure thread safety during node selection and backpropagation, while handling termination or expansion failure conditions. The task runs up to 600 iterations, performing...
def thread_task(lock, node): for _ in range(600): lock.acquire() selected_node = self.selection(node) if selected_node.terminate: lock.release() break expanded...
def oneparts(parts, bfrt): dict_t = dictSetUp() addPart1ToDict(parts[0], dict_t) addDictToBfrt(dict_t, bfrt) def twoparts(parts, bfrt): dict_t = dictSetUp() addPart1ToDict(parts[0], dict_t) addPart2ToDict(parts[1], dict_t) addDictToBfrt(dict_t, bfrt) def threeparts(parts, bfrt): dict_...
The function `addDomainToTable` processes a domain string by splitting it into parts and adding it to a table structure via helper functions (`oneparts`, `twoparts`, etc.), depending on the number of parts (1–4). It validates the domain, rejecting inputs with more than four parts. The main task is to parse and insert d...
def addDomainToTable(domain, bfrt): parts = domain.split('.') numParts = len(parts) if numParts > 4: print("error: " + domain) return -1 if numParts == 1: oneparts(parts, bfrt) elif numParts == 2: twoparts(parts, bfrt) elif numParts == 3: threeparts(parts,...
def addDomainToTable(domain, bfrt): parts = domain.split('.') numParts = len(parts) if numParts > 4: print("error: " + domain) return -1 if numParts == 1: oneparts(parts, bfrt) elif numParts == 2: twoparts(parts, bfrt) elif numParts == 3: threeparts(parts,...
The main task of the code is to configure a network filtering system by adding a list of domains and IP ranges to respective tables. It populates a domain table with specified domains, adds banned IPs to a blocked list, and sets allowed IPs in a permitted list. The code uses global variables for rule prioritization, en...
def main(bfrt): global globalID global globalPriority '''domains = [ 'collector.brandmetrics.com', 'www.google.com', 'calendar.google.com', 'pxml10.4publishers.com', 's1.4publishers.com', 'ssl.gstatic.com', '*.skype.com', '*.live.com', 'messenger.hotmail.com', '*.*.msn.com', '*.msn.com', 'c...
def get_action_card_message(reference_number): check_triggers() history = parts_history() messages = json.loads(history) for message in messages['messages']: msg = message['msg'] if "Please click the link to view the parts order form for customer" in msg: action_card_referenc...
This function processes a user's action on a task message by extracting relevant details, checking if the task is already completed, notifying the user if so, and updating/ archiving the task status if not. It modifies the message content, logs the action, updates the chat, and archives the task and user completion dat...
def action_event(msg, user, channel_id): message_id = msg['_id'] ts = msg['ts'] message = msg['msg'] content = message.split() del content[:3] content.pop() content = " ".join(content) message = message.split()[-1] action_card_message = get_action_card_message(message) if action_...
def setup_logging(args): """Setup logger.""" logging.basicConfig( format="%(asctime)s %(name)-12s %(levelname)-8s %(message)s", datefmt="%m-%d %H:%M" ) logger = logging.getLogger("") if args.verbose: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) def r...
The code processes genomic data to generate a VCF file. It maps ENST identifiers to ENSG/HGNC IDs, reads reference contigs, builds a VCF header, and writes filtered records to output. It handles ENST-to-ENSG mappings, HGNC annotations, and contig-specific filtering based on a regex pattern.
def run(args): setup_logging(args) logging.info("Starting processing") logging.info("Arguments are %s", args) logging.info("Loading ENST to ENSG map") enst_to_real = {} # GRCh37 has ucsc ids for ENST, so we hack it ensg_to_ensts = {} with open(args.enst_ensg[0], "rt") as inputf: re...
def request_html(self, url, ip): get_ip = self.send_request(ip, Client.LOC,url) if get_ip: html = self.send_request(get_ip, Client.GET, url) return html return None def get_hrefs(self,html): indexes =[m.start() for m in re.finditer(' href=', html)] ...
This code recursively scrapes web pages starting from a given URL, saving HTML content into structured folders. It processes links up to a specified depth, checks for valid links, and stores each page's HTML with appropriate file extensions. The function returns True if a broken link is encountered, otherwise False upo...
def scrap(self,req_addr,url,depth, base_path='',folder_name=0): if depth<0: return folder =f'{base_path}/{folder_name}' os.makedirs(folder) html = self.request_html(url,req_addr) if html is None: return True links = self.get_href...
def request_successor(self, ip_port, idx): response = self.send_request(ip_port, Chord_Node.FS, str(idx)) if response: return json.loads(response) return None def start_idx(self,k): return (self.id + 2**(k-1)) % (2**self.m) def request_update_predeccessor(self, ip_port): ...
The main task of the code is to initialize a node's finger table in a distributed system (likely a Chord network). It populates each finger entry by querying successor nodes, ensuring entries correctly point to the next node responsible for specific ID ranges. The code handles unstable networks by exiting if successor ...
def init_finger_table(self, ip): node_succ = self.request_successor(ip, self.start_idx(1)) if not node_succ: print('Unstable network, try again later') exit() self.finger[1] = (node_succ['id'], node_succ['ip']) self.finger[0] = node_succ['fg'][0] ...
def request_finger_table(self, ip_port): if self.ip == ip_port: return self.finger response = self.send_request(ip_port,Chord_Node.RFT, " " ) if response: return json.loads(response) return None def inbetween(self,key, lwb, lequal, upb, requal): i...
The `stabilize` method ensures a node's finger table and successor pointers are correctly updated in a distributed system. It acquires a lock, requests the successor's finger table, checks if the predecessor lies between the current node and the original successor, and updates the finger/successor pointers if valid. If...
def stabilize(self): self.lock_finger.acquire() successor_finger_table = self.request_finger_table(self.finger[1][1]) take_care_of = [] if successor_finger_table: predeccessor = successor_finger_table[0] if self.inbetween(predeccessor[0], self.id,Fals...
def request_finger_table(self, ip_port): if self.ip == ip_port: return self.finger response = self.send_request(ip_port,Chord_Node.RFT, " " ) if response: return json.loads(response) return None def inbetween(self,key, lwb, lequal, upb, requal): i...
This function finds the predecessor node for a given index in a distributed hash table (DHT). It iterates through finger tables, checks node aliveness, and navigates to the closest preceding node, returning its ID, IP, and finger table if successful. If no valid predecessor is found, it returns None.
def find_predecessor(self, idx): node = (self.id, self.ip) omit = [] while(True): id = node[0] ip = node[1] ft = self.request_finger_table(node[1]) if not ft: return None node_succ_id, node_succ_ip = ft[1] if...
def is_alive(self,ip_port): if ip_port == self.ip: return "OK" return self.send_request(ip_port,Chord_Node.ALIVE, ' ') def inbetween(self,key, lwb, lequal, upb, requal): if key== upb or key == lwb: if key == upb: return requal ...
This code handles a notification request by parsing incoming data, updating the finger table based on node status, and managing predecessor data. It splits the input into two JSON parts, checks if the current node is alive, and updates the finger entry if conditions are met. If the node is unreachable, it replaces the ...
def request_notify_handler(self, body): p, take_care = body.split("&", 1) p = json.loads(p) take_care = json.loads(take_care) if self.is_alive(self.finger[0][1]): if(self.inbetween(p[0], self.finger[0][0],False, self.id,False )): self.erase_last_predecessor_d...
def get_folder_name(self,url): self.update_id() id = self.next_req_id self.next_req_id+=1 url = url.split('//',1) try: url = url[1].split('/',1) except IndexError: pass url = url[0].replace(':', ' port ') ...
The code performs web scraping by fetching HTML content from a URL, creating a directory structure, extracting links, recursively scraping linked pages (with depth control), handling errors (broken requests), updating HTML content, and saving the result to a file. It returns success/failure statuses and file paths.
def base_scrap(self,req_addr,url,depth): folder = self.get_folder_name(url) folder = 'Requests/'+folder os.makedirs(folder) html = self.request_html(url,req_addr) if html == self.BR: return self.BR_TEXT if html is None: shutil.rmtree(fold...
def find_predecessor(self, idx): node = (self.id, self.ip) omit = [] while(True): id = node[0] ip = node[1] ft = self.request_finger_table(node[1]) if not ft: return None node_succ_id, node_succ_ip = ft[1] if...
This function identifies the next alive successor node for a given index in a distributed network. It retrieves the successor list from a predecessor node, checks for an active successor, and returns the successor's ID, IP, and finger table if available. If no valid successor is found, it returns None.
def find_succesor(self, idx): node = self.find_predecessor(idx) if not node: return None succesors = self.succesors if node['id'] != self.id: succesors = self.request_succesor_list(node['ip']) if not succesors: return None ...
def find_succesor(self, idx): node = self.find_predecessor(idx) if not node: return None succesors = self.succesors if node['id'] != self.id: succesors = self.request_succesor_list(node['ip']) if not succesors: return None ...
The main task of the code is to locate a successor node for a given data hash in a distributed system, adjust the node's port by incrementing it, and send a request to the updated IP address. It calculates the hash of the input body, identifies the successor node, modifies the port number, constructs a new IP string, a...
def request_locate(self, body): node = self.find_succesor(self.int_hash(body)) ip, port = split_ip(node['ip']) port = int(port) port += 1 ip = ip + ':' + str(port) self.s_rep_html.send_string(ip)
def saveImg(img): """Save the image in the temp folder""" if os.path.exists(r"./temp"): pass else: os.mkdir(r"./temp") save = randString() + 'save.jpeg' img.save(r"./temp/" + save) imgForPdf.append(save) def makeImg(chunks): """Add text to the image and save it in the temp f...
The code processes user input as text or a file, splits it into 45-character chunks (handling newlines specially), generates an image and PDF from these chunks, then deletes the temporary image. Its main task is to convert input text into formatted image/PDF outputs with chunked text handling.
def main(): """Main function""" print("Enter Text or File Path") text = input('> ') chunks = [] # try to open the text as a file try: with open(text, 'r') as file: text = file.readlines() for j in text: if len(j) > 45: temp = [...
def pairwise_overlap_indexing_list(single_result_frame, iou_threshold): pointwise = [[i] for i in range(len(single_result_frame))] pairwise = [[i, j] for i, x in enumerate(single_result_frame) for j, y in enumerate(single_result_frame) if i != j if filter_bbox_group(x, y, iou_thr...
The main task of the code is to merge overlapping bounding boxes in detection results. It first filters out low-confidence regions below a threshold, then groups overlapping regions using IoU, merges them into unified boxes, and compiles the final merged results.
def merge_boxes_in_results(results_dict, min_conf_threshold, iou_threshold): final_results = Results() # Clean dict to remove min_conf_threshold for _, regions in results_dict.items(): to_remove = [] for r in regions: if r.conf < min_conf_threshold: to_remove.app...
def printd(self, f, m, debug_level=0): if debug_level <= self.debug_level: print("["+f+"] "+m) def create_heuristic(self, target_point, heuristic_type): heuristic = np.zeros_like(self.map_grid) for x in range(len(heuristic)): for y in range(len(heuristic[0])): ...
This function manages a state machine for path planning, alternating between coverage search and nearest unvisited search algorithms based on the current state. It updates the robot's position, trajectory, and coverage grid, transitioning states when a path is found or failing to one that searches for the nearest unvis...
def compute_non_blocking(self): self.printd("compute_non_blocking", "{}".format(self.state_.name), 1) searching = False # Start the FSM by switching through the self.state_ attribute if self.state_ == PlannerStatus.COVERAGE_SEARCH: # Search using coverage_search algorithm ...
def get_paths_to_sensitive_methods(logcat_path): call_graph = read_logcat(logcat_path) transposed_graph = call_graph.generate_transpose_graph() sensitive_methods_path = os.path.join("data", sensitive_methods_file) sensitive_methods = read_sensitive_methods(sensitive_methods_path) paths = {} fo...
The main task of the code is to analyze Android app logcat data by comparing sensitive method access patterns between benign and malicious versions of each app, generating rankings of sensitive methods, calculating distances to these methods, and outputting structured JSON results containing app-specific comparisons, m...
def main(): apps = get_apps(apps_file) result = {} result[FIELD_APPS] = {} for app_name in apps: benign_filename = apps[app_name][FIELD_BENIGN_FILE] benign_logcat_path = os.path.join("input", benign_filename) benign_paths = get_paths_to_sensitive_methods(benign_logcat_path) ...
def check_processed(file_name, beta, csv_path): # Ensure the CSV file exists before attempting to read; if not, return False if not os.path.exists(csv_path): with open(csv_path, mode='w', newline='') as csvfile: fieldnames = ['FileName', 'Beta'] writer = csv.DictWriter(csvfile, f...
The code applies a double sigmoid transformation to a range of images using specified beta values, saving transformed images in organized folders. It checks a CSV file to avoid reprocessing already computed results, processes only unprocessed betas, and logs progress. The main task is to efficiently transform images wi...
def computeDoubleSigmoidTransform(args, betaList): imglist = os.listdir(args.input_folder) sortedImgList = sorted(imglist) start = args.start_index end = args.stop_index if args.stop_index <= len(sortedImgList) else len(sortedImgList) csv_path = 'processed_images.csv' for beta in betaList: ...
def get_num_unfold(decomposer): """Get number of unfolding based on decomposer""" return 1 if decomposer == "svd" else 3 def get_u_svd(x, rank=1): """Perform SVD, return rank first columns of u""" u, _, _ = torch.linalg.svd(x, full_matrices=False) return u[:, :rank] def svd(x, rank=1): u, _, v...
The code decomposes a tensor `x` using specified methods (Tucker, HOSVD, or SVD) and returns decomposition factors. For Tucker, it extracts factors with a uniform rank across modes. For HOSVD, it computes left singular vectors via SVD on each tensor unfolding. For SVD, it applies SVD to a specific unfolding mode. The f...
def decompose(x, decomposer="hosvd", rank=1, mode=0): """Get left_singulars based on decomposer and rank svd: [u, v] hosvd: [u1, u2, u3] tucker: [u1, u2, u3] """ if decomposer == "tucker": _, factors = tucker(x, rank=[rank, rank, rank]) return factors elif decomposer == "ho...
def genCandidate(self, c): res = set() R = c.getRMPathNodes() rmNode = c.getRMNode() gc = c.toGraph() lbMatchingTo = self.getLabelMatching() ## backward ext for i in R[1:]: if MyEdge((rmNode, i, VACANT_LABEL)) not in gc.edges: ## be res.add(MyDFSEdge((rmNode, i, (gc.nodes[rm...
This function recursively generates frequent itemsets by extending candidate patterns, checks their support against a threshold 's', and builds a tree structure (MyCodeGraph) of valid patterns. It uses local mining to evaluate candidates, appends valid ones as children nodes, and continues extension until support falls...
def PatExt(self, c, s, temp, MS, index): cdds = self.genCandidate(c) for cd in cdds: new = c.mcopy() new.append(cd) if new.isMin(): sup, newMS, newIndex = self.localMine(new, s, MS, index) if sup >= s: newtemp = MyCodeGraph(new, sup) temp.addChild(newtemp) ...
def __init__(self): # Initialises new array for board self.board = [] self.players = {-1:'O', 1:'X'} self.board = np.tile(0, (3,3)) def take_turn(self, strategy, computer, KnownArrangements=0): if strategy == 'random': return self.free_space() elif str...
The code simulates a two-player game using specified strategies, alternating turns to place moves on a board. It checks for a win after 5+ moves, declares a draw on a full board, and optionally displays the board and results. The function initializes the game, manages player turns, and returns the winning strategy if a...
def startgame(self, strategyP1, strategyP2, KnownArrangements=0,Show=True,Winner=True): # Call other functions in here to run the game. self.__init__() # added this so you can continually initiate game Plyr1=np.random.choice([-1, 1]) Plyr2=Plyr1*-1 player=1 co...
def __init__(self): # Initialises new array for board self.board = [] self.players = {-1:'O', 1:'X'} def setBoard(self): # Sets the 3 rows into a 2-D array self.board = np.tile(0, (3,3)) def firstTurn(self): # Determines the 1st turn being either 'X' or 'O' first = np.random.choice([-...
This code initializes and runs a tic-tac-toe game using specified strategies for players X and O. It sets up the board, alternates turns randomly, applies chosen strategies for moves, checks for wins after 5+ moves, handles draws on full boards, and returns the winner or declares a draw.
def startgame(self, strategyIndexX, strategyIndexO): # Call other functions in here to run the game. self.__init__() # added this so you can continually initiate game self.setBoard() print(self.board) count = 0 player = self.firstTurn() # randomly get first player whi...
def GameDebug(information): # file=open("Chess/GameDebug.txt","a") file = open("GameDebug.txt", "a") file.write(information) file.write('\n') file.close() def StringBuilder(*args): string="" for arg in args: string+=str(arg) return string def ConfirmMove(firstx,firsty,secondx,se...
The function `ValidateMove` checks the length of a move string to determine if it's a regular move (4 characters) or a capture move (5 characters). It extracts coordinates, calls `ConfirmMove` with appropriate parameters (including a boolean for capture), and returns the result. Invalid lengths trigger an error log and...
def ValidateMove(move,color): GameDebug(StringBuilder("Validate Move: ",move)) if len(move)==4: #not Taking firstx=move[0] firsty=move[1] secondx=move[2] secondy=move[3] return ConfirmMove(firstx,firsty,secondx,secondy,color, False) elif len(move)==5: ...
def GameDebug(information): # file=open("Chess/GameDebug.txt","a") file = open("GameDebug.txt", "a") file.write(information) file.write('\n') file.close() def inCheck(color): GameDebug("--- Checking if the king is in check ---") #find the king and return the king item string=...
The main task of the code is to determine if a player's king (specified by 'color') is in checkmate by analyzing whether the king can escape check through blocking, capturing the attacker, or moving. It iterates over attacking pieces, checks for potential counters (blocking or capturing), and evaluates if the king has ...
def Checkmate(color): GameDebug("Checking: " + color + "King") #exitLoop being false means that the King is able to move #exitLoop being true means that the King is unable to move exitLoop = False checklist = inCheck(color).getAttacker() if len(checklist)!=0: ...
def ValidateMove(move,color): GameDebug(StringBuilder("Validate Move: ",move)) if len(move)==4: #not Taking firstx=move[0] firsty=move[1] secondx=move[2] secondy=move[3] return ConfirmMove(firstx,firsty,secondx,secondy,color, False) elif len(move)==5: ...
The function `GetMove` prompts the user for a chess move based on the specified color (White or Black), validates the move using `ValidateMove`, and repeatedly requests input until a valid move is entered. Once valid, it executes the move, updates the game board with `PrintBoard`, and logs the move via `GameDebug`. The...
def GetMove(color): move="" if color=="W": move=input("White Move: ") if color=="B": move=input("Black Move: ") while ValidateMove(move,color)==False: GameDebug(StringBuilder("GetMove: Invalid Move: ",move)) move=input("Invalid Move, Try Again: ") MakeMove(move,len...
def PrintBoard(): global board for i in range(8): print(8-i, end = " ") for j in range(8): getPiece(j,i).printcharacter() # getPiece(j,i).printType() print("") print(" aa bb cc dd ee ff gg hh") def GetMove(color): move="" if color=="W": move...
The code simulates a chess game by alternating turns between White and Black, using functions to handle move input, board display, and checkmate detection. The loop continues until checkmate is detected for either player, at which point the game ends and a message is printed.
def main(): file = open("GameDebug.txt", "w") file.close() #Variables movelog=[] GameOver=0 while GameOver==0: #White Turn PrintBoard() GetMove("W") GameOver = Checkmate("W") + Checkmate("B") if not GameOver: PrintBoard() GetMove(...
def get_paths_A_to_L(self): if(self.computed_A_to_L == False): self.backtrack_paths_A_to_L("",self.Angelo) self.computed_A_to_L = True return self.paths_A_to_L def get_paths_L_to_A(self): if(self.computed_L_to_A == False): self.backtrack_paths_L_to_A("",sel...
The code simulates the movement of two agents, Leo and Angelo, along randomly selected paths. It checks if their paths intersect, returning (1,1) if they meet at Times Square, (0,1) if they meet elsewhere, and (0,0) if they never meet.
def run_simulation(self): if (self.computed_A_to_L == False): self.get_paths_A_to_L() if (self.computed_L_to_A == False): self.get_paths_L_to_A() """ Set current position to starting position """ curr_leo = [self.Leo[0],self.Leo[1]] curr...
def get_node(self, num): for node in self.nodes: if node.i_num == num: return node def add_conn(self, start, end, conn_num): if start == end: return False before_node = self.get_node(start) after_node = self.get_node(end) if after_node in self.in_nodes or before_node in self.out_nodes: return Fal...
The function inserts a new node between two existing nodes in a network, updating connections and ensuring no conflicts. It checks if 'before' and 'after' nodes are valid, deactivates existing direct connections between them, creates a new node, adds bidirectional connections (with specified IDs), and updates the netwo...
def add_node(self, before, after, node_num, conn_num): if before == after: return False before_node = self.get_node(before) after_node = self.get_node(after) if after_node in self.in_nodes or before_node in self.out_nodes: return False for conn in before_node.out_conns: if conn.end_node == after: ...
def cost_in_seconds(self): work_seconds = self._get_seconds_from_duration() cost_in_seconds = self.num_attendees * work_seconds return cost_in_seconds def _translate_seconds(self, seconds): # divmod returns quotient and remainder minutes, seconds = divmod(seconds, 60) hou...
The main task of the code is to convert a time cost from seconds into a human-readable formatted string representing work days, hours, minutes, and seconds, ensuring proper formatting for printing.
def time_cost_for_printing(self): seconds = self.cost_in_seconds() work_days, hours, minutes, seconds = self._translate_seconds(seconds) work_days, hours, minutes, seconds = self._make_pretty_for_printing(work_days, hours, minutes, seconds) time_cost = '{}, {}, {}, {}'.format(work_days, ...
def _make_dt_or_time_str_pretty_for_printing(self, dt_obj_or_str): if isinstance(dt_obj_or_str, str): if dt_obj_or_str[-6] == '-': dt_obj_or_str = dt_obj_or_str[:19] dt_obj_or_str = datetime.datetime.strptime(dt_obj_or_str, self.FORMAT_DATETIME_OBJ_TO_STR) pretty_...
The main task of the code is to print a formatted summary of meeting details, including its number, summary, start/end times, duration, attendees, cost, time cost, and percentage of time spent in meetings. It uses class attributes and helper methods to structure and display this information in a readable format.
def print_meeting_info(self): print(""" Meeting {0}: {1} ************************************************** Start: {2} End: {3} Duration: {4} Number of Attendees: {5} Cost: {6} Cost in Time: {7} Percentage of time spent in meeting: {8}% """...
def is_valid_location(self, col): return self.board[0][col] == 0 def visualize_solve_tree(self): self.screen.fill(WHITE) pygame.display.flip() root = convert_state_to_tree(self.tree) root_x = 400 root_y = 100 backIconAccent = pygame.image.load("images/back-icon.p...
The code renders a Connect Four game board by drawing colored squares and circular pieces based on the board's state, highlights the selected column with the current player's piece, and optionally displays a "Solve Tree" button for AI moves. It updates the board visualization, handles mouse interactions, and renders ad...
def draw_board(self, current_player): for c in range(COLUMN_COUNT): for r in range(1, ROW_COUNT + 1): pygame.draw.rect( self.screen, DARK_BLUE, (c * SQUARE_SIZE, r * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE), ) ...
def drop_piece(state, col, piece): for row in range(5, -1, -1): if state[row * 7 + col] == "0": newstate = ( state[: row * 7 + col] + str(piece)[0] + state[row * 7 + col + 1 :] ) break return newstate def minimax(state, depth, piece, maximizingPlayer, ...
The main task of the code is to evaluate the score of a game move using minimax or alpha-beta pruning based on the 'option' parameter. It generates a new game state by dropping a piece, recursively calculates its value, updates a tree structure with the result, and returns the computed score for decision-making in a tu...
def get_score(state, col, piece, depth, option): next_state = drop_piece(state, col, piece) if option == 1: new_dict = { next_state: { "depth": depth - 1, "piece": piece % 2 + 1, "value": 0, "childs": [], } }...
def convert_from_grid_to_string(grid): state = "" for i in range(0, 6): for j in range(0, 7): state += str(grid[i][j]) return state def get_valid_locations(state): locations = [] for col in range(7): if is_valid_location(state, col): locations.append(col) ...
The code implements a minimax algorithm with alpha-beta pruning to select the optimal move in a game (e.g., Connect Four). It evaluates valid moves, scores them based on depth and heuristic, selects the highest-scoring move randomly, and constructs a game state tree with node expansion tracking for analysis.
def agent(grid, depth, option): global NODE_EXPANDED NODE_EXPANDED = 0 min_tree.clear() state = convert_from_grid_to_string(grid) min_tree[state] = { "depth": depth, "piece": 1, "value": 0, "childs": [], } valid_moves = get_valid_locations(state) scores = ...
def resize_game_window(self, width, height, player): SQUARE_SIZE = min(width // COLUMN_COUNT, height // ROW_COUNT) self.screen = pygame.display.set_mode( (COLUMN_COUNT * SQUARE_SIZE, ROW_COUNT * SQUARE_SIZE), pygame.RESIZABLE ) self.animation_frames = [ pygame.tra...
The main task of the code is to handle the game's main menu interface, processing user events like quitting, resizing the window, and selecting game modes (player vs player or player vs AI). It initializes game variables, manages menu state transitions, displays animated backgrounds, and triggers AI selection menus. Th...
def main_menu(self): self.player1_value = 0 self.ai_value = 0 self.node_expanded = 0 while self.menu: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.typ...
def getLWAP(image_path): img = cv2.imread(image_path) while img.shape[1]>=800 or img.shape[2]>=800: img = cv2.resize(img, None, fx=0.9, fy=0.9) angle = rotationAngle(img) img = rotateImage(img, angle) img = croppedImage(img) length, width = leafLW(img) # print(length, width) # i...
This function extracts and returns multiple image features including geometric properties (length, width, area, perimeter, aspect ratio, form factor, rectangularity) and texture features (Hu moments, histogram) from a given image path.
def getAllFeatures(image_path): img, length, width, area, perimeter = getLWAP(image_path) aspect_ratio, form_factor, rectangularity = getAFR(length, width, area, perimeter) hu, hist = obtainHuMoments(image_path,img) return length,width,area,perimeter,aspect_ratio,form_factor,rectangularity,hu,hist
def count_control_condition_ascii(control_condition_ascii): return sum([abs(b-a)+1 for a, b in control_condition_ascii]) def count_permutation(m_range, n_range, mode): if mode == 'combination': for n in n_range: yield int(factorial(m_range)/(factorial(n)*factorial(n-1))) elif mode == 'co...
The function generates permutations based on control conditions and mode, either printing formatted results or returning them as a list. It calculates the ASCII range, computes permutations, and outputs them conditionally based on the print_mode flag.
def print_count_permutation(control_condition_length, control_condition_ascii, mode, print_mode=False): m_range = count_control_condition_ascii(control_condition_ascii) place = count_permutation(m_range, control_condition_length, mode) if print_mode: for p in place: print(formating_numbe...
def process_points(points, shape): points.append((0, 0)) points.append((0, shape[0])) points.append((shape[1], 0)) points.append((shape[1], shape[0])) return np.array(points) def blendPair(tri_list, images, points, alpha): avg = avg_pair_points(points[0], points[1], alpha) assert(images[0]....
This code generates a morphing sequence between two images (imgA and imgB) using Delaunay triangulation of corresponding points (pointsA and pointsB). It calculates intermediate frames by blending the images with decreasing alpha values (from 1 to 0) over numFrames, creating a smooth transition. The resulting frames ar...
def morphSequence(imgA, imgB, pointsA, pointsB, numFrames): shape = imgA.shape pointsA = process_points(pointsA, shape) pointsB = process_points(pointsB, shape) triA = Delaunay(pointsA) triangles = triA.simplices mov = [] fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1...
def getCorrespondence(picA, picB): face_detector = dlib.get_frontal_face_detector() shape_predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') corresp = np.zeros((68, 2)) imgs = [picA, picB] list1 = [] list2 = [] j = 1 for img in imgs: size = (img.shape[0],...
The code performs morphing between two images using OpenCV and scikit-image. It reads input images, extracts correspondence points, generates a midpoint morph (0.5 blend), displays it, and creates a 45-frame morph sequence between the images.
def morphFiles(nameA, nameB): picA = cv2.imread(nameA) picB = cv2.imread(nameB) skPicA = skio.imread(nameA) skPicB = skio.imread(nameB) [size, img1, img2, pointsA, pointsB, list3] = getCorrespondence(picA, picB) face = findMidwayFace(skPicA, skPicB, pointsA, pointsB, 0.5) skio.imshow(face...
def morphFiles(nameA, nameB): picA = cv2.imread(nameA) picB = cv2.imread(nameB) skPicA = skio.imread(nameA) skPicB = skio.imread(nameB) [size, img1, img2, pointsA, pointsB, list3] = getCorrespondence(picA, picB) face = findMidwayFace(skPicA, skPicB, pointsA, pointsB, 0.5) skio.imshow(face...
The code defines a `main()` function that conditionally executes image processing tasks based on boolean flags. It includes morphing two images, computing a mean face, generating a caricature, gender transformation, and class-based morphing. However, all flags are initialized to `False`, so none of the operations are t...
def main(): morph = False meanFace = False caricature = False changeToMale = False classMorph = False if morph: nameA = "nadia.jpg" nameB = "george.jpg" morphFiles(nameA, nameB) if meanFace: popMean = computeMeanFace("imm_face_db/", ".*-1f\.jpg", "danes_mea...
def generate_network(bond_matrix): network = [] for i in range(0,len(bond_matrix)): new_node = Node(i + 1) add_neighbors(bond_matrix, new_node) network.append(new_node) return network def generate_full_atom(coords, bond_network): full_atoms = [None] * len(coords) for atom in range(0,len(coords)): full_atom...
The code generates a dihedral key by identifying rotatable bonds in a molecular structure represented by a bond matrix and coordinates. It filters out non-rotatable dihedral angles using cycle detection and bond network analysis, then constructs a filtered dihedral key and an associated "everything after key" for molec...
def dihedral_key_generation(bond_matrix, coords): dihedralKey = [] bond_network = generate_network(bond_matrix) full_atoms = generate_full_atom(coords, bond_network) dihedralKey = len4(bond_network) #Filter out nonrotable dihedral angles cycles = cycle_check(full_atoms) nonrotable = nonrotable_pairs(cycles, bon...
def restore_population_size(settings, initial_generation, dihedralKey, everythingAfterKey): population_shortage = settings.GA_population_size - len(initial_generation) restore_population = [None] * population_shortage for i in range(0, population_shortage): random_parent = initial_generation[random...
The main task of the code is to generate the next generation in a genetic algorithm by restoring population size through mutation, preserving elite solutions, and using tournament-based selection with crossover and mutation to produce offspring until the target population size is achieved.
def next_generation_tournament(settings, initial_generation, dihedralKey, everythingAfterKey): #Mutate based on any randomly selected strucutre to climb back to pop-setting size next_generation = restore_population_size(settings, initial_generation, dihedralKey, everythingAfterKey) #In place sorts the arra...
def convert_date(my_date): """ Converts a string to datetime format""" return datetime.datetime.strptime(my_date, "%Y-%m-%d") def find_something(threl=2.0, my_limit=150, far=365, mystocks=None): """ Find stocks tha are worth buying""" global current_date, total_money, min_date, current_name, dates_dict,...
The code simulates a stock trading system that buys/sells assets based on dynamic conditions (date ranges, money ratios, and predefined thresholds), tracks portfolio performance, and generates visualizations of balance and portfolio value over time, while recording transaction data and saving results to files.
def run_now(): """Run the system""" global current_date, end_date, both_money, total_money, purchased, min_date_sell, sell_dict, reduced_stocks1, reduced_stocks2, dates_lists, total_list, portofolio_list date1 = convert_date('2010-01-01') date2 = convert_date('2005-01-01') date3 = convert_date('2000...
def convert_date(my_date): return datetime.datetime.strptime(my_date, "%Y-%m-%d") def find_something(threl=2.0, my_limit=150, far=365, mystocks=None): """ Find stocks tha are worth buying""" global current_date, total_money, min_date, current_name, dates_dict, mylist, min_date_sell, mylist2 worthing = l...
The main task of the code is to simulate stock trading strategies over a time period, managing buy/sell decisions based on predefined date thresholds and financial ratios. It tracks portfolio value, total money, and transaction history, then generates visualizations and outputs results to files. The code tests dynamic ...
def run_now(): """Run tests""" global current_date, end_date, both_money, total_money, purchased, min_date_sell, sell_dict, reduced_stocks1, reduced_stocks2, dates_lists, total_list, portofolio_list date1 = convert_date('2010-01-01') date2 = convert_date('2005-01-01') date3 = convert_date('2000-01-0...
def set_repo(self, user): id = user.get_id() title = str(id) all_titles = list(map(lambda x: x.title, self.common_repo.worksheets())) if title in all_titles: self.repo = self.common_repo.worksheet(title) else: self.repo = self.common_repo.add_worksheet(tit...
The main task of the code is to add a new site and encrypted password to a user's repository, checking for reserved names, existing entries, and row limits before saving. If valid, it encrypts the password, updates the repository with the new data, and returns a success message.
def add(self, user, info): self.set_repo(user) site = info.get_site() password = info.get_password() if self.is_reserved(site): return "Sorry, this name is reserved by me. Please, use another one." cell = self.repo.find(site) if cell is not None: ...
def _check_events(self): """Respond to key presses and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() self._che...
The main task of the code is to run the game loop, handling events, updating game elements (ship, bullets, aliens) when the game is active, and continuously rendering the screen to maintain gameplay and visuals.
def run_game(self): """Main loop for the game""" while True: self._check_events() if self.stats.game_active: self.ship.update() self._update_bullets() self.fleet.update_aliens() self._update_screen()
def quadrilateral_length_of_sides_coordinates(x1, y1, x2, y2, x3, y3, x4, y4): side_ab = round(((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5, 3) side_bc = round(((x2 - x3) ** 2 + (y2 - y3) ** 2) ** 0.5, 3) side_cd = round(((x3 - x4) ** 2 + (y3 - y4) ** 2) ** 0.5, 3) side_ad = round(((x4 - x1) ** 2 + (y4 - y1...
The function calculates and returns properties of a quadrilateral defined by coordinates: type, area, perimeter, side lengths, diagonals, and interior angles, using specific formulas for different quadrilateral types like parallelograms, rhombuses, rectangles, squares, and kites.
def quadrilateral_xy_method(): global area a, b, c, d, d_ac, d_bd = quadrilateral_length_of_sides_coordinates( x1, y1, x2, y2, x3, y3, x4, y4) quad = quadrilateral_type(x1, y1, x2, y2, x3, y3, x4, y4) perimeter = a + b + c + d if quad != "No Quad Possible": angle_a, angle_b, angle_c,...
def remdup(list1): # Removes duplicates from a list uniques = [] for i in list1: if i not in uniques: uniques.append(i) return uniques def factors(number): prime_factors1 = prime_factorisation(number) prime_factors2 = prime_factors1[:] # To be printed at last with non-prime...
The main task of the code is to compute the sum of all distinct factors and prime factors of a given number by combining the results of `factors(number)` and `prime_factorisation(number)`, removing duplicates, and summing the unique values.
def factorsum(number): return sum(remdup(factors(number) + prime_factorisation(number)))
def get_interface_info(): interfaces = netifaces.interfaces() interface_list = [] for interface in interfaces: addresses = netifaces.ifaddresses(interface) if netifaces.AF_LINK in addresses and addresses[netifaces.AF_LINK][0]['addr'] != '': mac_address =...
The code identifies the network interface with the current MAC address, updates its MAC address to a new value provided by `entry_new_mac`, and refreshes the GUI display (treeview) to reflect the change.
def changeMAC(): transportname = "" for interface in get_interface_info(): if clean_mac(currentMAC).lower() == clean_mac(interface[0]).lower(): transportname = interface[1] break change_mac_address(transportname, entry_new_mac.get()) update_tre...
def get_interface_info(): interfaces = netifaces.interfaces() interface_list = [] for interface in interfaces: addresses = netifaces.ifaddresses(interface) if netifaces.AF_LINK in addresses and addresses[netifaces.AF_LINK][0]['addr'] != '': mac_address =...
The code changes MAC addresses of all network interfaces to random values and updates a treeview if an event is triggered.
def changeall(event): for interface in get_interface_info(): change_mac_address(interface[1], get_random_mac_address()) if event: update_treeview()
def visualize(self, count): """visualize the result""" fig = plt.figure() sns_plot = sns.heatmap(self.policy, cmap='bwr') sns_plot.invert_yaxis() plt.title("Policy " + str(count)) # plt.show() fig.savefig("./figures/4.2/policy" + str(count) + ".png", bbox_inches='...
The code trains a reinforcement learning model by iteratively evaluating the policy's value function and improving it until convergence. It visualizes progress, saves the model after each iteration, and terminates when the policy stabilizes (no further improvements).
def train(self): """train the model""" count = 0 self.visualize(count) while True: count += 1 print("iter ", count, " start!") self.policyEvaluation() stable = self.policyImprovement() self.visualize(count) self.sa...
def valueIter(self): delta = 0 for money in range(1, 100): v = self.values[money] self.values[money] = self.getHighestValue(money) delta = max(delta, abs(v-self.values[money])) return delta def getBestAction(self, state, mode='smallest'): """ r...
This code performs value iteration for reinforcement learning, iteratively updating the value function until the change (delta) falls below a threshold (theta). It logs intermediate values, saves them for specific iterations, computes the optimal policy post-convergence, and visualizes results.
def train(self): count = 1 print("start training...") while True: t1 = time.time() delta = self.valueIter() t2 = time.time() if count in [1, 2, 3, 32]: if count == 1: self.value_save = np.array(self.values, copy...
def em_pwm(samples, num_samples_base, num_samples_big): shape,loc,scale = pwm_fit(samples) phi = 0.570376002 n = num_samples_big / num_samples_base emma = stats.genextreme.ppf(phi**(1/(n)),shape,loc,scale) return emma def pwm_fit(samples): # Generate moments from sample data samples = np.sor...
The function `test_projection` performs parametric bootstrapping to evaluate statistical measures (e.g., PWM, MOM) under varying projection sizes. It reshapes input data, iterates over projection scales, generates bootstrap samples, computes block maxima, fits distributions, and accumulates results. The process calcula...
def test_projection(sample,_NNODES,_NRANKS,_NITER,_PROJ_NNODES,p): sone=np.reshape(sample, sample.shape[0]*sample.shape[1]) # parameteric bootstrapping with mom mblock=[] lblock=[] pblock=[] emv_block=[] pwm_block=[] x=[] i=_NNODES # perform a series of intermediate projectio...
def __create_directory(self, dir): """ """ try: os.makedirs(dir, exist_ok=True) except FileExistsError: pass if os.path.isdir(dir): return True else: return False def _write_module(self, module_name, file_name, data=None): ...
This code manages PHP module configurations by writing module content to files, enabling/disabling modules based on the OS distribution (e.g., Redhat vs. Debian), and tracking changes. It processes each module's state, priority, and content, logs operations, and returns a summary of changes made, including success/fail...
def run(self): """ """ result_state = [] self.__create_directory(self.php_modules_cache_directory) # redhet needs an extrawurst ... # {{ '/conf.d/' if ansible_os_family | lower != 'redhat' else '/' }}" conf_d = "conf.d" # if self.distribution.lower() i...
def generate_real_samples(self, n, realsamplearray): keepshape=self.keep_shape # generate mnist samples if keepshape: sampleshape = realsamplearray[0].shape else: sampleshape = realsamplearray[0].reshape(-1).shape[0] array_inds = range(realsamplearray.shap...
The main task of the code is to train a Generative Adversarial Network (GAN) using a given dataset. It trains both the discriminator and generator in batches, updates models alternately, and saves intermediate checkpoints. The function supports resuming training from a previous state, evaluates performance periodically...
def train(self, dataset, scaler=None, n_epochs=1, n_batch=8, n_eval=400, #num of epoch intervals to do an eval process progress_bar=True, save_after_epoch_mult=10, train_discriminator=True, ...
def reset_the_scoreboard(score_board): score_board.show_score() score_board.show_high_score() score_board.show_level() score_board.show_ships() def reset_the_stats(stats): # Hide the mouse cursor pygame.mouse.set_visible(False) stats.reset_stats() stats.run_game = True def reset_the_scre...
The main task of the code is to handle user input events in a game, including exiting the game, starting the game by clicking the Play button, and controlling the ship's movement via keyboard inputs. It processes mouse clicks, key presses, and key releases, triggering actions like resetting game settings, updating the ...
def check_events(ai_settings, screen, ship, bullets, play_button, stats, aliens, score_board): """Respond to keypresses and mouse events""" for event in pygame.event.get(): # Exit the game when the user clicks the game window's close button if event.type == pygame.QUIT: sys.exit() ...
def get_user_id(email): conn = connection() cursor = conn.cursor() # Use a parameterized query to prevent SQL injection table_query = "SELECT user_id FROM users WHERE email = %s" cursor.execute(table_query, (email,)) result = cursor.fetchone() # Use fetchone() to retrieve a single row use...
The function identifies users with similar favorite artists to the current user by querying shared artists from the database, then maps each user (ID and name) to a list of common artists they both favor. It returns this dictionary for further analysis or recommendations.
def users_w_similar_artists(email): current_user_id = get_user_id(email) conn = connection() cursor = conn.cursor() list_artists = query_artists(email) outer_id_similar={} for artist_tuple in list_artists: artist = artist_tuple[0] # Unpack the value from the tuple art...
def diplay_grocery_list(): print('Your present grocery list contains',grocery_list) talk('Your present grocery list contains'+str(grocery_list)) return grocery_list def add_item(): talk('Which item would you like to add') items=str(input('Add Your items :')) if items in grocery_list: t...
The code defines a `shopping_list` function that handles user actions for managing a grocery list. Based on the `action_item` input (1-4), it performs tasks like displaying the list, adding/removing items, or checking item status. If the input is invalid, it prompts the user to select a value between 1 and 4.
def shopping_list(action_item): if action_item==1: diplay_grocery_list() elif action_item ==2: add_item() elif action_item ==3: remove_item() elif action_item ==4: check_item() else: talk('Action item should be between 1 to 4') print('Action item s...
def Dead_Reck(self): '''!@brief Estimate Romi position delta @details Use encoder position data to estimate the change in Romi's position in world coordinates. ASSUME: All of Romi's motion deltas are PERFECTLY CIRC...
The main task of the code is to control a robot (Romi) through a series of predefined states to navigate a track, including line following, obstacle avoidance, and returning to a starting position. It begins by initializing sensors, transitions to a term project task involving line movement, wall detection, and program...
def MainTask(self): '''!@brief Main cotask task for RomiMM. @details The RomiMM main task has states: 0: Init state. Romi waits without moving until BNO has reported that the sensors are calibrated and have begun t...
def pixels_fill(color): for i in range(len(ar)): pixels_set(i, color) def pixel_group_set(pg, color): for i in range(len(pg)): pixels_set(pg[i], color) def pixels_show(): dimmer_ar = array.array("I", [0 for _ in range(NUM_LEDS)]) for i,c in enumerate(ar): r = int(((c >> 8) & 0xFF...
The code simulates brake lights by blinking a specific pixel group (BRAKES) three times, then keeping them lit for 5 seconds before turning off. It also includes a delay and a "brakes released" message to indicate the completion of the brake simulation.
def brakes(): pixels_fill(BLACK) for blink in range(0,3): pixel_group_set(BRAKES, RED) pixels_show() utime.sleep(.1) pixels_fill(BLACK) pixels_show() utime.sleep(.1) pixel_group_set(BRAKES, RED) pixels_show() utime.sleep(5) pixels_fill(BLACK) p...
def leftTurn(): pixels_fill(BLACK) for blink in range(0,2): for i in range(0,len(LR)): pixels_set(LR[i], YELLOW) pixels_set(LF[i], YELLOW) pixels_show() utime.sleep(.02) pixel_group_set(LR, BLACK) pixel_group_set(LF, BLACK) pixels_s...
The main task of the code is to run an animation loop in a thread, continuously checking the global `ANIMATION` state to trigger specific actions (e.g., turning left/right, hazards, headlights, brakes) or random settings. It also monitors the `LASTREQUEST` timestamp, resetting animations to a blank state if no new comm...
def animThread(): global ANIMATION global LASTREQUEST print('Starting main animation thread') while True: if ANIMATION == "left": leftTurn() elif ANIMATION == "right": rightTurn() elif ANIMATION == "hazards": hazardLights() elif ANIMATI...
def all_good(): folder_name = Path.cwd().name os_api.show(f'Running moby on repo "{folder_name}", good.\n') if not branch_ok(): return False # TODO: implement --porcelain check; see e.g # https://stackoverflow.com/questions/5139290/how-to-check-if-theres-nothing-to-be-committed-in-the-curren...
The main task of the code is to execute a sequence of steps: first checking if conditions are met via `all_good()`, then running `five_first_minutes()` followed by `last_minute()` if all conditions are satisfied. If `all_good()` fails, the function exits early with `False`.
def run_once(): if not all_good(): return False five_first_minutes() last_minute()
def load_dataset(read_path, sub_dataset, max_life, cluster, train, test, finaltest): print("Loading Subdata set: ", sub_dataset) if train or test: if clusters: data_set = pd.read_csv(read_path + "train_FD"+str(sub_dataset)+'_cluster.csv') else: data_set = pd.read_csv(read...
The main task of the code is to preprocess training data for a predictive maintenance model. It loads sensor data, scales features, visualizes raw and scaled data, generates time-series sequences using a sliding window, and returns the processed sequences along with Remaining Useful Life (RUL) labels for model training...
def to_preprocess(self): training_set = load_dataset(self.read_path, self.sub_dataset, self.max_life, self.cluster, train=True, test=False, finaltest=False) #Plotting sensor data plot_sensors(training_set, scaled=False) #Train Data Feature Scaling scale...
def load_dataset(read_path, sub_dataset, max_life, cluster, train, test, finaltest): print("Loading Subdata set: ", sub_dataset) if train or test: if clusters: data_set = pd.read_csv(read_path + "train_FD"+str(sub_dataset)+'_cluster.csv') else: data_set = pd.read_csv(read...
The main task of the code is to preprocess test data by loading a dataset, applying feature scaling to handle missing values, generating time-windowed sequences for input, and producing corresponding Remaining Useful Life (RUL) labels. The processed test sequences and RUL values are returned for further analysis or mod...
def to_preprocess(self): testing_set = load_dataset(self.read_path, self.sub_dataset, self.max_life, self.cluster, train=False, test=True, finaltest=False) #TestData Feature Scaling scaled_df, cols_wo_na = get_scaleing(testing_set, self.scaler, self.scaler_range, train=False) ...
def load_dataset(read_path, sub_dataset, max_life, cluster, train, test, finaltest): print("Loading Subdata set: ", sub_dataset) if train or test: if clusters: data_set = pd.read_csv(read_path + "train_FD"+str(sub_dataset)+'_cluster.csv') else: data_set = pd.read_csv(read...
The main task of the code is to preprocess test data by scaling features and generating time-series sequences. It loads a dataset, applies feature scaling to handle missing values, and creates input sequences of specified window sizes for predictive modeling. The function returns the scaled sequence data and correspond...
def to_preprocess(self): final_testing_set = load_dataset(self.read_path, self.sub_dataset, self.max_life, self.cluster, train=False, test=False, finaltest=True) #TestData Feature Scaling scaled_df, cols_wo_na = get_scaleing(final_testing_set, self.scaler, self.scaler_range, train=Fals...
def _check_version(): """ Check that the code is being run with the right version of Python :raises: RuntimeError if Python 2 is used. """ if sys.version_info < (3,): raise RuntimeError('This course requires Python 3. Please uninstall Python 2 and install Python 3 in its place.' ...
The function `bits` displays the binary representation (as a hexadecimal string) of an input value `v`, which can be a `bytes`, `str`, or `int` object. For `bytes` and `str`, it ignores the `numbits` parameter and shows the exact stored bits. For `int`, it uses `numbits` to determine the number of bits to display, defa...
def bits(v, numbits=None): """ Display the bits used to store an object :param v: the value to display the bits of :param numbits: the number of bits to display. Only used for int objects. bytes objects always show the exact bits stored, and int objects default to ...
def _check_version(): """ Check that the code is being run with the right version of Python :raises: RuntimeError if Python 2 is used. """ if sys.version_info < (3,): raise RuntimeError('This course requires Python 3. Please uninstall Python 2 and install Python 3 in its place.' ...
The code converts an object's bit representation into hexadecimal shorthand. It handles `bytes`, `str`, and `int` types: `bytes` and `str` use fixed formatting (2 hex digits per byte/character), while `int` uses variable digits based on `numplaces`. It warns if `numplaces` is specified for non-int types, ignores it for...
def shorthand(v, numplaces=None): """ Display the bits used to store an object in hexadecimal shorthand :param v: The value to display the bits of in hexadecimal shorthand :param numplaces: The number of hexadecimal places (digits) to display. e.g. 0x1ef8 has four hexadecimal place...
def _log_error_and_quit(msg, out = None, err = None, code = 1): """ Log an error message and exit. """ warning_color = '\033[91m' end_color = '\033[0m' if err: logging.error(f'{err}') elif out: logging.error(f'{out}') logging.error(f'{warning_color}{msg} ({code}){end_color}') ...
The code updates version references in specified modules' configuration files (YAML, podspecs, Xcodeproj, and Readmes) by replacing an old version with a new one. It validates input arguments, constructs file paths, and applies the version change across all relevant files for each module.
def update(argv): if len(argv) < 3: _log_error_and_quit(f'usage: {__file__} update old_version new_version [package_name ...]') old = argv[0] new = argv[1] modules = argv[2:] if "." not in old or "." not in new: _log_error_and_quit(f'usage: {__file__} update old_version new_versio...
def new_data(self, transaction: Transaction): if not self.has_user_coin(transaction): raise CoinNotBelongToUserError if self.is_double_spending(transaction): raise DoubleSpendingError self.pending_data.append(transaction) def checkout(self, identity: rsa.PublicKey) -> L...
This code processes incoming requests by routing them to specific handling logic based on their type. It prints the payload, creates new coins, manages transactions, handles checkouts, and validates the blockchain, updating internal state accordingly.
def request(self, payload: GenericRequest): print(payload) if payload.type == RequestType.transactionRequest: self.new_data(payload.properties) # transactionCompleted will be on block creation elif payload.type == RequestType.createCoin: if isins...
def convert_to_matrix(expr, cutoff, buffer): new_expr = np.zeros([cutoff+buffer,cutoff+buffer]) if type(expr)==sp.core.add.Add: for elem in expr.args: new_expr = new_expr + convert_term_to_matrix(elem,cutoff+buffer) elif type(expr)==sp.core.mul.Mul: tmp=convert...
This code initializes a quantum system by converting bosonic and fermionic Hamiltonians into Pauli string representations. It processes input parameters, expands symbolic expressions, constructs matrices for bosonic and fermionic components, combines them via Kronecker product, and converts the resulting Hamiltonian ma...
def __init__(self, bosonic, fermionic, params, cutoff, encoding): self.bosonic = bosonic self.cutoff = cutoff #TODO: calculate the buffer...ensor charg self.buffer = 16 #let's just store the bosonic hamiltonian in all interesting forms self.harmonic = sp.expand(self.boso...
def gameEnded(board): return has_won(board,"X") or has_won(board,"O") or len(availableMoves(board)) == 0 def selectPosition(board, position:int, player:str): if position in range(0,10,1): row = int((position-1) /3) column = (position-1)%3 if board[row][column] == "X" or board[row][column...
The code implements a Tic-Tac-Toe game where user moves are read from a file, validated, and applied to the board. The AI uses the minimax algorithm to select optimal moves, updating the board and writing game states back to a file. The loop continues until the game ends, at which point it marks the game as concluded a...
def tictactoeGame(): while not gameEnded(board): gameStatDict = {} validMove = False while not validMove: userMove = None read = False while not read : # import fileWatch exec(open('fileWatch.py').read()) ...
def merge_datasets(self): logger.debug("%%%%%%%%%% Merging datasets:") merged_graphs = list() for graph in self.graphs: if graph not in merged_graphs: merged_graphs.append(graph) else: for merged_graph in merged_graphs: ...
The main task of the code is to apply data optimization based on the specified level. It merges datasets for level 1 or higher and further optimizes selections for level 2 or higher. The function logs debug messages to indicate the selected optimization level and performs the corresponding operations, defaulting to ful...
def optimize(self, level=2): if int(level) == 0: logger.debug("No optimization selected.") elif int(level) == 1: logger.debug("Level 1 optimization selected: merge datasets.") self.merge_datasets() elif int(level) >= 2: logger.debug( ...
def readImages(path): img_array = [] imgc = [] names = [] for filename in glob.glob(path): names.append(filename) names.sort() for filename in names: img = cv2.imread(filename, 0) img1 = cv2.imread(filename) img_array.append(img) imgc.append(img1) ret...
The code tracks a car in a sequence of images using an affine Lucas-Kanade tracker. It extracts a region of interest (ROI) from the first frame, applies the tracker iteratively to subsequent frames, updates the ROI's coordinates with affine transformations, and overlays the tracked region on each frame. The processed f...
def main(): path = "./Data/Car4/img/*.jpg" images, cimages = readImages(path) fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('trackcar2.avi', fourcc, 5.0, (images[0].shape[1], images[0].shape[0])) rect_roi = np.array([(69, 52), (175, 136)]) template = images[0][rect_roi[0][1]:rec...
def getTable(record): p = re.compile('arn:aws:dynamodb:.*?:.*?:table/([0-9a-zA-Z_-]+)/.+') m = p.match(record['eventSourceARN']) if m is None: raise Exception("Table not found in SourceARN") return m.group(1).lower() def generateId(record): keys = unmarshalJson(record['dynamodb']['Keys']) ...
The code modifies a document in Elasticsearch by converting a DynamoDB record into a JSON document. It retrieves the DynamoDB table name, generates a document ID, unmarshals the DynamoDB JSON, and indexes the transformed JSON into Elasticsearch using the table name as the index and the generated ID. The process logs ke...
def modify_document(es, record): table = getTable(record) print("Dynamo Table: " + table) docId = generateId(record) print("KEY") print(docId) # Unmarshal the DynamoDB JSON to a normal JSON doc = json.dumps(unmarshalJson(record['dynamodb']['NewImage'])) print("Updated document:") ...
def getTable(record): p = re.compile('arn:aws:dynamodb:.*?:.*?:table/([0-9a-zA-Z_-]+)/.+') m = p.match(record['eventSourceARN']) if m is None: raise Exception("Table not found in SourceARN") return m.group(1).lower() def unmarshalJson(node): data = {} data["M"] = node return unmarsha...
The code inserts a DynamoDB record into Elasticsearch. It checks if the corresponding Elasticsearch index exists, creating it if missing. It converts DynamoDB's JSON format to standard JSON, generates a unique document ID, and indexes the data with specified settings. The process ensures data is stored in Elasticsearch...
def insert_document(es, record): table = getTable(record) print("Dynamo Table: " + table) # Create index if missing if es.indices.exists(table) == False: print("Create missing index: " + table) es.indices.create(table, body='{"settings": { "index.mapping.coerc...
def insert_document(es, record): table = getTable(record) print("Dynamo Table: " + table) # Create index if missing if es.indices.exists(table) == False: print("Create missing index: " + table) es.indices.create(table, body='{"settings": { "index.mapping.coerc...
This Lambda function processes DynamoDB stream records to synchronize data with Elasticsearch (ES). It authenticates using AWS credentials, connects to an ES cluster, and updates ES documents based on DynamoDB events (INSERT, REMOVE, MODIFY). Errors during processing are logged, ensuring partial success with continued ...
def lambda_handler(event, context): session = boto3.session.Session() credentials = session.get_credentials() # Get proper credentials for ES auth awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, session.region_name, 'es', ...
def generate_tuples_from_file(training_file_path): """ Generates tuples from file formated like: id\ttext\tlabel Parameters: training_file_path - str path to file to read in Return: a list of tuples of strings formatted [(id, example_text, label), (id, example_text, label)....] """ f = open(traini...
The code performs 10-fold cross-validation on a combined training and testing dataset to evaluate and compare two text classification models: a base `TextClassify` and an improved `TextClassifyImproved`. For each fold, it trains the models on the remaining data, validates on the held-out fold, and reports precision, re...
def main(): training = sys.argv[1] testing = sys.argv[2] training_examples = generate_tuples_from_file(training) testing_examples = generate_tuples_from_file(testing) # print(training_examples) number_of_folds = 10 folds = k_fold((training_examples + testing_examples), number_of_folds) classifier ...
def run_cmd(cmd): """Runs a command and returns stdout""" return subprocess.run(cmd, stdout=subprocess.PIPE).stdout.decode("utf-8") def run_zeek_on_files(path, filenames): for f in filenames: if f.endswith(".zeek"): path = path.replace(pkg_script_dir + "/", "") path = path.re...
This code configures the environment for Zeek to generate ReST documentation files, executes Zeek scripts to create documentation, and post-processes ReST files to correct formatting and links for Sphinx conversion to HTML. It sets environment variables, constructs Zeek paths, runs Zeek on scripts, adjusts file referen...
def setup(app): """Zeek will run and generate the ReST files, which Sphinx will then convert to HTML. """ if "ZEEK_DISABLE_ZEEKYGEN" in os.environ: del os.environ["ZEEK_DISABLE_ZEEKYGEN"] os.environ["ZEEK_ALLOW_INIT_ERRORS"] = "1" zeekpath = pkg_script_dir zeekpath += ":" + run_cmd(["z...
def welcomeGame(): print('''Welcome to the game of Rock Paper Scissors Lizard Spock, a variation of the classic version as given in the TV series 'The Big Bang Theory'. The rules for playing are simple, given below in the words of Sheldon Cooper: \t"Scissors cuts Paper, \t Paper covers Rock, \t Rock crushes Lizard,...
The main task of the code is to manage a multiplayer game connection setup. It prompts the user to either initialize a connection by entering an IP address or accept an incoming connection. The code ensures both players are on the same network, facilitating direct communication between them for gameplay. It includes a ...
def main(): welcomeGame() if input('Do you want to initialize connection?(y/n): ') == 'y': print('Make sure the other player is in the same internal network') ip = input("Enter the other player's IP address: ") initConnection(ip) else: acceptConnection() print("Thankyou f...
def train_lstm(pathways_dict,pathway,train_mut=liu_mut,train_clin=liu_clin): ''' :param pathways_dict: :param pathway: :param train_mut: :param train_clin: :return: ''' x1,y1,sorted_data = prep_data_lstm(train_mut,train_clin,pathways_dict, pathway) layer1 = LSTM(5, input_shape=(1,...
The function `lstm_multiple_pathways` trains and evaluates LSTM models for multiple biological pathways using mutation and clinical data. It processes each pathway, computes AUC scores for training, validation, and test sets, and compiles results into a DataFrame. Optional features include saving models, returning mode...
def lstm_multiple_pathways(pathways, pathways_dict, train_mut, train_clin, val_mut, val_clin, test_mut = None, test_clin = None, csv_path_name = None, return_model_and_curve = False, save_model_path = None, save_model_ending = ''): ''' This is a function to run multiple pathways through lstm neural networks. ...
def getTokenV1(self, apiKey, email, password): headers = { 'api_key': apiKey, 'content-type': 'application/json' } body = { 'email': email, 'password': password, 'device_model': 'WEB', 'device_type': 'WEB', 'device_id': '1' } url = "https://sandbox-api.stagingapps.net/merchants/session/lo...
This function synchronizes merchant data and related entities from an external API into Odoo. It retrieves user credentials, fetches authentication tokens, creates/upgrades Odoo companies with merchant details, syncs customers/products/taxes/orders, and updates user company permissions. The process ensures data consist...
def cron_schedule(self, uid=False): print(' Sandbox Cron Job') print('========================================================================') # If uid isn't False then its manual update from button domain = [] if uid != False: domain = [('id', '=', uid)] # Get All User Data Users = http.request.env[...
def projectile_animation(r): if __parent_sprite_name[r] == "battlecruiser": up_motion(r, 5) elif __parent_sprite_name[r] == "fighter": down_motion(r, 5) elif __parent_sprite_name[r] == "bomber": if r in __bullet_motion_direction: if __bullet_motion_direction[r] == "down...
The code updates sprite movements and animations based on their type (torpedo, fighter, scout, bomber, support_ship). It manages bullet firing intervals (every 800ms) for fighters, bombers, and support ships, creating new projectiles when cooldowns expire. It also checks for out-of-bounds sprites, logging and removing ...
def add_sprite_movement(current_time): remove_filled_sprite_index = [] bolt_to_be_created = [] for r in shared_state.filled_index: if ( shared_state.sprite_name[r] == "torpedo" or shared_state.sprite_name[r] == "bolt" ): projectile_animation(r) eli...
def query2df(dirname: Path): count = len([file for file in dirname.iterdir()]) query_dict = {"qid": [], "query": []} for path in tqdm(dirname.iterdir(), total=count): filename = path.stem parser = ET.XMLParser(encoding="utf-8") root = ET.parse(path, parser=parser).getroot() ...
The main task of the code is to process training and test data by retrieving predictions for each query using an index directory. It loads query data into a DataFrame, performs retrieval on the index, and saves the results separately for "train" and "test" splits. The function orchestrates data loading, retrieval, and ...
def main(index_dir: Path): data_path = Path("data") for split in ["train", "test"]: query_path = data_path / f"{split}_query" query_df = query2df(query_path) pred_df = retrieve(query_df, index_dir) save_result(pred_df, split)
def check_state(self) -> GameState: king_status = self.check_king() if king_status == KingEndState.CAPTURED: self.game_state = GameState.ATTACKERS_WON return GameState.ATTACKERS_WON if king_status == KingEndState.SAVED: self.game_state = GameState.DEFENDERS_WI...
This function calculates a heuristic value for the board state based on the current game status and the specified player (attacker/defender). It returns infinity/-infinity for terminal states (win/loss) and a difference between attacker/defender heuristics for non-terminal states, aiding game strategy evaluation.
def get_board_heuristic(self, player : Character): gamestate = self.check_state() if gamestate == GameState.DRAW: return 0 if player == Character.DEFENDER: if gamestate == GameState.DEFENDERS_WIN: return inf elif gamestate == GameState.ATTACKERS_WON: ...
def helpConfigurationChangeAndStart(pPubsubserver, pConfig, pLogger, static=False, possibleFail=False): fd = open(DEFAULT_XML_PATH, "r") oldConfig = fd.read() fd.close() helpConfigurationChange(pPubsubserver, pConfig, pLogger) helpRestart(pPubsubserver, pLogger, possibleFail) # check configura...
This function tests the PubSub connection failure scenario by configuring a PubSub server, setting subscriber and publisher variables, waiting for a dynamic configuration interval, then verifying subscriber values remain unchanged (indicating no successful communication). If 'possibleFail' is False, it also asserts the...
def helperTestPubSubConnectionFail(pubsubserver, xmlfile, logger, possibleFail=False): helpConfigurationChangeAndStart(pubsubserver, xmlfile, logger, possibleFail=possibleFail) # Init Subscriber variables helpTestSetValue(pubsubserver, NID_SUB_BOOL, False, logger) helpTestSetValue(pubsubse...
def helpConfigurationChangeAndStart(pPubsubserver, pConfig, pLogger, static=False, possibleFail=False): fd = open(DEFAULT_XML_PATH, "r") oldConfig = fd.read() fd.close() helpConfigurationChange(pPubsubserver, pConfig, pLogger) helpRestart(pPubsubserver, pLogger, possibleFail) # check configura...
This function tests if a PubSub connection correctly propagates value changes from a publisher to a subscriber. It configures the server, sets initial subscriber values, updates publisher values, waits for propagation, then verifies subscriber values match the publisher's updated values (bool, uint16, int) and confirms...
def helperTestPubSubConnectionPass(pubsubserver, xmlfile, logger): helpConfigurationChangeAndStart(pubsubserver, xmlfile, logger) # Init Subscriber variables helpTestSetValue(pubsubserver, NID_SUB_BOOL, False, logger) helpTestSetValue(pubsubserver, NID_SUB_UINT16, 1456, logger) helpTestSet...
def getOptionalAttribute(node, attrName : str, defValue): try:return node.get(attrName, defValue) except:return defValue def handlePubConnection(publisherId, connection, index, result): cnxContext = CnxContext(connection) result.add(""" /** Publisher connection %d **/ """ % index) nbMsg...
The function `handlePubSub` generates C code for configuring PubSub connections in an OPC UA context. It parses XML elements for publishers and subscribers, allocates memory for their configurations, processes each connection to add dataset and subscription details, and constructs a `SOPC_PubSubConfiguration` structure...
def handlePubSub(pubSub, result): pubConnections = pubSub.findall("./%s[@%s='%s']" % (TAG_CONNECTION, ATTRIBUTE_CONNECTION_MODE, VALUE_CONNECTION_MODE_PUBLISHER)) subConnections = pubSub.findall("./%s[@%s='%s']" % (TAG_CONNECTION, ATTRIBUTE_CONNECTION_MODE, VALUE_CONNECTION_MODE_SUBSCRIBER)) pubDataSet...
def helpConfigurationChangeAndStart(pPubsubserver, pConfig, pLogger, static=False, possibleFail=False): fd = open(DEFAULT_XML_PATH, "r") oldConfig = fd.read() fd.close() helpConfigurationChange(pPubsubserver, pConfig, pLogger) helpRestart(pPubsubserver, pLogger, possibleFail) # check configura...
This code tests the dynamic configuration behavior of a PubSub server under various scenarios, including publisher-only, subscriber-only, and bidirectional configurations. It verifies if variables update correctly, handles security mismatches, invalid XML formats, and writer ID filters. Each test case checks if subscri...
def testPubSubDynamicConf(): logger = TapLogger("pubsub_server_test.tap") pubsubserver = PubSubServer(DEFAULT_URI, NID_CONFIGURATION, NID_START_STOP, NID_STATUS) defaultXml2Restore = False try: # backup of default XML file copyfile(DEFAULT_XML_PATH, DEFAULT_XML_PATH + ".bakup") ...
def analysis_client_requests(self, requests, name=""): wait_time_list = [] for request in requests: if self.is_valid_time(request.request_send_time) and self.is_valid_time(request.reply_receive_time): wait_time_list.append(request.get_wait_time() * 1e3) stats = ListSt...
The code generates a log report by aggregating and analyzing client request wait times, server CPU usage, and overall system efficiency. It processes data from client and server logs, performs analysis, compiles results, and writes them to a report file.
def generate_log(self): try: all_requests = [] for client_id, requests in self.client_log.items(): self.analysis_client_requests( requests, "{} request wait time (ms)".format(client_id)) all_requests += requests print() ...
def pairs(it): if not hasattr(it, "__next__"): it = iter(it) try: swap = next(it) for item in it: yield swap, item swap = next(it) yield item, swap except StopIteration: pass def dump_cave(cave, col_range): print() for digit in rang...
The code simulates sand falling into a cave with rock formations, calculating how many units of sand can be placed before they get blocked (Part 1) and then repeating the process with an added floor to prevent infinite falling (Part 2). It reads rock coordinates from input, constructs a grid representing the cave, fill...
def main(stream, opts): rocklines = [] row_range = [sys.maxsize, 0] col_range = [sys.maxsize, 0] for line in stream: parts = line.split(" -> ") rocklines.append([tuple(int(x) for x in part.split(",")) for part in parts]) for col, row in rocklines[-1]: if col < col_ra...
def handel_list_error(key, errors: list): return {key: default_format(message=errors)} def default_format(message=None, child=None): return {"message": message, "child": child} def manage_error(errors, temp_list=[]): temp_list_2 = [] for key, value in errors.items(): if isinstance(value, dict): ...
This code customizes JSON rendering to structure responses with success status, error messages, and result data. It wraps original rendered data in a standardized format, handling errors based on response status. If unsuccessful, it formats errors from the rendered data (list, string, or other types) and includes them ...
def render(self, data, accepted_media_type=None, renderer_context=None): renderer_context = renderer_context or {} rendered = json.loads(super(CustomJSONRenderer, self).render(data or [], accepted_media_type, renderer_context)) response = renderer_context['response'] errors = [] ...
def maincheck(self): for x in range(len(self.text)): # Reset variables self.a = "" self.stackString = "" # Print action output.add_row(["","",self.action]) #print(self.action) print(output) # Pushing into stack ...
This code implements a shift-reduce parser. It constructs a stack (self.a) by iterating through input elements, then uses maincheck() for parsing steps, checkrules() to apply production rules, and checkvalid() to validate syntax. The PrettyTable output displays the stack state during parsing.
def parser(self): for x in range(len(self.text) - self.inputElement): self.a = self.a + self.text[x + self.inputElement][0] #output = PrettyTable(["stack", "input", "action"]) output.add_row([self.a, "", ""]) print(output) #print("$" + self.a + "$" + "\t\t\t", end='')...
def LearnPOMDP_TO(self,POMDPDataset): """Method to learn the transition matrix of an MDP. T and O learn simultaneously using a DBN network with the following structure. O O O | | | T--T .... --T """ #self.checkIfOcta...
The code trains a POMDP by learning its transition (T) and observation (O) matrices, state rewards, action MDP transition (T_actionMDP), and action rewards. It then combines state and action rewards multiplicatively to form state-action pair rewards, enabling decision-making under uncertainty in partially observable en...
def trainPOMDP(self,POMDPDataset): """Method to train and learn the componenets of a POMDP.""" ########################## Transition and observation matrix print('Learning the transition and observation matrix ...') self.T,self.O = self.LearnPOMDP_TO(POMDPDataset) # assigning T ...
def admin_mode_options(self): self.labels = [] self.admin_dict = {'peru':'peru123', 'joseba':'joseba123', 'sara':'sara123', 'maialen':'maialen123', } self.canvas = Canvas(self.frame_main, width=500, height=5...
Your returnThe main task of the code is to create a GUI interface for managing a database, featuring buttons for actions like viewing data, updating attributes, deleting records, importing Excel projects, and searching, along with a table to display vehicle data. It dynamically configures widgets based on admin privile...
def widgets_window_main(self): '''Create widgets for the frame main''' admin_btn = ttk.Button(self.frame_main, text = 'ADMINISTRADOR MODE', style='primary.Outline.TButton',command=lambda: [self.admin_mode_options()]) admin_btn.grid...
def wheeload_values(self,evt,opt): dict_load_opt = {'':'QZ0', 'Wheel Load':'QZ0', 'Primary Load':'QZ1','Secondary Load':'QZ2'} self.load_select = dict_load_opt[opt.get()] tab_index = self.train.sheet.index('LOADS') tab = self.tabs[tab_index] frame = ScrollableFrame(tab,1500,400)...
The main task of the code is to import and display vehicle general data into a GUI interface. It populates a scrollable table with parameters, values, units, descriptions, sources, and comments from the train data object, while also visualizing car body configurations with labeled images and color-coded bogies to repre...
def insert_data (self): '''Import vehicle general data to the first notebook sheet''' tab_index = self.train.sheet.index('LOADS') tab = self.tabs[tab_index] options = ['Wheel Load', 'Primary Load', 'Secondary Load'] QZ012 = tk.StringVar() s = ttk.Style() s.con...
def hide_tabs(self): '''Method to hide, numpy tabs''' tabs = self.train.sheet can_show = ['Main','Carbody_links','Carbody_data','Track', 'LOADS'] bogi = self.train.BOGIE_CONFIG['value'] for tab in tabs: if tab in can_show: pass elif tab i...
(The main task of the code is to create GUI notebook sheets with configurable grids, add interactive widgets (buttons, images), and integrate data handling functions. It generates frames for each tab, sets layout parameters, places navigation/buttons, and links data visualization/export features. The function prepares ...
def create_sheets(self): '''Create notebook sheets, and general widgets for each sheet''' self.train = self.data_base.vehicle[self.data_base.name_list.index(self.vehicle_name)] tabs = self.train.sheet for tab in tabs: bogies= Frame(self.sheet) bogies.gri...
def select_all_checkbox(self): '''Check all the attributes''' for box in self.checkbox: box.select() def filter_description(self, filt, name): ''' Search entry text in all the attributes names and descritions''' filt = filt.lower() bogie = tools.class_bogie.Bogie('b...
The main task of the code is to filter and display attributes from a hierarchical table based on a search term, allowing users to select matching items. It clears existing data, creates a new window with a scrollable interface, applies a case-insensitive filter recursively through nested table items, marks matches, and...
def sortby_atr(self, filt): ''' Search your text in all the attributes and in it is descriptions''' self.names.clear() self.boxes.clear() self.checkbox.clear() self.i = 1 filt = filt.lower() self.tl = Toplevel(self.frame_compare_parameter) self.tl.geomet...
def __generate_params(**kwargs): params = "" if 'params' in kwargs: params = kwargs['params'] + "&" del kwargs['params'] params += ''.join(str(kwarg) + "=" + str(kwargs[kwarg]) + "&" for kwarg in kwargs if kwargs[kwarg] != "NULL")[ :-1] return pa...
The code retrieves the current best bid and ask prices for a given trading pair from a cryptocurrency exchange API. It constructs a request with a timestamp and signature, fetches market data, and returns the best offer (for buying) and best bid (for selling) as a list [best_offer, best_bid] to facilitate optimal tradi...
def get_current_optimal_price(self, pair): """ Obtain the current optimal order(Best bid and offer) # Use best bid to sell and use best offer to buy. """ path = "/openApi/swap/v2/quote/bookTicker" url = self.ROOT_URL + path parameters = self.__generate_params(symb...