dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def modulus_used(suite_name): filename = "%s.c" % suite_name myFile = open(filename,"r") str1 = myFile.read() # slurp whole file myFile.close() str1 = re.sub('\".*\"'," ",str1) # eliminate quoted strings str1 = re.sub('//.*'," ",str1) # eliminate one-line comments pattern = re.compile('/\\*...
The main task of the code is to execute a test suite by running individual test cases, apply penalties for detected modulus usage or lack of recursion (if configured), aggregate test outputs and scores, and return the results. It adjusts total scores by multiplying with configured penalties and collects per-test output...
def run_test_suite(self, test_suite_name, test_outputs, total_score): """ Run a test suite. """ print("Running tests for %s..." % (test_suite_name)) if self.modulus_penalty: # check for mod use for this suite -- actual penalty to be applied at the per-test le...
def parse_args(argv): parser = argparse.ArgumentParser(prog=argv[0], description='Fit Data With Linear Regression Using Pipeline') parser.add_argument('action', default='SGD', choices=[ "SGD", "show-function", "loss", "show-network" ], nargs='?', help="desired ac...
The main task of the code is to execute different functions based on the specified action argument. It parses command-line arguments, configures logging, and dispatches tasks such as training a model (SGD), displaying functions, loss details, or network structure. Unknown actions trigger an exception, ensuring only val...
def main(argv): my_args = parse_args(argv) # logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.WARN) if my_args.action == 'SGD': do_fit(my_args) elif my_args.action == "show-function": show_function(my_args) elif my_args.action == "loss": show_los...
def load_session(self): self.load_cookie() if "sessionId" in self.cookie: # cookie stores the session Id sessionId = self.cookie["sessionId"].value self.session = gSessionStore.getSessionData(sessionId) if self.session == None: # session ID...
The code handles HTTP GET requests by parsing the URL path to determine the collection (e.g., "governors") and optional ID. It checks user authentication, then retrieves either all entries from the specified collection or a specific entry by ID. If unauthorized, it returns a 401 error. If the collection is invalid, it ...
def do_GET(self): self.load_session() print("The path is -> ", self.path) parts = self.path.split('/')[1:] print("parsed path is -> ", parts) collection = parts[0] if len(parts) > 1: id = parts[1] else: id = None if self.isLoggedIn...
def load_session(self): self.load_cookie() if "sessionId" in self.cookie: # cookie stores the session Id sessionId = self.cookie["sessionId"].value self.session = gSessionStore.getSessionData(sessionId) if self.session == None: # session ID...
This code handles PUT requests by updating a governor's duty based on the URL path. It checks user authentication, parses the path for collection and ID, and routes to `handleUpdateDuty` if authenticated and the collection is "governors". Otherwise, it returns 401 Unauthorized or 404 Not Found.
def do_PUT(self): self.load_session() print("The path for do_PUT is -> ", self.path) parts = self.path.split('/')[1:] print("parsed path for do_PUT is -> ", parts) collection = parts[0] if len(parts) > 1: id = parts[1] else: self.handleNotF...
def load_session(self): self.load_cookie() if "sessionId" in self.cookie: # cookie stores the session Id sessionId = self.cookie["sessionId"].value self.session = gSessionStore.getSessionData(sessionId) if self.session == None: # session ID...
This code handles HTTP DELETE requests by parsing the URL path to identify a collection and an ID. It checks user authentication, deletes a governor's duty record if the collection is "governors" and the user is logged in, or returns a 401 error if unauthorized. If the collection isn't recognized, it triggers a not-fou...
def do_DELETE(self): self.load_session() print("The path for do_DELETE is -> ", self.path) parts = self.path.split('/')[1:] print("parsed path for do_DELETE is -> ", parts) collection = parts[0] if len(parts) > 1: id = parts[1] else: self.h...
def load_session(self): self.load_cookie() if "sessionId" in self.cookie: # cookie stores the session Id sessionId = self.cookie["sessionId"].value self.session = gSessionStore.getSessionData(sessionId) if self.session == None: # session ID...
This code handles POST requests by routing them based on the URL path. It processes user creation, governor resource creation (with login verification), session authentication, logout, and unknown paths. It checks authentication status for governor creation, sends 401 errors for unauthorized access, and delegates tasks...
def do_POST(self): self.load_session() if self.path == "/users": print("post request to create users") self.handleUsersCreate() elif self.path == "/governors": print("post request") # you can only create a govr resource if you are logged in ...
def getPathOfCWD(root, dirName): if root == None: return "" if root.name == dirName: return dirName for directory in root.subdirectories.keys(): path = getPathOfCWD(root.subdirectories[directory], dirName) if path != "": return root.name + "/" + path return ""...
The code defines a menu-driven interface for a file system, allowing users to perform operations like creating/deleting files, navigating directories, viewing memory maps, and managing files. It sets the current working directory, displays available commands, processes user input, and recursively handles navigation or ...
def Menu(currDir): global currWorkingDir currWorkingDir = currDir print(c.Fore.BLUE+"\n\tWelcome to the File System\n"+c.Fore.RESET) print("--> Create File") print("--> Delete File") print("--> Make Directory") print("--> Change Directory") print("--> Move File") print("--> Open File...
def _check_first_line(self) -> bool: """ Used to check wheter the first line confirms to passport standards This is the regex used to check: (P[A-Z<][A-Z]{3}([A-Z]{2,}<?)*<<([A-Z]{2,}<?)*<*) """ if len(self._line1) != 44: self._reasons.append("First line is not 44 ch...
This function checks if a passport complies with the TD3 standard by performing multiple validation checks on its components, including the first line, second line segments, and a master checksum. It returns True only if all checks pass, otherwise False.
def is_correct(self) -> bool: """ Checks if passport follows TD3 standard """ self._reasons = [] one = self._check_first_line() if not self.ignore_first_line else True two = self._check_second_line() if not two: # Make sure no value errors occur in t...
def run_predictions(self): """ Predicts cell states for each input sample """ comment_ = 1 for s1 in self.samples: for s2 in self.samples: # if organism1!=organism2: run_id = [s1, s2] logging.info(f'Running {str(comment_...
The code initializes an object by storing input arguments as samples in a dictionary, running predictions, merging network data, and generating a cell type similarity comparison dataframe.
def __init__(self, *args): self.samples = dict(zip(list(range(len(args))), args)) self.predictions = dict() self.run_predictions() self.network = self.get_merged_network() self.cell_types_similarity = self.generate_comparison_df()
def map_labels(input_path, output_folder, labels): labelled_data=pd.read_csv(input_path) labelled_data.drop([col for col in labelled_data.columns if 'Unnamed' in col], axis=1, inplace=True) labelled_data['label'] = labelled_data['label'].map(labels) labelled_data.rename(columns={'sample_name':'molecule_...
The code processes input data to train a time series classification model using labeled molecular data. It creates output directories, maps labels, prepares data by cleaning and splitting features/labels, trains a ResNet classifier, predicts labels, compares predicted vs actual labels, and generates a visual comparison...
def pipeline(input_path,output_folder, labels): output_folders = ['trained_model','validation'] for folder in output_folders: if not os.path.exists(f'{output_folder}{folder}/'): os.makedirs(f'{output_folder}{folder}/') #----------------------------- #train model section map_la...
def copyMatriks(self,matriks,command): posisi = [] if(command == 'atas'): posisi = [copy.deepcopy(matriks), command] if(command == 'bawah'): posisi = [copy.deepcopy(matriks), command] if(command == 'kiri'): posisi = [copy.deepcopy(matriks), command] ...
The code implements a branch-and-bound algorithm for exploring possible moves in a puzzle. It generates new matrix states by moving in four directions (up, down, left, right), checks for duplicates, and adds valid states to a priority queue. The queue is sorted, and the next state is selected to update the current matr...
def BnB(self): posUp = 0 atas = self.copyMatriks(self.matriks,'atas') self.gerak(atas) posbawah = 0 bawah = self.copyMatriks(self.matriks,'bawah') self.gerak(bawah) poskiri = 0 kiri = self.copyMatriks(self.matriks,'kiri') self.gerak(kiri) p...
def isFinished(self, depth) -> bool: return ( depth >= self.max_depth or self.n_class_labels == 1 or self.n_samples < self.min_samples_split ) def bestSplitting(x, y, features): split = {'score': -1, 'feat': None, 'thresh': None} for feat in features: ...
This code recursively builds a decision tree by selecting the optimal feature and threshold to split the dataset, creating left and right child nodes until a stopping condition is met. It constructs a tree structure where each node stores splitting parameters and child nodes, ultimately classifying data based on majori...
def createTree(self, x, y, depth=0): self.n_samples, self.n_features = x.shape self.n_class_labels = len(np.unique(y)) if self.isFinished(depth): return Node(value=np.argmax(np.bincount(y))) best_feat, best_thresh = bestSplitting(x, y, list(range(self.n_features))) ...
def load(filename): try: kbFile = open(filename) except: printError ("Error: file '" + filename + "' not found") return kb_dict = interpret_file(kbFile.read()) kbFile.close() return kb_dict def tell(tokens_line): tokens = tokens_line.strip() tokens = tokens.split(" ...
The main task of the code is to create an interactive knowledge base interpreter. It processes user commands like loading data, adding atoms, printing the knowledge base, clearing data, and inferring new atoms. The loop handles input, executes corresponding operations on the KB object, and supports quitting the interpr...
def main(): kb = KB() while True: # Quit interpreter command print() text = input("kb> ") text = text.strip() print() if text in [":q", ":Q", "quit", "end"]: break # Load command if text[:4] == "load": new_kb = load(text[5...
def save_password(account, username, password): encrypted_password = encrypt_password(password) c.execute("INSERT INTO passwords (account, username, password) VALUES (?, ?, ?)", (account, username, encrypted_password)) conn.commit() def retrieve_password(account): c.execute("SELECT usernam...
The main task of the code is to provide a menu-driven password manager interface. It allows users to add passwords, retrieve stored passwords, generate and save new passwords, or exit. The function handles user input, calls appropriate helper functions for operations, and recursively restarts the menu for continuous us...
def main_menu(): print("Password Manager") print("1. Add a password") print("2. Retrieve a password") print("3. Generate and save a password") print("4. Exit") choice = input("Enter your choice: ") if choice == "1": account = input("Enter account name: ") username = input("...
def venue_tracklist(sp, venue_id): """Generates list of Spotify tracks fron Songkick venue id""" showlist = show_list(venue_id) artists = artist_list(sp, showlist) playlist_tracks = build_tracklist(sp, artists) return(playlist_tracks) def name_playlist(venue_id): """Constructs ShowQuester playli...
The function creates a Spotify playlist for a venue by generating a name and description, adding tracks from the venue's tracklist, and returning the playlist URI. It uses the Spotify API to create, populate, and update the playlist details for the user's account.
def save_playlist_to_account(sp, venue_id): """Create an empty Showquester playlist on Spotify for a given venue""" playlist_tracks = venue_tracklist(sp, venue_id) playlist_name = name_playlist(venue_id) username = sp.me()['id'] results = sp.user_playlist_create(username, playlist_name, public=True)...
def init(): #Change global inputs inputs = [] global ex ex = [] # expected values (arranged by index) inline = r'^((\d )*)=> (\d)$' for arg in sys.argv: if os.path.isfile(arg) and arg != sys.argv[0]: lines = open(arg, 'r').read().splitlines() # for i, c in e...
This code trains a neural network using backpropagation to minimize prediction errors. It iteratively adjusts weights via error calculation and updates, resetting weights randomly if errors exceed thresholds. The loop continues until the error (E) falls below 0.01, printing weights and layer structures periodically.
def tot(): """weights = [] for col in WEIGHTS: weights = weights + col""" E = 1 oldE = 0 init() while E > 0.01: times = 0 a = 1 E = 0 #print('begin', E) for case in range(len(inputs)): # first run NN = main(case) error = ex...
def init(): #Change # expected values (arranged by index) inline = r'^x\*x\+y\*y(>=|<=|>|<)(\d+.?\d+)$' for arg in sys.argv: match = re.search(inline, arg, re.M) if match: ##Init Equation ##Init -> Bound ex: <= 1.21 <- bound global bound ...
This code trains a neural network using backpropagation to minimize error by iteratively adjusting weights. It initializes weights, computes error between predicted and expected outputs, updates weights via backpropagation, and dynamically adjusts the learning rate based on error trends. If error exceeds thresholds, we...
def tot(): """weights = [] for col in WEIGHTS: weights = weights + col""" E = 1 oldE = 0 count = 1 exb = True init() a = 3 while count < 50000 or E > 0.001: if a < 0: a = -1*a #Set new input and ex -> new method inputs = randPoint(bound, exb, count) ...
def load_tasks(self): if os.path.exists(TASKS_FILE_PATH): with open(TASKS_FILE_PATH, "r") as file: self.tasks = json.load(file) def create_ui(self): self.root.grid_columnconfigure(0, weight=1) self.root.grid_columnconfigure(1, weight=1) self.root.grid_rowconfi...
The code initializes a GUI-based Personalized Task Manager application. It sets up the main window with a title, size, and background, initializes task storage variables, loads existing tasks, creates the user interface, and updates the task list display. The main purpose is to manage tasks by loading, displaying, and ...
def __init__(self, root): self.root = root self.root.title("Personalized Task Manager") self.root.geometry("400x540") self.root.configure(bg='white') self.selected_due_date = "" self.tasks = [] self.load_tasks() self.create_ui() self.update_task_...
def timestamps(): access_key = os.environ.get("API_KEY") leopard = pvleopard.create(access_key=access_key) transcript_file_path= os.path.join(audio_directory, "transcript.wav") transcript, words = leopard.process_file(transcript_file_path) leopard.delete() return words def diaritize(path): a...
The main task of the code is to generate a speaker-separated transcript from an audio file. It uses diarization to identify speaker segments, matches timestamps with corresponding speakers, and constructs a formatted output where each speaker's dialogue is separated by newlines, ensuring words are correctly attributed ...
def transcript(): times = timestamps() transcript_file_path= os.path.join(audio_directory, "transcript.wav") seperated=diaritize(transcript_file_path) count=0 matches= match() previous = matches[str(seperated[count].speaker_tag)] output = f"{previous}: " endtime= float(seperated[0].end_s...
def regProducers(b, e): for i in range(b, e): a = accounts[i] retry(args.clacc + 'system regproducer ' + a['name'] + ' ' + a['pub'] + ' https://' + a['name'] + '.com' + '/' + a['pub']) def sleep(t): print('sleep', t, '...') time.sleep(t) print('resume') def listProducers(): run(args....
The function `stepRegProducers` registers a sequence of producers starting from `firstProducer` up to `firstProducer + numProducers`, pauses execution for 2 seconds using `sleep(2)`, and then lists all registered producers via `listProducers()`. Its main task is to automate the registration, delay, and verification of ...
def stepRegProducers(): regProducers(firstProducer, firstProducer + numProducers) sleep(2) listProducers()
def vote(b, e): for i in range(b, e): voter = accounts[i]['name'] k = args.num_producers_vote if k > numProducers: k = numProducers - 1 prods = random.sample(range(firstProducer, firstProducer + numProducers), k) prods = ' '.join(map(lambda x: accounts[x]['name'],...
The function `proxyVotes(b, e)` delegates voting rights to a designated proxy in a blockchain context. It first casts a vote for the initial producer, registers the proxy using the `regproxy` command, then iterates through a range of voters (from index `b` to `e-1`). For each voter, it delegates their voting power to t...
def proxyVotes(b, e): vote(firstProducer, firstProducer + 1) proxy = accounts[firstProducer]['name'] retry(args.clacc + 'system regproxy ' + proxy) sleep(1.0) for i in range(b, e): voter = accounts[i]['name'] retry(args.clacc + 'system voteproducer proxy ' + voter + ' ' + proxy)
def vote(b, e): for i in range(b, e): voter = accounts[i]['name'] k = args.num_producers_vote if k > numProducers: k = numProducers - 1 prods = random.sample(range(firstProducer, firstProducer + numProducers), k) prods = ' '.join(map(lambda x: accounts[x]['name'],...
The main task of the code is to execute a voting process for a specified number of voters (`args.num_voters`), followed by listing producers with delays of 2 and 5 seconds between actions.
def stepVote(): vote(0, 0 + args.num_voters) sleep(2) listProducers() sleep(5)
def run(args): print('bios-boot-tutorial.py:', args) logFile.write(args + '\n') if subprocess.call(args, shell=True): print('bios-boot-tutorial.py: exiting because of error') sys.exit(1) def jsonArg(a): return " '" + json.dumps(a) + "' " def sleep(t): print('sleep', t, '...') tim...
The main task of the code is to automate a multi-signature system action replacement process on a blockchain, specifically handling 'fast.unstake' operations. It executes steps to buy RAM, propose, approve, and execute the replacement using account credentials, with delays between actions to ensure proper blockchain pr...
def msigReplaceSystem(): run(args.clacc + 'push action acc buyrambytes' + jsonArg(['acc', accounts[0]['name'], 200000]) + '-p acc') sleep(1) msigProposeReplaceSystem(accounts[0]['name'], 'fast.unstake') sleep(1) msigApproveReplaceSystem(accounts[0]['name'], 'fast.unstake') msigExecReplaceSystem(...
def copy_to_clipboard(self, text): pyperclip.copy(text) print(f"Copied to clipboard: {text}") def open_edit_template_window(self, template_name, template_text): self.edit_template_window = EditTemplateWindow(template_name, template_text, self.edit_template) self.edit_template_window.setW...
The code defines a callback function that checks the selected mode (copy, edit, delete) and performs corresponding actions: copying text to clipboard, opening an edit window, or confirming a deletion. It acts as a handler to trigger different operations based on user-selected modes in an application.
def callback(): if self.copy_mode.isChecked(): self.copy_to_clipboard(template_text) elif self.edit_mode.isChecked(): self.open_edit_template_window(template_name, template_text) elif self.delete_mode.isChecked(): self.confirm_delete(fr...
def z(self, index): # returns the slope at index i # we could save z as an array but since it contains the same information as h[] # this reduces the need for constant syncing of the two arrays if index == self.L - 1: return(self.h[index]) return(self.h[index] - self....
This code simulates the evolution of a pile's height over N_steps, updating an evolution array. It executes steps using a specified algorithm, tracks crossover events, and optionally prints lattice states based on print_mode. If terminate_on_crossover is True, the simulation halts early upon detecting a crossover. The ...
def simulate(self, N_steps = 100, print_mode = 'never', step_alg = 'ceilidh', terminate_on_crossover = False): # The main loop for a basic simulation # updates the hiegh of the pile as an array # returns the evolution array t = 0 printed_last_it = False trotel = [] ...
def workaround_classes_with_commonmark_syntax(code, classes, keyvals, value): ''' Configuration string as a pytho comment to get classes and key-vals Example of configuration: #filter: {.c1 .c2 key1=val1 key2="value 2" } ''' try: re.search(r'^\s*#\s*filter:\s+{', code).group() except AttributeError: return f...
This code processes Python code blocks for execution, capturing output and handling inline plots. It checks if the code should be run, executes it, adjusts output formatting, and returns an AST with the code and results. It also manages matplotlib figures for inline display, ensuring proper rendering in the target form...
def run_py_code_block(key, value, format, meta): return_ast = [] if key == 'CodeBlock': [[ident, classes, keyvals], code] = value workaround_classes_with_commonmark_syntax(code, classes, keyvals, value) if "python" in classes and "run" in classes: # caption, typef, keyvals = get_caption(keyvals) prin...
def calculate_slope(self) -> float: """ Calculates and retuns slope of line connecting the two nodes """ x1, x2 = self.node1.x, self.node2.x y1, y2 = self.node1.y, self.node2.y delta_y = y2 - y1 delta_x = x2 - x1 if delta_x == 0: return np.i...
The code initializes a class instance representing a line segment between two nodes. It calculates and stores the slope, angle (in degrees and radians), and length of the segment using helper methods. The main task is to set up geometric properties of the line defined by the two nodes for further processing or analysis...
def __init__(self, node1: Node, node2: Node) -> None: self.node1, self.node2 = node1, node2 self.slope = self.calculate_slope() self.angle = self.calculate_angle(in_radians=False) self.angle_in_radians = self.calculate_angle(in_radians=True) self.length = self.calculate_lengt...
def getMYChannel(mol): from collections import OrderedDict props = OrderedDict() # print(mol.element) # elements = np.array([el.upper() for el in mol.element]) elements = np.array([el for el in mol.element]) # print(elements) #props['positive_ionizable'] = (mol.charge > 0) & (elements != 'M...
The main task of the code is to generate 3D feature maps from molecular data using specified channel parameters, compute non-zero element counts for analysis, and save the processed data (including images, targets, metadata, and statistics) as a NumPy file for later use in machine learning or visualization tasks.
def save_image(mol,origin,inverse_transformation_matrix,save_path,PDBname,chainid,resid,resname): # make the transform here # image_channels = getKDEEPChannel(mol) image_channels_sigmas,image_channels_values = getMYChannel(mol) target_channels_sigmas,target_channels_values = getMGChannel(mol,2.5) im...
def send_super(receiver, selName, *args, **kwargs): """Send a message named selName to the super of the receiver. This is the equivalent of [super selname:args]. """ if hasattr(receiver, '_as_parameter_'): receiver = receiver._as_parameter_ superclass = get_superclass_of_object(receiver) ...
This code initializes an object by calling its parent class's initializer, assigns the result to `self`, sets an instance variable `observed_object` to the provided `anObject`, and returns the initialized object. It likely handles object setup in a subclass, linking it to another object for observation or interaction.
def initWithObject_(self, cmd, anObject): self = send_super(self, 'init') self = self.value set_instance_variable(self, 'observed_object', anObject, c_void_p) return self
def get_instance_variable(obj, varname, vartype): "Return the value of `obj.varname`, where the value is of type vartype." variable = vartype() objc.object_getInstanceVariable(obj, ensure_bytes(varname), byref(variable)) return variable.value def send_super(receiver, selName, *args, **kwargs): """Se...
This code deallocates an object by removing its reference from a cache and invoking the superclass's dealloc method. It retrieves the 'observed_object' instance variable, removes it from ObjCInstance._cached_objects, then calls send_super to execute the parent class's dealloc logic, ensuring proper memory management in...
def dealloc(self, cmd): anObject = get_instance_variable(self, 'observed_object', c_void_p) ObjCInstance._cached_objects.pop(anObject, None) send_super(self, 'dealloc')
def get_instance_variable(obj, varname, vartype): "Return the value of `obj.varname`, where the value is of type vartype." variable = vartype() objc.object_getInstanceVariable(obj, ensure_bytes(varname), byref(variable)) return variable.value def send_super(receiver, selName, *args, **kwargs): """Se...
This code's main task is to handle resource cleanup during garbage collection by removing an observed Objective-C object from a cache and invoking the superclass's finalize method, ensuring proper memory management when garbage collection is explicitly enabled.
def finalize(self, cmd): # Called instead of dealloc if using garbage collection. # (which would have to be explicitly started with # objc_startCollectorThread(), so probably not too much reason # to have this here, but I guess it can't hurt.) anObject = get_instance_variable(sel...
def straight_flush(community,p): ''' Function checks if straight flush category is being fulfilled. If yes the winning combination is returned else a 'False' is returned. ''' straight_combo=[] winning_combo=[] is_straight=straight(community,p) is_flush=flush(community,p) if is_straight and i...
The function `check` evaluates a poker hand by sequentially testing for specific high-ranking combinations (from highest to lowest: straight flush, four of a kind, etc.). It terminates upon the first matching condition, returning the hand's name and its value. If no valid hand is found, it returns "Nothing" and `False`...
def check(community,p): ''' Function checks if any one of the categories is being filled. Order of checking starts with highest ranking and search terminates as soon as first category is fulfilled. ''' if straight_flush(community,p): return ("Straight Flush",straight_flush(community,p)) elif fo...
def converged(self, loss_values, iteration, num_values): if loss_values.size > num_values: print(f"\tIteration {iteration}, loss difference: {abs(numpy.mean(loss_values[-1*num_values:]) - numpy.mean(loss_values[-2*num_values:-1*num_values]))}") if abs(numpy.mean(loss_values[-1*num_values...
The code implements mini-batch stochastic gradient descent for model training. It processes input data by adding intercept terms, shuffles the dataset, and iteratively performs forward/backward propagation to update weights. The learning rate adapts over epochs, and training stops when convergence is detected via loss ...
def train(self, dataframe): loss_values = numpy.empty((0,)) iteration = 0 batch_no = 1 epoch_no = 1 eta = self.learning_rate self.dataframe = dataframe self.train_X = dataframe.iloc[:, 0:-1].to_numpy() intercept = numpy.ones((self.train_X...
def create_widgets(self): main_frame = tk.Frame(self) main_frame.pack(fill="both", expand=True) self.tree = ttk.Treeview(main_frame, columns=("ID", "Name", "Grade", "Registration Grade Date", "Module"), show="headings") self.tree.heading("ID", text="ID") self.tree.heading("Name"...
The code initializes a GUI component by setting up the master window, creating interface widgets, displaying grades, and scheduling periodic updates for dynamic content.
def __init__(self, master): super().__init__(master) self.master = master self.create_widgets() self.show_grades() self.schedule_update()
def clean_title(self, text): """Clean up the gonwild title""" return self.hack_title(self.re_title_brackets.sub(r'\1', text)) def dblog(self, code, text): self.db.execute("INSERT INTO rp_log (code, data) VALUES (?, ?)", (code, text)) self.db.commit() def debug(*s): if...
The code crossposts a Reddit submission to a destination subreddit, adding a comment linking back to the original, applying a 'x-post' flair, and logging the repost in a database. It handles API errors, formats the title with the original author, and stores metadata including the new submission's ID for tracking.
def crosspost(self, post, flair=None): """Create the crosspost from the provided submission; also add comment with link back.""" title = self.clean_title(post.title) title = title + " - [via: " + post.author.name + "]" try: submission = self.subreddit_destination.submit(titl...
def db_fetch_rp_data(self, subreddit, key): """Fetch value from the table that records various "last submission" data. And do some data casting in one case. """ result = self.db.execute("""SELECT value FROM rp_data WHERE subreddit=? AND key=?""", (subreddit,key)).fetchone...
The code checks for new posts in a subreddit, filters out self-posts and low-scoring ones, and crossposts eligible posts. It compares post timestamps against a stored value to identify new content, updating the database with the latest post ID and timestamp for future reference.
def check_for_posts(self): """Check for new posts in the source subreddit, and crosspost any found. Was going to update local database with old submission comment and score numbers, but then didn't. """ submissions = self.subreddit_source.new(limit=source_limit) new_post...
def getSubjectAttributeValue(arr): if arr is not None: if len(arr) > 0 and arr[0] is not None and arr[0].value is not None: return arr[0].value else: return "" def generate_csr_util(country, state, locality, organization_name, organization_unit, common_name, email): # Build the O...
The function renews an SSL certificate for a user by retrieving the existing certificate, extracting its attributes, generating a new CSR, signing it, and updating the certificate in the database. It handles errors like certificate not found, signing issues, and exceptions, returning appropriate JSON responses.
def renew_certificate(user_id,certificate_id): try: certificate = SSLCertificate.query.filter(SSLCertificate.created_by == user_id).filter(SSLCertificate.id == certificate_id).first() if not certificate: return jsonify({ "error": f"Certificate with ID {certificate_id} not...
def simplifyPara(simPara): """ Removes redundant parentheses from a regular expression. :param simPara: Regular expretion to simplify :return: Simplified regular expression with redundant parentheses removed """ # Remove unnecessary parenthesis i = 0 j = 0 stop = 0 # Remove whi...
The code simplifies regular expressions by removing redundant parentheses, stars, and additions, applying transformation rules, trimming whitespace, and handling empty strings with lambda symbols, iteratively refining the expression until no further changes occur.
def simplifyRegexp(regexp): """ Simplifies a regular expression by applying simplifying rules to it in addition to removing redundant parentheses and additions. :param regexp: Regular expretion to simplify :return: Simplified regular expression with duplicate additions removed """ # Remove ...
def getInitialState(G): """ Returns the start node of graph G. :param G: digraph object of the NFA to convert :return: The initial state of graph G """ for n in G.edges(): if n[0] == 'qi': return n[1] print("Error: Initial state not found") print("Initial st...
The main task of the code is to convert a Non-Deterministic Finite Automaton (NFA) into an equivalent regular expression by transforming the NFA into a Generalized Transition Graph (GTG), then iteratively eliminating intermediate states while combining transitions using a `combineEdges` function, ultimately yielding a ...
def nfa2Rex(G): """ Converts an NFA to an equivalent regular expression. :param G: digraph object of the NFA to convert :return: An equivalent GTG to the NFA """ p = getInitialState(G) q = getFinalState(G) G = nfa2Gtg(G) init = getInitialState(G) final = getFinalState(G) f...
def displayParameters(self): self.label_ParName = [] self.lineEdit_ParValue = [] self.label_Units = [] self.spacerItem17 = [] grid_row=1 grid_col=1 iParValueslen = len(self.lParValues) for num in range(0,self.parCount): self.label_ParName.appen...
The code sets up a GUI for a home page, configuring window properties, device status variables, and arranging UI elements like buttons, labels, and layouts. It dynamically creates device buttons based on detected hardware, initializes menus, toolbars, and connects actions, preparing the interface for device monitoring ...
def setupUi(self, homePage): homePage.setObjectName("homePage") homePage.resize(954, 749) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.se...
def read_room_file(self,filename) ->list: ''' reads the file contains room information and return it in nested list format ''' with open(filename,'r') as file: #opens file text=file.readlines() ...
The main task of the code is to read a file containing castle information, parse entrance and exit details, set players' initial positions at the entrance, and construct the castle structure using extracted room data. It processes the file to build the environment, configure doors, and prepare the game state for player...
def initialize_from_file(self,filename) -> None: ''' read a file containing the information about the Castle, create the Castle based on the information provided, set the initial position of the players to the room with the entrance. read the file, build the castle, set initial p...
def tou_word(): #1,000 , 2,000 print(ones_number[int(digits[-4])]+"_thousand",end=" ") #prints - one + thousand, two + thousand hun_word() def ttou_word(): if int(digits[-5]) == 0 and int(digits[-4]) == 0 : #for 00,100 hun_word() ...
This function processes the hundreds of thousands and thousands place in a number-to-word conversion. It checks digit positions to determine if the value is zero or non-zero, then calls helper functions (tou_word, ttou_word, hun_word) or prints specific phrases like "hundred thousand" or "hundred and" based on the digi...
def htou_word(): if int(digits[-6]) == 0 and int(digits[-5]) == 0 : #for 001,000 tou_word() elif int(digits[-6]) == 0 and int(digits[-5]) != 0 : #for 010,000 ttou_word() elif int(digits[-6]) != 0 and (int(digits[-5]) == 0 and int(digits[-4]) == 0): #100,000 , 200,000...
def tou_word (digits): if int(digits[-4]) != 0 : #1,000 , 2,000 answer.append(str(ones_number[int(digits[-4])]+"_thousand ")) #prints - one + thousand, two + thousand hun_word (digits) def ttou_word (digits): if int(digits[-5]) == 0 and int(digits[...
The function `htou_word` processes a numeric string to convert the hundreds and thousands place into words, appending appropriate textual representations (e.g., "one_hundred thousand", "one_hundred and") to a global list `answer`, while delegating further processing to helper functions based on digit patterns.
def htou_word (digits): if int(digits[-6]) == 0 and int(digits[-5]) == 0 : #for 001,000 tou_word (digits) elif int(digits[-6]) == 0 and int(digits[-5]) != 0 : #for 010,000 ttou_word (digits) elif int(digits[-6]) != 0 and (int(digits[-5]) == 0 and int(digits[-4]) == 0): ...
def KeyMaskedInput(self, Mask, Input, KeyCode): # If a valid key is pressed, add to the input buffer. if len(Input) < Mask.count("#") and KeyCode >= ord("0") and KeyCode <= ord("9"): Input += chr(KeyCode) # If delete key is pressed, delete the last entered key. elif KeyCode == 127 and len(Input) > ...
This function processes key input to add a schedule item. When the Enter key (KeyCode 10) is pressed, it parses masked user input (date, time, relay state, and duration) from the input buffer. It converts the input into a schedule with calculated time periods, adds it to the schedule system, and transitions to the main...
def KeysAddSchedule(self, KeyCode): Result = KeyCode self.InputBuffer = self.KeyMaskedInput("####-##-## ##:##:## ### ##:##:## ## #", self.InputBuffer, KeyCode) # If enter key is pressed, change to display main menu. if KeyCode == 10: # If full user input has been gathered, add a schedule item. ...
def KeyMaskedInput(self, Mask, Input, KeyCode): # If a valid key is pressed, add to the input buffer. if len(Input) < Mask.count("#") and KeyCode >= ord("0") and KeyCode <= ord("9"): Input += chr(KeyCode) # If delete key is pressed, delete the last entered key. elif KeyCode == 127 and len(Input) > ...
This function processes user input to set the system time and RTC module when the Enter key is pressed. It validates the input format (####-##-## ##:##:##), updates the system time if valid, initializes the RTC module, and transitions to the main menu interface.
def KeysSetSystemTime(self, KeyCode): Result = KeyCode self.InputBuffer = self.KeyMaskedInput("####-##-## ##:##:##", self.InputBuffer, KeyCode) # If enter key is pressed, change to display main menu. if KeyCode == 10: # If full user input has been gathered, set the system time. if len(self.In...
def KeysMainMenu(self, KeyCode): Result = KeyCode # If menu item 1 is selected, change to display add schedule. if KeyCode == ord("1"): self.SetInterfaceState(STATE_ADD_SCHEDULE) # If menu item 2 is selected, change to display del schedule. if KeyCode == ord("2"): self.SetInterfaceSt...
The code handles keyboard input by routing the key press to state-specific functions based on the current interface state, then returns the processed result from the corresponding handler method.
def KeyPress(self, KeyCode): Result = KeyCode if self.InterfaceState == STATE_MAIN_MENU: Result = self.KeysMainMenu(KeyCode) elif self.InterfaceState == STATE_ADD_SCHEDULE: Result = self.KeysAddSchedule(KeyCode) elif self.InterfaceState == STATE_DEL_SCHEDULE: Result = ...
def doConfusion(filename): #for file in workspace: # theWorkSpace = filename["workspace"].encode('utf-8') theWorkSpace = filename["workspace"] # print("theWorkSpace") # print(theWorkSpace) if "studyD" in filename["study"] and 'newrun.run-pink' in filename["workspace"]: print("skipping a ...
The code processes "info.json" files by loading their contents, extracting workspace and user data, and updating session, user, and workspace totals if the workspace is not in a predefined list. It initializes tracking dictionaries and calls functions to handle label times and error handling.
def inner_loop(pfile): #for file in filenames: # print(file) if("info.json" in pfile): # print("file in loop") # print(file) filename = "None" try: with open(pfile) as data_file: filename = json.load(data_file) except ValueError: ...
def getStudyInfo(guidelines): studyInfo = {} for task in guidelines['tasks']: videoNames = task['name'] # Ignore data points that are from surveys if task['type'] != 'survey': survey = task['survey'] data = task['data'] if 'hide' in data: ...
The function `getData` loads study guidelines from a JSON file, extracts study and question information, and executes a survey variation process, returning the resulting data points.
def getData(studyType): os.chdir(survey_directions) with open(studyType + '.tasks.json', 'r') as file: guidelines = json.load(file) studyInfo = getStudyInfo(guidelines) quesInfo = getQuesInfo(guidelines) file.close() points = runOneVariationOfSurveys(studyInfo, quesInfo, studyType) r...
def removeCheckMoves(self, moveList, piece, grid, whitePieces, blackPieces): result = [] whiteKing = self.getKing(whitePieces) blackKing = self.getKing(blackPieces) for move in moveList: originalPiece = grid[move.ypos][move.xpos].piece grid[piece.ypos][piece.xpos...
This function handles chess piece movement on a graphical board. It selects pieces, highlights valid moves, executes moves (including captures, castling, and pawn promotion), updates the game state, checks for check/checkmate, and switches turns. It manages canvas updates, piece repositioning, and maintains piece lists...
def movePiece(self, event): x = (event.x - 2) // 75 y = (event.y - 2) // 75 selectedSquare = self.grid[y][x] selectedPiece = selectedSquare.piece if (self.selectPiece == True and selectedPiece is not None and selectedPiece.color == self.turn): #If we click on a valid piece ...
def locstr(): #this was repeated a lot so I made a function return ",".join(str(i) for i in player_location) + "," + str(z) def updatemap(): #Better if it could automatically update the variables. only assigns them once, thats why it is in a function. to run it more! global locations locations = { #set up ...
This function handles player movement in a text-based game by updating the player's location based on directional input (north, south, east, west). It checks if movement in the specified direction is allowed, prints descriptive text or a simple message, adjusts the player's coordinates and a 'z' variable, and triggers ...
def navigation(direction): #move around n s w or w global player_location, z x = locstr() if direction in ["north", "n"]: if locations[x].m_north == True: if len(locations[x].t_north) > 0: print(locations[x].t_north) else: print("Going north") ...
def makeFirstGeneration(formula): firstGeneration = [] for i in range(0, 100): newSolution = makeRandomSolution(formula.nv) newSolutionEvaluation = evaluation(newSolution, formula) firstGeneration.append((newSolution, newSolutionEvaluation)) return firstGeneration def generationEvalu...
This code implements an enhanced genetic algorithm to solve a given logical formula. It initializes a population, evaluates generations, and evolves solutions through crossover and mutation. The algorithm adjusts crossover and mutation rates dynamically, tracks evaluation data, and returns whether a solution exists, th...
def enhancedGeneticAlgorithm(formula): data = [] hasSolution = False solver = Solver() solver.append_formula(formula.clauses) if solver.solve(): hasSolution = True solver.delete() currentGeneration = makeFirstGeneration(formula) currentMaxIndex, currentGenerationEvaluation = gene...
def test_knn(train_x, train_y, test_x, num_nn): num_test_data = len(test_x) temp_pred_y = np.zeros(num_test_data) # loop through testX # compute Euclidean with trainX # find K nearest # sort & get num_nn neighbors for i in range(len(test_x)): distance_to_trainX = [] for ...
The code loads a letter recognition dataset, splits it into training and test sets, subsamples the training data, and evaluates a k-NN classifier and pocket algorithm for classification accuracy. It tests k-NN with a fixed k=3 on the subsampled data and iteratively trains the pocket algorithm for each letter class, out...
def main(): # Read the data file szDatasetPath = './letter-recognition.data' # Put this file in the same place as this script listClasses = [] listAttrs = [] with open(szDatasetPath) as csvFile: csvReader = csv.reader(csvFile, delimiter=',') for row in csvReader: listCla...
def get_event(record: logging.LogRecord) -> dict[str, Any]: """Prepares a flattened dictionary from a LogRecord that includes the basic ECS fields. Users of this library are expected to be hygienic about their use of field names. """ event = {"@timestamp": iso_date(record), "message": record.getMessage...
This code formats a log message by extracting and structuring fields from a LogRecord. It removes timestamp, message, and log level from the event, suppresses error-related fields, formats remaining key-value pairs, and combines them into a structured log line with timestamp, level, and enhanced message.
def formatMessage(self, record: logging.LogRecord) -> str: event = get_event(record) event = flatten_dict(event) timestamp = event.pop("@timestamp") message = event.pop("message") level = event.pop("log.level") # this method is just formatting the "message". LogFormat...
def get_event(record: logging.LogRecord) -> dict[str, Any]: """Prepares a flattened dictionary from a LogRecord that includes the basic ECS fields. Users of this library are expected to be hygienic about their use of field names. """ event = {"@timestamp": iso_date(record), "message": record.getMessage...
This code formats a log message by extracting and processing event data, applying color coding based on log level, suppressing specific error fields, and constructing a formatted string with timestamp, level, and message. It ensures structured, readable logs with colorized severity levels and additional metadata.
def formatMessage(self, record: logging.LogRecord) -> str: event = get_event(record) color = self.COLORS.get(record.levelno) event = flatten_dict(event) timestamp = event.pop("@timestamp") message = event.pop("message") level = self.colorize(event.pop("log.level"), col...
def lift(self, scores_source, scores_target, embeddings, edge_index): """ Lifts i.e. duplicates certain vectors depending on the edge index. One of the tensor dims goes from N -> E """ src_nodes_index = edge_index[0] trg_nodes_index = edge_index[1] # Using index_...
The code implements a forward pass for a Graph Attention Network (GAT), computing node representations via multi-head attention. It projects node features into head-specific embeddings, calculates attention scores using edge indices, applies softmax normalization, and aggregates weighted neighbor features. The process ...
def forward(self, node_features, edge_index): node_features = self.dropout(node_features) # shape = (N, FIN) * (FIN, NH*FOUT) -> (N, NH, FOUT) where NH - number of heads, FOUT - num of output features # We project the input node features into NH independent output features (one for each attent...
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
The code defines a function `north_button_click` that handles a button press event for the "north" direction. It updates the description with "N", executes a command associated with "north", and updates the current state. The main task is to process user input for navigating north in a program, likely a game or interac...
def north_button_click(): print_to_description("N", True) perform_command("N", "") set_current_state()
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
The main task of the code is to handle a "South" button click event by updating the description with "S", executing a "S" command, and setting the current state. It likely controls navigation or state transitions in a GUI application or game, where "S" represents a directional action.
def south_button_click(): print_to_description("S", True) perform_command("S", "") set_current_state()
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
The code defines a function `east_button_click` that updates a description with "E", executes a command associated with "E", and updates the current state when the east button is clicked.
def east_button_click(): print_to_description("E", True) perform_command("E", "") set_current_state()
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
The function `west_button_click` handles a west-direction action by logging "W" to a description, executing a "W" command, and updating the current state. It likely controls navigation or interaction in a game/app, triggering movement or a west-oriented action.
def west_button_click(): print_to_description("W", True) perform_command("W", "") set_current_state()
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
This function handles user input from a widget by retrieving the command string, splitting it into verb/noun, executing the command with case adjustments, and updating the system state. It prints the command, clears input, and uses `perform_command` with conditional casing for 'debug' commands.
def return_key_enter(event): if( event.widget == command_widget): command_string = command_widget.get() print_to_description(command_string, True) command_widget.delete(0, END) words = command_string.split(' ', 1) verb = words[0] noun = (words[1] if (len(words) > 1) ...
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
The function `north_button_click` handles the action when the "North" button is clicked. It prints the direction "N" to a description area, executes a "N" command (likely for movement or interaction), and updates the current state of the application, typically used in games or navigation interfaces.
def north_button_click(): print_to_description("N", True) perform_command("N", "") set_current_state()
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
The code defines a function `south_button_click` that handles a button click event. It prints the letter "S" to a description area, executes a command associated with "S" (likely moving south in a game), and updates the current state to reflect the action. The function coordinates UI feedback, command execution, and st...
def south_button_click(): print_to_description("S", True) perform_command("S", "") set_current_state()
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
The function `east_button_click` handles a button action by printing a description for "E", executing a command associated with "E", and updating the current state. Its main task is to trigger and manage the response to an "East" button interaction in a program, likely part of a game or application with directional con...
def east_button_click(): print_to_description("E", True) perform_command("E", "") set_current_state()
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
The function `west_button_click` handles a button click event by printing the character "W" to a description, executing a command associated with "W", and updating the current state of the system or application.
def west_button_click(): print_to_description("W", True) perform_command("W", "") set_current_state()
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
This function handles Enter key input in a command widget. It retrieves the command string, splits it into verb/noun, prints the command, clears the input, and executes the command with uppercase parameters (except for 'debug'), then updates the application state.
def return_key_enter(event): if( event.widget == command_widget): command_string = command_widget.get() print_to_description(command_string, True) command_widget.delete(0, END) words = command_string.split(' ', 1) verb = words[0] noun = (words[1] if (len(words) > 1) ...
def add_finder_patterns(self): """ Adds the top-left, top-right and bottom-left finder patterns :return: """ top_right = self._calculate_finder_position() bottom_left = self._calculate_finder_position(is_bottom_left=True) self.add_finder_pattern(0, 0) sel...
This function adds essential static patterns to a QR code, including finder patterns, separators, alignment patterns, reserved modules, timing patterns, and the dark module. These components ensure proper structure, alignment, and functionality of the QR code.
def add_static_patterns(self): """ Helper function to add all of the static patterns required by the QR code to function properly """ self.add_finder_patterns() self.add_separators() self.add_alignment_patterns() self.add_reserve_modules() self.add_timing_...
def create_mapping_old_ses_2_scrambled_ses(bids_dir: str, days_to_shift: int) -> pd.DataFrame: """This function loops over all sub-ses combinations and for each of those it creates a corresponding scrambled session in the range +- [0, days_to_shift]. When multiple sessions are present, the function applies the ...
This function scrambles session dates in a BIDS dataset by randomly shifting them within ±[0, days_to_shift] days while preserving per-subject session order. It generates a session mapping, applies date scrambling to original data and derivative folders, and updates the participants.tsv file. The process ensures tempor...
def scramble_sessions(bids_dir: str, out_dir: str, days_to_shift: int = 31) -> None: """This function loops over all directories and files of the input BIDS dataset (https://bids.neuroimaging.io/) and randomly scrambles the session dates in the range +- [0, days_to_shift]. If one subject has more than one sessi...
def update_current_touches(self): self.current_touches.clear() self.get_current_touches_from_slider_state() self.inherit_touch_identifers() self.assign_touch_identifiers() def get_simulate_touches_from_current_touches(self): touch_events: list[SimulateTouch] = [] # Touch...
The code updates touch events by refreshing the touch state, processing current touches into simulated events, sending them to iOS, and storing a copy of current touches as previous touches for tracking changes.
def update(self): self.tasoller.update() self.update_current_touches() touch_events = self.get_simulate_touches_from_current_touches() self.send_simulate_touches_to_ios(touch_events) self.previous_touches = self.current_touches.copy()
def theta(x, mu): # The main function to minimize return f(x) + mu*alpha(x, mu) def alpha(x, mu): # penalty function # Build the vector a to include the relevant value from each restriction function a = [0 for i in range(len(g))] for i in range(len(g)): if g[i](x) > 0: a[i] = math.po...
The code implements a cyclic coordination method for optimization, iterating over different mu values to minimize a function. For each mu, it updates variables in each direction using single-dimensional optimization (golden section search), checks convergence via a norma stopping criterion, and prints results including...
def Optimize(): global x epsilon = 0.01 k=0 xk = x # initial first point new_x = [0 for i in range(len(xk))] # the x that gets updated in the iterations, in the same length as xk print("[k , mu , [x1 , x2] , f(x) , alpha(x) , theta(x) , mu*alpha(x)]") for mu in [0, 0.1, 1, 10, 100, 1000, 100...
def on_follower(self): # can go to candiate with timeout (otherwise will always be follower) while self.heartbeat_event.wait(timeout=self.heartbeat_timeout): logger.debug("hearbeat recvd") self.heartbeat_event.clear() # repeat the waiting for heartbeat logge...
The main task of the code is to continuously monitor the current role in a state machine and execute corresponding state-specific logic (e.g., follower, candidate, leader) in a loop. It ensures the system reacts to role changes by calling `on_follower()`, `on_candidate()`, or `on_leader()` methods, maintaining proper b...
def start_state_thread(self): while True: if self.role == Role.FOLLOWER: self.on_follower() elif self.role == Role.CANDIDATE: self.on_candidate() elif self.role == Role.LEADER: self.on_leader() else: ...
def re_establish_connection(self, sender_id): sender_peer_conn = self.peer_conn_dict[sender_id][1] request = {EVENT_KEY: Event.TEST_CONNECTION, SENDER_ID: self.client_id, } time.sleep(1) try: sender_peer_conn.sendall(pickle.dumps(request)...
This function processes incoming peer requests by checking the event type in the request. If the sender's connection is active, it routes the request to specific handler methods for events like NEW_CONNECTION, REQUEST_VOTE, APPEND_ENTRY, and CLIENT_REQUEST. It skips processing if the connection is broken, logging a mes...
def handle_request_from_peer(self, req): sender_id = req[SENDER_ID] if self.peer_conn_dict[sender_id][0]: if req[EVENT_KEY] == Event.NEW_CONNECTION: self.re_establish_connection(sender_id) elif req[EVENT_KEY] == Event.REQUEST_VOTE: self.handle_r...
def act_on_commited_entries(self, prev_commit_idx, commit_idx): for log_entry in self.state.log[prev_commit_idx:commit_idx + 1]: command = log_entry.command if command[LOG_ENTRY_TYPE] == Log_entry_type.CREATE_ENTRY: self.handle_create_entry(command) elif comma...
(This function provides a command-line interface for a client to interact with a distributed system. It continuously displays a menu, processes user commands (e.g., creating groups, adding/kicking members, sending messages), updates system state, and handles special commands like 'failProcess' to terminate the client. ...
def start_ui(self): user_req_id = 0 while True: user_req_id += 1 self.client_menu.display_menu() # first ever command implemented # self.send_new_command_to_leader() # logger.info(" - createGroup <client_ids>") # logger.info(" - add...
def MakeTimeUpdate(tracks): for track in tracks: track.predict() return tracks def update_tracks_and_remove_measurements(tracks, measurements, time): associations = associate(tracks, measurements) row_indices, col_indices = associations # Initialize a set to keep track of associated measure...
The main task of the code is to update confirmed and candidate tracks with measurements, remove associated measurements, initialize new tracks from remaining measurements, manage track lifecycles (kill/confirm), and increment time. It focuses on tracking state updates, measurement association, and track maintenance in ...
def main(measurements): global time confirmed_tracks = track_holder.get_confirmed_tracks() candidate_tracks = track_holder.get_candidate_tracks() MakeTimeUpdate(confirmed_tracks) MakeTimeUpdate(candidate_tracks) # Update confirmed tracks and remove associated measurements measurements = upd...
def MakeTimeUpdate(tracks): for track in tracks: track.predict() return tracks def create_validation_matrix(tracks, measurements, gate_threshold): validation_matrix = np.zeros((len(measurements), len(tracks))) for i, measurement in enumerate(measurements): for j, track in enumerate(track...
The main task of the code is to update and manage confirmed and candidate tracks in a tracking system using measurements. It calculates JPDA (Joint Probabilistic Data Association) probabilities for associating measurements with tracks, initializes new tracks if measurements exist, and periodically resets tracks to mana...
def main(measurements): global time confirmed_tracks = track_holder.get_confirmed_tracks() candidate_tracks = track_holder.get_candidate_tracks() MakeTimeUpdate(confirmed_tracks) MakeTimeUpdate(candidate_tracks) validation_matrix = create_validation_matrix(confirmed_tracks + candidate_tracks, me...
def parse_args(self): class ReqFileAppend(argparse.Action): def __call__(self, parser, namespace, value, option_string=None): getattr(namespace, self.dest).extend(["-r", value]) ap = argparse.ArgumentParser() # We use realpath to match distlib: see https://github.com...
The main task of the code is to install Python packages for multiple Android ABIs, separating pure (platform-independent) and native (ABI-specific) packages. It creates a "common" directory to store shared files, removes ABI-specific metadata from .dist-info directories, and consolidates native packages for other ABIs ...
def main(self): # This matches pip's own logging setup in pip/basecommand.py. self.parse_args() verbose = ("-v" in self.pip_options) or ("--verbose" in self.pip_options) config_logging(verbose) if verbose: os.environ["DISTUTILS_DEBUG"] = "1" try: ...
def block(self, template="", *args): self.line(template.format(*args) + " {") self.indent += 4 yield self.indent -= 4 self.line("}") def line(self, template="", *args): s = template if args: s = s.format(*args) s = " ".join(s.split()) # Collap...
This code generates exception-handling blocks for a method. If the method declares thrown exceptions, it wraps the method in a try-catch structure: catching UndeclaredThrowableException, rethrowing its cause if it matches declared exceptions, and rethrowing the original exception otherwise. If no exceptions are declare...
def handle_exceptions(self, method): if method.throws: with self.block("try"): yield with self.block("catch (UndeclaredThrowableException ute)"): with self.block("try"): self.line("throw ute.getCause();") with self.block...
def format_list(self, *args): if len(args) == 1: prefix, l = "", args[0] else: prefix, l = args return self.format_optional(prefix, ", ".join(l)) def block(self, template="", *args): self.line(template.format(*args) + " {") self.indent += 4 yield ...
This code generates Java method code to interface with Python objects, handling constructors/methods by formatting headers, managing exceptions, and converting Python return values to Java types. It constructs method signatures, calls a Python function via '_chaquopyCall', and returns results with proper type conversio...
def method(self, cls, method): is_ctor = isinstance(method, Constructor) header = "{} {} {}({}) {}".format( method.modifiers, "" if is_ctor else method.return_type, cls.name if is_ctor else method.name, self.format_list("{} arg{}".format(t, i) for i, t in ...
def join(*paths): return os.path.join(*paths).replace("\\", "/") def line(self, template="", *args): s = template if args: s = s.format(*args) s = " ".join(s.split()) # Collapse consecutive spaces print((" " * self.indent) + s, file=self.out_file) def block(self, templat...
This code generates a Java class file for a specified Python class, creating necessary directory structures and writing imports, class definitions, method stubs, and Python integration code. It handles package creation, writes generated comments, defines class modifiers, extends/implements clauses, static initializatio...
def __init__(self, root_dirname, cls): pkg_dirname = join(root_dirname, cls.package.replace(".", "/")) if not isdir(pkg_dirname): os.makedirs(pkg_dirname) self.indent = 0 with open(join(pkg_dirname, cls.name + ".java"), "w") as self.out_file: self.line("// Genera...
def create_distance_matrix(self): size = len(self.trajectories) self.dist_mat = np.ones((size, size)) for r in range(size): for c in range(size): dist = self.mod_haus_dist(r, c) self.dist_mat[r, c] *= dist def create_std_devs(self): row_sorted...
The function performs spectral clustering on trajectory data to group similar trajectories into clusters. It computes a distance matrix, affinity matrix, and uses eigendecomposition to estimate cluster numbers. If clusters=-1, it automatically determines the optimal number. Finally, it applies k-means clustering using ...
def cluster_spectral(self, trajectories, clusters=-1): """ The function performs spectral clustering of trajectories and for each trajectory sets an index t.ci denoting estimated cluster. the function estimates the number of resulting clusters automatically. :param trajectories:...
def findBrightEndEdge(self,imageData,startCoord,edgeThreshold): """ returns a list with col,row coordinates of the edges found """ imageRows,imageCols = np.shape(imageData) startCol,startRow = startCoord firstCol = 0 ...
This code processes image data to detect and validate contours of a coronal mass ejection (CME). It identifies bright and contrast edges, refines them through smoothing and intersection, constructs initial contours from a central point, removes outliers if enabled, and validates the perimeter's dimensions. If invalid, ...
def processCMEContour(self,qRemOut=False,qStop=False): self._beEdge = self.findBrightEndEdge(self._diffImageData,self._brCen,self._brPxVal) if(self._qTrace): print(str(len(self._beEdge))+" bright edges") self._smoothImageData = self.circSmooth(sel...
def appestrtofile(list): for word in list: gitig.appe_str_to_file(working_path, word) def find_linebreaks(string):# uses the linebreaks to make a word tuple for n in range(len(string)): if string[n] == '\n': return [string[:n]] + find_linebreaks(string[n + 1:]) return [string] de...
The main task of the code is to test if words are correctly appended to and retrieved from a file, verifying that each word in the input list matches the corresponding entry in the processed file content, ensuring proper file handling and line break processing.
def test_gitignore(wrds_to_test): appestrtofile(wrds_to_test)# adds r = open(working_path, 'r') rs = r.read() r.close() d = open(working_path, 'w')# blanks the test file d.write('') d.close() rs = find_linebreaks(rs) for i in range(len(wrds_to_test)): assert wrds_to_test[i] ...
def _sample_x(self, n): return torch.rand((n, self.dim_x), device=self.device) def _sample_z_from_x(self, x): # Takes a batch of x, encodes their posteriors and draws from them mu, kappa = self.forward(x) if self.family == "vmf": z_distrs = VonMisesFisher(mu, kappa) e...
The function generates (x_ref, x_pos, x_neg) triplets for training, sampling reference inputs (x_ref) and corresponding positive/negative examples from a latent space. It uses oversampling to select candidates, with options to fix x_ref across the batch (for debugging) and control the number of negatives. The output in...
def sample(self,n=64, n_neg=1, oversampling_factor=1, same_ref=False): # Generates (x_ref, x_pos, x_neg) triplets. # Input: # n - integer, batchsize (number of x_ref) # n_neg - integer, number of negatives (0 to return None) # oversampling_factor - integer, how many candidates to...
def listOfImages(self): listOfFiles = os.listdir(self.dir_name) pattern = "*.jpg" list_img=[] for entry in listOfFiles: if fnmatch.fnmatch(entry, pattern): list_img.append(entry) return list_img def connect_to_pvpsit(self,config_dict): #print("...
The code processes multiple images by extracting their properties, features, and suggestions using a configuration dictionary. It connects to a database, iterates through each image file, and inserts the extracted data into the database. The process terminates after completing all insertions.
def extract_properties_bulk_images (self,config_dict,insertion): list_of_files = self.listOfImages() my_db = self.connect_to_pvpsit(config_dict) #print(list_of_files) for img in list_of_files: image_properties,features,suggestions = self.extrac...
def rook_movement( self: ChessPiece, x: int, y: int, board: list[list[ChessPiece]] ) -> list[list[int]]: """TODO:""" move_rook = [] for xx in range(x, 7): move_rook.append(move_once(self, xx + 1, y, board)) if evaluate_movement(self, board[xx + 1][y]) in [ MovementType.CAPT...
The function determines valid moves for a chess piece based on its type (rook, knight, bishop, queen, king, pawn) by applying specific movement rules, checking board boundaries, and handling capture logic. It returns a list of possible moves after processing each piece's unique movement pattern and removing invalid ent...
def movement_options( self: ChessPiece, x: int, y: int, board: list[list[ChessPiece]] ) -> list[list[int]]: """Defines how the pieces move.""" if self.type == ChessPieceType.ROOK: print("Rook") move_rook = rook_movement(self, x, y, board) return move_rook if self.type == ChessP...
def update_tasks(self): if self.settings['diodes', 'acquisition'] == 'Monitor': self.channels_ai = [AIChannel(name=self.settings.child('diodes', 'ai_monitor_plus').value(), source='Analog_Input', analog_type='Voltage', ...
This method prepares and initiates hardware-based data acquisition with configurable averaging. It checks for parameter changes (Naverage, live mode), updates internal state if needed, initializes a data buffer, sets up a callback for data reading, and starts the acquisition task. It handles both live and debug modes, ...
def grab_data(self, Naverage=1, **kwargs): """ Parameters ---------- Naverage: (int) Number of hardware averaging kwargs: (dict) of others optionals arguments """ update = False if 'live' in kwargs: if kwargs['live'] != self.live: ...
def get_list_of_download_links (self, link: str) -> set[str]: html = requests.get(link).text links: set[str] = set() for index in self.find_all_case_sensitive(html, "download"): element = self.find_element_by_tag(html, "a", index) if element: generated_l...
The function's main task is to find a downloadable file link (e.g., .exe or .zip) from a webpage accessed via an "unversioned" link by recursively searching for valid links. It avoids macOS/Linux-specific links and processes webpage content to identify the correct download link, ensuring compatibility with an updater p...
def find_link_from_unversioned (self, unversioned_link: str) -> str: """This function will retrieve a link from a "versioned" link by recursively searching a webpage for a new link that could go to a download page, an exe specifically, or so on. Here, a versioned link refers to any download link which c...
def _is_versioned (self, link: str) -> bool: path = urlparse(link).path coincidence = 0 nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] for char in path: if char in nums or char == '.': coincidence += 1 if coincidence > 3: ...
The code's main task is to clean a potentially versioned link to obtain a usable download link. It checks if the input link is versioned, and if so, recursively processes it to remove versioning, handles 404 errors by adjusting the network location, and extracts a clean, unversioned link. If the link is already clean, ...
def __init__ (self, link: str): print("Link is currently being checked...") self._raw_link = link self.versioned = self._is_versioned(link) if self.versioned: print("Link is not clean, cleaning to commence\nThis process can take a few seconds...") # The unversion...
def file_selection(ftype): files=[] table = Table() table.add_column("File Options", style="magenta") for f in os.listdir('input'): if f.endswith(f'.{ftype}') and os.path.isfile(f'input/{f}'): files.append(f) table.add_row(f) print(table) selected = Prompt.ask('Wh...
The function processes input files to generate specified output formats (webapp, source, windows) by cleaning temporary directories, creating an output folder, and calling corresponding conversion functions, returning the conversion result.
def mac(output,jsinput): file = file_selection('zip') if os.path.exists('temp/'): shutil.rmtree('temp/') if os.path.exists('output/'): shutil.rmtree('output/') os.makedirs('output/') val = False if output == 'webapp': val = mac_to_webapp(jsinput,file) elif output == '...
def folder_selection(): folders=[] table = Table() table.add_column("Folder Options", style="magenta") for f in os.listdir('input'): if os.path.isdir(f'input/{f}') and '.' not in f: folders.append(f) table.add_row(f) print(table) selected = Prompt.ask('Which folde...
The code generates platform-specific outputs (webapp, Windows, macOS) from JavaScript input by cleaning existing directories, creating an 'output' folder, and delegating processing to platform-specific functions based on the 'output' parameter.
def source(output,js_input): folder=folder_selection() if os.path.exists('temp/'): shutil.rmtree('temp/') if os.path.exists('output/'): shutil.rmtree('output/') os.makedirs('output/') val = False if output == 'webapp': val = source_to_webapp(js_input,folder) elif outp...
def file_selection(ftype): files=[] table = Table() table.add_column("File Options", style="magenta") for f in os.listdir('input'): if f.endswith(f'.{ftype}') and os.path.isfile(f'input/{f}'): files.append(f) table.add_row(f) print(table) selected = Prompt.ask('Wh...
The main task of the code is to process a selected ZIP file by cleaning temporary and output directories, then converting the file into a specified format (webapp, source, or mac) using corresponding conversion functions, returning the conversion result.
def windows(output,js_input): file = file_selection('zip') if os.path.exists('temp/'): shutil.rmtree('temp/') if os.path.exists('output/'): shutil.rmtree('output/') os.makedirs('output/') val = False if output == 'webapp': val = windows_to_webapp(js_input,file) elif o...
def file_selection(ftype): files=[] table = Table() table.add_column("File Options", style="magenta") for f in os.listdir('input'): if f.endswith(f'.{ftype}') and os.path.isfile(f'input/{f}'): files.append(f) table.add_row(f) print(table) selected = Prompt.ask('Wh...
This function converts an Android APK file into different output formats (source code, web app, Windows/Mac applications) based on the 'output' parameter. It cleans temporary directories, processes specified files, and delegates conversion tasks to specialized functions like android_to_source or android_to_webapp, retu...
def android(output,jsinput): names = [ 'css', 'font', 'img', 'lang', 'snd', 'app.html', 'index.html' ] file = file_selection('apk') if os.path.exists('temp/'): shutil.rmtree('temp/') if os.path.exists('output/'): shutil.rmtree('...
def single_epoch(self, train=True): avg_loss = 0. if train: self.net.train() else: self.net.eval() for ip, jp, jg, ia, ic in self.train_dataloader: # noise augmentation sigma = float(torch.FloatTensor(1).uniform_(0.4, 0.6)) ia...
This code trains a machine learning model for a specified number of epochs, calculated based on total steps and batch size. It performs training, periodically evaluates average loss, logs images, and saves model checkpoints at intervals defined by arguments. The training loop includes logging progress and ensuring succ...
def fit(self, args): logging.info(f"Starting training") data_len = len(self.train_dataloader) epochs = round((args.total_steps * args.batch_size_train) / data_len) if epochs < 0: epochs = 1 self.running_train_steps = 0 for epoch in range(epochs): ...
def feed_wdt(): if wdt is not None: wdt.feed( ) def update_bat(self): tmp = 0 for _ in range(10): tmp += bat.read_uv() sleep_ms(10) tmp /= 10 tmp *= 0.00000475 self.bat_label.set_text(f"{tmp:.2f} v") print_colored(f'battery vol...
The code's main task is to run an infinite loop that periodically updates sensor data (rain, temperature, SDI12), manages communication (AIS, RS485, SMS), logs data to SD, checks location/GPS, and handles watchdog timers. It spawns threads for async updates, monitors intervals, and ensures data transmission via GPRS/SM...
def loop(self): while True: feed_wdt() try: self.update_bat() if self.config['sensors']['ra']['en']: if not self.prcip_update_running and time() - self.last_prcip_update > _prcip_update_interval: _thread.start_ne...
def __getDetectionsToTracksDistanceMatrix(self, detections: List[RoI]): # 1) check matching of detections to trackers dtMatrix = defaultdict(dict) usedTrackersInds = [] for dInd, detection in enumerate(detections): for tInd, tracker in enumerate(self.__trackers): ...
This function matches detections to active trackers using a distance matrix, updates tracker bounding boxes with detection data, and identifies new detections requiring tracker creation. It prioritizes closest active trackers, corrects their positions, and assigns detection features. Unmatched detections are returned f...
def __matchTrackersDetections(self, frame, detections: List[RoI]): # get distances between detections and trackers detections_to_trackers_DistanceMatrix = self.__getDetectionsToTracksDistanceMatrix(detections) # get new detections to create new trackers newDetections = [det for dInd, det...
def __updateBaseTrackers(self, frame): notCorrectedTrackedRoIs = [] # used for debug purposes for tracker in self.__trackers: #if not tracker.getActive(): continue tracker.setRedetected(False) if tracker.update(frame): tracker.setActive(T...
This code processes video frames to track objects using existing and newly created trackers. It updates trackers, matches detections with existing ones, reactivates inactive trackers via feature matching, creates new trackers from unmatched detections, checks redetection status, identifies overlapping regions, and upda...
def __call__(self, frame, detections: List[RoI], newSelections: List[RoI] = []): # 1) update all created previous base trackers notCorrectedTrackedRoIs = self.__updateBaseTrackers(frame) # notCorrectedTrackedRoIs are used for debug purposes if len(newSelections) > 0: self.__createT...
def flexasr_pattern(mod): linear_pattern = linear_layer_definition().body main_func = mod["main"] match_bias_add_dense = annotate_exact_matches( main_func, linear_pattern, "ilaflex", "ilaflex.linear") return match_bias_add_dense def hlscnn_pattern(mod): x = relay.Var("x") y = relay.Var("...
The main task of the code is to load a pre-trained ResMLP model, convert it into TVM's Relay IR, and analyze its operation count and overload patterns after applying three different optimization strategies: flexasr_pattern, hlscnn_pattern, and vta_pattern. The code tests how these transformations affect the model's str...
def resmlp(): print("RESMLP") # This is a hack to make the ResMLP model load correctly. sys.path.append(os.path.join(os.path.dirname(__file__), 'e2e', 'resmlp')) net = init_net("./e2e/resmlp/cifar_net.pth") # with open("./models/res_mlp/resmlp.relay", "r") as fp: # mod = tvm.parser.fromtext(...
def flexasr_pattern(mod): linear_pattern = linear_layer_definition().body main_func = mod["main"] match_bias_add_dense = annotate_exact_matches( main_func, linear_pattern, "ilaflex", "ilaflex.linear") return match_bias_add_dense def hlscnn_pattern(mod): x = relay.Var("x") y = relay.Var("...
The code applies and evaluates different pattern transformations (flexasr, hlscnn, vta) on a ResNet20 model in TVM, measuring operation counts before and after each transformation to analyze their impact on the model's computational complexity.
def resnet20(): print("RESNET") with open("./models/resnet20/resnet20.relay", "r") as fp: glob = fp.read() mod = tvm.parser.fromtext(glob) mod = relay.transform.SimplifyInference()(mod) print("total:", count_all_ops(mod)) mod["main"] = flexasr_pattern(mod) print(count_all_ops_in_...
def flexasr_pattern(mod): linear_pattern = linear_layer_definition().body main_func = mod["main"] match_bias_add_dense = annotate_exact_matches( main_func, linear_pattern, "ilaflex", "ilaflex.linear") return match_bias_add_dense def hlscnn_pattern(mod): x = relay.Var("x") y = relay.Var("...
The code parses a Relay model, applies three different pattern-based transformations (flexasr, hlscnn, vta) to its main function, and prints operation counts before and after each transformation to analyze the impact of the optimizations.
def transformer(): print("TRANSFORMER") with open("./models/transformer/transformer.relay", "r") as fp: mod = tvm.parser.fromtext(fp.read()) print("total:", count_all_ops(mod)) mod["main"] = flexasr_pattern(mod) print(count_all_overloads(mod)) with open("./models/transformer/transformer....
def import_into_relay(net): trace = get_trace(net) input_names = [f"{INPUT_PREFIX}_0"] input_shapes = [(f"{INPUT_PREFIX}_0", (BATCH_SIZE, 3, 32, 32))] custom_convert_map = {} mod, params = relay.frontend.from_pytorch(trace, input_shapes, custom_convert_map) for arg in mod["main"].params[: len(in...
The main task of the code is to compare the performance and accuracy of a neural network model on PyTorch, Relay (TVM), and optionally an accelerated version. It evaluates numerical differences between outputs, execution times, and prediction correctness, storing results in CSV files for analysis.
def compare_on_data(net, testloader, num_images, use_accelerators, use_im2col): mod, params = import_into_relay(net) compile_start = time.time() relay_model = compile_into_tvm(mod, params) compile_end = time.time() print(f"Relay compile time: {compile_end - compile_start}") if use_accelerators:...
def load_data(shuffle=True): transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform) te...
The main task of the code is to test a neural network model by loading test data, initializing the model with specified parameters, and evaluating its performance on a dataset. It uses flags to control data shuffling, accelerator usage, and im2col optimization, then compares model outputs against test data to assess ac...
def main(params_path, num_images, use_accelerators, shuffle, use_im2col): testloader = load_data(shuffle=shuffle) net = init_net(params_path) compare_on_data(net, testloader, num_images, use_accelerators, use_im2col)