dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def all_macro(yhat, y): return macro_accuracy(yhat, y), macro_precision(yhat, y), macro_recall(yhat, y), macro_f1(yhat, y) def all_micro(yhatmic, ymic): return micro_accuracy(yhatmic, ymic), micro_precision(yhatmic, ymic), micro_recall(yhatmic, ymic), micro_f1(yhatmic, ymic) def recall_at_k(yhat_raw, y, k): ...
The function `all_metrics` computes and returns a dictionary of evaluation metrics for binary classification tasks. It calculates macro and micro averages of accuracy, precision, recall, and F1 scores. If raw prediction scores (`yhat_raw`) are provided, it also computes AUC and @k metrics (precision, recall, F1 at spec...
def all_metrics(yhat, y, k=8, yhat_raw=None, calc_auc=True): """ Inputs: yhat: binary predictions matrix y: binary ground truth matrix k: for @k metrics yhat_raw: prediction scores matrix (floats) Outputs: dict holding relevant metrics ...
def gini(self, X): counts = class_counts(X) impurity = 1 for lbl in counts: prob_of_lbl = counts[lbl] / float(len(X)) impurity -= prob_of_lbl**2 return impurity def partition(self, X, question): true_X, false_X = [], [] for row in X: ...
The function identifies the optimal feature-value split in a dataset to maximize information gain, using Gini impurity as the uncertainty measure. It iterates through all features and their unique values, partitions the data, calculates gain, and retains the best split with highest information gain for decision tree no...
def find_best_split(self, X): best_gain = 0 best_question = None current_uncertainty = self.gini(X) n_features = len(X[0]) - 1 for col in range(n_features): values = set([row[col] for row in X]) for val in values: question = Question(col,...
def find_best_split(self, X): best_gain = 0 best_question = None current_uncertainty = self.gini(X) n_features = len(X[0]) - 1 for col in range(n_features): values = set([row[col] for row in X]) for val in values: question = Question(col,...
The code recursively builds a decision tree by finding the best feature/threshold split, partitioning data into true/false branches, and creating decision nodes until no further splits improve the model, returning a tree structure with leaf nodes for terminal decisions.
def fit(self, X): gain, question = self.find_best_split(X) if gain == 0: return Leaf(X) true_X, false_X = self.partition(X, question) true_branch = self.fit(true_X) false_branch = self.fit(false_X) self.tree = Decision_Node(question, true_branch, false_branc...
def _display(self) -> None: """ Displays what the field looks like now. """ self.surface.fill(BACKGROUND_COLOR) pygame.draw.rect(self.surface, FIELD_COLOR, FIELD_RECT) cells_to_flash = [] for i, row in enumerate(self.game.field[-1::-1]): for j, cell in enumerate(row)...
The main task of `_play_game` is to manage the game loop by repeatedly generating and dropping a faller, allowing user interaction, letting it fall until freezing, clearing matched jewels, and checking for game-over conditions when the field is full or a faller cannot be placed.
def _play_game(self) -> None: """ Assuming field has contents in its field attribute, repeatedly takes a faller and repeats letting user alter it repeatedly and lowering it as time passes until it freezes, until a faller could not be fully displayed, in which case the game is over. ...
def get_real_data(task, train_extra_data, accum=True, encode=True): task_idx = args.tasks.index(task) gen_size = DATA_ATTRS[task]["train"]["data_size"] if accum: prev_tasks = args.tasks[:task_idx] gen_size = int(np.ceil(gen_size * args.gen_lm_sample_percentage))//len(prev_tasks) else: ...
This function generates synthetic extra training data for a machine learning model. It either loads pre-existing generated data or creates new data by sampling from a model trained on previous tasks. The generated data is formatted, filtered, and saved for use in training, with parameters controlling generation size, t...
def create_extra_data(task, prev_task, model, train_extra_data): if args.real_sample: logger.info(f"using real data as extra data") return get_real_data(task, train_extra_data) task_cnt = args.tasks.index(task) model_dir = get_model_dir([prev_task]) gen_path = os.path.join(model_dir,"lm....
def get_gen_token(task): if args.add_task_tokens: return '__' + task + '__' else: return '__gen__' def data_tokenization(self, data): if args.debug: data = data[:10] new_data = [] for datum in data: new_data.append(self.parallel_tokeniz...
This code initializes a data processor for handling tasks like question answering or generation. It loads and processes data from specified paths, tokenizes the data, incorporates optional extra data, and prepares it for model training by handling special tokens, task-specific formatting, and answer file integration.
def __init__(self, data_paths, data_type, gen_token, extra_data=[]): self.data_type = data_type self.gen_token = gen_token if args.use_sep: self.sep_token = SPECIAL_TOKEN_IDS["sep_token"] self.ans_token = SPECIAL_TOKEN_IDS["ans_token"] self.eos_token = SPECIAL_TOKEN_I...
def constraint_extrapolation_iai(self, class_c): ''' It returns a matrix with all the constraints that describe the tree. This function returns constraints for each leaf. the column ID represent the reference leaf. IMPORTANT: (constraint structure) the sign is always <=. ''' ...
The function `constraint_extrapolation` determines the machine learning algorithm type (`self.__algorithm`) and delegates constraint generation to the corresponding private method (e.g., IAI, CART, RF, GBM, etc.). It returns the computed constraints for the given class `class_c`, enabling model-specific constraint hand...
def constraint_extrapolation(self, class_c): if self.__algorithm in ["iai","iai-single"]: constraints = self.constraint_extrapolation_iai(class_c) elif self.__algorithm == "cart": constraints = self.constraint_extrapolation_skTree(class_c) elif self.__algorithm == "rf": ...
def master_problem(model, u, outcome, clf_type, mfile, F_countefactual_features, rho, unc_type, lb, ub, S, time_limit=1000): """ This function defines and solves the master problem. """ model_temp = add_objective(model, u, 'l1') if clf_type == 'cart': master_model = constraints_tree(mode...
The function implements an adversarial algorithm that iteratively solves a master problem and an adversarial problem to refine a machine learning model's constraints. It alternates between optimizing the model's parameters (via the master problem) and checking for adversarial examples (via the adversarial problem), add...
def adversarial_algorithm(model, outcome, clf_type, save_path, u, mfile, F_countefactual_features, rho, unc_type, lb, ub, time_limit): """ Adversarial algorithm with the iteration between the master problem and the adversarial problem """ print('time limit: %i' % time_limit) if not pd.isna(ub): ...
def constraints_linear(model, outcome, class_, linear_table, F_countefactual_features, rho, unc_type, lb, ub): """ This function generates the constraints for a linear predictive model. """ intercept = linear_table['intercept'][0] coeff = linear_table.drop(['intercept'], axis=1, inplace=False).l...
This function adds validity constraints to a model for machine learning classifiers (e.g., MLP, trees), using an adversarial approach when needed. It defines variables, loads classifier data, applies type-specific constraints, solves the model with Gurobi, and returns the optimized solution, computation time, and itera...
def add_validity_constraint(model, clf, clf_type, save_path, u, F_countefactual_features, rho, unc_type, adversarial, time_limit): """ The validity constraints require an adversarial approach in the case of MLP and optionally in the case of tree based models. """ ...
def write_tables(save_path, X_train, y_train, clf, clf_type, task_type, unc_type): """ This function uses constraint_learning to write the ML models in a tabular format and it saves the csv file in 'save_path'. """ if not os.path.exists(save_path + '/' + clf_type): os.makedirs(save_p...
This function generates robust counterfactual explanations by creating a constrained optimization model with validity constraints, iteratively refining solutions, and returning the model, iterations, computation time, and valid counterfactual solutions for a given classifier and feature constraints.
def generate(clf, X_train, y_train, save_path, clf_type, task_type, u, F_countefactual_features, F_binary, F_integers, F_coherence, F_immutability, F_larger_than, F_positivity, rho, unc_type='ball', iterative=False, time_limit=100): """ This function generate the robust counterfact...
def assert_healthy(self): if config.getoption('--single-node'): assert self.get_node_count() == 1 assert self.get_cluster_status() in ['yellow', 'green'] else: assert self.get_node_count() == 2 assert self.get_cluster_status() == 'g...
(The code initializes an Elasticsearch connection, verifies cluster health, retrieves Java processes, and prepares a clean testing environment by loading an index template and deleting existing data to ensure a fresh state for subsequent operations.)
def __init__(self): self.url = 'http://localhost:9200' self.auth = HTTPBasicAuth('elastic', 'changeme') self.assert_healthy() self.process = host.process.get(comm='java') # Start each test with a clean slate. assert self.load_index_template().st...
def initialize_directories(): """ Initialize directory structure for complex version. """ for directory in directory_list: os.makedirs(directory, exist_ok=True) return def find_path(filename): """ Find the path of a file in the source directory provided a filename. Parameters ...
The main task of the code is to process Fortran files by initializing directory structures, modifying file contents (excluding specified files), and generating build instructions. It iterates through a file list, reads each file, applies transformations if allowed, writes updated files, and compiles a list of output pa...
def main(): # Initialize Directory Structure initialize_directories() fortranFiles = [] for filename in file_list: # Find File path_in, path_out = find_path(filename) # Read File lines = read_file(path_in) # Complexify File if filename not in exclude_l...
def remove_stopwords(words): """Remove stop words from list of tokenized words""" new_words = [] for word in words: if word not in stopwords.words("english"): new_words.append(word) return new_words def remove_non_ascii(words): """Remove non-ASCII characters from list of tokenize...
This function processes a string by splitting it into tokens and applying text preprocessing steps such as removing stopwords, non-ASCII characters, lemmatizing verbs, stemming, replacing integers/numbers with text or blanks, and handling special codes based on specified parameters.
def process_token( str, removeStopwords=True, removeNonASCII=True, lemmatizeVerbs=True, stemWords=False, replaceIntegerToText=False, replaceNumberToBlank=True, methodOption=0, noReplaceCodeName=True, ): """ Parameters: 1. removeStopwords: Start to remove stopwords. ...
def find_next_leader(self): while len(self.replica_addresses) > 0: current_leader_server, current_leader_port = self.replica_addresses[0] try: self.connection = new_route_guide_pb2_grpc.ChatStub(grpc.insecure_channel(f"{current_leader_server}:{current_leader_port}")) ...
This code initializes a connection to a server replica, manages login authentication, handles message retrieval, and maintains communication. It prioritizes server replicas, connects to the first available, logs in repeatedly until successful, retrieves offline messages, and loops to send chat messages with retries. It...
def __init__(self, test=False): if test: return """ List of ports of replicas in order of priority (for power transfer) List will decrease in size as servers go down; first port in list is the leader """ self.replica_addresses = [(SERVER1, PORT1), (S...
def make_adjacent(state: PuzzleState) -> List[PuzzleState]: """ Return a list of PuzzleState objects that represent valid, non-opposing moves from the given PuzzleState. A move is considered valid if it moves a tile adjacent to the blank tile into the blank tile. A move is considered non-opposing if...
The function performs uniform-cost search to find the shortest path from a start state to a goal state in a puzzle. It uses a queue to explore states, adding valid adjacent moves not yet explored. When a state matches the goal, it returns the path; otherwise, it continues until the queue is empty, returning None if no ...
def uniform_cost_search(start: PuzzleState, endgoal: Tuple, explored: List[PuzzleState]) -> Optional[str]: queue = [] queue.append(start) while bool(queue) is True: current = queue.pop(0) explored.append(current) if current.tiles == endgoal: return...
def load_samples(directory): """ Loads the allophone samples from the provided directory. These are stored in a dict keyed by filename (minus .wav) as "int16" NumPy arrays. Silence at the start and end is trimmed, and the audio is run through a lowpass filter (Fc 5000Hz). All ".wav" files in the ...
The code initializes a class by loading audio samples, a CMU phoneme dictionary, and an allophone mapping, then creates a zero-padded array for inter-word spacing in speech synthesis or processing.
def __init__(self, sample_dir, dict_file_path, allo_map_file_path): self.sounds = load_samples(sample_dir) self.cmu_dict = load_cmu_dict(dict_file_path) self.allo_map = load_allophone_map(allo_map_file_path) self.interword_pad = np.zeros(4000).astype("int16")
def driveStraight_dividedistanceby2(driveStraight_distance_heading_velocity_kp__distance, driveStraight_distance_heading_velocity_kp__heading, driveStraight_distance_heading_velocity_kp__velocity, driveStraight_distance_heading_velocity_kp__kp): global myVariable, error, output #drives very Straight and works v...
The code defines a function `actual_autostart` that controls a robot's movements and sensor activations. It involves driving forward/backward, turning left, and triggering yellow/blue sensors, likely to navigate a path or perform a task like object detection/interaction. The sequence combines directional movement comma...
def actual_autostart(): driveStraight_dividedistanceby2(-150,0,60,2) yellow_activate() driveStraight_dividedistanceby2(100,0,60,2) leftTurn(150) driveStraight_dividedistanceby2(250,210,60,2) leftTurn(30) driveStraight_dividedistanceby2(-100,-180,60,2) BlueTrigger() driveStraight_divi...
def Drivebase_Reverse2(Time): LeftBase.spin(REVERSE) RightBase.spin(REVERSE) WaitTime(Time) def yellow_activate(): #yellow already in position bucket.spin(FORWARD) wait(2.5,SECONDS) bucket.stop() LeftBase.set_velocity(100,PERCENT) RightBase.set_velocity(100,PERCENT) #driveMM(55)...
The code controls an LED (touchled_4) based on button presses, cycling through red, green, and blue states. When pressed, it triggers movement commands (e.g., reversing, driving, turning) and activates functions like `yellow_activate`. On the third press, it resets the LED to blue. The loop continuously checks for inpu...
def touchled_control(): touchlednum = 0 while True: brain_inertial.set_heading(0,DEGREES) if touchled_4.pressing() or controller.buttonL3.pressing(): touchlednum = touchlednum + 1 wait(0.25,SECONDS) if touchlednum == 1: touchled_4.set_color(Col...
def check_permission(self,pk): logger.debug(f'Migration_API check_permission initial ') result = {'error':'','status':False,'message':''} try: History_Instance = TMigration_Batch_History.objects.using(MIGRATION_DATABASE).get(pk=pk) if History_Instance.status == 0: result['status'] = True else: cu...
This function initiates a migration process by checking permissions, retrieving batch history data, and executing either 'FIR-wise' or 'table-wise' migration based on the batch type. It logs progress, handles success/failure/abortion states, updates migration statuses, and returns a result with status/error messages.
def migration_initial(self,pk): logger.debug(f'Migration_API migration_initial initial ') result = {'error':'','status':False,} try: check_permission_status = self.check_permission(pk) if check_permission_status['status'] is False: result['error'] = check_permission_status['error'] logger.debug(f'Mi...
def _client(self): """Initiates a Docker client :returns: DockerClient """ try: logger.info("Connecting to Docker API") if not self.client: self.client = docker.from_env() return self.client except ConnectionError: r...
The code defines an `__init__` method that initializes three components: `_client()`, `_image()`, and `_container()`. Its main task is to set up these components when an object is instantiated, likely preparing resources or configurations for client interactions, image management, and container operations.
def __init__(self): self._client() self._image() self._container()
def CutRod(priceTable, rodSize): rodValue = 0 if rodSize > 0: rodValue = -sys.maxsize - 1 for i in range(1, rodSize + 1): rodValue = max(rodValue, priceTable[i] + CutRod(priceTable, rodSize - i)) return rodValue def MemoizedCutRod(priceTable, rodSize): minVal = ...
The code tests three rod-cutting algorithms (CutRod, MemoizedCutRod, BottomUpCutRod) to ensure they all return the same result (10) when given a price table and rod length 4, verifying correctness and consistency across implementations.
def testCase1(self): self.assertEqual(10, CutRod(self.PriceTable, 4)) self.assertEqual(10, MemoizedCutRod(self.PriceTable, 4)) self.assertEqual(10, BottomUpCutRod(self.PriceTable, 4))
def CutRod(priceTable, rodSize): rodValue = 0 if rodSize > 0: rodValue = -sys.maxsize - 1 for i in range(1, rodSize + 1): rodValue = max(rodValue, priceTable[i] + CutRod(priceTable, rodSize - i)) return rodValue def MemoizedCutRod(priceTable, rodSize): minVal = ...
This test case verifies that three rod-cutting algorithms—CutRod, MemoizedCutRod, and BottomUpCutRod—correctly return 0 when given a rod length of 0, ensuring they handle the base case where no cuts are possible. It checks consistency across iterative and dynamic programming approaches for the rod-cutting problem.
def testCase2(self): self.assertEqual(0, CutRod(self.PriceTable, 0)) self.assertEqual(0, MemoizedCutRod(self.PriceTable, 0)) self.assertEqual(0, BottomUpCutRod(self.PriceTable, 0))
def CutRod(priceTable, rodSize): rodValue = 0 if rodSize > 0: rodValue = -sys.maxsize - 1 for i in range(1, rodSize + 1): rodValue = max(rodValue, priceTable[i] + CutRod(priceTable, rodSize - i)) return rodValue def MemoizedCutRod(priceTable, rodSize): minVal = ...
The main task of the code is to test the correctness of three rod-cutting algorithms (recursive, memoized, and bottom-up dynamic programming) by verifying they all return the same optimal value (22) for a rod of length 8 using the provided PriceTable. This ensures consistency and correctness across different implementa...
def testCase3(self): self.assertEqual(22, CutRod(self.PriceTable, 8)) self.assertEqual(22, MemoizedCutRod(self.PriceTable, 8)) self.assertEqual(22, BottomUpCutRod(self.PriceTable, 8))
def predict_data(self, x): # Predict result from each neurons isValid = True #self.checkInput(x) if not isValid: raise SystemExit() else: predictions = [] predictions.append(self.predict_layer(x, self.model[0]["neurons"], self.model[0]["activation_function...
The main task of the code is to compute the error deltas for each layer in a neural network during backpropagation for a given mini-batch of data. It initializes a delta storage structure, performs forward propagation to generate predictions, calculates output layer deltas by comparing predictions with actual labels, a...
def calculate_mini_batch_error(self, mini_batch, outputs): all_deltas = [] for layer in self.model: all_deltas.append([]) for _ in layer["neurons"]: all_deltas[-1].append(0) for data in mini_batch: # Forward Propagation predictions...
def calculate_mini_batch_error(self, mini_batch, outputs): all_deltas = [] for layer in self.model: all_deltas.append([]) for _ in layer["neurons"]: all_deltas[-1].append(0) for data in mini_batch: # Forward Propagation predictions...
This code trains a neural network using mini-batch gradient descent. It iteratively updates weights based on calculated errors from training data, stopping when error thresholds are met or after max iterations. It handles softmax and standard error calculations, tracks progress, and returns convergence status with iter...
def train(self, training_data, mini_batch_size, learning_rate, error_threshold, max_iteration=1000, test_data=None): if test_data: n_test = len(test_data) n = len(training_data) below_threshold = False i = 0 while (i < max_iteration) and not below_threshold: ...
def query_ourfish_data(session_id): all_data = get_ourfish_data() return all_data def query_geo_data(session_id): all_data = query_ourfish_data(session_id) # from cache geo = get_geo_data(all_data) return geo def apply_filters(session_id, sel_maa, start_date, end_date): """ Pull full cached ...
The main task of the code is to generate the initial app layout when the application loads. It queries data from data.world, processes the past 6 months of OurFish data, applies filters, and creates visualizations, filters, and download components. The layout includes a session ID, map, filters, plots, download button,...
def serve_layout(): """ Create app layout on page load Query data.world to process data, giving the initial data that is displayed. "Initial" in this sense means the first dataset after loading the app; it is the past 6 months of OurFish data. We also pull the full dataset which is used to upda...
def random_handle(self): return str(uuid.uuid4()) def random_gender(self): return random.choice([Person.MALE, Person.FEMALE]) def add_random_name(self, person: Person, surname=None): """Add a random name to a person object.""" name = person.primary_name if person.gender == Person...
This function generates a random person with attributes like handle, gender, name, birth date (1970-2000), optional birth place, note, and face, then adds them to the database, sets them as the default person, and returns the created Person object.
def add_start_person(self) -> Person: """Add & commit a start person.""" person = Person() person.handle = self.random_handle() person.gender = self.random_gender() self.add_random_name(person) birth_place_handle = None if self.places: birth_place = ra...
def add_places(self): for _ in range(self.NUM_PLACES): place = self.random_place() colored = bool(random.randint(0, 1)) self.places.append(place) self.add_image(place, "town", str(place.name.value), color=colored) with DbTxn("Add place", self.db) as tr...
The code's main task is to initialize a structured data model by adding geographical places, creating a starting person, and recursively generating their family relationships. The `build` method orchestrates this process by sequentially invoking `add_places` for location setup, `add_start_person` to define an initial i...
def build(self): self.add_places() person = self.add_start_person() self.add_family(person, recursive=True)
def cruise(shape,board): liste = [] if board.is_empty_cell((0,shape[1]//2)): liste.append((0,shape[1]//2)) if board.is_empty_cell((shape[0]-1,shape[1]//2)): liste.append((shape[0]-1,shape[1]//2)) if board.is_empty_cell((shape[0]//2,0)): liste.append((shape[0]//2,0)) if board....
The main task of the code is to generate a list of actions for placing pieces on a board during phase 1 of a game. It identifies player and enemy positions, calculates potential empty cells using helper functions, prioritizes valid placements, and selects up to two cells to add new pieces, returning these actions for t...
def phase1(self, state): board = state.get_board() this_id = self.color.value ennemy_id = -self.color.value mcolor = Color(self.color.value) ecolor = Color(-self.color.value) shape = board.board_shape actions = [] liste = [] booleane = False my_cells = board.get_player_pieces_on_...
def ssd(): #computing disparity maps of the left and right images left, right, templateSize, window = initImage() cv2.imwrite('3. Corner Response Left Image.jpg', left) cv2.imwrite('4. Corner Response Right Image.jpg', right) cv2.imshow('Corner Response Left Image SSD', left) cv2.imshow('C...
The function `scoreSelect()` prompts the user to choose a matching score (SSD, SAD, or NCC) for disparity map computation. Based on the input, it generates left and right disparity maps using corresponding methods, saves them as images, displays them, and passes them to `validity()` and `averaging()` functions for furt...
def scoreSelect(): score = input('Select a matching score: 1 for SSD, 2 for SAD, 3 for NCC: ') if score == '1': left, right = ssd() cv2.imwrite('5. Left Disparity SSD.jpg', left) cv2.imwrite('6. Right Disparity SSD.jpg', right) cv2.imshow('Left Dispar...
def initsocket(self): # Datagram (udp) socket try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) print('Socket created') except socket.error as msg: print('Failed to create socket. ') print(msg) sys.exit() # Bind socket ...
The code initializes a socket, prompts the user for a non-empty username, and enters a loop where it lets the user select a service. It collects arguments, converts them to bytecode, sends them to the server, receives and processes the response, then executes the result. The loop repeats until the user presses "Return"...
def start(self): # TODO: setup socket self.socket = self.initsocket() # TODO: read username from user and start up the interface main loop while 1: self.username = input("Type in your name: ") if self.username == '': print("Input Error: your name ...
def dist(A: List[float], B: List[float]): vecA = np.array(A) vecB = np.array(B) return np.linalg.norm(vecA - vecB) def set_disp(self): disp = np.array(self.mw_disp) for i, a in enumerate(self.atom): disp[:, 3*i:3*i+3] /= math.sqrt(mendeleev.element(a).atomic_weight * units.DALTON...
This code initializes a molecular vibration analysis tool by processing geometric coordinates, frequency data, and displacement matrices. It converts units (Bohr/Angstrom, Hartree/cm⁻¹, AMU/a.u.), constructs atomic bonds using covalent radii, prepares displacement matrices, and optionally diagonalizes the Hessian matri...
def __init__(self, geom: List[List[Union[str, Tuple[float,float,float]]]], freq: Optional[List[float]] =None, mw_disp: Optional[List[List[float]]] =None, mw_hess: Optional[np.ndarray] =None, unit_xyz: Optional[str] ='Bohr', unit_xyz_hess: Optional[str] ='Bohr', un...
def getMetaFile(): if exists(f"{dirname(__file__)}/data/meta.json"): with open(f"{dirname(__file__)}/data/meta.json", "r") as f: metaFile = json.load(f) elif exists(f"{dirname(__file__)}/meta.json"): with open(f"{dirname(__file__)}/meta.json", "r") as f: metaFile = j...
This function checks the "structure-version" in a meta.json file. If it's "0", it upgrades the structure to version "1" by creating a "data" directory, generating required files (icons.txt, games.txt, customGameIDs.json), moving them into "data/", and updating meta.json. It handles errors like missing imports or file o...
def verifyProjectVersion(): metaFile = getMetaFile() if metaFile["structure-version"] == "0": print("----------------------------------------------------------") log("updating meta.json's structure-version to `1`") log("importing libraries for meta update") try: impor...
def log(log): print(f"[{datetime.now().strftime('%b %d %Y - %H:%M:%S')}] {log}") def getImageFromSGDB(loops=0): global coverImage global coverImageText log("searching for an icon using the SGDB") # searches SGDB for the game you're playing results = sgdb.search_game(gameName) if le...
The main task of the code is to retrieve or fetch a game's cover image. It first checks a local cache file (`icons.txt`) for pre-saved image/text data. If not found, it attempts to fetch the image from an external source (`getImageFromSGDB()`) or as a backup from Steam's store page (`getImageFromStorepage()`), ensuring...
def getGameImage(): global coverImage global coverImageText coverImage = "" log(f"fetching icon for {gameName}") # checks if there's already an existing icon saved to disk for the game with open(f'{dirname(abspath(__file__))}/data/icons.txt', 'r') as icons: for i in icons...
def log(log): print(f"[{datetime.now().strftime('%b %d %Y - %H:%M:%S')}] {log}") def getGamePrice(): r = makeWebRequest(f"https://store.steampowered.com/api/appdetails?appids={gameSteamID}&cc=us") if r == "error": return # sleep for 0.2 seconds, this is done after every steam request, to av...
The main task of the code is to update Discord's rich presence with dynamic game details, including custom states, review scores, and Steam store buttons. It checks for default app IDs to set game names, handles rich presence updates, constructs truncated Steam buttons with pricing info, and ensures proper initializati...
def setPresenceDetails(): global activeRichPresence global startTime details = None state = None buttons = None # if the game ID is corresponding to "a game on steam" - set the details field to be the real game name if appID == defaultAppID or appID == defaultLocalAppID: de...
def get_uncompleted_instructions(include_past=True, include_future=False, sort='chronological', limit=0): """ Looks at 'trials' database and return a list of uncompleted instructions This should be useful e.g. for a CRON job to check if anything needs to be sent. Inputs include_past if True, inc...
This function retrieves uncompleted meditation instructions from a database, sends personalized Facebook messages to users instructing them to meditate or not based on their assigned condition, and updates the database to mark instructions as sent with timestamps. It handles both past and future instructions, logging a...
def fb_send_outstanding_instructions(): """Uses get_uncompleted_response_prompts() to get to-do list, then sends facebook messages telling people to meditate or not. """ outstanding = get_uncompleted_instructions(include_past=True, include_future=False) if not outstanding: # if list is empty lo...
def get_uncompleted_response_prompts(include_past=True, include_future=False, sort='chronological', limit=0): """ Looks at 'trials' database and return a list of uncompleted response prompts This should be useful e.g. for a CRON job to check if anything needs to be sent. Inputs include_past if T...
The function retrieves outstanding response prompts, sends a calmness rating request via Facebook to each user, and updates the trial records to mark the request as sent with timestamps. It returns the count of emails sent or None if no prompts exist.
def fb_send_outstanding_response_prompts(): """Uses get_uncompleted_response_prompts() to get to-do list, then sends messages. Returns number of emails sent """ outstanding = get_uncompleted_response_prompts(include_past=True, include_future=False) if not outstanding: # if list is empty lo...
def log(message): # simple wrapper for logging to stdout on heroku print(str(message)) sys.stdout.flush() def coll(collection_name): """Return pymongo object pointing towards the collection You can use this for example like so: coll('users').find({'fb_id': fb_id}) """ _, _, coll = open...
The function attempts to store a user's numeric response as a rating for the most recent pending trial. It validates the input rating, checks for an outstanding response prompt, and stores the rating if valid, otherwise informing the user of errors.
def store_response_attempt(fb_id, hypothesized_rating): """ Attempt to store a rating if there is an oustanding response prompt Quick replies are not very reliable. If people just type a number in response to the response_prompt, we should store that. input fb_id user...
def read_stop_list(stop_file): stop_word_list=[] with open(stop_file, 'r') as stop: for i in stop: stop_word_list.append(i.strip()) stop.close() return stop_word_list def single_index_generation(file,files, dict2, dict3, stop_word,initial_time,limit): docno = 0 wordno = 0 ...
The main task of the code is to generate different types of document indexes (single-word, phrase, position-based, or stemmed) based on user-specified modes. It processes input documents, filters stop words, and constructs inverted indexes while adhering to memory constraints. The code measures execution time and outpu...
def main(): start_time=time.time() doc_id = collections.defaultdict(int) single_word_dict = collections.defaultdict(int) single_id=collections.defaultdict(int) phrase_word_dict = collections.defaultdict(int) phrase_id = collections.defaultdict(int) position_word_dict = collections.default...
def read_stop_list(stop_file): stop_word_list=[] with open(stop_file, 'r') as stop: for i in stop: stop_word_list.append(i.strip()) stop.close() return stop_word_list def single_index_generation(file,files, dict2, dict3, stop_word,initial_time): docno = 0 #temporary diction...
The code generates an inverted index based on a specified mode (single, phrase, position, or stemming) using input documents and stopwords. It parses command-line arguments, processes files, and constructs respective index structures. The execution time is measured and printed for each mode.
def main(): start_time=time.time() doc_id = collections.defaultdict(int) single_word_dict = collections.defaultdict(int) single_id=collections.defaultdict(int) phrase_word_dict = collections.defaultdict(int) phrase_id = collections.defaultdict(int) position_word_dict = collections.default...
def paintlabel(sc): Label(sc,text="Welcome "+name+"",font=("arial",40),bg="light grey").place(x=700,y=50) Label(sc,text="Add new card",font=("arial",30),bg="light grey").place(x=150,y=400) Label(sc,text="Card No",font=("arial",20),bg="light grey").place(x=50,y=500) Label(sc,text="Validity",font=("arial"...
The main task of the code is to create a full-screen GUI for a credit card payment system using facial recognition. It initializes window properties, sets the background, title, and screen size, then calls helper functions to paint labels, input fields, buttons, user images, and combo boxes. The `mainloop()` starts the...
def buildUi(sc,pid): global li li=[StringVar(),StringVar(),StringVar(),StringVar()] w,h=sc.winfo_screenwidth(),sc.winfo_screenheight() sc.geometry("%dx%d+0+0"%(w,h)) sc.state('zoomed') sc.configure(bg="light grey") sc.title("CREDIT CARD PAYMENT SYSTEM USING FACIAL RECOGNITION") pain...
def paintlabel(sc): Label(sc,text="Welcome",font=("arial",40),bg="light grey").place(x=820,y=50) Label(sc,text="Enter Your ID ",font=("arial",30),bg="light grey").place(x=805,y=400) def paintfields(sc): Entry(sc,font=("arial",20),textvariable=t1,justify='center').place(x=780,y=500) def paintimage(sc): r...
The code defines a function `buildUi` to create a full-screen GUI for a "CREDIT CARD PAYMENT SYSTEM USING FACIAL RECOGNITION." It sets window properties, initializes UI components via helper functions (`paintlabel`, `paintfields`, `paintimage`, `paintbutton`), and starts the main event loop. The interface uses a light ...
def buildUi(sc): global t1 t1=StringVar() w,h=sc.winfo_screenwidth(),sc.winfo_screenheight() sc.geometry("%dx%d+0+0"%(w,h)) sc.state('zoomed') sc.configure(bg="light grey") sc.title("CREDIT CARD PAYMENT SYSTEM USING FACIAL RECOGNITION") #Labels paintlabel(sc) #Fields ...
def paintimage(sc): img=PhotoImage(file="ocr-b.jpg") canvas=Canvas(sc,bg="light grey",width=img.width(),height=img.height(), highlightthickness=0, relief='ridge') canvas.place(x=751,y=150) canvas.create_image(0,0, anchor=NW, image=img) canvas.image=img def paintlabel(sc): Label(sc,text="Welcome"...
This code defines a function `buildUi` that initializes and configures a Tkinter GUI window for a "CREDIT CARD PAYMENT SYSTEM USING FACIAL RECOGNITION." It sets the window to full-screen mode, applies a light grey background, adds a title, and calls helper functions to paint images, labels, input fields, and buttons. T...
def buildUi(sc): global li li=[StringVar(),StringVar(),StringVar()] w,h=sc.winfo_screenwidth(),sc.winfo_screenheight() sc.geometry("%dx%d+0+0"%(w,h)) sc.state('zoomed') sc.configure(bg="light grey") sc.title("CREDIT CARD PAYMENT SYSTEM USING FACIAL RECOGNITION") paintimage(sc) ...
def check_memory_variable(self) -> bool: if self.data[0].__eq__("M") and self.data[2].__eq__("M"): self.operand_1 = self.memory self.operand_2 = self.memory return True elif self.data[0].__eq__("M"): self.operand_1 = self.memory self.operand_2...
The code executes mathematical operations by validating operands and operators, handling division-by-zero errors, printing results, and allowing user interaction to continue or exit calculations.
def execute_equation(self) -> None: flag: bool = True while True: if self.check_memory_variable(): if self.data[1].__eq__("/") and self.operand_2 == 0: self.divide_by_zero() flag = False else: self....
def check_files(self): """Checks existence of settings and solutions files. Displays results on main window's info_label.""" # Checking for file containing results of experiments try: self.solutions_file = pd.read_csv("solution.csv") except FileNotFoundError: # pa...
This code creates a GUI for a simulation/training application using Tkinter. It initializes a window with buttons to control experiments, start simulations, and initiate training (with options for fresh training or resuming from saved data). It checks for required files (CSV/JSON) and dynamically adds buttons based on ...
def main_func(self, param_queue): self.queue = param_queue # Creating the main window\ self.window = tk.Tk() self.window.title("Ball Thrower x2000") self.window.config(padx=50, pady=50, bg="white") self.main_label = tk.Label(text="Simulate throw or begin GA training", fo...
def check_files(self): """Checks existence of settings and solutions files. Displays results on main window's info_label.""" # Checking for file containing results of experiments try: self.solutions_file = pd.read_csv("solution_neat.csv") except FileNotFoundError: ...
The main task of this code is to create a GUI application for a simulation/training system. It initializes a Tkinter window with interactive buttons for cycling through experiments, starting simulations, initiating NEAT training (with options for screenshots), and shutting down the program. The GUI dynamically checks f...
def main_func(self, param_queue): self.queue = param_queue # Creating the main window\ self.window = tk.Tk() self.window.title("Ball Thrower x3000") self.window.config(padx=50, pady=50, bg="white") self.main_label = tk.Label(text="Simulate throw or begin NEAT training", ...
def initInstruction(self,instruction_name):#calls singletonTable to get the instruction Opcode to save it in instruction_obj if(singletonTables.unique_instruction_table.get(instruction_name[0],-1) != -1): #error #print(instruction_name[1:], instruction_name[0]) if(instruction_name[0] == ...
This code initializes an object with attributes based on input array length, setting symbol, instruction, and target objects while managing flags and error handling. It assigns `object_code` with a 33rd bit flag, adjusts flags for target objects, and exits on invalid input lengths.
def __init__(self, str_arr, loc_counter): #initializes these objects, then calls singletonTables.assignSymbolTable() self.loc_counter = loc_counter self.array_length = len(str_arr) #python automatically turnicates unused zeroes, so to prevent that i'm making the 33rd bit = 1, then removing it du...
def person(x, y): angle = mouse_angle(x, y) rot_image = rotate_image_by_angle(personImg, angle) gameDisplay.blit(rot_image, (x, y)) def update_towers(): for t in tower_placeholder_list: if t.level > 0: angle = math.atan2(t.posx - t.target.posx, t.posy - t.target.posy) rec...
The main task of the code is to update all game elements on the screen for rendering. It updates the player's position, towers, bullets, enemies, and placeholder towers, likely as part of a game loop to refresh the display with current states before rendering.
def update_screen(): person(x, y) update_towers() update_bullets() update_enemies() update_placeholder_towers()
def show_fps(window, clock): fps_overlay = FPS_FONT.render(str(int(clock.get_fps())), True, black) window.blit(fps_overlay, (0, 0)) def mouse_pointer(): pygame.mouse.set_visible(True) pointerImg_rect = cursorImg.get_rect() pointerImg_rect.center = get_mouse_position() gameDisplay.blit(cursorImg,...
The main task of the code is to upscale the game display by scaling the original gameDisplay surface to a larger resolution (w, h) using Pygame's transform.scale, then rendering the upscaled frame onto the window and updating the display. It also handles FPS display, mouse pointer logic (though currently unthreaded), a...
def upscale_screen(): show_fps(gameDisplay, clock) #mouse = threading.Thread(target=mouse_pointer) #mouse.start() mouse_pointer() update_screen() w = int(640 * scale_multiplier) h = int(360 * scale_multiplier) #if w == monitor_info.current_w: #window = pygame.display.set_mode((w,...
def createKnotVector(numCp, degree): tLen = numCp+degree+1 knots = [0]*(tLen) # generage a knot vector for i in range(tLen): if i <= degree: knots[i] = 0 elif i > tLen - degree - 2: knots[i] = tLen-2*degree - 1 else: knots[i] = (i - degree) ...
The code generates a B-spline curve from control points, calculates its length, interpolates a specific point along the curve's length, computes the tangent at that point, and visualizes the curve and tangent. It samples the curve, differentiates for length calculation, and outputs key geometric data for rendering and ...
def updateCurve(cvNames, numSamples = 120, degree = 3, pAtLength = 2.18): knots = createKnotVector(len(cvNames), degree) cvPos = getCpPositions(cvNames) pSq = sampleBSpline(numSamples, degree, cvPos, knots) diffSq = differentiate(pSq) lengthSq = lengthSequence(diffSq) samplePoints(pSq, 0.002, 3,...
def move_image() -> None: global timer if check_position(): # true: timer start and move image canvas_animal.move(canvas_image, -10, 0) timer = root.after(40, func=move_image) else: # false: timer stop and no more image moving root.after_cancel(timer) def btn_flash(fl...
The function `btn_send` validates user input against a global sheep count. If the user's input matches the current sheep count, it increments the count and triggers an image move; otherwise, it resets the count and flashes the button to indicate an error. The function also clears the input field, ensuring proper state ...
def btn_send() -> None: global sheep_count global user_count if user_count == "": user_count = 0 if int(user_count) == sheep_count: sheep_count += 1 move_image() else: # wrong input, user miscounted sheep_count = 1 btn_flash(True) btn_clear()
def get_all_experiments(self, project, subjects=None, experiments=None, **kwargs): """ Parameters ---------- project : str XNAT project name (e.g. "OASIS3") subject : [list of] str, optional XNAT subject label (or selection patt...
This function retrieves all XNAT assessor labels under a specified project, optionally filtered by subjects, experiments, or assessor patterns. It constructs full paths by combining project, subject, experiment, and assessor identifiers, returning them as a list of strings.
def get_all_assessors( self, project, subjects=None, experiments=None, assessors=None, **kwargs): """ Parameters ---------- project : str XNAT project name (e.g. "OASIS3") subject : [list of] str, optional XNAT subject label (or sel...
def get_all_experiments(self, project, subjects=None, experiments=None, **kwargs): """ Parameters ---------- project : str XNAT project name (e.g. "OASIS3") subject : [list of] str, optional XNAT subject label (or selection patt...
This function retrieves all XNAT scan paths under a specified project, optionally filtered by subjects, experiments, or scan patterns. It aggregates scans from all experiments in the project, applying filters and formatting results as full XNAT-style paths (e.g., "project/subject/experiment/scan").
def get_all_scans( self, project, subjects=None, experiments=None, scans=None, **kwargs): """ Parameters ---------- project : str XNAT project name (e.g. "OASIS3") subject : [list of] str, optional XNAT subject label (or selection p...
def test_queries(): for idx, terms in enumerate([['Democrats’', 'welfare', 'and', 'healthcare', 'reform', 'policies'], ['Drug', 'company', 'bankruptcies'], ['George', 'Bush']]): print(terms) save_query_results(bm25query(terms, 'index.txt', 'index_doc.txt'), 'bm25_tes...
This function implements a console-based query system allowing users to select between BM25 ranked retrieval, AND/OR queries, single keyword searches, or test queries. It validates user input, processes search terms, and executes corresponding search functions while looping until the user chooses to stop.
def get_query_input(): """ implements query search in console """ print('started query processor') user_input = input( 'Type 1 for BM25 ranked retrieval, 2 for an AND query, 3 for an OR query, 4 for a single keyword query, ' 't for the test queries and stop for ending the query. \n')...
def parse_matter_test_args(argv: List[str]) -> MatterTestConfig: parser = argparse.ArgumentParser(description='Matter standalone Python test') basic_group = parser.add_argument_group(title="Basic arguments", description="Overall test execution arguments") basic_group.add_argument('--tests', ...
The main task of the code is to execute a single test class from a Matter test script by parsing command-line arguments, configuring test parameters, initializing a Matter test environment with certificate authorities and controllers, and running the specified tests. It handles configuration overrides, sets up necessar...
def default_matter_test_main(argv=None, **kwargs): """Execute the test class in a test module. This is the default entry point for running a test script file directly. In this case, only one test class in a test script is allowed. To make your test script executable, add the following to your file: ...
def getFilePath(name): fullpath = os.path.join(CHIP_ROOT_DIR, name) checkFileExists(fullpath) return fullpath def detectZclFile(zapFile): print(f"Searching for zcl file from {zapFile}") path = 'src/app/zap-templates/zcl/zcl.json' data = json.load(open(zapFile)) for package in data["package...
This function parses command-line arguments for generating artifacts from .zapt templates, handling default values for template and output paths, detecting ZCL files if not specified, and determining the output directory based on user input or default logic. It returns the paths to the ZAP file, ZCL file, templates fil...
def runArgumentsParser(): default_templates = 'src/app/zap-templates/app-templates.json' default_output_dir = 'zap-generated/' parser = argparse.ArgumentParser( description='Generate artifacts from .zapt templates') parser.add_argument('zap', help='Path to the application .zap file') parser...
def checkPythonVersion(): if sys.version_info[0] < 3: print('Must use Python 3. Current version is ' + str(sys.version_info[0])) exit(1) def runArgumentsParser(): default_templates = 'src/app/zap-templates/app-templates.json' default_output_dir = 'zap-generated/' parser = ...
The main task of the code is to generate code from ZAP/ZCL files and templates, apply formatting tools (Clang/Java prettifiers) to the output, and ensure sufficient memory allocation for processing. It parses input arguments, runs generation logic, and processes the output with specified formatters to standardize code ...
def main(): checkPythonVersion() # The maximum meory usage is over 4GB (#15620) os.environ["NODE_OPTIONS"] = "--max-old-space-size=8192" zap_file, zcl_file, templates_file, output_dir = runArgumentsParser() runGeneration(zap_file, zcl_file, templates_file, output_dir) prettifiers = [ r...
def preprocess_data_series(ds): ''' Receives a pandas.Series and process it, by (i) removing null values (ii) if the type of data is numerical, it takes the logarithm of the data and then replaces inf values (due to log(0)) to -0.1 :param ds: (pandas.Series) :return: (pandas.Series) ''' d = ds.copy() d = d[...
This function calculates bias scores between a target dataframe and multiple sample dataframes for each feature. It preprocesses data if enabled, determines feature types, and computes pairwise bias scores using a specified method, storing results in a dataframe indexed by features and named by sample datasets.
def bias_score_dataframe(target_df, sample_df_dict, preprocess=True, **params): bias_df = pd.DataFrame(index=target_df.columns) for col in target_df.columns: ds1 = target_df[col] if preprocess: ds1 = preprocess_data_series(ds1) for s_name, s_df in sample_df_dict.items(): ds2 = s_df[col] if preprocess:...
def get_url(): # enter the url while True: url = input("Enter the website URL (eg. 'mikesBlog.com.au')\n") # uses my validators module for checking the expression entered for url validity if validators.validate_url(url): print("\t---->> Nice one\n") break ...
The code creates a user entry by gathering details (URL, email, username, password), encrypting the password, and storing the entry in a runtime data structure. It then persists the updated state and displays the entry.
def create_entry(this_user): url = get_url() email = get_email(this_user) username = get_username() password = get_password() encrypted_pwd = krypto.encrypt_password(password.encode()) usr = persistence.get_user_record(this_user) entry = {'url': url, 'email': email, 'password': encrypted_pwd...
def begin(): cmd(0x33) cmd(0x32) cmd(0x06) cmd(0x0C) cmd(0x28) cmd(0x01) time.sleep(0.001) def InitMPU(): bus_obj.write_byte_data(device_addr, DIV, 7) bus_obj.write_byte_data(device_addr, PWR_M, 1) bus_obj.write_byte_data(device_addr, CONFIG, 0) bus_obj.write_byte_data(device...
The code initializes sensors, calibrates, and continuously measures acceleration to calculate steps. It logs temperature, step count, and timestamp to a database in an infinite loop, with a commented-out alternative for timezone-aware data insertion. The main task is real-time step tracking and environmental data loggi...
def main(): begin() time.sleep(1) InitMPU() calibrate() total_steps = 0 while 1: pedometer_val = [] InitMPU() clear() tempC = temp() print(f'Current temperature: {tempC}\n') clear() time.sleep(1) for i in range(50): avg_...
def scale(point, minS, maxS, minPoint, maxPoint): return int(((point - minPoint) / (maxPoint - minPoint)) * (maxS - minS) + minS) def arr(color, start, end): r = math.degrees(math.atan2(start[1] - end[1], end[0] - start[0])) + 90 pygame.draw.polygon(screen, color, ( (end[0] + 10 * math.sin(math.radi...
This code visualizes a graph by rendering nodes and edges on a screen, allowing interactive operations like calculating TSP paths, shortest paths, and identifying center nodes. It scales coordinates, handles user input via buttons, and dynamically updates the display with Pygame, using tkinter for dialog inputs.
def plot_graph(self) -> None: minx = 100000.0 maxx = 0.0 miny = 100000.0 maxy = 0.0 edges = {} for i in self.graph.nodes: if self.graph.nodes[i].pos.x == 0 and self.graph.nodes[i].pos.y == 0: p_x = random.uniform(35.18, 35.213) ...
def _createMigrationTables(db: Database): cursor = db.cursor() for table in [MIGRATIONS_TABLE, CODE_MIGRATIONS_TABLE]: cursor.execute("SELECT EXISTS(SELECT * FROM information_schema.tables WHERE table_name='{}')".format(table)) if cursor.fetchone()[0]: _print("{} tabl...
The main task of the code is to perform database migration by creating migration tables, applying SQL scripts, and executing Python-based migration logic to update or transform the database schema and data systematically.
def migrate(db: Database): _createMigrationTables(db) _sqlMigrate(db) _pythonMigrate(db)
def h(config): total = 0 rows = config.shape[0] cols = config.shape[1] #to compute for every spin for i in range(rows): for j in range(cols): #each of 4 neighbours for k in range(len(dx)): nx = i + dx[k] ny = j + dy[k] i...
The code initializes a 50x50 matrix of random 0s/1s, computes its Hamiltonian, and thermally equilibrates it via 10,000 steps. It then collects 10,000 samples (every 100 steps) by repeatedly updating the matrix, storing each state. Finally, it calculates the average magnetization of these samples using the `M` function...
def initialise(): #initialise system current = np.random.choice(a=[0, 1], size=(50, 50)) #create matrix and true and false, current is the matrix HAM = h(current) #take the ham #thermalisation print('therm') import matplotlib.pyplot as plt for i in range(10000): #therm # print(i) ...
def set_difficulty(): """Creates an array of words based on the Google sheet data, to pass into generate_random_word function""" while True: print("This game has 3 modes") print("Easy") print("Difficult") print("Hard") print("press 4 to view the leader board") ...
The code defines a game function that orchestrates a password hacking game. It sets the difficulty level, checks for valid input, displays instructions, clears the screen, generates a random word from a password array, and initiates the hacking game with that word. The main task is to manage game flow, ensuring proper ...
def game(): """Orders functions for the password_hacking_game""" password_array = set_difficulty() if password_array is False: return else: game_instructions() os.system('cls||clear') random_word = generate_random_word(password_array) password_hacking_game(random_...
def extractFilePath(self): temp = self.mainWindow.windowTitle() filePath = str() if('[' in temp): s = temp.find('[') e = temp.find(']') filePath = temp[s+1:e] return filePath def changeWindowTitleTo(self, fullPath): import os self.mainW...
This method saves the content of a code editor (self.codeArea) to a file specified by self.extractFilePath(). If a valid path exists, it writes the text to the file and updates the window title. If no path is provided, it triggers a dialog to save as a new file. Finally, it notifies of a file extension change.
def saveCodeFile(self): filePath = self.extractFilePath() if(len(filePath) != 0): with open(filePath,'w') as f: f.write(self.codeArea.toPlainText()) self.changeWindowTitleTo(filePath) else: self.saveCodeFileAs() self.fileEx...
def get_model_dict(records): model_dict = {} for rec in records: for feature in rec.features: model_dict[feature.id] = feature return model_dict def delete_gene_model(seqfeature, orig_models, idx): # logging gene_name = seqfeature.qualifiers.get('Name')[0] print("delete gene...
This function updates gene models by comparing original and new models. It deletes, modifies, or adds genes in the original list based on features from the new models. It uses gene names from 'description' qualifiers, handling 'delete' tags for removal, existing genes for updates, and new entries for additions, returni...
def update_gene_model(orig_models, new_models ): # get the gene and corresponding feature orig_models_dict = get_model_dict(orig_models) # get reference index in SeqRecord list orig_index = {l.id : idx for idx,l in enumerate( orig_models )} # read the new model from apollo exported gff for rec...
def init_U(img, n_classes): U = np.zeros((img.shape[0], img.shape[1], n_classes)) for i in range(0, n_classes): for x in range(0, img.shape[0]): for y in range(0, img.shape[1]): ind = random.randint(0, n_classes-1) if i == ind: U[x][y][i] =...
This code performs image segmentation using a variant of Fuzzy C-Means (FCM) clustering with spatial kernel constraints. It initializes cluster memberships (U) and centers (V), iteratively updates them to minimize an objective function incorporating spatial information (sigma, alpha), and terminates early if changes in...
def SKFCM(img, sigma, n_classes, m, alpha, itr_times, epsilon, first=True, shared=False, x0=0, y0=0, h=0, w=0): U = init_U(img, n_classes) V = init_V(n_classes) for itr in range(0, itr_times): old_U = np.copy(U) updateV(img, U, V, n_classes, m, sigma, alpha, first, x0, y0, h, w) u...
def read_img(loc): img_type = imghdr.what(loc) if img_type is None: ds = pydicom.read_file(loc) rows = ds.get(0x00280010).value cols = ds.get(0x00280011).value # instance_number = int(ds.get(0x00200013).value) try: window_center = int(ds.get(0x00281050).valu...
The code processes a medical image slice by applying blurring and preprocessing, detecting kidney regions using `get_kidney`, and accumulating results into a destination directory. It either saves the detected kidney region or combines it with an existing image. The function returns a binary mask and detected regions f...
def process_slice(prefix, dest, side, start_num, num, rects, X, last=False, binary=None): img_origin = read_img(prefix + str(int(num)) + ".dcm") img = cv.medianBlur(img_origin, 3) img = preprocess(img) if start_num == num: kidney, binary, rects, X = get_kidney(img_origin, img, side, first=True, ...
def _tuple_stack(x, axis=1): # check if we have a list of tuples, if so then # we actually want to have a tuple of stacks if type(x[0]) is tuple: return tuple(tf.stack([xi[i] for xi in x], axis=axis) for i in range(len(x[0]))) return tf.stack(x, axis=axis) def _model_slice_inputs(inputs, i): ...
This code defines a training step for a neural network model that performs both standard and adversarial training. It computes gradients via gradient tape, updates model weights using an optimizer, applies adversarial perturbations to inputs, recalculates loss, and updates weights again. It tracks standard and adversar...
def train_step(self, data): """See :py:class:`tf.keras.Model.train_step`""" # Unpack the data. Its structure depends on your model and # on what you pass to `fit()`. if len(data) == 3: x, y, sample_weight = data else: x, y = data sample_weight ...
def winner(b, l): return ((b[0][0] == l and b[0][1] == l and b[0][2] == l) or (b[1][0] == l and b[1][1] == l and b[1][2] == l) or (b[2][0] == l and b[2][1] == l and b[2][2] == l) or (b[0][0] == l and b[1][0] == l and b[2][0] == l) or (b[0][1] == l and b[1][1] == l and...
The main task of the code is to handle a player's move in a Tic-Tac-Toe game. It updates the board with 'O' when the player clicks an empty cell, disables the button, and checks for a win or tie. If the player doesn't win, it triggers the AI's move (nextMove()), checks for an AI win, and displays messages for wins or t...
def click(r, c): global chance if (chance == True and board[r][c] == " "): board[r][c] = 'O' btn_array[r][c].configure(text='O', state=DISABLED) chance = not chance if (winner(board, 'O')): clear() return messagebox.showinfo("Winner O", "Winnnnnnerrrr") ...
def inference(encoder, model, dl, args, desc=''): model.eval() logits = [] for x in tqdm(dl, desc=desc): x = x.to(args.device) if encoder is not None: x, _ = encoder(x) _, l = model(x) logits.append(l.cpu()) logits = torch.cat(logits, dim=0) return logits...
The function `predict` generates model predictions and computes loss for evaluation. It processes logits from the model, converts them to probabilities, aggregates slide-level probabilities, and calculates final predictions. If a loss function is provided, it computes validation loss using grouped logits and true label...
def predict(model, dl, args, loss_fn=None, desc=''): dl.dataset.set_mode('eval') logits = inference(None, model, dl, args, desc) probs = process_model_output(logits, args).numpy() slide_probs = compute_slide_probs(probs, dl.dataset.slide_idxs, len(dl.dataset.df), args) preds = compute_preds(slide_pr...
def process_model_output(logits, args): if args.loss == 'ce': return F.softmax(logits, dim=1) elif args.loss in ['bce', 'masked_bce']: return torch.sigmoid(logits) elif args.loss == 'mse': return logits * args.labels_std + args.labels_mean def compute_slide_probs(tile_probs, slide_id...
This function trains a model for one epoch using a data loader, computes loss with a given loss function, performs backpropagation, and evaluates performance metrics like Cohen's kappa score. It handles encoder preprocessing, accumulates logits and targets, and returns average loss and kappa.
def train_epoch(encoder, model, dl, loss_fn, optimizer, args): model.train() cumloss = 0 all_logits, all_targets = [], [] with tqdm(total=len(dl), desc=f'Training epoch {args.epoch}') as pbar: for i, (x, y) in enumerate(dl): x, y = x.to(args.device), y.to(args.device) i...
def update_training_data(model, ds, args): ds.set_mode('eval') if args.resample_classes is not None: ds.resample(args.resample_classes) dl = make_dataloader(ds, 'train', args.valid_batch_size, shuffle=False, args=args, quiet=True) # no grads here so run on larger valid batch size logits = infere...
This function trains a model (with an optional encoder) on a dataset for specified epochs, updating training data, performing training epochs, and periodically evaluating on a validation set. It logs statistics, saves checkpoints when the validation score improves, and handles data loading and model updates. The main t...
def train(encoder, model, train_ds, valid_dl, loss_fn, optimizer, writer, args): for _ in range(args.epoch, args.epoch + args.n_epochs): args.epoch += 1 update_training_data(encoder if encoder is not None else model, train_ds, args) train_dl = make_dataloader(train_ds, 'train', args.train_b...
def getDocsConfig(lines: list[str]): docsLineRegex = r"^## (?P<category>.+?) // (?P<action>.+?)\s+(// (?P<keybinding>.+?))*##" docsConfig: list[DocsConfig] = [] for index, line in enumerate(lines): match = re.match(docsLineRegex, line) if (match): config = DocsConfig() ...
The function `getDocsList` processes a list of input lines to generate a sanitized document configuration by retrieving document settings, creating a symbol mapping, and applying sanitization, then returns the processed configuration.
def getDocsList(lines: list[str]): docsConfig = getDocsConfig(lines) symbolDict = getSymbolDict(lines) sanitizedConfig = sanitize(docsConfig, symbolDict) return sanitizedConfig
def addCanonical(run): #newData = [getCanonical(expr) for expr in run["equation"]] #newData = [] #for expr in run["equation"]: # newData.append(getCanonical(expr)) newData = map(getCanonical, run["equation"]) #print(len(newData)) run[["canonEquation", "parameters", "canonComplexity", "sim...
The code processes input CSV data by splitting it into runs, applying transformations (canonical form, removing repeats, calculating min complexity, adding thermo values), and combining runs into a single DataFrame for output. It reads input files, processes each run sequentially, modifies data columns, and writes the ...
def main(argv): inputFile = "" outputFile = "" if len(argv) != 2: print("Requires input and output file names (pandas csv)") sys.exit(2) inputFile = argv[0] outputFile = argv[1] print("reading from", inputFile) # do stuff # read in parsed data data = pd.read_csv(...
def _check_keydown_events(self,event): if event.key == pygame.K_RIGHT: self.farmer.moving_right = True elif event.key == pygame.K_LEFT: self.farmer.moving_left = True elif event.key == pygame.K_q: sys.exit() elif event.key == pygame.K_SPACE: self._fire_ketmon() def _check_keyup_events(se...
This function handles user input events in a Pygame application. It checks for quit events to exit the game, processes key presses and releases by calling dedicated methods, and detects mouse clicks to check if the play button is pressed, passing the mouse position to a method for further processing.
def _check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) elif event.type == pygame.MOUSEBUTTONDOWN: ...
def _check_fleet_edges(self): for abdulla in self.abdullas.sprites(): if abdulla.check_edges(): self._change_fleet_direction() break def _farmer_hit(self): if self.stats.farmers_left > 0: self.stats.farmers_left -= 1 self.sb.prep_farmers() self.abdullas.empty() ...
This method updates the movement of 'abdullas' (likely game entities), checks for collisions between the farmer and abdullas, triggers a hit response if collided, and verifies if any abdullas have reached the screen's bottom, handling game logic accordingly.
def _update_abdullas(self): self.abdullas.update() self._check_fleet_edges() if pygame.sprite.spritecollideany(self.farmer, self.abdullas): self._farmer_hit() self._check_abdullas_bottom()
def _check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) elif event.type == pygame.MOUSEBUTTONDOWN: ...
The main task of the code is to run the game loop by continuously checking for events, updating game elements like the farmer, ketmons, and abdullas when the game is active, and rendering the screen. The loop ensures real-time interaction and visual updates, maintaining the game's state and responsiveness.
def run_game(self): while True: self._check_events() if self.stats.game_active: self.farmer.update() self._update_ketmons() self._update_abdullas() self._update_screen()
def _normalize_main_user(username: str): """ Normalize the main user txt file. :param username: A string of the user name :return: None """ user_data = np.array([]) if os.path.exists(PATH + username): for filename in os.listdir(PATH + username): print(filename) ...
The function `create_train_file` generates an h5 file for model training by normalizing text data from txt files. It processes the main user's data and other users' data, saves the normalized results with the username in the filename, and prints "DONE!" upon completion.
def create_train_file(username: str): """ Creates the h5 file for the model to work with from the txt files. :param username: A string of the user name, to create the files names. :return: Saves the h5 file. """ _normalize_main_user(username) _normalize_other_users() _save_normalized_d...
def create_displayframe(self): frame = tk.Frame(self.root, height=200, bg=SLATE_GREY) frame.pack(expand=True, fill="both") return frame def create_displaylabels(self): total_label = tk.Label(self.displayframe, text=self.total_exp, anchor=tk.E, bg=SLATE_GREY, ...
This code initializes a Tkinter-based calculator GUI, setting up the main window, display frames for expressions, digit/operator buttons, and their layout. It configures button grid positions, creates interactive elements like clear and equals buttons, and launches the application's main event loop to enable user inter...
def __init__(self): #creating the basic window for the calculator self.root = tk.Tk() self.root.geometry("320x500") self.root.title("Calculator") self.total_exp = "" self.current_exp = "" self.displayframe = self.create_displayframe() self.total_label, s...
def ensure_network_exists(args, gcloud_compute, network_name): """Create the specified network if it does not already exist. Args: args: The Namespace returned by argparse gcloud_compute: Function that can be used for invoking `gcloud compute` network_name: The name of the network Raises:...
The function `prepare` executes pre-creation tasks for a Google Cloud VM, ensuring necessary resources like networks, firewalls, disks, and repositories exist. It validates or creates a network, configures firewall rules (if enabled), provisions a disk, and sets up subnets/private IP access if specified. It also create...
def prepare(args, gcloud_compute, gcloud_repos): """Run preparation steps for VM creation. Args: args: The Namespace instance returned by argparse gcloud_compute: Function that can be used to invoke `gcloud compute` gcloud_repos: Function that can be used to invoke `gcloud source repo...
def keyExpansion(self, key, nk, nr): # key = 0x2b7e151628aed2a6abf7158809cf4f3c (128 bit) w = [] nb = 4 i = 0 while i < nk: w.append( (key >> (32 * (nk - i - 1))) & 0xFFFFFFFF) i += 1 # after the for loop => w = [2b7e1516, 8aed2a6a, bf715880, 09cf...
This code implements AES encryption (128/192/256-bit) by processing input data through multiple rounds of substitution, shifting, mixing, and key addition operations. It logs detailed encryption steps—including plaintext, key, round states, and intermediate values—into 'output.txt', following AES specifications for Nb=...
def cipher(self, input, key, nk, nr, bit_len): file = open("output.txt", "a") if bit_len == 128: file.write("C.1 AES-128 (Nk=4, Nr=10)\n") elif bit_len == 192: file.write("C.2 AES-192 (Nk=6, Nr=12)\n") elif bit_len == 256: file.write("C.3...
def eliminate_implication(root): T = root.children # traverse the children for branch in T: if type(branch) == Node and branch.type == 'Op': if branch.name == "→": branch.name = "V" branch.children = [ Node("¬", children=[branch.childre...
The code converts a knowledge base (KB) into Conjunctive Normal Form (CNF) by applying a sequence of transformations: eliminating implications, moving negations inward, standardizing variables, repositioning quantifiers, Skolemization, dropping universal quantifiers, distributing disjunctions, and splitting into clause...
def convert_to_cnf(KB): cnf = [] for sentence in KB: eliminate_implication(sentence) move_negations_inside(sentence) standardize_variables(sentence) sentence = move_quantifiers_left(sentence) skolemization(sentence) sentence = drop_universal_quantifiers(sentence) ...
def ReadOrbitalData(): #Takes in data for the two planets orbit_data = np.loadtxt('OrbitData.csv', delimiter =",", skiprows = 1) return orbit_data def Distance(T): t=0 d1=0 d2=0 T=T while t<T: d1 = d1 + 1 t = t + DeltaT(d1)[0] t=0 while t<T: d2 = d2 + 1 ...
The code calculates the Cartesian coordinates (x, y) of two orbiting bodies at time T using their orbital elements (eccentricity, semi-major axis) and distance functions. It converts polar coordinates to Cartesian coordinates, applying the elliptical orbit equation to determine positions.
def XandY(T): e1 = ReadOrbitalData()[0][0] e2 = ReadOrbitalData()[1][0] a1 = ReadOrbitalData()[0][1]*10**10 a2 = ReadOrbitalData()[1][1]*10**10 d1 = Distance(T)[0] x1 = Radius(d1)[0]*np.cos(d1) y1 = np.sqrt((1-e1)*(a1**2-x1**2)) d2 = Distance(T)[1] x2 = Radius(d2)[1]*np.cos(d2) y...
def init_world(self): while True: try: # Connect to carla self.client = carla.Client(self.host, self.port) self.client.set_timeout(self.timeout) # Create world wrapper if self.town: self.world = World...
The code resets a CARLA simulation environment by initializing the world, setting a destination waypoint, spawning a vehicle at a specified or random location, attaching sensors (cameras, bird's-eye view), initializing observation buffers, and preparing for a new episode. It handles both predefined and random routes, c...
def reset(self, **kwargs): self.init_world() if self.world is not None: self.world.destroy() # Get destination waypoint if self.dst_loc: self.goal_wp = self.world.map.get_waypoint(carla.Location(x=self.dst_loc[0], y=self.dst_loc[1])) else: spa...
def nInit(self, param=None): ''' This method initializes the neural network variables, it is already implemented for you. Check it and relate to the mathematical description above. You are going to use these variables in forward and backward propagation. ''' if param is...
This function implements gradient descent to optimize model parameters by iteratively performing forward and backward propagation on the full dataset. It updates weights using computed gradients, appends loss values to self.loss at every 1000th iteration, and prints progress. Parameters include input data (x), labels (...
def gradient_descent(self, x, y, iter = 60000, use_momentum=False, local_test=False): ''' This function is an implementation of the gradient descent algorithm. Notes: 1. GD considers all examples in the dataset in one go and learns a gradient from them. 2. One iteration here is ...
def nInit(self, param=None): ''' This method initializes the neural network variables, it is already implemented for you. Check it and relate to the mathematical description above. You are going to use these variables in forward and backward propagation. ''' if param is...
The main task of the code is to implement batch gradient descent by iteratively processing mini-batches of input data, computing predictions and losses, and updating model parameters via backpropagation. It handles batch indexing, supports momentum, and logs loss and batch data at specified intervals (every 1000 iterat...
def batch_gradient_descent(self, x, y, iter = 60000, use_momentum=False, local_test=False): ''' This function is an implementation of the batch gradient descent algorithm Notes: 1. Batch GD loops over all mini batches in the dataset one by one and learns a gradient 2. One iter...
def _init_components(self, **kwargs): # [5pts] """ Args: kwargs: any other arguments you want Return: pi: numpy array of length K, prior mu: KxD numpy array, the center for each gaussian. sigma: KxDxD numpy array, the diagonal standard deviation o...
The code implements the Expectation-Maximization (EM) algorithm to estimate parameters (pi, mu, sigma) of a probabilistic model. It iteratively performs E-step (computing posterior cluster assignments gamma) and M-step (updating parameters) until convergence, determined by absolute/relative tolerance thresholds on the ...
def __call__(self, full_matrix=FULL_MATRIX, abs_tol=1e-16, rel_tol=1e-16, **kwargs): # No need to change """ Args: abs_tol: convergence criteria w.r.t absolute change of loss rel_tol: convergence criteria w.r.t relative change of loss kwargs: any additional arguments...
def bias_augment(self, x: np.ndarray) -> np.ndarray: # [3pts] """Prepend a column of 1's to the x matrix Args: x (np.ndarray): (N, D) numpy array, N data points each with D features Returns: x_aug: (np.ndarray): (N, D + 1) numpy array, N data points each with a column o...
Your returnThe code implements gradient descent to train a logistic regression model by iteratively updating parameters (weights and bias) using training data. It initializes parameters, computes predicted probabilities, calculates gradients, and adjusts theta with the learning rate. Periodically, it evaluates training...
def fit( self, x_train: np.ndarray, y_train: np.ndarray, x_val: np.ndarray, y_val: np.ndarray, lr: float, epochs: int, ) -> Tuple[ np.ndarray, List[float], List[float], List[float], List[float], List[int] ]: # [5pts] """Use gradient descent...
def spAND(inputs): s = inputs[0] for i in range(1, len(inputs)): s *= inputs[i] return s def spOR(inputs): s = 1-inputs[0] for i in range(1, len(inputs)): s *= (1-inputs[i]) return 1-s def spXOR(inputs): s = sp2XOR(inputs[0], inputs[1]) for i in range(2, len(inputs)): ...
This function processes a logical gate element by evaluating its input signals from the SignalsTable, applying the corresponding Boolean operation (AND, OR, XOR, etc.), and updating the SignalsTable with the computed output value for the element's output pin.
def process(element, SignalsTable): inputs = [] for i in element.inputs: inputs.append(SignalsTable[i]) if element.type == 0: # AND SignalsTable[element.output] = spAND(inputs) elif element.type == 1: # OR SignalsTable[element.output] = spOR(inputs) elif element.type == 2: ...
def setInputs(inputs, inputKeys, signalTable): sTable = copy.deepcopy(signalTable) for i in range(0, len(inputKeys)): sTable[inputKeys[i]] = inputs[i] return sTable def process(element, SignalsTable): inputs = [] for i in element.inputs: inputs.append(SignalsTable[i]) if element....
The function calculates a score for each individual in IndividualsTable by comparing signal changes (switches) before and after processing two workloads through circuit elements. It sets inputs for each workload, applies processing steps using ElementsTable, copies signal states, and computes switches between states to...
def calculateScores(IndividualsTable, ElementsTable, sortedCircuit, signalsTable): for i in range(0, len(IndividualsTable)): SignalsTable1 = setInputs(IndividualsTable[i].workload[0], sortedCircuit[1], signalsTable) for j in ElementsTable: SignalsTable1 = process(j, SignalsTable1) ...
def setInputs(inputs, inputKeys, signalTable): sTable = copy.deepcopy(signalTable) for i in range(0, len(inputKeys)): sTable[inputKeys[i]] = inputs[i] return sTable def process(element, SignalsTable): inputs = [] for i in element.inputs: inputs.append(SignalsTable[i]) if element....
The function evaluates each individual in a population by simulating signal transitions through their workload, counting state changes (switches) between signal states before and after processing each element. It assigns the total switches as the individual's score, then selects parent individuals for reproduction usin...
def measurePopulation(population, signalsTable, tlpinputs, ElementsTable): for individual in population.individuals: switches = 0 signalsBefore = copy.deepcopy(signalsTable) for input in individual.workload: SignalsTable1 = setInputs(input, tlpinputs, signalsBefore) ...
def readCircuit(): with open('circuit.txt') as f: lines = [line.rstrip('\n') for line in f] inputs = lines[0].split()[1:] flag = [lines[1:], inputs] while len(flag) != 1: flag = sort(flag[0], flag[1]) return [[lines[0]]+flag[0], inputs] def preprocess(circuit): ElementsTable =...
The code implements an evolutionary algorithm to optimize circuit design by generating populations of individuals with random workloads, evaluating their fitness scores, and evolving them through generations via crossover and mutation. It compares three population runs, visualizes score trends, and saves results to a f...
def main(): Individuals = 2000 sortedCircuit = readCircuit() pp = preprocess(sortedCircuit) ElementsTable = pp[0] SignalsTable = pp[1] cleanSignalsTable = copy.deepcopy(SignalsTable) # print(SignalsTable) # 4.1 IndividualsTable = [] for i in range(0, Individuals): randWo...
def _make_instantiation_root(self): return ET.Element( "InstantiateVAppTemplateParams", {'name': self.name, 'xml:lang': 'en', 'xmlns': "http://www.vmware.com/vcloud/v0.8", 'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance"} ) def _add_...
The main task of the code is to construct an XML tree structure for instantiation parameters. It creates a root element, adds a VApp template, and generates sections for product details, virtual hardware, and network configurations. The function builds the "InstantiationParams" element, including subelements for produc...
def _build_xmltree(self): self.root = self._make_instantiation_root() self._add_vapp_template(self.root) instantionation_params = ET.SubElement(self.root, "InstantiationParams") # product and virtual hardware self._make_product_sec...
def generate_cluster_pairs(clusters_list): """ Return a dictionary-valued dictionary indexed by the cluster pairs. The indices are 2-tuples, whose elements are the clusterIDs. Despite this, each pair is conceptually considered to be an unordered pair, and hereby appearing only once. This dictio...
The code performs multiple iterations (num_iterations) of sampling 30% of clones randomly, simulating data distributions, and calculating the median ratio of observed to expected metric values for each cluster pair. It iteratively computes these ratios, stores them, and returns the median across all iterations for each...
def compute_distributions(csv_data_clone_cells, num_iterations , cluster_pairs, clusters, clusters_names, clones): """ Return distribution median for each cluster pair. Do the num_iterations iterations of random 30% samples of clones and subsequent simulation, and return the median metric value of ...
def _get_plug_state_int(self, state, reverse=False): if state.lower() == 'on': if reverse: state_int = 0 else: state_int = 1 elif state.lower() == 'off': if reverse: state_int = 1 else: state...
The main task of the code is to toggle the state of specified electrical plugs by constructing and sending a JSON relay command. It converts input parameters into a formatted command string, including plug identifiers and desired state, then executes the command via a protocol-specific send method.
def toggle_plugs(self, state, plug_num_list=None, plug_name_list=None): state_int = self._get_plug_state_int(state) plug_id_list_str = self._get_plug_id_list_str(plug_num_list=plug_num_list, plug_name_list=plug_name_list) all_relay_command = '{"context":{"child_ids":' + plug_id_list_str + '},...
def _get_plug_state_int(self, state, reverse=False): if state.lower() == 'on': if reverse: state_int = 0 else: state_int = 1 elif state.lower() == 'off': if reverse: state_int = 1 else: state...
This function toggles a smart plug's state by converting the input state to an integer, identifying the plug via its number/name, constructing a JSON relay command with the plug ID and state, then sending it through a protocol to control the device.
def toggle_plug(self, state, plug_num=None, plug_name=None): state_int = self._get_plug_state_int(state) plug_id = self._get_plug_id(plug_num=plug_num, plug_name=plug_name) relay_command = '{"context":{"child_ids":["' + plug_id + '"]},' + \ '"system":{"set_relay_state"...
def clear_safe(self, plug_num=None, plug_name=None, id=None): if id == None and plug_num == None and plug_name == None: relay_command = '{"count_down":{"delete_all_rules":null}}' elif plug_name != None or plug_num != None: plug_id = self._get_plug_id(plug_num=plug_num, ...
The code toggles a plug's state and sets a delayed countdown to turn it off, using retry logic if command sending fails. It retrieves the plug's ID, sends a relay command with a countdown rule, and fetches updated rules afterward.
def timed_toggle(self, state, plug_num=None, plug_name=None, delay=5, retry=True): self.clear_safe(plug_num=plug_num, plug_name=plug_name) self.toggle_plug(state, plug_num, plug_name) plug_id = self._get_plug_id(plug_num=plug_num, plug_name=plug_name) relay_command = '{"conte...
def crawl_countries(): url = "https://en.wikipedia.org/wiki/List_of_countries_by_population_(United_Nations)" r = requests.get(url) doc = lxml.html.fromstring(r.content) countries_lst = doc.xpath("""//table[contains(@class, 'wikitable')] //tr/td[1][not(contains(text(), '('))]//@ti...
The main task of the code is to construct an ontology by crawling data from countries, country-related information, and people, then serializing the resulting graph data into a standardized NT format file named "ontology.nt" for storage or sharing.
def build_ontology(): crawl_countries() crawl_data_from_countries() crawl_data_from_people() g.serialize("./ontology.nt", encoding="utf-8", format="nt", errors="ignore")
def get_accession(path): if get_lines(path,'DBREF'): PDB_accession=get_lines(path,'DBREF')[0][7:11] UP_accession= [line[33:].split()[0] for line in get_lines(path,'DBREF')] if (PDB_accession)=='XXXX': return UP_accession[0] else: return PDB_accession else...
The main task of the code is to generate a CSV metadata file containing details like file names, accession numbers, coverage statistics, and other properties from each file in a specified directory. It lists all files, extracts metadata using helper functions, writes the data into a "Metadata.csv" file, and outputs the...
def get_metadata(directory_path,op_path=None): if op_path==None: op_path=directory_path csv_file_path=os.path.join(op_path,'Metadata.csv') files = os.listdir(directory_path) # List all files in the folder with open(csv_file_path, 'w', newline='') as csv_file: csv_writer = csv.wr...