dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def optparser(): op = optparse.OptionParser("\n %prog [OPTIONS] GOLD TEST\n\nDescription:\n evaluates tagging against gold") op.add_option("-s","--suffix", default="ann", help="Suffix of annotated files.") op.add_option("-e","--exact", action="store_true", default=False, ...
The code processes command-line arguments for a program, validating input criteria (e.g., exact, overlap, boundaries) and ensuring only one is specified. It prepares filter types and checks if both inputs are directories or files. If mismatched (one directory, one file), it errors. Otherwise, it directs processing via ...
def main(argv): global options options, args = optparser().parse_args() if len(args) != 2: optparser().print_usage() return 1 # argument sanity criterion_count = sum([1 if a else 0 for a in \ (options.exact, options.overlap, ...
def view_all_records(): """ Function to display the full record collection as a DataFrame in Alphabetical order. Error is printed if API data fetch fails. """ print(colored("\nNow printing all records in " "the collection...\n", "green")) try: df_catalog = get_all_c...
The code defines a function that displays a numbered menu for user navigation, looping indefinitely until an option is selected. It processes user input to execute actions like viewing all records, searching, adding new entries, or deleting records. Each menu choice triggers a corresponding function, with a colored tha...
def user_input_menu(): """ Display a numbered menu for the user. Allows user to navigate to desired option by entering number """ # Run indefinitely while True: menu_options = pyip.inputMenu([MENU_OPTION_VIEW_ALL, MENU_OPTION_SEARCH_COLLECTION, ...
def find_cable_path(self, target_position, cable_routes, house_output): """ Find the cable path of a coordinate and find the connected battery """ for route in cable_routes.values(): for coordinate in route: if coordinate == target_position: ...
The main task of the code is to implement the Nearest Battery Heuristic Algorithm, connecting houses to batteries via cables while minimizing costs. It initializes data structures, iterates through shuffled houses, and assigns each to the closest available battery with sufficient capacity. The algorithm dynamically cre...
def run(self): """ Execute Nearest Battery Heuristic Algorithm """ cables = {} cable_routes = {} connections = {} sum_costs = 5000 * (len(self.batteries)) assign_again = {} optimize = {} houses_copy = self.houses.copy() ran...
def info(self): """Information about device, returns dictionary""" if self._info_loaded: return self._info else: # read from database self._info = self._load_info_from_db() self._info_loaded = True return self._info def snmpget(self, o...
This function retrieves device information via SNMP, compares it with the current stored data, and updates the database with new values if discrepancies are found. It specifically handles model, sysname, and MAC address fields, applying formatting rules (e.g., truncating sysname, converting MAC to hex). If the sysname ...
def update_info_from_snmp(self): """Read info via snmp and update in DB""" item_to_oid_dict = {'model': self.MODEL_OID, 'sysname': self.SYSNAME_OID, 'mac': self.SELF_MAC_OID} cur_info = self.info() device_ip = cur_info.get('management_ip') if not device_ip: return...
def add_water(latlan, area): location = str(latlan) location = ''.join(location.split()) latitude = re.split(',', location)[0] longitude = re.split(',', location)[1] water_form = WaterForm(data={"latitude": float(latitude), "longitude": float(longitude), "area": float(area)}) if(water_form.is_va...
This Django view handles POST requests to add various geographical data types (water, well, airport, highway, river) by routing to respective functions. It extracts parameters like coordinates, area, and name from the request, then renders the 'add_data.html' template with a provided API key.
def add_data(request): if request.method == 'POST': if request.POST["button"] == "water": latlan = request.POST['latlng'] area = request.POST['area'] add_water(latlan, area) elif request.POST["button"] == "well": latlan = request.POST['latlng'] ...
def get_node_type_dict(edges_data, rels_type): typed_node_dict = {x: [] for x in set(sum([i.split("-") for i in rels_type], []))} for idx, edge in enumerate(edges_data): type1, type2 = rels_type[idx].split("-") typed_node_dict[type1] = typed_node_dict[type1] + list(edge.nonzero()[0]) ty...
The code loads graph data, constructs a global graph with node features, and generates meta-learning tasks by creating support/query sets for each task, using random class selection and graph structures.
def load_data(file_dir, dataset_info, args): dataset, rels_type, tar_type, comm_rels, diff_rels = dataset_info with open(osp.join(file_dir, dataset, 'raw', 'edges.pkl'), 'rb') as f: edges_data = pickle.load(f) # get type node dict and node type dict node_type_dict = get_node_type_dict(edges_da...
def _read_first4bytes(self, d): """RTR RFC 8210 protocol""" protocol_version = int(d[0]) pdu_type = int(d[1]) if pdu_type in [0, 1, 3, 7]: session_id = int(d[2]) * 256 + int(d[3]) header_flags = None error_code = None elif pdu_type in [2, 4, 6, 8]: session_id = None header_flags = None erro...
The code processes packets using the RTR RFC 8210 protocol by parsing a buffer to extract Protocol Data Units (PDUs). It checks for sufficient data, reads header fields (type, session ID, flags, error code), determines packet length, and processes the payload. If processing fails or data is incomplete, it stops. Finall...
def process(self, packet_buffer): """RTR RFC 8210 protocol""" data_index_max = len(packet_buffer) data_index = 0 while data_index < data_index_max: if (data_index_max - data_index) < 8: # self._debug_('DATA EXPIRED: not enough for eight bytes') break d = packet_buffer[data_index:data_index + 4] ...
def init_solver(self) -> None: """ Generates the zeroth iteration data :return: """ state_vec = np.array([self._get_state_vector(n=n) for n in range(len(self._bodies))]) self._update_bodies(state_vec=state_vec, i=0, t=self._t) self.print_debug(i=0) def compute_it...
The code simulates a physical system by iterating over a predefined number of steps. It initializes the solver, updates the simulation time, computes rotational dynamics for rigid bodies (RBody), advances the simulation state, and logs debug information. Finally, it returns a Results object containing the updated bodie...
def solve(self) -> Results: """ :return: """ self.init_solver() for i in np.arange(1, self._iterations): self._t = i * self._dt for body in self._bodies: if type(body) is RBody: body.compute_rotation() s...
def progress(iter): for res in iter: s = f"test={res.test}, method={res.method}, format={res.format}" print(s.ljust(80), end="\r") yield res def bench_methods( rgb, name, warmup=3, tests=10, formats=None, implementations=None, qoi_lossy_scale=0.5, jpeg_quality=80 ): jpg = formats is ...
The function benchmarks image encoding/decoding methods by testing them on three scenarios: all-black (best case), random noise (worst case), and a koi photo. It runs warmup iterations, then executes tests for specified formats/implementations, measuring performance metrics. Results are aggregated and converted to a ta...
def benchmark( warmup=3, tests=10, images=".*", formats=None, implementations=None, qoi_lossy_scale=0.5, jpeg_quality=90 ): size = (1080, 1920, 3) kwargs = dict( warmup=warmup, tests=tests, formats=formats, implementations=implementations, qoi_lossy_scale=qoi_lossy_sc...
def clear(): if name == 'nt': _ = system('cls') else: _ = system('clear') def LoopRunner(storeNums,userProfile): loopBreaker = 0 loopCounter = 1 while loopBreaker < 1: clear() print('Product --> ' + userProfile[0]) print('\nChecker counte...
The main task of the code is to check BestBuy product availability using user profiles and store locations. It retrieves store numbers from a location list, processes them, and runs a loop to check products across stores. It includes error handling for profile setup issues and re-executes the main function if needed.
def mainBrain(): print(""" Welcome to BestBuy Product Checker Version: 1.01 -------------------------------------- """) print('Profiles\n________\n') userProfile = Profile.check_If_Files_Exist() print(userProfile) clear() userStoreList = Locati...
def train_d(self, conf): self.optimizer_D2.zero_grad() if self.dscMask==False: #1001 1111 g_pred = self.G.forward(self.g_input) d2_pred_fake = self.D2.forward((g_pred + torch.randn_like(g_pred) / 255.).detach()) l_d2_fake = self.criterionGAN(d2_pred_...
The code trains a Deep Image Prior (DIP) model to generate super-resolution images by iteratively refining a kernel. It uses SSIM/MSE loss for optimization, corrects the kernel with a neural network, and alternates between forward (image generation) and backward (loss calculation) steps. The kernel is frozen initially ...
def train(self, g_input, d_input, g_inputB, d_inputB, mg_inB, md_inB, conf): self.g_input = g_input.contiguous() self.d_input = d_input.contiguous() self.train_d(conf) self.train_g(conf) ############################################################# self.calc_kernel...
def execute_open(self, folder_name): directory_path = os.path.join('matches', folder_name) if os.path.exists(directory_path): operating_system = sys.platform try: if operating_system.startswith('win'): # Windows subprocess.Popen(['explorer', d...
The code creates a GUI for managing personnel data, featuring a search bar, scrollable display of individuals' info (images, details), and action buttons (Found, Delete, Not Found, TIME/DATE). It loads JSON data, dynamically generates UI elements per entry, and enables/disables buttons based on folder existence. The la...
def setupUi(self, Form): Form.setObjectName("Form") Form.resize(1400, 900) # Create a horizontal layout for the top bar top_bar_layout = QtWidgets.QHBoxLayout() # Create a search bar widget and add it to the top bar layout (on the left side) self.search_bar = QLineEdit(...
def get_directories(args): if args.config is None or args.name is None: raise ValueError("Must have name and config") config = pathlib.Path(args.config).stem if args.log_dir is None: run_base_dir = pathlib.Path( f"runs/{config}/{args.name}/prune_rate={args.prune_rate}/{args.task...
The main task of the code is to evaluate the robust accuracy of pruned neural networks against adversarial attacks. It iterates through multiple checkpoint files, loads corresponding pruned models, and measures their performance on validation data using an attack model. Results are logged, including accuracy metrics fo...
def main_worker(args): # Set up directories args.task = 'transfer' run_base_dir, ckpt_base_dir, log_base_dir = get_directories(args) args.ckpt_base_dir = ckpt_base_dir log = logging.getLogger(__name__) log_path = os.path.join(run_base_dir, 'log.txt') handlers = [logging.FileHandler(log_pat...
def find_pairs_of_ten(input_list): pairs_of_sum10=[] #i and j are traversal variables. #i traverses the list. for i in range(len(input_list)): curr_val=input_list[i] for j in range(len(input_list)): #j traverses the list to compare elements with the current value (curr_value) to find sum...
The main task of the code is to present a menu-driven program that performs four mathematical/data analysis tasks based on user input: finding number pairs summing to 10, calculating list range, computing matrix powers, and identifying the most frequent character in a string. The code handles input collection, function...
def main(): #Menu to select the question. print("Which function?") op=int(input(''' 1. Find pairs of numbers in a list such that sum is 10. 2. Find the range in a list of numbers. 3. Find A power m for a square matrix A and integer m. 4. Fi...
def Interclass_and_Intraclassspread(df,class1,class2): df_class1=df[df['Species'].isin([class1])] df_class2=df[df['Species'].isin([class2])] cols_to_calculate1=df_class1.iloc[:,1:5] cols_to_calculate2=df_class2.iloc[:,1:5] matrix1=cols_to_calculate1.values matrix2=cols_to_calculate2.values m...
The code provides a menu-driven interface for analyzing a dataset, offering options to compute interclass/intraclass spread, generate histograms, calculate Minkowski distance, split data, train a KNN model, evaluate accuracy, and generate confusion matrices. It reads a dataset, cleans it by removing NaN rows, and execu...
def main(): df=pd.read_excel("Dataset.xlsx") #Opens and reads the dataset. clean_df=df.dropna(axis=0,inplace=False) #Removes rows with NaN values op=int(input('''Enter the option: 1. Interclass and Intraclass spread. 2. Histogram of feature. 3. M...
def get_page_posts(url): post_keys=["User", "Date","Index", "Text"] page_db=[] raw_html=simple_get(url) html = BeautifulSoup(raw_html, 'html.parser') for article in html.select('article'): post_dict= dict.fromkeys(post_keys) for div in article.select('div'): if ...
The code recursively crawls web pages starting from a given URL, collects posts from each page into a database, and returns the aggregated database once all pages are processed. It appends each page's posts to the database, checks for the "LAST_PAGE" marker to terminate recursion, and continues to the next page URL unt...
def recursive_crawler(url, db): page_posts = get_page_posts(url) next_page_url = get_next_page(url) db = db + page_posts if next_page_url=="LAST_PAGE": return(db) else: return(recursive_crawler(next_page_url, db))
def get_AO3_jobs(cron): return [job for job in cron if job.command == AO3_cron_command] def print_AO3_jobs(AO3_jobs): if len(AO3_jobs) < 1: print('There are no current times AO3 data is being collected.') return None data = list() for index, job in enumerate(AO3_jobs): minute = s...
This function allows users to manage cron jobs for scheduling AO3 data tracking. It provides options to view, add, remove, or modify scheduled times, with real-time updates to the cron table. Duplicate jobs are automatically removed, and changes are saved to the system's crontab upon user confirmation. The interface en...
def interact_with_cron(): # Initialize cron interaction cron = CronTab(user=True) AO3_jobs = get_AO3_jobs(cron) # Begin user interaction cm.clear_screen() print('This function allows you to chose when your computer tracks AO3 info.') print('Your computer will NOT track info if it is turned ...
def print_fics(fics): if len(fics) < 1: print("You have no fics you're currently tracking.") return None # Create a list of lists for the tabulate function data = list() for index, fic in enumerate(fics): filepath = os.path.join(cm.DATA_DIRECTORY, cm.make_workHistory_filename(fi...
This function provides a command-line interface for managing tracked fics, allowing users to add/remove/change fics, adjust tracking schedules, update fics immediately, or exit. It maintains the save file, interacts with external modules for cron jobs and AO3 updates, and handles user input to modify tracking configura...
def user_interface(save_filepath): # Loop that allows the user to interact with and change the file commanding what fics are tracked. # This will also move and/or rename the stat files if the user changes those in any way. cm.ensure_fic_save_file_exists(save_filepath) # Also creates the save folder if it ...
def getStartRow(self, tile):#get the far left tile in the next row if tile.S == None: return tile tile = tile.S while tile.W != None: #gets to the left of the next row tile = tile.W return tile def checkIfValid(self, tile): #goes to the next row and check...
This function explores a grid to place a queen in the first valid position, backtracking if no moves are available. It checks each tile in a row, updates the grid state, and returns the modified tile. If a valid spot is found, it marks the tile as a queen, records its path, and proceeds. If no further moves exist, it b...
def directionalArc(self, tile): if tile.S == None: return tile tempTile = self.getStartRow(tile) while tempTile is not None: if tempTile.value == value.avail: availableMove = self.checkIfValid(tempTile) #check if placing a queen will ...
def getTile(self, row, col, board): return board.tiles[row][col] def setTile(self, tile, value): tile.setTile(value) def forwardCheck(self, tile): if tile.S == None: return self.check(tile) def placeNext(self, tile): flag = True if tile.S == None: ...
The code solves a constraint satisfaction problem, likely the N-Queens puzzle, by placing queens on a board using forward checking and directional arc consistency (DARC) algorithms. It validates user input for a starting position, iteratively places queens while checking constraints, backtracks when conflicts arise, tr...
def run(self): flag = True Board = board(8) Board.generateTiles(Board.size) Board.connectTiles() while(flag): start = input("select a starting position from row 1 (A1, B1 etc)") #conversion from input to correct ints let = str(start[0]) ...
def same_state(node1, node2): comparison = node1.state == node2.state result = comparison.all() return result def print_path(n): solution = [] solution.append(n.parent) while solution[-1] is not None: solution.append(solution[-1].parent) solution.remove(None) return solution def ...
The code implements Greedy Best-First Search (GBFS) to find a path to a goal state from a root node. It uses a priority queue (frontier) to explore nodes, expanding the most promising (lowest cost) node first. The algorithm checks if the current node matches the goal state, returns the path, nodes visited, and computat...
def gbfs(n): # create frontier, explored/closed list, and push the root node to the frontier start_time = time.time() frontier = PriorityQueue() explored = [] goal_node = Node(goal_state, [1, 1], 0) root = n frontier.push(root) i = 0 # iterates through search until depth limit is re...
def same_state(node1, node2): comparison = node1.state == node2.state result = comparison.all() return result def print_path(n): solution = [] solution.append(n.parent) while solution[-1] is not None: solution.append(solution[-1].parent) solution.remove(None) return solution def ...
The code implements Uniform Cost Search (UCS) to find the shortest path from a root node to a goal state in a state space. It uses a priority queue (frontier) to explore nodes in order of increasing cost, tracks visited nodes, and checks for goal state matches. If a solution is found, it outputs the path, number of nod...
def ucs(n): start_time = time.time() frontier = PriorityQueue() explored = [] goal_node = Node(goal_state, [1, 1], 0) root = n frontier.push(root) i = 0 for i in range(d): if frontier.is_empty(): print("A solution could not be found or maximum iterations were met") ...
def same_state(node1, node2): comparison = node1.state == node2.state result = comparison.all() return result def print_path(n): solution = [] solution.append(n.parent) while solution[-1] is not None: solution.append(solution[-1].parent) solution.remove(None) return solution def ...
This code implements the A* algorithm to find the shortest path from a start node to a goal state. It uses a priority queue (frontier) and tracks explored nodes. If the goal is reached, it prints the path, nodes visited, and computational time. If no solution is found, it outputs explored nodes and the frontier state.
def a_star(n): start_time = time.time() frontier = PriorityQueue() explored = [] goal_node = Node(goal_state, [1, 1], 0) root = n frontier.push(root) for i in range(d): if frontier.is_empty(): print("A solution could not be found or maximum iterations were met") ...
def buildVersionFromDirectory(pathRoot, version, metadata, dlroot): verpathRoot = os.path.normpath(pathRoot + version) + '/' if not os.path.isdir(verpathRoot): print(' Version path is not valid: %s' % verpathRoot) return None ret = { 'version' : version, 'version_ra...
The function constructs metadata for a software artifact by processing a directory structure, organizing version data under MC version keys, and loading configurations. It initializes metadata with group, artifact, and version info, processes each version to categorize classifiers, and integrates configurations from th...
def buildMetadataFromDirectory(pathRoot, mavenRoot, group, name, versions, dlroot): if dlroot[-1] != '/': dlroot = dlroot + '/' print('Building Metadata: ') print(' Root: ' + pathRoot) print(' Maven: ' + mavenRoot) print(' Group: ' + group) print(' Artifact...
def loadVersions(cache): data = Util.readFile(os.path.join(cache, 'versions.json')) if data is None: return None return json.loads(data) def updateVersionsWeb(url, auth, repo, group, name, cache): obj = {'repo': repo, 'group': group, 'name': name} data = postJson(url, '/service/rest/v1/scrip...
The function gathers metadata about software versions from a repository, checking a local cache for existing data. If the cache is outdated or missing, it fetches updated version information from a server. It organizes version data into a structured format, including mappings between versions and Minecraft versions, an...
def gatherMetadata(url, auth, repo, group, name, version, cache): root = os.path.join(cache, group.replace('.', '/'), name) versions = loadVersions(root) if versions is None or not 'versions' in versions or (not version is None and not version in versions['versions']): versions = updateVersionsWeb(u...
def _get_text(element: Element, name) -> Optional[str]: child = _get_child(element, name) if child is None: return None return child.text.strip() def _get_attribute_text(element: Element, name, attribute) -> Optional[str]: children = _get_children(element, name) if children is None: ...
The code fetches an XML feed from a given URL, parses it to extract metadata (title, icon, image, and link), retrieves items using a helper method, and constructs a `Channel` object with these details.
def fetch(self, url) -> Channel: response = requests.request('GET', url) root = defused_xml_parse(response.content) title = _get_text(root, './feed:title') icon = _get_text(root, './feed:icon') image = _get_text(root, './feed:logo') url = _get_attribute_text(root, './feed...
def set_up(): global trades global excel_df global prev_dict global anomaly anomaly = False prev_dict = {"Top": 0, "Bottom": 0} prev_hl = {"HH": 0, "LL": float("inf")} excel_df = pd.DataFrame( columns=[ "Action", "Trade_LS", "Entry_Date", ...
The code processes financial data to generate trading visualizations and reports. It fetches historical price data for indices, equities, or futures, extracts OHLC (open, high, low, close) values, and creates candlestick charts. It applies trading logic using entry/exit buffers and trailing stops, iterates through data...
def run(info): set_up() index = info[0].split() line = info[1] entry_buff = info[2] exit_buff = info[3] risk_percent = info[4] tsl_1 = info[5] tsl_2 = info[6] start_date = info[7] end_date = info[8] # ind = yf.Ticker(index) # ind_history = ind.history(start= start_date,...
def set_up(): global trades global excel_df global prev_hl global prev_hls global week1 global week2 week1 = {"High" : 0, "Low" : float('inf')} week2 = {"High" : 0, "Low" : float('inf')} prev_hl = {"High" : 0, "Low" : float('inf')} prev_hls = {"HH": 0, "LL": float('inf')} exc...
The code processes financial data to analyze trading strategies by fetching historical prices for indices/futures, tracking weekly highs/lows, simulating trades based on entry/exit buffers, and generating a profit/loss report in Excel. It handles different asset types, adjusts for market days, and applies stop-loss mec...
def run(info): set_up() global week1 global week2 index = info[0].split(" ") line = info[1] entry_buff = info[2] exit_buff = info[3] msl = info[4] bep = info[5] start_date = info[6] end_date = info[7] # ind = yf.Ticker(index) # ind_history = ind.history(start= ...
def stackDat(datdir, kw='PEM.dat', timestamp_reference_list=[], existing_datlist=[], **par): if not existing_datlist: datlist = get_filelist(datdir, kw) else: datlist = existing_datlist if timestamp_reference_list: datlist = [x for _, x in sorted(zip(timestamp_reference_list, datlist...
This function loads and processes EEM (Excitation-Emission Matrix) data stacks from a directory, applying optional corrections (inner filter, scattering), smoothing, range trimming, and contour masking. It returns the processed EEM stack, adjusted emission/excitation ranges, and file lists, enabling advanced fluorescen...
def load_eem_stack_interact(filedir, scattering_correction=False, em_range_display=[250, 820], ex_range_display=[200, 500], gaussian_smoothing=True, inner_filter_effect=True, sigma=1, truncate=3, otsu=True, binary_threshold=50, tolerance=15, ...
def gaussconvolve2d(array,sigma): return convolve2d(array, gauss2d(sigma)) def sobel_filters(img): # Make sobel filters x_filter = np.array([ [-1, 0, 1], [-2, 0, 2], [-1, 0, 1] ], dtype = 'float32') y_filter = np.array([ [1, 2, 1], [0, 0, 0], ...
The code performs Canny edge detection on an image. It converts the image to grayscale, applies Gaussian blurring, computes gradients using Sobel filters, suppresses non-maximal edges, applies double thresholding, and finalizes edges via hysteresis. The result is a detected edge map of the input image.
def main(): im = Image.open('iguana.bmp') im_grey = im.convert('L') im_array = np.asarray(im_grey) im_array = im_array.astype('float32') img_array = gaussconvolve2d(im_array, 1.6) img = Image.fromarray(img_array) # Original picture # im.show() # Greyscaled Picture # im...
def boxfilter(n): # assert : Raises error if condition is not true assert n%2 == 1, 'n should be odd number' # numpy.full(shape, fill_value, dtype=None, order='C', *, like=None) return np.full((n, n), 1.0 / (n*n)) def gauss1d(sigma): xlen = math.ceil(sigma * 6) # if xlen is even, make it to odd...
The code demonstrates various image filtering techniques: it applies box filters, Gaussian blurs (1D/2D), and generates hybrid images by combining low-frequency (blurred) and high-frequency (sharpened) components from different images. It also tests filter functions with different parameters and visualizes results, inc...
def main(): # BoxFilter print(boxfilter(3)) print(boxfilter(4)) print(boxfilter(7)) # Gauss1d print("gauss1d(0.3): ", gauss1d(0.3), end="\n\n") print("gauss1d(0.5): ", gauss1d(0.5), end="\n\n") print("gauss1d(1): ", gauss1d(1), end="\n\n") print("gauss1d(2): ", gauss1d(2), end="\n\n...
def get_logstream(bucket, key): logGroupName = "/aws/s3/" + bucket try: cloudwatch.create_log_group(logGroupName=logGroupName) except cloudwatch.exceptions.ResourceAlreadyExistsException: pass try: cloudwatch.create_log_stream( logGroupName=logGroupName, logStreamNam...
This Lambda function processes S3 object events by checking bucket tags to route notifications to SQS queues or Lambda functions based on tag prefixes. If a configuration tag is present, it retrieves and parses log files from S3, applies SSM-defined configurations, and sends parsed logs to CloudWatch. The function hand...
def lambda_handler(event, context): # Get the object from the event account_id = boto3.client('sts').get_caller_identity().get('Account') logger.info(f"Got Account ID {account_id}") bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.parse.unquote_plus( event['Records'][0]['s3'...
def filter_user_events(event) -> bool: is_match = match_user_agent(event['userAgent']) is_read_only = match_readonly_event_name(event['eventName']) is_ignored_event = match_ignored_events(event['eventName']) is_in_event = 'invokedBy' in event['userIdentity'] and event['userIdentity']['invokedBy'] == 'AW...
The main task of the code is to process CloudTrail logs stored in S3 buckets, filter events originating from the AWS Console, extract relevant user activity details, and publish alerts via SNS when manual changes are detected. It reads compressed JSON logs, parses event records, constructs notification messages with us...
def lambda_handler(event, context) -> None: """ This functions processes CloudTrail logs from S3, filters events from the AWS Console, and publishes to SNS :param event: List of S3 Events :param context: AWS Lambda Context Object :return: None """ s3 = boto3.client('s3') for record in ev...
def findAPrime(a, b, k): '''Return a pseudo prime number roughly between a and b, (could be larger than b). Raise ValueError if cannot find a pseudo prime after 10 * ln(x) + 3 tries. ''' x = random.randint(a, b) for i in range(0, int(10 * math.log(x) + 3)): if millerRabin(x, k): ...
This function generates RSA public and private keys by finding two distinct large pseudo-primes within a specified range [a, b], computing the modulus (n = p*q) and Euler's totient (m = (p-1)*(q-1)), selecting a coprime public exponent e, and determining the private exponent d via modular inversion. It returns the key ...
def newKey(a, b, k): ''' Try to find two large pseudo primes roughly between a and b. Generate public and private keys for RSA encryption. Raises ValueError if it fails to find one''' try: p = findAPrime(a, b, k) while True: q = findAPrime(a, b, k) if q != p: ...
def get_coprime2(n): while True: e = random.randint(1, n) if coprime([e, n]): break return e def multiplicative_inverse(e, phi): d = 0 x1 = 0 x2 = 1 y1 = 1 temp_phi = phi while e > 0: temp1 = temp_phi / e temp2 = temp_phi - temp1 * e t...
The function `getED` generates RSA public and private keys by finding a coprime `e` with `n` and computing its modular inverse `d` modulo `phi`, ensuring valid key pairs for encryption/decryption.
def getED(n,phi): e = 3 # This loop makes sure that the coprime generated (e) # also has a multiplicative inverse ((d*1)mod phi = 1 ) while True: #e = get_coprime(n,phi,e) e = get_coprime2(n) d2 = multiplicative_inverse(e,phi) #d = modinv(e, phi) d = modInv(e,n) ...
def generate_keypair(p, q): # p and q should be not equal, prime numbers n = p * q # Phi is the totient of n phi = (p - 1) * (q - 1) # Get e and integer thats coprime to phi # Use Euclid's Algorithm to generate the private key e,d = getED(n,phi) # Return public and private keypair ...
This code benchmarks RSA decryption performance by repeatedly generating RSA key pairs, encrypting a message, and decrypting it, measuring the average time per loop to evaluate decryption speed.
def baseMainSlowDecryp(message,loops): print("SLOW RSA Encrypter/ Decrypter") # p = 36568813 # q = 36568627 #p = 28724974744256171210604537402133690870051111739655285872546166668885450610413079893885519106791870497 #q = 28554857743402135305774283412588218725858350542800965497651716463331429073144765...
def generate_keypair(p, q): # p and q should be not equal, prime numbers n = p * q # Phi is the totient of n phi = (p - 1) * (q - 1) # Get e and integer thats coprime to phi # Use Euclid's Algorithm to generate the private key e,d = getED(n,phi) # Return public and private keypair ...
This code measures the average time required for RSA encryption and decryption processes using small prime numbers (p=821, q=811) over multiple loops. It generates RSA key pairs, encrypts a message, and decrypts it repeatedly, calculating the average execution time for these operations.
def baseMainSmallPrimes(message,loops): print("RSA Encrypter/ Decrypter") # p = 36568813 # q = 36568627 p = 821 q = 811 #p = 53 #q = 61 c = 0 for i in message: c+=1 print("Amount of chars",c) #print("Amount of Bytes:",bytes_needed(message)) start = time.process_ti...
def generate_keypair(p, q): # p and q should be not equal, prime numbers n = p * q # Phi is the totient of n phi = (p - 1) * (q - 1) # Get e and integer thats coprime to phi # Use Euclid's Algorithm to generate the private key e,d = getED(n,phi) # Return public and private keypair ...
This code benchmarks RSA encryption/decryption performance by generating key pairs, encrypting, and decrypting a message multiple times. It measures total and average time per loop using fixed large primes p/q, counts message characters, and outputs timing results for performance analysis.
def baseMain(message,loops): print("RSA Encrypter/ Decrypter") # p = 36568813 # q = 36568627 p = 28724974744256171210604537402133690870051111739655285872546166668885450610413079893885519106791870497 q = 2855485774340213530577428341258821872585835054280096549765171646333142907314476525515859307059809...
def generate_keypair(p, q): # p and q should be not equal, prime numbers n = p * q # Phi is the totient of n phi = (p - 1) * (q - 1) # Get e and integer thats coprime to phi # Use Euclid's Algorithm to generate the private key e,d = getED(n,phi) # Return public and private keypair ...
The code demonstrates RSA encryption and decryption by generating public/private key pairs from large primes, encrypting a message, and decrypting it, while timing the process. It showcases the RSA algorithm's workflow, including key generation, encryption, and decryption steps.
def main(message): print("TIME STARTED:", datetime.datetime.now().time()) print(datetime.datetime.now().time()) print("RSA Encrypter/ Decrypter") # p = 53 # q = 61 p = 28724974744256171210604537402133690870051111739655285872546166668885450610413079893885519106791870497 q = 285548577434021353...
def get_digits_amount(n): c = 0 while n > 0: n = n//10 c+=1 return c def generate_keypair(p, q): # p and q should be not equal, prime numbers n = p * q # Phi is the totient of n phi = (p - 1) * (q - 1) # Get e and integer thats coprime to phi # Use Euclid's Algorith...
The code performs RSA encryption/decryption using large primes p and q, validates correctness by comparing decrypted output with the original message, and measures average execution time over 100 iterations. It checks if p*q exceeds the message length, generates key pairs, encrypts/decrypts data, and confirms successfu...
def only_one_encrypt(message): print("RSA Encrypter/ Decrypter") # p = 36568813 # q = 36568627 p = 28724974744256171210604537402133690870051111739655285872546166668885450610413079893885519106791870497 q = 28554857743402135305774283412588218725858350542800965497651716463331429073144765255158593070598...
def connect(): """ establish connection to the database :return: connection and cursor objects to interact with the database """ conn = sqlite3.connect("database.db") cursor = conn.cursor() return conn, cursor def get_hashed_match(match, key): """ finds the corresponding encrypted en...
The function `del_passwd` deletes a password entry from a database by matching the provided app name and username (after hashing with the master password key) and executes a SQL DELETE query to remove the corresponding record from the `passwords` table.
def del_passwd(match, key): """ :param match: list consisting app_name, username, password; which user want to delete :param key: hashed value of master password :return: """ conn, cursor = connect() hashed_match = get_hashed_match(match, key) appn, usern, _ = [i for i in hashed_match] ...
def input(self): keys = pygame.key.get_pressed() if keys[pygame.K_SPACE]: if self.if_in_rect(TP_IN_RECT_1_X, TP_IN_RECT_1_Y, TP_IN_RECT_1_W, TP_IN_RECT_1_H): self.tp(TP_OUT_RECT_1_X, TP_OUT_RECT_1_Y) event = pygame.event.Event(EVENT_TP_1) pyga...
The code's main task is to update an object's state by sequentially handling user input, moving the object, retrieving its current status, and animating it, ensuring dynamic interaction and visual representation in a program.
def update(self): self.input() self.move() self.get_status() self.animate()
def convert_pressures(pressures, to:str): """Convert the pressure from Pa to psia""" con_factor = 6895.0 if to == 'imp': try: pressures = pressures/con_factor return pressures except: return np.array(pressures)/con_factor elif to == 'SI': try: ...
The code calculates and plots performance metrics for a turbofan engine configuration using given thermodynamic parameters, including compressor, turbine, and combustor characteristics. It generates engine configurations, evaluates operating limits, and visualizes results based on input values like altitude, thrust, an...
def rfp2(): # General values alt = 30000 # ft thrust = [4800, 4800, 4800, 4800, 4800, 4800] # lbf spec_trust = 98.4 # lbf/lbmass flow through compressor fuel_vol = 1600 # gallons # Ambient values mach0 = .8 Ts0 = -44.4 # C Ps0 = 4.36 # psia # Inlet values inlet_press_rec = .9...
def extendedterm2string(self, p): # Legacy. if p[0] in ['perm', 'viol', 'pow']: r = p[0] + '(' + self.term2string(p[1]) + ')' elif p[0] == 'obl': r = p[0] + '(' + self.term2string(p[1][0]) + ',' + self.term2string(p[1][1]) + ',' + self.term2string( p[1][2]...
The code generates Answer Set Programming (ASP) aggregate and fluent definitions based on input parameters. It constructs rules to count occurrences of predicates, defines new fluents with variables and types, and handles different term lengths. The function processes variables, builds ASP syntax strings, and prints fo...
def printAggregates(self,c,term,institution: str=None): #self.instal_print(" {} = #count {{P: ".format(term) ) #self.instal_print(" N = #count {P: ") #print('Term: ',term, ' ',len(term)) if len(term)==1: t= term[0] else: for i in term: t+=...
def instal_print(self, to_append: str) -> None: #Legacy. InstAL print used to print to file: it now just adds to an out variable which is returned. self.out += to_append + "\n" def extendedterm2string(self, p): # Legacy. if p[0] in ['perm', 'viol', 'pow']: r = p[0] + '(' + se...
This function recursively processes and prints logical conditions in a formatted string. It handles 'and', 'not', and comparison operators, using 'instal_print' to output structured clauses. If no institution is provided, it defaults to a stored value. It avoids printing 'revise' unless explicitly included, formatting ...
def printCondition(self, c, institution: str=None): if not institution: institution = self.names["institution"] if not c: return if c[0] == 'and': self.printCondition(c[1],institution=institution) self.printCondition(c[2],institution=institution) ...
def term2string(self, p): # Legacy. args = p[1] r = '' if len(args) == 0: r = p[0] elif len(args) == 1: r = p[0] + '(' + args[0] + ')' elif p[0] in ['==', '!=', '<', '>', '<=', '>=']: r = p[1][0] + p[0] + p[1][1] elif p[0] == 'a...
This function processes a condition structure recursively. It handles 'and' and 'not' operators by recursively processing sub-conditions, and for other cases, constructs a logical literal string using term2string. If 'revise' is absent, it invokes prepPrintTryDel with the generated literal, increments an ID counter, an...
def prepPrintTryUseForCondition(self,rId, bId, c): if c==[]: return if c[0]=='and': self.prepPrintTryUseForCondition(rId,bId,c[1]) self.prepPrintTryUseForCondition(rId,bId+1,c[2]) elif c[0]=='not': self.preTemp='not_' self.prepPrintTryUseForConditi...
def instal_print(self, to_append: str) -> None: #Legacy. InstAL print used to print to file: it now just adds to an out variable which is returned. self.out += to_append + "\n" def collectVars(self, t, d, compiler: 'InstalCompiler' = None): # A legacy function. Not removed because a lot of the t...
This function generates Prolog-style rules for event occurrences based on input conditions and events. It iterates through a list of 'generates' rules, extracts variables, formats conditional logic, and prints constraints ensuring events occur under specified conditions. Time steps are partially unimplemented, with pla...
def instal_print_generates(self, generates: list) -> None: # generates self.instal_print("%\n% generate rules\n%") for rl in generates: [inorexev, inev, cond, ti] = rl vars1 = {} self.collectVars(inorexev, vars1) self.collectVars(cond, vars1) ...
def instal_print(self, to_append: str) -> None: #Legacy. InstAL print used to print to file: it now just adds to an out variable which is returned. self.out += to_append + "\n" def collectVars(self, t, d, compiler: 'InstalCompiler' = None): # A legacy function. Not removed because a lot of the t...
This method translates initiation rules into Prolog-style clauses, printing formatted logic constraints with variable type checks. It processes each rule's components (inev, inits, cond), collects variables, and generates instantiated rules with conditions, ensuring proper typing and institutional context.
def instal_print_initiates(self, initiates: list) -> None: # initiates self.instal_print("%\n% initiate rules\n%") for rl in initiates: [inev, inits, cond] = rl vars1 = {} self.collectVars(inev, vars1) self.collectVars(cond, vars1) for ...
def instal_print(self, to_append: str) -> None: #Legacy. InstAL print used to print to file: it now just adds to an out variable which is returned. self.out += to_append + "\n" def collectVars(self, t, d, compiler: 'InstalCompiler' = None): # A legacy function. Not removed because a lot of the t...
This function generates Prolog-style termination rules from input data. It iterates through termination rules, collects variables, and prints formatted clauses defining when terms are terminated under specific conditions. It ensures proper variable type declarations and constructs logical constraints using occurred/hol...
def instal_print_terminates(self, terminates: list) -> None: # terminates self.instal_print("%\n% terminate rules\n%") for rl in terminates: [inev, terms, cond] = rl vars1 = {} self.collectVars(inev, vars1) self.collectVars(cond, vars1) ...
def instal_print(self, to_append: str) -> None: #Legacy. InstAL print used to print to file: it now just adds to an out variable which is returned. self.out += to_append + "\n" def checkAggregates(self,c): i=0 arr = [] aggr = False term = '' #print('In checkAggreg...
The main task of the code is to process noninertial rules by translating them into structured logical statements, handling two cases: (1) when conditions include aggregates (specialized data structures), it prints translated rules with aggregate handling and variable constraints; (2) otherwise, it generates standard Pr...
def instal_print_noninertials(self, whens: list) -> None: # noninertials self.instal_print("%\n% noninertial rules\n%") for rl in whens: [nif, ante] = rl vars1 = {} #Modified by Andreasa 07/07/2021 - BEGINS #print("first condition"+ant...
def instal_print(self, to_append: str) -> None: #Legacy. InstAL print used to print to file: it now just adds to an out variable which is returned. self.out += to_append + "\n" def extendedterm2string(self, p): # Legacy. if p[0] in ['perm', 'viol', 'pow']: r = p[0] + '(' + se...
This function generates Prolog-style logical rules defining initial states for an institutional model. It prints holdsat predicates for live, perm, and pow conditions, then iterates through input initial states to create rules with formatted terms, variable types, and optional conditions, translating them into formal l...
def instal_print_initially(self, initials: list) -> None: # initially self.instal_print("%\n% initially\n%") if True: self.instal_print("% no creation event") self.instal_print("holdsat(live({inst}),{inst},I) :- start(I), inst({inst})." # 20190606 JAP: add arg to holdsat ...
def instal_print(self, to_append: str) -> None: #Legacy. InstAL print used to print to file: it now just adds to an out variable which is returned. self.out += to_append + "\n" def collectVars(self, t, d, compiler: 'InstalCompiler' = None): # A legacy function. Not removed because a lot of the t...
This code translates rules from a domain-specific language into Prolog-style logic clauses, handling both revisable and non-revisable conditions. It generates formal rule representations with variable typing, time constraints, and exception handling, while maintaining rule IDs and mode declarations for a logic programm...
def print_prep_generates(self, generates: list) -> None: self.instal_print("%") self.instal_print("% ---------------------------------------------------------------- ") self.instal_print("% Pre-processing: generates rules") self.instal_print("% ------------------------------------------...
def instal_print(self, to_append: str) -> None: #Legacy. InstAL print used to print to file: it now just adds to an out variable which is returned. self.out += to_append + "\n" def collectVars(self, t, d, compiler: 'InstalCompiler' = None): # A legacy function. Not removed because a lot of the t...
This function translates 'initiates' rules into Prolog-style clauses for a logic programming system. It generates rule templates with conditions, variable type checks, and try-use statements, handling revisable/non-revisable cases differently. The output includes rule headers, instantiated predicates, and mode declarat...
def print_prep_initiates(self, initiates: list) -> None: self.instal_print("%") self.instal_print("% ---------------------------------------------------------------- ") self.instal_print("% Pre-processing: initiates rules") self.instal_print("% ----------------------------------...
def instal_print(self, to_append: str) -> None: #Legacy. InstAL print used to print to file: it now just adds to an out variable which is returned. self.out += to_append + "\n" def collectVars(self, t, d, compiler: 'InstalCompiler' = None): # A legacy function. Not removed because a lot of the t...
This function translates 'terminates' rules into structured Prolog-like clauses, generating logic statements with conditions, variables, and rule IDs. It processes each rule to output formatted translations, handling revisable conditions by adding try-use statements and exceptions, while maintaining variables and insti...
def print_prep_terminates(self, terminates: list) -> None: self.instal_print("%") self.instal_print("% ---------------------------------------------------------------- ") self.instal_print("% Pre-processing: terminates rules") self.instal_print("% -------------------------------...
def _get_train_loader(self): dataset = self._get_train_dataset() dataloader = data_utils.DataLoader(dataset, batch_size=self.args.train_batch_size, shuffle=True, pin_memory=True) return dataloader def _get_val_loader(self): return self._get_eval...
This function returns training, validation, and test data loaders for PyTorch. It retrieves train and test loaders unconditionally, while the validation loader is only obtained if the mode is 'train'. The loaders are returned as a tuple for model training/evaluation.
def get_pytorch_dataloaders(self): train_loader = self._get_train_loader() if self.args.mode == 'train': val_loader = self._get_val_loader() else : val_loader = None test_loader = self._get_test_loader() return train_loader, val_loader, test_loader
def wait_til_present(self, xpath): is_present = False while not is_present: if len(self.driver.find_elements(by=By.XPATH, value=xpath)) > 0: is_present = True return is_present def wait_til_enabled(self, xpath): attempt_counter = 0 while attemp...
The main task of the code is to extract and process LPM product codes from a web application by navigating through UI elements, clicking to open specifications, scrolling through dynamic content, and decoding product codes from grid cells to input associated LPM specifications.
def get_lpm_product_codes(self): '''Get LPM Product Specification Codes''' self.driver.implicitly_wait(4) # Highlight the LPM Quality Controls row lpm_quality_controls_row = self.driver.find_element(by=By.XPATH, value="/html/body/div[2]/div[2]/div/div[2]/div/div/div/div/section/div...
def remove(string): return "".join(string.split()) def HillCipher1(message, key,cipherMatrix,messageVector): getKeyMatrix(key) for i in range(3): messageVector[i][0] = ord(message[i]) % 65 encrypt_hill(messageVector,cipherMatrix) CipherText = [] for i in range(3): CipherText.append(chr(cipherMatri...
The code implements a Hill Cipher web application for encryption and decryption. It validates input, ensures key/plaintext length matches, and uses matrix operations for encryption (HillCipher1) and decryption (HillCipher2). Decryption checks matrix invertibility, computes the inverse (mod 26), and handles errors. Resu...
def hill(request): if request.method == 'POST' and 'enc' in request.POST: # get post parameters of encryption plaintext = request.POST['plaintext'] key1 = request.POST['key'] plaintext = remove(plaintext) key1 = remove(key1) plaintext = plaintext.upper() key...
def remove(string): return "".join(string.split()) def key_sdes(key): list_key=[] temp = apply_table(key, p10_table) left = temp[:5] right = temp[5:] left = left_shift(left) right = left_shift(right) key1 = apply_table(left + right, p8_table) left = left_shift(left) right = left_...
This Django view function handles SDES encryption/decryption via POST requests. It validates input lengths (8-character plaintext/ciphertext, 10-character key), generates subkeys, performs encryption/decryption, and displays results with error handling. The function processes both encryption ('enc') and decryption ('de...
def sdes(request): if request.method == 'POST' and 'enc' in request.POST: # get post parameters of encryption plaintext= request.POST['plaintext'] key= request.POST['key'] plaintext=remove(plaintext) key=remove(key) if key=='' or plaintext=='': messages...
def get_store_name_of_model(file_names): return f'storage/models/{file_names[1]}_{file_names[2]}_model.pt' def get_architecture_length(file): if '100k' in file: length = 100000 elif '500k' in file: length = 499733 elif '12bit' in file: length = 4096 elif '_sep_' in file or '_...
The function processes each file by splitting data into training, validation, and test sets, loads hyperparameters based on file characteristics, and runs a model if no saved model exists for that file.
def run_on_all_data(args, root, files): for file in files: file_names = file.split('/') # Only run if there is so corresponding saved model if not os.path.isfile(get_store_name_of_model(file_names)): length = get_architecture_length(file) ids = list(range(length)) ...
def get_pathway_length (result): return len(np.unique(get_all_children(result))) def get_all_children(tree, field = 'smiles', reactions=True): reactions_list = [] if reactions==True : query = 'is_reaction' else: query = 'is_chemical' if query in tree.keys(): if tree[query]:...
The main task of the code is to identify and extract the shortest metabolic pathways from a list of results. It calculates pathway lengths, finds those with the minimum length, and retrieves their reactions, transformation rules, and template sources. The function then displays these pathways and returns them as a stru...
def show_shortest_path (result_ls): lengths = [get_pathway_length(result) for result in result_ls] min_length = np.min(lengths) idxs = [idx for idx, length in enumerate(lengths) if length==min_length] pathways = [] for i, idx in enumerate(idxs): print ('Pathway number {}'.format(i)) ...
def get_pathway_length (result): return len(np.unique(get_all_children(result))) def get_all_children(tree, field = 'smiles', reactions=True): reactions_list = [] if reactions==True : query = 'is_reaction' else: query = 'is_chemical' if query in tree.keys(): if tree[query]:...
The function filters pathways from `result_ls` that match `query_length`, extracts their reactions, transformation forms, and sources, displays them, and returns a list of tuples containing these components for each matching pathway.
def show_paths_by_length (result_ls, query_length): lengths = [get_pathway_length(result) for result in result_ls] idxs = [idx for idx, length in enumerate(lengths) if length==query_length] pathways = [] for i, idx in enumerate(idxs): print ('Pathway number {}'.format(i)) reactions...
def get_canonical_smiles(smi): mol = Chem.MolFromSmiles(smi) smiles = Chem.MolToSmiles(mol, isomericSmiles=True) return smiles def score_precursor(precursor, ppg=None, rank = 1): """Score a given precursor using a combination of the template relevance score and a heuristic rule Source: h...
This function explores chemical and enzymatic reaction paths starting from a given molecule (SMILES), using a priority queue to prioritize nodes based on scores (chem/enzy) and depth. It generates reaction pathways up to a specified depth, avoids revisiting nodes, and returns explored reactions, nodes, and the initial ...
def get_chemoenzy_path_async(self,smiles, max_depth=10, chem_topk = 10, max_num_templates=250, max_branching=15, time_lim=180, deepef=None, sfef=None): timeout = time.time() + time_lim if not deepef: deepef = self.deepe...
def get_canonical_smiles(smi): mol = Chem.MolFromSmiles(smi) smiles = Chem.MolToSmiles(mol, isomericSmiles=True) return smiles def score_precursor(precursor, ppg=None, rank = 1): """Score a given precursor using a combination of the template relevance score and a heuristic rule Source: h...
This function generates chemical reaction pathways from a given molecule using a priority-based search. It explores synthetic routes by iteratively expanding molecular nodes, scoring precursors, and prioritizing paths via a heuristic (deepef). The algorithm limits depth, branching, and templates, returning explored rea...
def get_chemoenzy_path_sync(self,smiles, max_depth=10, chem_topk=10, max_num_templates=250, max_branching=15, fully_hybrid=False, time_lim=180, margin=0.15, deepef=None): if not deepef: deepef = self.deepef timeout = ti...
def function_one(string_list): unique_list = [] unique = True for x in range(len(string_list)): string_test = string_list[x] for y in range(len(string_list)): if string_test == string_list[y] and x != y: unique = False break elif string...
The code executes five functions with specific inputs to demonstrate their outputs, then creates a Circle object with radius 5 to calculate and print its area and circumference, testing functionality across list processing, mathematical checks, and geometric computations.
def main(): print(function_one(['good', 'cat', 'bad', 'cat'])) print(function_two(496)) print(function_three(2048)) print(function_four([1, ['A', 2], 'B', 3, 'C', 4, ['D', 5]])) print(function_five(['A', ['A', 'B'], 'C'])) my_circle = Circle() my_circle.radius = 5 print(my_circle.area(...
def PointToVoxel(self, x, y, z): grid_x = int((x - self._x_min) / self._x_res) grid_y = int((y - self._y_min) / self._y_res) grid_z = int((z - self._z_min) / self._z_res) return (grid_x, grid_y, grid_z) def Visualize(self, sensor_x, sensor_y, yaw): m = Marker() m.header....
This function processes sensor data to update a 3D voxel map by transforming points from the sensor's frame to a global frame, checking robot orientation and position validity, and probabilistically updating voxel occupancy states based on sensor readings. It handles TF transformations, coordinate conversions, random d...
def SensorCallback_2(self, msg): if not self._initialized: rospy.logerr("%s: Was not initialized.", self._name) return try: # print(self._fixed_frame, self._sensor_frame) pose = self._tf_buffer.lookup_transform( self._fixed_frame, ...
def recompute_goal(self): if self.recalculate_mode == RecalculateEnum.GOAL: self.goal = self.occupancy_grid.object_center(self.original_goal) + self.offset elif self.recalculate_mode == RecalculateEnum.OFFSET: offset_size = np.around(np.linalg.norm(self.offset)) orien...
This code updates the pathfinding process in a dynamic environment by adjusting the start position, recomputing the goal, handling grid changes, and recalculating the shortest path using D* Lite algorithm. It ensures fairness in the priority queue, updates vertex information based on grid changes, and adjusts the path ...
def callback(self): # keeping new entries of the priority queue fair by adding existing progress self.start = self.occupancy_grid.get_current_location() ## Update object center if we learn more information self.recompute_goal() if np.array_equal(self.start, self.goal): ...
def DINFO(content): print(f"\033[93m{content}\033[0m") def read_data(filename, verbose): data = {'data': [], 'start': None, 'end': None, 'filename': filename} fo = open(filename, "r", errors='ignore') if not fo.readable(): DERROR(f"Error : {filename} couldn't be read.") return data ...
The code reads multiple files, aggregates their data into a structured dictionary, appends a 'Shutdown' event if multiple files are processed, sorts entries by timestamp, and sets start/end times. It handles missing files, logs progress if verbose, and returns processed data for analysis.
def read_files(filenames, verbose): tdata = dict() tdata['start'] = None tdata['end'] = None tdata['data'] = [] for filename in filenames: if not os.path.exists(filename): DINFO(f"warning : \"{filename}\" : No such file") continue if verbose and not json: ...
def write_into_ctype(ctype, bytevals): """ Write bytes directly into a ctype. Copy byte values from bytevals into the current backing of the object """ mutable_bytevals = bytearray(bytevals) sizeof_self = sizeof(ctype) backing_class = (c_ubyte * sizeof_self) # backing = backing_class...
This function parses a resource directory table from a binary buffer, starting at a given offset. It reads the directory table structure, processes name and ID entries, recursively parses subdirectories, and collects data entries. It updates internal lists with parsed data and returns the next offset for further parsin...
def __parse_rsrc_dir_tab_at(self, offset): rsrc_dir_tab_type = self._structs['ResourceDirectoryTable'] rsrc_dir_tab = rsrc_dir_tab_type() next_offset = offset write_into_ctype(rsrc_dir_tab, self._rsrc_bytes[next_offset:]) self._rsrc_dir_tabs.append(rsrc_dir_tab) next_off...
def rva_to_offset(self, rva): section_header = self._get_section_header_by_virtual_address(rva) if section_header is None: return 0 offset = (rva - section_header.virtual_address) return section_header.pointer_to_raw_data + offset def cast_ctype_from_bytearray(ctype, byte_arr...
This function parses the PE export table by converting virtual addresses to offsets, extracting function addresses and names from the export directory, aligning their lists, and mapping names to their corresponding addresses in a symbol dictionary.
def _parse_export_table(self): va = self.DataDirectories.export_table.virtual_address if va == 0: return export_dir_off = self.rva_to_offset(va) export_dir_tab = cast_ctype_from_bytearray(self._structs['ExportDirectoryTable'], self.contents,...
def rva_to_offset(self, rva): section_header = self._get_section_header_by_virtual_address(rva) if section_header is None: return 0 offset = (rva - section_header.virtual_address) return section_header.pointer_to_raw_data + offset def get_non_zero_ctype_entries_from_off(ctype...
This function parses a PE file's import directory to extract imported libraries and their symbols. It converts RVA addresses to offsets, reads import table data, and processes each entry to retrieve library names. For each library, it parses the import lookup table, distinguishing between ordinal imports (numeric IDs) ...
def _parse_imports(self): import_table_info = self.DataDirectories.import_table if import_table_info.virtual_address == 0: return off = self.rva_to_offset(import_table_info.virtual_address) size = import_table_info.size import_table_bytes = self.contents[off:off+size]...
def __get_dos_header_bytes(self): return self.contents[2:self.__PE_HDR_PTR_OFF] def create_pe_structures(petype=PEHdrType.PE32, endian=PEEndian.LITTLE_ENDIAN, additional_bases=None): """ This function serves as a factory for all of the structure types ...
This code parses a Windows Portable Executable (PE) file by reading its binary contents, validating the MZ signature, extracting DOS/PE headers, determining architecture type (PE32/PE32+), and parsing critical sections like resources, imports, exports, and load configuration data to analyze or manipulate the executable...
def __init__(self, filepath): self.filepath = filepath with open(filepath, "rb") as f: self.contents = bytearray(f.read()) assert self.contents[:2] == self._MZ_SIG self.__dos_header_bytes = self.__get_dos_header_bytes() # TODO: fix the unpacking stuff # dep o...
def split_streams( msg, num_streams=NUM_STREAMS ): """ splits the msg into distinct streams based on estimated key length """ streams = [] for i in range(num_streams): pos = i stream = [] while pos < len(msg): stream.append(msg[pos]) pos += num_streams streams.append(stream) return streams def shift_s...
The main task of the code is to decrypt ciphertext stored in 'ctext.txt' using a stream cipher technique. It converts hexadecimal ciphertext to numeric values, splits and shifts data streams, cleans them to retrieve plaintext, and saves the decrypted text to 'ptext.txt'. Additionally, it generates a key file ('key.txt'...
def main(): with open('./ctext.txt') as fin: ctext = fin.read() ctext = th.hex_to_nums(ctext) streams = split_streams(ctext) streams_shifted = shift_streams(streams) ptext = clean_streams(streams_shifted) with open('./ptext.txt', 'w') as fout: fout.write(ptext) with open('./key.txt', 'w') as fout: text...
def collide(self): # Collision with paddle if self.ball.rect.colliderect(self.paddle.rect): self.settings.ball_speed_y *= -1.1 self._get_collision_coords() # Collision with game window elif self.ball.rect.right >= self.screen.get_rect().right: self.set...
The function `_update_ball` updates the ball's position and handles collisions. If hacks are inactive, it updates the ball and checks collisions; if active, it uses a hacked ball method. It then checks for brick collisions. If the ball goes out of bounds, it logs remaining tries and bricks, then restarts the game.
def _update_ball(self): # print(self.settings.ball_speed_x, self.settings.ball_speed_y) if not self.hacks_active: self.ball.update() self.collide() else: self.ball.hacked_ball() self._ball_brick_collision() if self.ball.rect.bottom - self.bal...
def _check_hacks(self): keys = pygame.key.get_pressed() mods = pygame.key.get_mods() if keys[pygame.K_DELETE] and keys[pygame.K_SPACE]: if self.settings.ball_speed_y < 0: self.settings.ball_speed_y = -1 else: self.settings.ball_speed_y = 1 ...
The main task of the code is to run the game loop, handling continuous game operations such as updating the ball's movement, checking for hacks, updating the paddle (when hacks are inactive), processing user events, and rendering the game screen. The loop runs indefinitely until the game is exited, maintaining real-tim...
def run_game(self): '''Main Game Loop''' while True: if self.game_running: pygame.mouse.set_visible(False) self._check_hacks() self._update_ball() if not self.hacks_active: self.paddle.update() s...
def valid_date(var1): ''' The valid_date() function will take a date in "YYYYMMDD" format, and return True if the given date is a valid date, otherwise return False. ''' if (len(var1) != 8): # Check date format print("Error: wrong date entered") exit() else: year = int(var1[0:4]) month = int(var1[4:6])...
The `dbda()` function calculates the number of days between two dates (if `var2` is an 8-digit date) or adjusts a date by adding/subtracting days (if `var2` is an integer). It supports optional step-by-step output via the `--step` command-line flag, printing intermediate dates. The function returns the adjusted date or...
def dbda(var1,var2): ''' The dbda() function will take a date in "YYYYMMDD" format and a positive or negative integer. The function will calculate the days need to add or subtract and return the date Examples: dbda(20190101, 15) 20190116 dbda(20190101, 20180101) 365 dbda(20190101,3) 20190102 20190103 ...
def mutare_pion(coloana_piesa, rand_piesa): mutari_posibile = [] if pion_alb[rand_piesa][coloane[coloana_piesa]] == 1: if rand_piesa == 6 and concatenare_piesealbe()[rand_piesa - 2][coloane[coloana_piesa]] == 0: mutari_posibile.append((rand_piesa - 2, coloane[coloana_piesa])) if conc...
The function determines possible moves for a chess piece at a given position. It checks the piece type (pawn, rook, bishop, knight, queen, king) using 2D arrays, calls the corresponding move-generating function, and returns either formatted move options or a raw list based on the 'lista' parameter.
def posibilitati(coloana_piesa, rand_piesa, lista = 0): mutari_posibile = [] if pion_alb[rand_piesa][coloane[coloana_piesa]] == 1 or pion_negru[rand_piesa][coloane[coloana_piesa]] == 1: mutari_posibile = mutare_pion(coloana_piesa, rand_piesa) if tura_alb[rand_piesa][coloane[coloana_piesa]] == 1 or t...
def afisare(printare = 0): masa = [[0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] piese = { "pion_alb": "♙", ...
The code implements a turn-based board game where two players (ALB and NEGRU) alternately move pieces. It validates moves by checking if a selected piece exists, determining its possible moves, and ensuring the target position is valid. Invalid moves trigger an error message. The game loops indefinitely, switching turn...
def joc(): while True: print("ALB MUTA") afisare(1) coloana = input("Coloana piesei pe care doriti sa o mutati: ") rand = int(input("Randul piesei pe care doriti sa o mutati: ")) if concatenare_piesealbe()[rand][coloane[coloana]] == 0: print("Nu exista piesa pe ac...
def read_training_and_validation_sets_from_file(input_shape): X_train = np.load(os.path.join(OUTPUT_FOLDER,'X_train_'+str(input_shape[0])+'.npy'),mmap_mode='r+') X_val = np.load(os.path.join(OUTPUT_FOLDER,'X_val_'+str(input_shape[0])+'.npy'),mmap_mode='r+') y_train = np.load(os.path.join(OUTPUT_FOLDER,'y_tr...
This code trains an AlexNet model on a dataset, validates it, saves the trained model, and generates performance metrics. It reads training/validation data, constructs the AlexNet architecture, configures TensorBoard logging, trains the model for 30 epochs with batched data, and outputs training history and ROC curves....
def run_AlexNet_model(): # read items from file X_train,X_val,y_train,y_val = read_training_and_validation_sets_from_file(AlexNet_input_shape) # create model AlexNet_model = build_AlexNet_model() run_logdir = get_run_logdir() tensorboard_cb = keras.callbacks.TensorBoard(run_logdir) tra...
def read_training_and_validation_sets_from_file(input_shape): X_train = np.load(os.path.join(OUTPUT_FOLDER,'X_train_'+str(input_shape[0])+'.npy'),mmap_mode='r+') X_val = np.load(os.path.join(OUTPUT_FOLDER,'X_val_'+str(input_shape[0])+'.npy'),mmap_mode='r+') y_train = np.load(os.path.join(OUTPUT_FOLDER,'y_tr...
This function trains a VGG model on image data by loading training/validation sets, building the model, configuring TensorBoard logging, creating batched datasets, training for 30 epochs with validation, saving the trained model to disk, and generating performance metrics including ROC curves.
def run_VGG_model(): # read items from file X_train,X_val,y_train,y_val = read_training_and_validation_sets_from_file(VGG_input_shape) # create model VGG_model = build_VGG_model() run_logdir = get_run_logdir() tensorboard_cb = keras.callbacks.TensorBoard(run_logdir) train_ds = tf.data....
def read_training_and_validation_sets_from_file(input_shape): X_train = np.load(os.path.join(OUTPUT_FOLDER,'X_train_'+str(input_shape[0])+'.npy'),mmap_mode='r+') X_val = np.load(os.path.join(OUTPUT_FOLDER,'X_val_'+str(input_shape[0])+'.npy'),mmap_mode='r+') y_train = np.load(os.path.join(OUTPUT_FOLDER,'y_tr...
The code trains a GoogleNet model on image data by loading training/validation sets, building the model, configuring callbacks, creating TensorFlow datasets, training for 30 epochs with validation, saving the trained model, and generating performance metrics including ROC curves.
def run_GoogleNet_model(): # read items from file X_train,X_val,y_train,y_val = read_training_and_validation_sets_from_file(GoogleNet_input_shape) # create model GoogleNet_model = build_GoogleNet_model() run_logdir = get_run_logdir() tensorboard_cb = keras.callbacks.TensorBoard(run_logdir) ...
def getMatrices(xFile, yFile, zFile): return tuple([ getMat(fName) for fName in [xFile, yFile, zFile]]) def genTestData(fDir): _, numRec, numPoints = matrixDims() xData = np.zeros([numRec, numPoints]) yData = np.zeros([numRec, numPoints]) zData = np.zeros([numRec, numPoints]) for i in range(numR...
The code loads sensor data matrices and event data, generates test statistics, trains a logistic regression model to predict earthquakes, evaluates its accuracy, and visualizes predicted events over time using time slices. It outputs model coefficients and plots predictions against time.
def main(): xFile = "../cleanData/xMat" yFile = "../cleanData/yMat" zFile = "../cleanData/zMat" eventFile = "../cleanData/eventMotion.csv" testDir = "../data/test/simulation_0" xMat, yMat, zMat = getMatrices(xFile, yFile, zFile) eventDF = pd.read_csv(eventFile) xMatTest, yMatTest, ...
def remove_exsiting_transactions(self, cash_balance): Transaction.objects.filter(cash_balance=cash_balance).delete() def remove_exsiting_positions(self, cash_balance): Position.objects.filter(cash_balance=cash_balance).delete() def remove_exsiting_cash_transaction(self, cash_balance): CashTransa...
The code processes CSV transactions by resetting a user's cash balance, removing existing financial records (transactions, positions, cash transactions), creating an initial cash transaction, and uploading new transactions to update the user's financial data.
def process_csv(self, transactions): user = self.get_user_object() cash_balance = self.get_cash_balance(user) self.reset_balance(cash_balance) self.remove_exsiting_transactions(cash_balance) self.remove_exsiting_positions(cash_balance) self.remove_exsiting_cash_transacti...
def _wait_for_boot(self): for _ in range(1000): if self._read_register(_VL53L4CD_FIRMWARE_SYSTEM_STATUS)[0] == 0x03: return time.sleep(0.001) raise TimeoutError("Time out waiting for system boot.") def _write_register(self, address, data, length=None): if ...
This code initializes a sensor by configuring its registers with predefined byte sequences to set operational modes, interrupt behaviors, timing parameters, and other hardware-specific settings, ensuring proper functionality and communication with the device.
def _sensor_init(self): # pylint: disable=line-too-long init_seq = ( # value addr : description b"\x12" # 0x2d : set bit 2 and 5 to 1 for fast plus mode (1MHz I2C), else don't touch b"\x00" # 0x2e : bit 0 if I2C pulled up at 1.8V, else set bit 0 to 1 (pull up at ...
def makeGrid(): grid = [] with open('input20228.txt') as file: for line in file.readlines(): line = [int(i) for i in line.strip('\n')] grid.append(line) gridT = list(map(list, zip(*grid))) return grid, gridT def getTallestGrid(grid, gridT): gridCC = copy.deepcopy(grid...
The code processes a grid to determine the best treehouse location by identifying the tallest trees, filtering out edge positions, and selecting the optimal inner position based on these values.
def main(): grid, gridT = makeGrid() tallest = getTallestGrid(grid, gridT) inner = list(filter(lambda x: (len(grid) - 1) not in x and 0 not in x, tallest)) print(getBestTreeHouse(inner, grid, gridT))
def apply_preset(self, preset_name, mode, output_path): if not os.path.exists(output_path): os.makedirs(output_path, exist_ok=True) self.main_layout.sidebar.log_text(f"Applying the preset " f"[{preset_name}]...") items = read_preset(preset_na...
This code displays a dialog for selecting a preset configuration file (YAML) and applying it to an image or multiple images. It lists available presets, allows directory selection if not loading for a user, and triggers different application methods based on user input.
def get_preset_name(self, load_for_user=False): presets = [] for file in os.listdir("presets"): if os.path.isfile(os.path.join("presets", file)) and re.match( r"[\s\S]+.yaml", file): presets.append(file) dialog = QDialog() dialog.setWindowT...
def open_file(self, add=False): self.main_layout.image_editor.scene().clearSelection() self.main_layout.sidebar.log_text("Open file(s)...") loaded_images = QFileDialog.getOpenFileNames( filter="Image files (*.bmp *.BMP *.gif " "*.GIF *.jpeg *.JPEG *.jpg *.JPG " ...
The code initializes a menu system by connecting various menu actions to corresponding functions, such as opening files, adding text/images, saving/loading presets, managing settings, and displaying about information. It sets up the menu bar with File, Watermark, Settings, and About menus, linking each action to specif...
def init_menu(self): self.menus.action_open.triggered.connect(self.open_file) self.menus.action_open_add.triggered.connect(lambda: self.open_file( add=True)) self.menuBar().addMenu(self.menus.menu_file) self.menus.action_add_text.triggered.connect(self.add_text) self....
def init_status_bar(self): self.statusBar().addPermanentWidget(self.item_pos) self.statusBar().addPermanentWidget(self.current_image_name) def init_menu(self): self.menus.action_open.triggered.connect(self.open_file) self.menus.action_open_add.triggered.connect(lambda: self.open_file( ...
This code initializes a MainWindow GUI, setting up the interface with menus, layouts, status bar elements, and required directories for watermark processing. It configures window properties, initializes UI components, and prepares environment settings for handling visible/invisible watermark operations.
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.icon = QIcon("logo.png") self.menus = Menus() self.main_layout = MainLayout() self.central_widget = QWidget(parent=self) self.central_widget.setLayout(self.main_layout) sel...
def getCellAt(self, i, j): index = (i % self.cellSize) * self.cellSize + j % self.cellSize return self.cells[self.coordinatesToCell(i, j)].getCellAt(index) def coordinatesToCell(self, i, j) -> int: reducedRowNumber = i // self.cellSize reducedColNumber = j // self.cellSize return...
This function checks if a cell at position (i,j) can be filled by validating its possible values against row, column, and cell constraints. If invalid values are removed or the cell is filled, it updates the grid and propagates changes. It returns True if any modifications occurred, otherwise False.
def checkAtRowCol(self, i, j) -> bool: currentNumber = self.getCellAt(i, j) if currentNumber.value != 0: return False modified = False for value in currentNumber.possibleValues.copy(): if value in self.rowValues[i] or \ value in self.colValue...
def getProfile(self, profile_id=None): profile = self.profile_id if profile_id==None else profile_id headers = { 'Authorization': 'Bearer ' + self.access_token, 'User-Agent': 'Selenium-API' } data = json.loads(requests.get(API_URL + '/browser/' + profile, headers=...
The main task of the code is to create or configure a startup profile by removing an existing local profile directory (if not in local mode), downloading a profile zip (if not local), updating preferences, and returning the profile path. It ensures a clean setup by handling directory deletion errors and preparing the p...
def createStartup(self): if self.local==False and os.path.exists(self.profile_path): try: shutil.rmtree(self.profile_path) except: print("error removing profile", self.profile_path) self.profile = self.getProfile() if self.local==False: ...
def crop_plates(image, circle_centers): return [cut_plate(image, center) for center in circle_centers] def get_combined_shape(circle_centers): positions = coordinates_to_positions(circle_centers) columns, rows = positions.max(0) + 1 return rows, columns def save_combined_plates(output_folder, path, comb...
The function `_save_combined_plates` processes an image by cropping detected license plates using their centers, calculates a combined layout shape, merges the cropped plates into a single image, and saves the result to the specified output folder with the given path.
def _save_combined_plates(output_folder, path, image, centers): plates = crop_plates(image, centers) shape = get_combined_shape(centers) save_combined_plates(output_folder, path, combine_plates(plates, shape))
def update_image(window, image: Optional[bytes]): window[Key.image].update(data=image) def get_scaled_image(values, image, scale=None): if scale is None: scale = calculate_scale(values, image) return image_to_png_bytes(image, scale) def update_preview(window, image: Optional[bytes]): window[Key....
The code reads an image from a given path, scales it based on provided values, updates a window with the scaled image, and resets the preview display by setting the image to None. The main task is to load, scale, and display an image in a GUI window while managing preview updates.
def show_image(window, values, path): image = cv.imread(path.as_posix()) update_image(window, get_scaled_image(values, image)) update_preview(window, image=None)
def selected_files(values) -> List[Path]: return [Path(values[Key.folder]) / file_name for file_name in values[Key.file_list]] def update_image(window, image: Optional[bytes]): window[Key.image].update(data=image) def update_preview(window, image: Optional[bytes]): window[Key.preview].update(data=image) def...
The function processes a file selection update by displaying an image in a window, either with a cropping preview or normally, based on user input. It handles cases where no files or multiple files are selected by clearing the display or returning early, ensuring only one file is processed at a time.
def process_selection_update(values, window): selected = selected_files(values) if not selected: update_image(window, image=None) update_preview(window, image=None) return if len(selected) > 1: return assert len(selected) == 1 path = selected[0] if with_preview...
def process_folder_update(values, window): window[Key.file_list].update([f.name for f in folder_files(values)]) window[Key.output_folder].update(Path(values[Key.folder]) / 'cropped') update_image(window, image=None) update_preview(window, image=None) def process_selection_update(values, window): sel...
This function processes GUI events from a window, executing specific actions based on the triggered event. It returns False if the window is closed, otherwise handles folder updates, selection updates, preview toggling, and cropping operations by calling corresponding functions, returning True after each event handling...
def process_events(window): event, values = window.read() if event == sg.WINDOW_CLOSED: return False if event == Key.folder: process_folder_update(values, window) return True if event == Key.file_list: process_selection_update(values, window) return True if...
def parse_artist_page(query, index): """Parse a single page of releases on an artist's page. Return array of release URLs.""" results = [] urlQuery = urlCleanup(query + str(index)) session = HTMLSession() response = session.get(urlQuery) response.html.render(sleep=10, timeout=0) # < tabl...
The main task of the code is to parse an artist's data by iteratively fetching pages from a URL, collecting release information, processing each release with `process_release()`, updating the provided `info_object` with processed data, and returning the updated object. It handles errors, skips empty pages, and aggregat...
def parse_artist(query, info_object): """ Keyword Arguments: query -- url to be searched info_object -- Information object with any previous history (default to None) Parse artist, calling parse_artist_page() for each page. Return: formatted list of songs downloaded. """ # TODO inclu...
def determinePlacingNotes(time, times): i = times.index(time) return notePlacements[i] def generateNote(prevNote, prevHandedNote): while True: # nextNote = noteDict[prevHandedNote][random.randint(0, len(noteDict[prevHandedNote]) - 1)] nextNote = None n = random.randint(1, sums[prevHa...
This function generates and modifies note sequences in a music game's difficulty file by reading existing JSON data, clearing its '_notes' list, and appending new notes based on left/right placement rules, dominance logic, and randomization. It ensures valid note pairs, writes updated JSON back to the file, and adjusts...
def mapDifficulty(songFolderName, difficulty, style, numBeats=200): dat = open(songFolderName+'\\'+difficulty+style+'.dat', 'r') datJSON = json.load(dat) dat.close() dat = open(songFolderName+'\\'+difficulty+style+'.dat', 'w') datJSON['_notes'] = [] lastNotes = { '0': FIRST_LEFT_NOTE, ...
def print_usage(): print('Usage:') for i in range(len(syntax_list)): print(syntax_list[i]) print def encode_create(argc, args): packet = '' dtype = '' syntax = syntax_list[0] if argc < 3 : print('Invalid number of arguments') print(syntax_list[0]) return ...
The function `encode_request` processes a user input string by parsing its command type (e.g., 'c', 'd', 'a') and arguments, then delegates to corresponding encoding functions like `encode_create` or `encode_delete`. It validates input format, handles raw mode for 's' commands, and returns processed data or errors.
def encode_request(request): if request.find(' ') < 0 : print_usage() return argc = len(request.split(' ')) - 1 # all commands take at least one argument if argc < 1 : print_usage() return request_type,args = request.split(' ', 1) request_type = request_type.l...
def wait_for_user_login(driver): url = f"https://www.mubawab.ma/" print("Loading website:", url) driver.get(url) WebDriverWait(driver, 100).until(EC.url_contains(url)) close_button = driver.find_element(By.CSS_SELECTOR, "div.fancybox-close") close_button.click() post_button = driver.find_e...
The code automates web scraping by launching a Chrome browser, logging in to a website, selecting a region, extracting city, district, and town data, saving it to a CSV file, and closing the browser. The main task is to retrieve and store geographical administrative data from a web interface after user authentication a...
def main(): chrome_options = ChromeOptions() driver = Chrome(options=chrome_options) wait_for_user_login(driver) wait_for_region_selection(driver) dataset = get_city_district_town_dataset(driver) save_to_csv(dataset) driver.quit()
def add_player(self, controller): self.player_controllers.append(controller) self.player_crystals.append([]) def generate_all_players_maps(self): for player in range(PLAYERS): self.player_controllers[player].set_map( self.generate_player_map(player)) def tick(self): ...
This code runs a simulation with multiple bots, initializing players, generating maps, executing game ticks until most players are eliminated, then saving the simulation history and generating a scoreboard to evaluate bot performance.
def run(self): # Use this for local testing for x in range(PLAYERS): self.add_player(Player(x, "./bot.py")) # Load all bots, they are all equal, feel free to change this if you want to experiment with different types of bots print("Starting simulation") self.generate_all_players_ma...
def prettify_results(results, options={'digits': 3}): """ Formats and prints a summary table of regression results from a list of 'linearmodels.panel.results.PanelEffectsResults' objects. The function prints a table that includes the dependent variables, estimated coefficients with t-statistics, fixed ...
The function `prettify_result` formats and prints regression results (from statsmodels, linearmodels, or arch_model) in a style resembling R's `summary()` output. It generates a structured summary including the model formula, coefficients table, residuals (optional), and statistics like R-squared, F-statistic, and obse...
def prettify_result(result, options={'digits': 3, 'include_residuals': False, 'max_width': 80}): """ Format and print regression result in a style similar to R's summary() output for linear models. This function takes regression result from statsmodels and prints a summary that resembles the outpu...
def trygui(): #window = tk.Tk() #global runPeriodicBaseline #global runBaseline mainframe = ttk.Frame(window, padding="5") # padding at edge of window mainframe.grid(column=0, row=0, sticky=("N, W, E, S")) #window.columnconfigure(0, weight=1,uniform='a') #window.rowconfigure(0, weight=1,uniform='a') window.titl...
The main task of the code is to initialize and configure a hardware controller, set up a chip's parameters (thresholds, reset cycles, voltage references), enable/disable analog monitoring, and verify configurations. It initializes the system, adjusts settings for periodic reset, voltage levels, and other chip-specific ...
def mainish(): trygui() exit() # this code was moved to runtests for personnel efficiency c=init_controller() init_board(c) chip=init_chips(c) print(chip) # Set global threshold setGlobalThresh(c,chip,100) # Read some Data #c.run(1,'test') #print(c.reads[-1]) # Enable analog monitor on one chan...