dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_vbo(self): vertex_data=self.get_vertex_data() vbo=self.ctx.buffer(vertex_data) return vbo def get_shader_program(self,shader_name): with open(f'shaders/{shader_name}.vert')as file: vertex_shader = file.read() with open(f'shaders/{shader_name}.frag')as file: ...
This code initializes a graphics rendering component by setting up a vertex buffer object (VBO), shader program, vertex array object (VAO), model matrix, and texture. It configures OpenGL resources for rendering 3D objects, using a provided application context and default shaders, then triggers initialization logic via...
def __init__(self,app): self.app=app self.ctx=app.ctx self.vbo=self.get_vbo() self.shader_program=self.get_shader_program('default') self.vao=self.get_vao() self.m_model=self.get_model_matrix() self.texture=self.get_texture(path='texture/a.jpg') self.on_in...
def _get_partition(self, partition_key: str) -> _Partition: """Read partition from files""" partition_hash = Dynafile._hash_key(partition_key) partition = self._partitions.get(partition_hash) if partition is None: partition = self._new_pratition(partition_hash) se...
This method retrieves an item from a partition using the provided key's primary and sort keys, checks if the item is expired based on TTL, and returns the item or None if expired.
def get_item(self, *, key: dict) -> Optional[dict]: pk = key.get(self._pk_attribute) # if pk is None: # raise Exception("Partition key have to be set") partition = self._get_partition((pk)) sk = key.get(self._sk_attribute) # if sk is None: # raise Excepti...
def __parse_filter(self, _filter: Optional[Filter]) -> Callable: if _filter is None: return bool elif callable(_filter): return _filter elif type(_filter) is str: try: import filtration return filtration.Expression.parseString(...
The code scans files in a partition path, applies a filter to items, deletes those marked for deletion by TTL, and yields filtered items.
def scan(self, _filter: Optional[Filter] = None) -> Iterable[dict]: _filter = self.__parse_filter(_filter) for file in self._partition_path.glob("*/"): partition = _Partition(path=file, sk_attribute=self._sk_attribute) for item in partition.query(None, True): if ...
def __parse_filter(self, _filter: Optional[Filter]) -> Callable: if _filter is None: return bool elif callable(_filter): return _filter elif type(_filter) is str: try: import filtration return filtration.Expression.parseString(...
This method retrieves items from a partition using a primary key, applies optional filters, checks for time-to-live (TTL) expiration, and yields valid items while handling deletions.
def query( self, pk, *, starts_with="", scan_index_forward=True, _filter: Optional[Filter] = None, ) -> Iterable[dict]: _filter = self.__parse_filter(_filter) partition = self._get_partition(pk) for item in partition.query( starts_...
def prepare_combinations_file(metadata_loc,N,tr_times): metadata = pd.read_csv(metadata_loc,index_col=0) d_c_t_ps = ["%s_%0.2f_%0.0f"%names for names, group in \ metadata.groupby(["Drug","Concentration","Treatment time (hrs)"])\ if float(names[2]) >= min(tr_times) and float(names[2]...
The script `MLSynergy.py` processes drug combination data using machine learning. It supports two commands: `Make_combinations` (generates drug combination files from metadata) and `Score_combinations` (predicts synergy scores using a trained model). Key tasks include data normalization, combination generation, score c...
def main(argv): #### help strings help_str1 = "MLSynergy.py --command <> --[conditional]classifier <> --[conditional]metadata <> --[conditional]combinaitons --[conditional]data <> --[conditional]ref_ids <> --output [OPTIONS]" options_str2 = "--help or -h: Display description of options\n\ --command or -c: <...
def get_mtr_df(file_name=None, amz_setting=None): amz_setting = frappe.get_cached_doc("Amazon SP Settings", amz_setting) is_b2b, df, items = False, None, [] if not file_name: for d in frappe.get_all( "File", {"file_name": ["like", "GST_MTR_B2%"]}, order_by="creat...
The function processes Amazon MTR files to generate Sales Invoices in ERPNext. It validates data, constructs invoice details (customer, items, taxes), handles B2B/B2C specifics, creates and submits invoices, logs entries, and manages errors.
def process_mtr_file(file_name=None, amz_setting=None, submit=True): df = get_mtr_df(file_name, amz_setting) if not len(df): frappe.throw("No Order lines to import in file.") amz_setting = frappe.get_cached_doc("Amazon SP Settings", amz_setting) amz_common = frappe.get_single("Amazon SP Common ...
def load_data(cifar=False, one_hot_labels=False, normalize=False, flatten=False, full=False): ''' A function to load the MNIST (CIFAR) data and create an input and target set for both training and testing :param cifar: use cifar data set :param one_hot_labels: whether to transform labels into one hot...
The function creates data loaders for a federated learning setup, splitting training data into IID or non-IID distributions across clients. It optionally includes a validation set and handles mixed non-IID splits. It returns training loaders per client, a validation loader, and a test loader for federated training and ...
def get_data_loaders(batch_size, num_clients, iid_split=True, percentage_val=0.2, full=False, non_iid_mix=0): ''' A function to create the data loaders for each client in the Federated Learning Setup :param batch_size: set the number of samples in a batch for each client :param nu...
def readData(filepath: str) -> List: """ Function to read the data from a csv file """ with open(filepath, "r") as f: reader = csv.reader(f) data = list(reader) return data def parseData(csv_data: List) -> Dict: """ Function to parse the data into a list of Course objects """ courses...
The code reads course data, parses it, prompts the user to select courses, generates possible schedules, translates them into matrix formats, and displays them interactively for the user to review and cycle through.
def main(): csv_data = readData("CourseData.csv") total_course_dict = parseData(csv_data) user_courses = userPrompt(total_course_dict) user_course_list = organizeCourses(user_courses, total_course_dict) # Print the user's selected courses in the dictionary format # print("\033c", end="") ...
def userPrompt() -> List: """ Function to prompt the user for a course name """ # Clear the terminal print("\033c", end="") # Print a welcome splash screen print("Welcome to the UO Schedule Data Parser!") # Prompt a input splash screen term_output = "Please enter a term to search for.\nEx...
The code's main task is to generate and display possible course schedules for a user based on their selected courses. It reads course data from a database, parses and organizes it, identifies valid base schedules, translates them into time matrices, and iteratively prints each potential schedule in a matrix format. The...
def main(): user_courses = userPrompt() DB_data = readDB(user_courses) total_course_dict = parseData(DB_data) user_course_list = organizeCourses(user_courses, total_course_dict) # Print the user's selected courses in the dictionary format print("\033c", end="") print("Possible Schedule...
def readDB(user_courses: List) -> List: """ Function to read the data from the database """ # Extract the first element from each tuple in the list connection = None cursor = None try: connection = mysql.connector.connect(**db_config) cursor = connection.cursor() qu...
The main task of the code is to generate and return feasible course schedules in a matrix format based on user-provided course codes. It handles CORS preflight requests, validates input data, fetches and processes course data from a database, generates base schedules, expands them into full schedules, limits results to...
def lambda_handler(event, context): # Handle OPTIONS requests for CORS if event['httpMethod'] == 'OPTIONS': return { 'statusCode': 200, 'headers': { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access...
def stop_timer(self): self.t1 = time.time() def get_time(self): return self.t1 - self.t0 def print_board(self): """" Prints the move numbers of the solved chess board """ print(" ") print("------") for elem in self.board: print(elem) # column...
The code implements a recursive knight's tour algorithm to find a path where a knight visits every square on a chessboard exactly once. It uses backtracking with Warndorff's heuristic (optional) to explore neighbors, marks visited positions, tracks the path, and terminates when all squares are covered or no valid moves...
def tour(self, start_pos, wand): """ Recursive definition of knights tour. Inputs are as follows: start_pos = starting position wand = option to use Warndorfs heuristic on pathfinding """ self.board[start_pos[0]][start_pos[1] ] = self.visi...
def get_board_size(): columns = int(input("Enter the number of columns: ")) check_user_input(columns) rows = int(input("Enter the number of rows: ")) check_user_input(rows) starting_column = int(input("Enter the starting column: ")) check_user_input(starting_column) starting_row = int(input(...
(The code's main task is to determine a chessboard's size, compute a valid route (e.g., knight's tour), and visualize the result. It first retrieves the board dimensions, calculates a path covering all squares, then displays the route on the board.)
def main(): chessboard = get_board_size() chessboard = calculate_route(chessboard) visualise_board(chessboard)
def get_incidents(): incidents = [] for incident in app.database.incidents.find(): incident["id"] = str(incident.pop("_id")) incidents.append(incident) return { "data": incidents, "metadata": { "amount": len(incidents) } } def get_components(): com...
The function `status()` aggregates and returns system status data as a JSON response, combining incident reports, component statuses, and overall system status retrieved from three separate functions: `get_incidents()`, `get_components()`, and `get_status()`. This likely provides a consolidated view of system health fo...
def status(): return jsonify({ "incidents": get_incidents(), "components": get_components(), "status": get_status() })
def get_incidents(): incidents = [] for incident in app.database.incidents.find(): incident["id"] = str(incident.pop("_id")) incidents.append(incident) return { "data": incidents, "metadata": { "amount": len(incidents) } } def get_components(): com...
The function `status_raw` aggregates and returns system status data in JSON format by combining incident data, component details, current status, and metadata from separate functions, providing a consolidated API response for monitoring or dashboard purposes.
def status_raw(): return jsonify({ "incidents": get_incidents()['data'], "components": get_components()['data'], "status": get_status(), "metadata":metadata() })
def rearrange_vector(vec): rob_po = vec % 100 cop_po = int(vec / 100) cop_agents = int(len(str(cop_po)) / 2) cop_list = [] for ca in range(cop_agents): if ca == 0: cop_list.append(int(cop_po % 100)) else: cop_list.append(int(cop_po / (10 ** 2 ** ca) % 100)) ...
The code generates valid game state vectors for a specified number of players and grid size. It either loads precomputed vectors from a file or generates them by iterating through numbers, checking validity, and ensuring uniqueness. The function returns two lists: one with all valid vectors and another with the final c...
def createVecs(numOfPlayers, max_grid=9): full_vecs = [0] vecs = [0] path = f"tests/vecs{numOfPlayers}{max_grid}.txt" if os.path.exists(path): with open(path, 'r') as fr: vecs = fr.read()[1:-1] vecs = list(vecs.split(", ")) vecs = list(map(int, vecs)) else...
def next_positions(pl_turn, list_of_position, max_digit=10): cop_po = list_of_position[0] rob_po = list_of_position[1] res_po = [] if pl_turn == 1: # cop turn for cp in cop_po: i = cp[0] j = cp[1] if i > 1 and [i - 1, j] not in cop_po: if len(...
This function generates and writes transition rules for a game state machine. It processes vector states from l_vecs, calculates next states using next_positions and copWin logic, filters valid transitions, selects maximum value states from p1, and writes formatted rules to a file, skipping invalid states and ensuring ...
def writeCop(p1, l_vecs, max_digit, filename): if os.path.exists(filename): os.remove(filename) with open(filename, 'w') as fw: for s in l_vecs: if s == 0: continue swpos = str(s) wpos = [[], []] for lw in range(int(len(swpos[:-2]) ...
def next_positions(pl_turn, list_of_position, max_digit=10): cop_po = list_of_position[0] rob_po = list_of_position[1] res_po = [] if pl_turn == 1: # cop turn for cp in cop_po: i = cp[0] j = cp[1] if i > 1 and [i - 1, j] not in cop_po: if len(...
The main task of the code is to generate and write state transition rules into a file. It processes vectors from `l_vecs`, calculates their next states using position logic and `copWin` checks, filters valid transitions, selects maximum-value states from `p1.states_value`, and formats the results in a structured syntax...
def writeCop1(p1, l_vecs, max_digit, filename): if os.path.exists(filename): os.remove(filename) with open(filename, 'w') as fw: for s in l_vecs: if s == 0: continue swpos = str(s) wpos = [[], []] for lw in range(int(len(swpos[:-2])...
def writeStart(l_v, filename): if os.path.exists(filename): os.remove(filename) # return with open(filename, 'w') as fw: fw.write("MODULE main\n\nVAR\n vec : ") lw = '{0, ' for av in l_v: if av == 0: continue lw = lw + 'v' + str(av) + ', '...
The function `writeSmv` generates an SMV file by concatenating pre-generated text files. It removes an existing main file, then writes content from three files (`add_start_*.txt`, `*playersnextR*.txt`, `*playersnextC*.txt`) and a fixed `add_end.txt` into the main SMV file. Each section is created by helper functions (`...
def writeSmv(numOfPlayers, max_digit, p1, all_vecs, l_vecs): filename_main = 'tests/test_t3.smv' if os.path.exists(filename_main): os.remove(filename_main) with open(filename_main, 'w') as fw: filename_start = f'tests/add_start_{numOfPlayers}{max_digit}.txt' writeStart(l_vecs, filena...
def writeStart1(l_v, filename): if os.path.exists(filename): os.remove(filename) # return with open(filename, 'w') as fw: fw.write("MODULE main\n\nVAR\n vec : ") lw = '{0, ' for av in l_v: if av == 0: continue lw = lw + 'v' + str(av) + ', ...
The function `writeSmv1` generates an SMV model file by concatenating precomputed components. It deletes an existing `test_t3.smv` file, then writes content from three dynamically named text files (`add_start_...`, `nextR...`, `nextC...`) and a fixed `add_end_LTL.txt`, each generated by helper functions. The output com...
def writeSmv1(numOfPlayers, max_digit, p1, all_vecs, l_vecs): filename_main = 'tests/test_t3.smv' if os.path.exists(filename_main): os.remove(filename_main) with open(filename_main, 'w') as fw: filename_start = f'tests/add_start_{numOfPlayers}{max_digit}.txt' writeStart1(l_vecs, file...
def get_df_img_batch(df_batch, np_dir=NUMPY_DIR): n_images = (df_batch.rmax - df_batch.rmin).sum() b_images = np.zeros((n_images, 240, 240, 4), np.float32) b_label = np.zeros((n_images, 240, 240, 4), np.int8) ind=0 for index, row in df_batch.iterrows(): b_i...
This function generates training batches for a machine learning model by combining randomly sampled images from a DataFrame with images of specific labels (1 and 3). It creates batches of size `batch_size` with normalized images and categorical labels, shuffling data to ensure diversity. The batch includes half randoml...
def generate_faste_train_batch(batch_size = 12, df = df_train ,np_dir=NUMPY_DIR): # *** COMMENT ABOVE LINE AND UNCOMMENT BELOW LINE TO RUN WITH NO BOUNDING BOX, AND VICE-VERSA *** # def generate_faste_train_batch(batch_size = 12, df = df_train_full_img ,np_dir=NUMPY_DIR): batch_images = np.zeros((batch_si...
def train_net_fedavg(self, epochs, lr, args_optimizer, loss_fn, args, specified_data_loader = None, device="cpu"): if specified_data_loader is None: specified_data_loader = self.train_loader logger.info('n_training: %d' % len(specified_data_loader.sampler)) train_ac...
The function trains a local model using specified federated learning algorithms (fedavg, solo, fedprox, fedcoad), adjusting epochs and parameters accordingly. It logs training details, executes the chosen training method, records test accuracy, and returns training/test accuracies while managing device placement for mo...
def local_train_net(self, args, global_model, loss_fn = nn.CrossEntropyLoss(), round=None, c_global=None): if global_model: global_model.to(self.device) if c_global is not None: c_global.to(self.device) logger.info(f"Training network {self.id} n_trai...
def speechInput(): r = sr.Recognizer() with sr.Microphone() as source: print("Please wait. Calibrating microphone...") r.adjust_for_ambient_noise(source, duration=1) print("Say something!") global t_begin t_begin = time.time() audio = r.listen(source) ...
The code processes speech input, calculates latency, and triggers predefined responses. If the input is "sing a song," it plays an audio file; for "what is your name" or "hello," it displays and speaks specific replies. For other inputs, it uses a responder function to generate responses, updating the UI and vocalizing...
def call(): speech=speechInput() global t_end t_end = time.time() print("latency:",t_end-t_begin) if speech=="sing a song": reply.configure(text="playing") playsound.playsound('still_alive.mp3') elif speech == "what is your name": response="I'm Margot" reply.confi...
def __makePointBlock(self, mesh): block = VMAP.sPointsBlock(mesh.NPoints()) pts = mesh.points() for i in range(mesh.NPoints()): #print("{}: {}/{}/{}; {}".format(i+1, pts[i][0], pts[i][1], pts[i][2], type(pts[i][0]))) block.setPoint(i, i+1, float(pts[i][0]), float(pts[i][1...
This method writes mesh data to a file by generating point and element blocks, adding a specified name as a string attribute if provided, and ensuring element types are defined. It uses the vmapRoot object to write points, elements, and element types, marking the elements as written upon completion.
def writeMesh_vedo(self, mesh: str, name=""): print("Writing PointBlock") #self.handler.vmap.writePointsBlock(self.path, pb) self.vmapRoot.writePointsBlock(self.path, self.__makePointBlock(mesh)) #self.handler.vmap.writeElementsBlock(self.path, self.__makeElementsBlock(mesh)) sel...
def getElementBlock(self, update=False): if not self.elementsRead or update: self.elementBlock = VMAP.sElementBlock() self.vmapRoot.readElementsBlock(self.path, self.elementBlock) self.elementsRead = True self.elementsParsed = False return self.elementBloc...
The code parses mesh elements into faces and tetrahedrons (tets) by checking element types, reading connectivity data, and categorizing elements into faces (triangles/quads) or tets (tetrahedrons/pyramids/hexes/wedges) using specific node indices. It updates internal lists (`faces`, `tets`) if parsing is needed, return...
def getElements(self, update=False): if not self.elementsParsed or update: if not self.elementsRead: self.getElementBlock(update) if not self.elemTypesRead: self.getElementTypes(update) if not self.pointsRead: self.getPoints(upd...
def get_module_adjacency_list(top_level_module, use_queryview): # The main module graph containing _all_ modules in the Soong build, # and the list of converted modules. try: module_graph, converted = generate_module_info(top_level_module, use_queryview) ex...
This script processes command-line arguments to generate either dependency graphs or reports for specified Soong modules. It uses `queryview` or `module_info` based on the flag, processes each module's adjacency list, and either creates DOT files for graphs or aggregates report data. For "report" mode, it combines modu...
def main(): parser = argparse.ArgumentParser(description="") parser.add_argument("mode", help="mode: graph or report") parser.add_argument( "--module", "-m", action="append", help="name(s) of Soong module(s). Multiple modules only supported for report" ) parser.add_argument( "--u...
def calc_nearest_index(state, cx, cy, cyaw): dx = [state.x - icx for icx in cx] dy = [state.y - icy for icy in cy] d = [idx ** 2 + idy ** 2 for (idx, idy) in zip(dx, dy)] mind = min(d) ind = d.index(mind) mind = math.sqrt(mind) dxl = cx[ind] - state.x dyl = cy[ind] - state.y an...
The code simulates closed-loop trajectory tracking for a vehicle to reach a goal. It uses PID control for speed and rear-wheel feedback for direction, updating the vehicle's state iteratively. The loop checks proximity to the goal, stopping when within a threshold. It logs trajectory data (position, yaw, velocity) and ...
def closed_loop_prediction(cx, cy, cyaw, ck, speed_profile, goal): T = 500.0 # max simulation time goal_dis = 0.3 stop_speed = 0.05 state = State(x=-0.0, y=-0.0, yaw=0.0, v=0.0) time = 0.0 x = [state.x] y = [state.y] yaw = [state.yaw] v = [state.v] t = [0.0] goal_flag = F...
def buildRRT(MAXPOINT,rcv): path = np.ones(MAXPOINT, dtype=np.float64 ) * np.NaN rrt_obj = rrtInit(rcv) #print("rrt_obj initialzed") rrt_obj.get_path(path) path = np.delete(path,np.where(np.isnan(path))[0],0) #delete the nan values in numpy list return rrt_obj,path def drawpath(dbg,path): ...
The code implements rear-wheel feedback tracking using RRT (Rapidly-exploring Random Tree) path planning and spline interpolation. It initializes communication ports, constructs a path with RRT, processes coordinates for trajectory generation, calculates a smoothed spline course, sets target speed profiles, and perform...
def main(): print("rear wheel feedback tracking start!!") ip = "127.0.0.1" MAXPOINT = 20 # receive from the port rcvport = 23333 dbgport = 20001 dbg = Dbg(dbgport,ip) print ("clock2:{}".format(time.process_time_ns())) rcv = Rcv(rcvport,ip) cmdport = 50001 cmd = Cmd(cmdport,...
def analyze_HFSS(self): print('Running HFSS analysis...') try: with redirect_stdout(io.StringIO()) as f: self.hfss_instance.analyze() except: print('HFSS analysis failed.') print('...done!') def run_EPR(self): print('Running pyEPR...') ...
The main task of the code is to iteratively optimize a design by updating variables, analyzing electromagnetic simulations (HFSS), calculating performance parameters (EPR), and checking convergence status, with a maximum iteration limit to prevent infinite loops.
def iterate_loop(self, max_num=100): self.analyze_HFSS() # Solve current design (will skip if already solved) self.run_EPR() # calculate all the frequencies, shifts, etc we are designing for self.assign_mode_indices() counter = 0 while True: self.update_design_va...
def c1(self, Phi_ext): if not self.modulation_done: self.Modulation() return self.c1_itp(np.mod(Phi_ext, 2 * self.n * self.m * PI)) def c2(self, Phi_ext): if not self.modulation_done: self.Modulation() return self.c2_itp(np.mod(Phi_ext, 2 * self.n * self.m * PI)) ...
The main task of the code is to plot four coefficients (C1-C4) against a list of external phi values (phi_ext_list), visualizing their relationships. It generates a graph with labeled curves, x-axis as 'phi_external', y-axis as 'coefficients (J)', and a legend to distinguish the coefficients.
def plotCoefficients(self, phi_ext_list): plt.figure() plt.plot(phi_ext_list, self.c1(phi_ext_list), label='C1') plt.plot(phi_ext_list, self.c2(phi_ext_list), label='C2') plt.plot(phi_ext_list, self.c3(phi_ext_list), label='C3') plt.plot(phi_ext_list, self.c4(phi_ext_list), label...
def processData(pathToData): headers = ["DATE", "POPULATION", "G", "I_DWF", "E", "DWF_REPORTED", "FFT", "PE_REPORTED", "PE_FORECAST"] data = pd.DataFrame = pd.read_csv(resource_path(pathToData), names=headers) data = data.drop(data.index[0]) data = data.reset_index() ## convert date to correct form...
The main task of the code is to analyze energy data by comparing reported and forecasted values of PE (Power Export) and DWF (Demand Weighted Factor), calculate discrepancies, generate visualizations, and produce a PDF report. It processes input CSV data, recalculates DWF, evaluates significance/severity of differences...
def main(file_name): FILENAME = file_name[0:-4] print(FILENAME) # reads the csv file in a panda dataframe, checks all required attributes are present # and cleans/formats the data data = processData(resource_path("resources/"+file_name)) # assign required data fields to variables to be used fo...
def StepRecognize(category, key): if key == 'none': key = None elif key == 'auto': key = FeatureUnion([(k,v()) for k,v in StepClass[category].items() ]) else: key = StepClass[category][key]() return key def ModelBuilding(ylabel, method='rf', scaler=None, decom=None, cv=5, sc...
The function performs hyperparameter tuning and model evaluation for multiple classifiers (e.g., random forest) on training data. It uses cross-validation (5 or 10 folds based on data size), applies scaling/decomposition, trains models with best parameters, computes metrics like ROC AUC, and returns fitted models, trai...
def ModelTuningGrid(x_train, y_train, ylabel, sample_names, scaler='none', decom='none', method=['rf'], scoring='roc_auc', random_state=1234, n_jobs=-1): # cv definition if len(y_train) < 100: cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=random_state) #...
def GetArgs(): parser = argparse.ArgumentParser(description='Find best classify method and parameters', formatter_class=argparse.RawTextHelpFormatter) parser._action_groups.pop() # required required = parser.add_argument_group('Required arguments') required.add_argument('--matrix', help='matrix to b...
The main task of the code is to process gene expression data for classification, either training machine learning models (with cross-validation and evaluation) or testing pre-trained models. It handles data preprocessing (normalization, reference gene adjustment, feature filtering), model tuning, and outputs prediction...
def Main(): args = GetArgs() count_matrix = pd.read_csv(args.matrix, sep='\t', low_memory=False, index_col=0) print('Number of sample: {}\nNumber of feature: {}'.format(str(count_matrix.shape[1]),str(count_matrix.shape[0]))) stats_path = args.stats.strip('.tsv') if args.stats.endswith('.tsv') else args....
def calculate(self, standalone: bool = False) -> None: """ Function does calculations based on self.operator, self.var1 and input from TextStorage Outputs the result of the calculation onto TextStorage, and the equation for the answer onto LabelResult :param standalone: Boolean. Whether...
This code initializes a calculator GUI by setting up variables for storing input values and operations, connecting buttons to respective functions for arithmetic operations, clearing inputs, and calculation, while configuring the UI layout and initial state of display elements.
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.var1 = None self.var2 = None self.var3 = None # to store previous results. self.operation = None self.setupUi(self) self.setFixedSize(285, 432) self.ButtonCalc.clicked.connect(...
def weatherDescription(weatherId): ''' Changes the color of the weather description based on the id and adds an emoji args: weatherId (int): Weather id returns: weatherParm (tuple): weather symbol and color ''' # Initialize Variables # Weather Condition codes from OpenW...
The main task of the code is to format and print current weather details (temperature, description, symbol), weather alerts (event, sender, dates, description), and a multi-day forecast using input weather data, units, and city name. It uses color formatting for visual clarity and handles optional alert data if present...
def printData(weatherData, units, cityName): ''' Formats and prints the current weather, forecast and alerts args: weatherData (json): Weather data from API units (str): temperature unit of measure cityName (str): Name of City returns: None ''' # Variables from ...
def draw_X_O(self, btn): if self.me['symbol'] is 'X': self.btn_dict[btn].config(text='X') if self.me['symbol'] is 'O': self.btn_dict[btn].config(text='O') self.block_playboard() self.update_status(6) self.client.response(self.me, btn) def draw_win_loose...
(The code initializes a game board GUI with a 3x3 grid of buttons for a turn-based game, sets up button positioning and styling, connects to a client for multiplayer functionality, and prepares the interface for handling player moves and game outcomes.)
def __init__(self): print('STATE_PLAYBOARD') self.me = {} # player info self.type = '' self.exit = False self.GAME_WIDTH = GUI.GAME_WIDTH self.GAME_HEIGHT = GUI.GAME_HEIGHT self.BTN_WIDTH = 0.45 * self.GAME_WIDTH self.BTN_HEIGHT = 0.14 * self.GAME_HEIGHT ...
def expect_peek(target, tokens): '''Look at the top of the token stream. Return True if the top token matches {token}; raise an exception if it doesn't.''' if peek(target, tokens): return True error(tokens, target.pattern) def accept(target, tokens, pop=True): '''By calling this function, th...
This function parses a time-related clause from a token list into a dictionary. It identifies date, time, and timezone components based on keywords like 'AT' and 'ON'. If 'AT' is found, it assigns the preceding literal as the date and subsequent literal as time. Without 'AT', it treats the initial literal as time. It a...
def parse_time_clause(tokens): stmt = {} initial_literal = None if expect_peek(LITERAL, tokens): initial_literal = tokens.pop(0) if accept(AT, tokens): stmt['date'] = initial_literal if expect_peek(LITERAL, tokens): stmt['time'] = tokens.pop(0) try: ...
def accept(target, tokens, pop=True): '''By calling this function, the caller is declaring that it is acceptable for {tokens[0]} to match {target}. If {pop} is True, consume it; otherwise, leave the token in the list for the caller to deal with. If {tokens[0]} doesn't match {target} or there aren't any ...
This function parses a "create" statement from a token stream into a structured dictionary, handling both calendar and event creation. It identifies the statement type, extracts parameters like name, calendar reference, time ranges (from/until/for), and timezone info, while managing optional default flags and error han...
def parse_create_stmt(tokens): stmt = {'action': 'create'} default = False if accept(DEFAULT, tokens): default = True expect_peek(CALENDAR, tokens) if accept(CALENDAR, tokens): stmt['type'] = 'calendar' stmt['default'] = default if expect_peek(LITERAL, tokens): ...
def accept(target, tokens, pop=True): '''By calling this function, the caller is declaring that it is acceptable for {tokens[0]} to match {target}. If {pop} is True, consume it; otherwise, leave the token in the list for the caller to deal with. If {tokens[0]} doesn't match {target} or there aren't any ...
The code parses a list of tokens into a dictionary representing a command. It checks the first token against `CREATE`, `LIST`, `SET`, or `QUIT`, invoking the corresponding parser function to build the dictionary. After parsing, it verifies the input ends with an end-of-line marker and returns the structured dictionary....
def parse(tokens): '''Parse a list of tokens into a dictionary of its components.''' if accept(CREATE, tokens): stmt = parse_create_stmt(tokens) elif accept(LIST, tokens): stmt = parse_list_stmt(tokens) elif accept (SET, tokens): stmt = parse_set_stmt(tokens) elif accept(QUIT...
def connect(self): """## This is to connect to the mysql database. (automatically loaded in init function.) """ self.db = pymysql.connect( host = self.host, user = self.user, passwd = self.passwd, database = self.dbname ) self....
This code initializes a database connection by setting up parameters like dbname, host, user, and password. It attempts to connect to the database, creates it if the connection fails (likely due to non-existent database), and loads data into a dictionary using the `loaddoc()` method. The primary task is to establish an...
def __init__(self, dbname, host="", user="", passwd=""): """## The contructor function to initialize the database. The default document is main. ### Args: - `dbname (str)`: The name of the database. - `host (str, optional)`: The host for mysql. Defaults to "". - `use...
def delete_ip(clock, ip_port_to_delete, ips, shards): ip_port_array = environ.get("VIEW").split(",") clock.remove_vc(ip_port_array.index(ip_port_to_delete)) ip_port_array.remove(ip_port_to_delete) environ["VIEW"] = ",".join(str(x) for x in ip_port_array) if ip_port_to_delete == environ.get("IP_POR...
This code handles the deletion of a node (ip_port) from a distributed system's view. It parses input parameters, checks if the node exists, removes it, reconstructs affected shards, and broadcasts updates if no checkpoint is provided. If the node isn't found, it returns an error. The response indicates success or error...
def delete_handling(request, details): clock = details["clock"] shards = details["shards"] store = details["store"] body_unicode = request.body.decode("utf-8") body = urllib.parse.parse_qs(body_unicode) ip_port_to_delete = body["ip_port"][0] checkpoint = None if "checkpoint" in body: ...
def is_row_echelon_form(m: M) -> bool: """Function to check if Matrix m is in row echelon form.""" return below_pivots_only_zeroes(m) def all_pivots_are_one(m: M) -> bool: pivots = list(map(lambda t: t[1], get_pivots(m))) if next((k for k in pivots if k != 1), 1) != 1: return True else: ...
The function checks if a matrix is in reduced row echelon form by verifying three conditions: it is in row echelon form, all pivot elements are 1, and all entries above each pivot are zero. This ensures the matrix meets the strict criteria for reduced row echelon form, where leading entries are 1s, each pivot is the on...
def is_reduced_echelon_form(m : M) -> bool: """Function to check if Matrix m is in reduced row echelon form.""" return is_row_echelon_form(m) and all_pivots_are_one(m) and above_pivots_only_zeroes(m)
def verify_data(data): """ There are some assumptions made about the date we operate with for both baseline series and new measurements, they're going to be verified below. """ assert data, "Benchmark data must be not empty" data_grouped = process(data) for group, values in data_grouped: ...
The function merges baseline data with new measurement data, ensuring each test type doesn't exceed a threshold by trimming older entries. It groups data by VmConfig and CollectionMethod, retains baseline entries if they lack corresponding new data, sorts by timestamp, and trims excess entries before combining results ...
def add_to_baseline_file(input_file_name, baseline_data, threshold): if baseline_data: verify_data(baseline_data) with open(input_file_name, "r") as measure: new_measurement = json.load(measure) verify_data(new_measurement) new_measurement_keys = [ data[0] for data ...
def verify_data(data): """ There are some assumptions made about the date we operate with for both baseline series and new measurements, they're going to be verified below. """ assert data, "Benchmark data must be not empty" data_grouped = process(data) for group, values in data_grouped: ...
The code compares baseline and test datasets by verifying their structure, grouping data, and checking for statistical differences. It calculates median values, detects outliers using IQR, and ensures group consistency. Results include group names, medians, and outlier flags for benchmark and collector metrics.
def compare(input_file_name, baseline_data): if not baseline_data: print("Baseline file is empty, nothing to compare.", file=sys.stderr) return verify_data(baseline_data) with open(input_file_name, "r") as measurement: test_data = json.load(measurement) verify_data(test_dat...
def get_repo_handle(path: str): """ Provides a sh.Command baked to run git commands on a repository. Parameters: path: A path to a repository, if it is empty, the returned handle points to the directory this script lives in. Returns: An sh.Command ready to run git commands. """ ...
This function creates a new Git tag and associated empty commit for a specified version in a repository. It handles dry runs, ensures branch rollback, fetches updates, checks out the release branch, creates the tag, and optionally pushes the branch and tag. If not pushing, it provides commands to manually publish chang...
def main(version: str, dry_run: bool, push: bool, path: str, remote: str): repo = get_repo_handle(path) new_tag = find_tag_version(repo, version) print(f'New tag to be created: {new_tag}') if dry_run: print('This is a dry run, no tag created.') return # Before doing anything else...
def authenticate(self): # Set the token endpoint url = get_env_variable('MP_CLIENT_URL') # Set the client ID and secret client_id = get_env_variable('MP_CLIENT_ID') client_secret = get_env_variable('MP_CLIENT_SECRET') # Create the headers headers = { ...
The code initializes an MP Client by authenticates to obtain an access token, retrieves the API URL from an environment variable, calculates a query time threshold (5 minutes prior to the current time in New York timezone), and fetches form fields and locations data for subsequent operations. The main tasks include cli...
def __init__(self): log.info("Initializing MP Client...") self.access_token = self.authenticate() self.api_url = get_env_variable('MP_API_URL') # Query anything newer than the historical minutes ago (newer than 5 minutes ago) self.query_time = (datetime.now(pytz.timezone('Americ...
def get_endpoint(self, endpoint, params = ''): # Make the GET request url = self.api_url + endpoint log.debug("GET: {url}") # print(url) # print_json(params) try: response = requests.get(url, headers=self.get_auth_headers(), params=params).json() ...
The code retrieves pastoral care form responses created after a specified date, filters them by Form_ID 36, and associates them with specific answer fields (800-808). It enriches each form with corresponding answers, maps location IDs from responses, adds field labels, and attaches contact details. The result is a list...
def get_pastoral_care_form_responses(self): log.info(f"Getting Form Responses created after: {self.query_time}") form_query_params = { '$filter': f"Response_Date >= '{self.query_time}' AND Form_ID = 36" } answer_query_params = { '$filter': "Form_Field_ID IN(800,8...
def check_win(self): # Column Check for i in range(3): if self.temp[0][i].text() == self.temp[1][i].text() \ and self.temp[0][i].text() == self.temp[2][i].text() \ and self.temp[0][i].text() != "": self.clear_all() return self.temp[0...
The main task of the code is to handle a turn-based game where it alternates between 'X' and 'O' marks, updates the UI with corresponding colors, disables the clicked widget, checks for a win/draw, and switches turns between players or the computer in single-player mode.
def main_prog(self): sender = self.sender() if self.flag%2 == 0: mark = 'X' sender.setStyleSheet("""background-color: rgb(35, 35, 35);\n color: red;""") else: mark = 'O' sender.setStyleSheet("""background-color: rgb(35, 35, 35);\n color: rgb(83, 7...
def setup_pygsheets(): credentials = build_credentials(SCOPES) return pygsheets.authorize(custom_credentials=credentials) def parse_first_row(cell_values): meetings = [] first_row = cell_values[0] for value in first_row: if value != "": meetings.append(value) del meetings[-1]...
The code retrieves data from a Google Sheet using pygsheets, parses the first row as meeting information, extracts student data based on the meetings, and returns the structured data along with a 200 status code.
def get_point_data(): parsed_result = {} gc = setup_pygsheets() worksheet = gc.open_by_key(os.environ.get('GOOGLE_FILE_ID')).sheet1 cell_values = worksheet.get_all_values() first_row_result = parse_first_row(cell_values) parsed_result['meetings'] = first_row_result parsed_result['students'...
def determine_starting_node(self, mode): # check the validity of the given mode, sets the 'self.node_selection_mode' # and adds the newest starting node to 'self.starting_nodes'. if mode == 'random': self.node_selection_mode = 'random' self.starting_nodes.append(self.find_random_node_in_graph()) elif mode...
This code performs community detection in a graph by iteratively identifying communities through local search starting from selected nodes. It continues until all nodes are discovered, managing overlaps and updating ignored nodes based on the overlap flag. After processing, it optionally amends the partition for refine...
def community_detection(self, node_selection_mode, overlap_enabled=False, with_amend=True): # THE MAIN FUNCTION OF THE CLASS, finds all communities of the graph. while self.number_discovered_nodes < self.graph.number_of_nodes(): self.determine_starting_node(node_selection_mode) community = self.local_searcher...
def contains(text, pattern): """Return a boolean indicating whether pattern occurs in text.""" assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) # TODO: Implement contains here (iteratively and/or recursively...
The code tests string algorithms by checking if a pattern exists in a text, finding its first occurrence index, and all occurrence indexes, then printing results. It uses functions contains(), find_index(), and find_all_indexes() which are to be implemented.
def test_string_algorithms(text, pattern): found = contains(text, pattern) print('contains({!r}, {!r}) => {}'.format(text, pattern, found)) # TODO: Uncomment these lines after you implement find_index index = find_index(text, pattern) print('find_index({!r}, {!r}) => {}'.format(text, pattern, index)...
def read_css(path): file = open(path, mode='r') # read all lines at once css_file = file.read() file.close() return css_file def find_block(string, name): regex_string = name + r"[^{]*[{][^{]*[}]" match = re.findall(regex_string, string) if match is not None and len(match) >...
The main task of the code is to parse a CSS file, extract theme-specific (light/dark) style blocks, combine them with general styles, and return a dictionary of color values associated with the specified theme. It separates CSS rules into theme-specific and general blocks, merges the selected theme blocks with general ...
def get_theme_from_file(path, theme = "dark"): css_file = read_css(path) blocks = find_block(css_file, "") light_theme_name = ".theme-light" dark_theme_name = ".theme-dark" general_blocks = [] ligt_theme_blocks = [] dark_theme_blocks = [] for block in blocks: if dark_theme_na...
def test_error_01(self,test_y,y_bar): test_y = np.array(test_y).reshape(-1,) y_bar = np.array(y_bar).reshape(-1,) if len(test_y) != len(y_bar): raise ValueError('two y should have same length') total = 0 for i in range(len(y_bar)): if y_bar[i] - test_y[i] ...
The main task of the code is to train a model using Newton's method by iteratively updating parameters (theta) with a specified learning rate (lr) until convergence (when parameter changes fall below epsilon). It evaluates training and test errors (0-1 loss) before and after convergence, printing results for both datas...
def fit(self,test_x=None,test_y=None,lr=1,eps=1e-4): i = 0 print("Before Newton, the trianing error(0-1) is: {J}".format(J=self.test_error_01(self.y,self.forward(self.x)))) while True: theta_old = deepcopy(self.theta) i += 1 self.one_step_newton(lr) ...
def save_name(self): path = self.path filename = os.path.basename(path) # This will get '20221017_005.mat' variable_name = os.path.splitext(filename)[0] #remove the extension, giving you file name/date ex: '20221017_005' self.variable_name = variable_name print(variable_name...
The code generates a DataFrame containing first peak values, average baseline, first response in pA, and time data, then saves it as a CSV file named after a variable. It returns the created DataFrame for further use.
def peak_df(self): variable_name = self.save_name() avg_baseline = self.avg_baseline() times = self.time_correlates() first_peak_list = self.calc_min_first_peak() first_response_pA = self.calculate_first_response() df = pd.DataFrame( {'first_peak': first...
def load_data(self, path): path = self.path data = loadmat(path) self.data = data print("total sweeps: " + str(len(data))) return data def save_name(self): path = self.path filename = os.path.basename(path) # This will get '20221017_005.mat' variable_nam...
The main task of the code is to process and analyze data by loading, editing, and visualizing sweeps, calculating baseline averages, identifying first peaks, determining initial responses, and computing time correlations. It ultimately returns a DataFrame containing peak-related data extracted from the processed datase...
def run_all(self): self.load_data() self.save_name() self.edit_data() self.plot_sweeps(0,188, 0,100) self.avg_baseline() self.calc_min_first_peak() self.calculate_first_response() self.time_correlates() df = self.peak_df() return df
def unix_build(self): win_bash = sys.platform == "win32" target = self._get_target() self.run_in_src("./Configure %s %s" % (target, self._get_flags()), win_bash=win_bash) self.run_in_src("make depend") self._patch_makefile() self.output.warn("----------MAKE OPENSSL %s-...
The code determines the appropriate build method based on the operating system and compiler settings. It calls `unix_build()` for Linux, SunOS, FreeBSD, Android, macOS, or Windows with GCC; `ios_build()` for iOS; and `visual_build()` for Visual Studio. If none match, it raises an exception for unsupported OS.
def build(self): if self.settings.os in ["Linux", "SunOS", "FreeBSD", "Android", "Macos"] or \ (self.settings.os == "Windows" and self.compiler == "gcc"): self.unix_build() elif self.settings.os == "iOS": self.ios_build() elif self.compiler == "Visual Stud...
def is_final(self, state): player = state.get_last_player() moves = state.get_moves() if 0 not in moves: self.winner = 0 return True self.winner = player for k in range(0, 3): # verific linia if moves[3 * k] == player and moves[...
This code runs a two-player game loop where Player 1 inputs moves, while Player 2 (AI) selects moves automatically. It validates moves, updates the game state, alternates turns, and declares a winner or tie once the game ends.
def start(self): print() player = 1 while self.is_final(self.state) is False: print(f"Player {player}, 's turn. Remaining moves: {self.get_possible_values(self.state)}") if player == 1: move = int(input()) if self.move_is_valid(move) is Fal...
def finish_game(self) -> None: """ Finishes a game by awarding final coins. Also calculates the winning team(s) """ # Award leg coins self.finish_leg() # Overall winner/loser bets positions = self.get_positions() payoffs = [8, 5, 3, 2, 1] ...
This function moves a camel of a specified color by a given number of spots on a board, handling removal from the current spot, insertion into the new spot, and processing any movement card effects. It adjusts positions, manages linked lists for camel order, and triggers additional movements if a movement card is prese...
def move_camel(self, color: Color, spots: int) -> None: """ Given a color, move that camel `spots` number of spots """ if spots == 0: return camel = self.camels[color] spot = self.spots[camel.pos] temp_node = spot.camels.head while temp_node i...
def roll_dice() -> int: """ A roll of a die in Camel Up. Camels can move 1, 2, or 3 spaces """ return randint(1, 3) def move_camel(self, color: Color, spots: int) -> None: """ Given a color, move that camel `spots` number of spots """ if spots == 0: return ...
The method `roll_dice` increments the active team's coins, removes a die color from the remaining dice, rolls the die to determine a move, moves the camel of the corresponding color, checks if all dice have been used to trigger a leg finish, ends the turn, and returns the color and move result.
def roll_dice(self) -> Tuple[Color, int]: """ Team `team` rolls the dice """ self.teams[self.active_team].coins += 1 color = self.die_remaining.pop() move = roll_dice() self.move_camel(color, move) if len(self.die_remaining) == 0: self.finish_...
def findBlankIndex(puzzle): for x in range(PUZZLEWIDTH): for y in range(PUZZLEHEIGHT): if puzzle[x][y]==0: return (x,y) def drawPuzzle(msg,puzzle): DISPLAYSURF.fill(BGCOLOR) if msg: textSurf,textRect=drawText(msg,MESSAGECOLOR,BGCOLOR,5,5) DISPLAYSURF.blit...
This function animates a tile sliding in the specified direction (up/down/left/right) within a puzzle game. It calculates the moving tile's new position, creates a base surface with a blank space, then incrementally redraws the tile's movement across frames using Pygame, producing a smooth sliding animation at the give...
def slideAnimation(puzzle,move,msg,animationSpeed): x,y=findBlankIndex(puzzle) if move=='up': movex=x-1 movey=y elif move=='down': movex=x+1 movey=y elif move=='left': movex=x movey=y-1 elif move=='right': movex=x movey=y+1 #prepare...
def getStartingPuzzle(): counter=0 puzzle=[] for x in range(PUZZLEWIDTH): row=[] for y in range(PUZZLEHEIGHT): row.append(counter) counter+=1 puzzle.append(row) return puzzle def drawPuzzle(msg,puzzle): DISPLAYSURF.fill(BGCOLOR) if msg: te...
The main task of the code is to generate a randomized puzzle by applying a specified number of random moves to an initial solved puzzle state. It uses animations to visualize each move, ensuring the puzzle transitions through randomized configurations. The function returns the final scrambled puzzle after executing the...
def randomizePuzzle(num): puzzle=getStartingPuzzle() drawPuzzle('',puzzle) pygame.display.update() pygame.time.wait(500) lastMove=None for i in range(num): move=getRandomMove(puzzle,lastMove) slideAnimation(puzzle,move,'Generating new puzzle...',int(TILESIZE/10)) doMove(p...
def getStartingPuzzle(): counter=0 puzzle=[] for x in range(PUZZLEWIDTH): row=[] for y in range(PUZZLEHEIGHT): row.append(counter) counter+=1 puzzle.append(row) return puzzle def drawPuzzle(msg,puzzle): DISPLAYSURF.fill(BGCOLOR) if msg: te...
The code implements a sliding puzzle game with Pygame, allowing users to select difficulty levels (Easy, Normal, Hard), generate random puzzles, and solve them. It initializes the game window, handles button presses to modify the puzzle state, checks for a solved condition, and updates the display in a loop. The game u...
def main(): global FPSCLOCK,DISPLAYSURF,BASICFONT,INDEXFONT,EASY,NORMAL,HARD,RANDOM,SOLVE pygame.init() FPSCLOCK=pygame.time.Clock() #set window mode: BORDERlESS WINDOWED #os.environ['SDL_VIDEO_CENTERED']='1' #DISPLAYSURF=pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT),pygame.NOFRAME) #s...
def extractUserName(name): return str(name, 'utf-8').rstrip('\0') def registerUser(name, pubKey): try: userID = db.insertClient(name, pubKey) return makeHeader(REG_SUCC, UUID_SIZE) + userID except: return errorMsg() def getUserList(uid): db.updateConnTime(uid) uList = db.getU...
This function processes incoming requests by routing them to appropriate handlers based on the request code, performing actions like user registration, retrieving user lists, public keys, pending messages, or sending messages, and returning corresponding results.
def requestHandler(request): if request.request_code == REGISTER_USER: userName = extractUserName(request.payload[:USERNAME_SIZE]) publicKey = request.payload[USERNAME_SIZE:] return registerUser(userName, publicKey) elif request.request_code == GET_USERLIST: return getUserList(re...
def sourcetext_characteristics(): '''sourcetext_characteristics concatenates default sourcetexts and parses it :returns: returns combined sourcetexts without punctuation ''' plainAlphabet = string.ascii_lowercase # default sourcetexts path = os.path.abspath(os.path.join(os.path.dirname( __fil...
The code implements a decryption framework using simulated annealing (SA) to find the best plaintext from ciphertext. It processes source text and ciphertext characteristics, iterates over n-gram sizes, and applies SA with parameters like cooling factor and initial temperature. The algorithm evaluates decryption fitnes...
def main(ciphertext, n_gram, max_time, coolingFactor, initial_temperature): '''main is framework for the decryption, it creates, gets all needed vars for SA :param ciphertext: ciphertext to decrypt :param n_gram: size of block :param max_time: maximum runtime in minutes per n_gram :param coolingFac...
def controls(self): is_down = base.mouseWatcherNode.is_button_down # only one direction is valid at a time if is_down(left_button): self.move_left() elif is_down(right_button): self.move_right() else: # stop moving faster vel = sel...
This code handles a game frame update when not paused by invoking control input, camera centering, and enemy collision checks, then returns 'task.cont' to sustain the task loop.
def frame(self, task): if not self.game.paused: self.controls() self.center_camera() self.check_enemy_collision() return task.cont
def skipWhite(self): while self.curr_char.isspace(): self.advance() def parse_str(self): self.skipWhite() if self.curr_char == '"': res = "" res += self.advance() while self.curr_char and self.curr_char != '"': res += self.advance() if self.curr_char == '"': res...
The main task of the code is to parse a term from input, handling either quoted strings or identifiers followed by optional arguments in parentheses. It constructs and returns a `Term` object with the parsed name and list of sub-terms, or `None` if parsing fails.
def parse_term(self): self.skipWhite() if self.curr_char == '"': fname = self.parse_str() if fname is not None: return Term(fname, []) return fname = self.parse_name() if fname == "": return if not self.parse_const("("): return Term(fname, []) subs = [] ...
def __registeringToHrHandle(self, gatttool) -> [str, str]: hr_handle, hr_handle_ctl = self.__lookingForHandle(gatttool) gatttool.sendline(f"char-write-req {hr_handle_ctl} 0100") return hr_handle, hr_handle_ctl def __readOutput(self, gatttool, hr_handle: str, listener: RecordingListener): ...
The code's main task is to initiate heart rate data recording when connected to a BLE device. It registers to the heart rate handle, starts reading data, sends decoded results to a logger, disconnects from the device, and updates the connection status to False. The method uses GATTtool for BLE communication and relies ...
def startRecording(self, listener: RecordingListener): """ If connected this methode looks for the right hearrate handler and register itself. It starts to listen and send decodec results to logger Parameters ---------- deviceMac : str Mac of your Hea...
def create_arg_parser(): p = ArgumentParser(description='A recursive CRC32', formatter_class=ArgumentDefaultsHelpFormatter) p.add_argument('paths', nargs='*', help='the paths to analize, it could be a file or a directory') p.add_argument('--log-level', default='INFO...
This script processes files by adding or verifying CRC32 checksums in filenames. It lists files from specified paths, filters by extension, name, or randomness, then checks or adds CRC32 hashes. Files with mismatched hashes are marked as corrupt. If adding CRC32, it renames files with the checksum. It returns 0 for suc...
def main(): parser = create_arg_parser() args = parser.parse_args() logging.basicConfig(level=args.log_level) logger.debug("Listing files") files = list_files(args.paths) extensions = set(x.lower() for x in args.extension if x) if extensions: logger.debug("Filtering files by exten...
def is_collection_present(self, collection_name, db_name): """ Checks if a collection in a given database is present or not Parameters: collection_name (str): name of the collection db_name (str): name of the database Returns: bool: True if the collec...
The main task of the code is to insert data from a pandas DataFrame into a specified MongoDB collection. It checks if the collection exists, creates the database and collection if necessary, converts the DataFrame to a JSON-compatible format, and inserts the records. The function returns a success message or raises an ...
def df_to_collection(self, db_name, collection_name, df): """ Inserts the data from a dataframe into a collection Parameters: db_name (str): name of the database collection_name (str): name of the collection df (str): name of the dataframe from which data shou...
def _mutate_once(ind1, params, toolbox, index_pb, method, param_pb=None): """ The individual is mutated according to probabilities. Parameter mutation is performed using a hill-climbing algorithm. The individual is modified in place. :param ind1: The individual to be mutated :param p...
The function `mutate_individual` probabilistically applies one of three mutation strategies to an individual (`ind1`) in a genetic algorithm. With probabilities `swap_pb`, `len_pb`, and `param_pb`, it either swaps elements, adjusts the individual's length, or modifies parameters using `_mutate_once`, `mutate_length`, o...
def mutate_individual(ind1, params, prepro_names, toolbox, index_pb, param_pb, swap_pb, len_pb, n_iter=4): """ :param ind1: :param params: :param toolbox: :param index_pb: :param param_pb: :param swap_pb: :param len_pb: :param n_iter: :return: """ if random.random() < s...
def _ggm_prob_wait_whitt_pi_1(m, rho, ca2, cs2): """ Part of Equation 3.11 on p139 of Whitt (1993). Used in approximation for P(Wq > 0) in GI/G/c/inf queue. See Whitt, Ward. "Approximations for the GI/G/m queue" Production and Operations Management 2, 2 (Spring 1993): 114-161. Parameters -----...
This function calculates an intermediate term `pi_2` from Equation 3.11 in Whitt's 1993 paper, used to approximate the probability $ P(W_q > 0) $ in a GI/G/c/∞ queue. It combines results from helper functions `pi_1` and `pi_6`, weighted by the squared coefficient of variation of arrivals (`ca2`). The term contributes t...
def _ggm_prob_wait_whitt_pi_2(m, rho, ca2, cs2): """ Part of Equation 3.11 on p139 of Whitt (1993). Used in approximation for P(Wq > 0) in GI/G/c/inf queue. See Whitt, Ward. "Approximations for the GI/G/m queue" Production and Operations Management 2, 2 (Spring 1993): 114-161. Parameters -----...
def _ggm_prob_wait_whitt_z(ca2, cs2): """ Equation 3.8 on p139 of Whitt (1993). Used in approximation for P(Wq > 0) in GI/G/c/inf queue. See Whitt, Ward. "Approximations for the GI/G/m queue" Production and Operations Management 2, 2 (Spring 1993): 114-161. Parameters ---------- ca2 : flo...
This function computes an intermediate term `pi_3` for approximating the probability of waiting time in a GI/G/c/∞ queue (P(Wq > 0)) using Whitt's method. It combines parameters like server count (`m`), traffic intensity (`rho`), and squared coefficient of variations (`ca2`, `cs2`) with helper functions to calculate a ...
def _ggm_prob_wait_whitt_pi_3(m, rho, ca2, cs2): """ Part of Equation 3.11 on p139 of Whitt (1993). Used in approximation for P(Wq > 0) in GI/G/c/inf queue. See Whitt, Ward. "Approximations for the GI/G/m queue" Production and Operations Management 2, 2 (Spring 1993): 114-161. Parameters -----...
def _ggm_mean_qwait_whitt_phi_1(m, rho): """ See p124 immediately after Eq 2.16. :param m: int number of servers :param rho: float lambda / (mu * m) :return: float """ return 1.0 + gamma_0(m, rho) def _ggm_mean_qwait_whitt_psi_0(c2, m, rho): """ See p125 , Eq 2.22....
The function calculates the mean waiting time in a multi-server queueing system using Whitt's approximation. It takes parameters like traffic intensity (rho), squared coefficients of variation for arrivals (ca2) and service (cs2), and the number of servers (m). Depending on whether ca2 is greater than or equal to cs2, ...
def _ggm_mean_qwait_whitt_phi_0(rho, ca2, cs2, m): """ See p125 , Eq 2.25. :param rho: float lambda / (mu * m) :param ca2: float squared CV for arrival process :param cs2: float squared CV for service process :param m: int number of servers :return: float ...
def _ggm_prob_wait_whitt_z(ca2, cs2): """ Equation 3.8 on p139 of Whitt (1993). Used in approximation for P(Wq > 0) in GI/G/c/inf queue. See Whitt, Ward. "Approximations for the GI/G/m queue" Production and Operations Management 2, 2 (Spring 1993): 114-161. Parameters ---------- ca2 : flo...
This function calculates an intermediate term 'pi' used in approximating the probability of non-zero waiting time in a GI/G/c/inf queue, as per Whitt (1993). It computes 'z' and 'gamma' from input parameters (servers, traffic intensity, squared coefficients of variation) and selects between three specialized formulas (...
def _ggm_prob_wait_whitt_pi(m, rho, ca2, cs2): """ Equation 3.10 on p139 of Whitt (1993). Used in approximation for P(Wq > 0) in GI/G/c/inf queue. See Whitt, Ward. "Approximations for the GI/G/m queue" Production and Operations Management 2, 2 (Spring 1993): 114-161. Parameters ---------- ...
def dmm_mean_qwait_whitt(arr_rate, svc_rate, m, ca2=0.0, cs2=1.0): """ Return the approximate mean queue size in D/M/m/inf queue using Whitt's 1993 approximation. See Whitt, Ward. "Approximations for the GI/G/m queue" Production and Operations Management 2, 2 (Spring 1993): 114-161. Specifically, this ...
The function `ggm_mean_qwait_whitt` computes the approximate mean queue wait time for a GI/G/c/inf queue using Whitt's 1993 method. It combines parameters like arrival rate, service rate, number of servers, and squared coefficients of variation (ca2, cs2) to calculate the wait time. For specific cases (e.g., determinis...
def ggm_mean_qwait_whitt(arr_rate, svc_rate, m, ca2, cs2): """ Return the approximate mean queue wait in GI/G/c/inf queue using Whitt's 1993 approximation. See Whitt, Ward. "Approximations for the GI/G/m queue" Production and Operations Management 2, 2 (Spring 1993): 114-161. It's based on interpo...
def opds_response(page_number, count, page_size): total_pages = ceil(count/page_size) return { "metadata": { "title": "Springer Test Feed", "itemsPerPage": page_size, "currentPage": page_number, "numberOfItems": count }, "links": opds_respo...
The main task of the code is to query a database for DOI identifiers with specific attributes, calculate statistics about their classifications and editions, generate paginated OPDS responses containing publication data, and cache these responses in a specified directory. The process involves filtering, joining databas...
def main(): output_base_dir = "output_test/springer/opds" os.makedirs(output_base_dir, exist_ok=True) q = db_session.query(Identifier).join(Classification, Classification.identifier_id == Identifier.id, isouter=True) count = q.filter(Identifier.type == 'DOI').filter(Classification.id == None).count() ...
def _draw_cell(self, i: int, j: int): self._cells[i][j].draw( self._cell_size_x * i + self._x1, self._cell_size_y * j + self._y1, self._cell_size_x * (i + 1) + self._x1, self._cell_size_y * (j + 1) + self._y1 ) if self._win is None: ret...
The main task of the code is to create a grid of `Cell` objects for a maze, initialize their visual representation, and prepare the maze structure by breaking walls and setting entrance/exit points. It constructs a 2D list of cells, draws each cell, then calls methods to break walls recursively and reset visited states...
def _create_cells(self): self._cells: list[list[Cell]] = [] for i in range(self._num_cols): self._cells.append([Cell(self._win)]) for j in range(1, self._num_rows): self._cells[i].append(Cell(self._win)) for i in range(len(self._cells)): for j ...
def parse_line(line): global FS, CWD, CRUMBLE if line[:4] == '$ cd': tgt = line[5:] if tgt == '..': CRUMBLE.pop() else: CRUMBLE.append(tgt) DIR_PATHS.add(tuple(CRUMBLE)) CWD = get_by_path(FS, CRUMBLE) elif line[:3] == 'dir': dir ...
The code processes input lines to parse data, calculates directory sizes from a file system structure, prints a formatted tree view of the file system, and executes two puzzles (puzzle1 and puzzle2) to solve specific tasks related to the parsed data.
def main(): global DIR_SIZES with open(IN_PATH, 'r') as file: for line in file.readlines(): parse_line(line.strip('\n')) DIR_SIZES = [calc_dir_size(get_by_path(FS, dir)) for dir in DIR_PATHS] print(pretty_tree(FS)) puzzle1() puzzle2()
def create_camera_matrix(rotation_angle, elevation_angle, camera_radius): device = 'cpu' n = rotation_angle.shape[0] phi = elevation_angle theta = rotation_angle sample_r = camera_radius output_points = torch.zeros((n, 3), device=device) output_points[:, 0:1] = sample_r * torch.sin(phi) * to...
This function generates a camera condition vector by combining extrinsic (rotation, elevation, radius) and intrinsic (projection parameters) matrices, returning a concatenated numpy array of floats for 3D rendering/view synthesis tasks.
def create_condition_from_camera_angle( rotation, elevation, radius): fovy = np.arctan(32 / 2 / 35) * 2 fovyangle = fovy / np.pi * 180.0 ###################### # # fov = fovyangle # focal = np.tan(fovyangle / 180.0 * np.pi * 0.5) # proj_mtx = projection(x=focal, f=1000.0, n=1.0, near_plane=0.1)...
def generatePoss(self): pos = [] for i in range(1, 10): pos.append(f'{i}') possibilities = [] for row in range(9): possRow = [] for column in range(9): if self.board[row][column] == '.': possRow.append(pos.copy()) ...
This code solves a Sudoku puzzle by iteratively updating possible values for each cell, using a backtracking approach. It initializes possible moves, identifies cells needing updates, and repeatedly applies valid numbers until the board is fully solved. The function modifies the input board in-place to reflect the solu...
def solveSudoku(self, board: List[List[str]]) -> None: self.board = board self.possibility = self.generatePoss() self.needsUpdate = self.generateNeedsUpdate() while self.unsolved(): while self.hasNeedsUpdate(): self.updateAll()
def segregate_vectors(dest_folder): print('start segregate_vectors') pos_dest_folder = os.path.join(dest_folder, "Positive") if not os.path.exists(pos_dest_folder): os.makedirs(pos_dest_folder) neg_dest_folder = os.path.join(dest_folder, "Negative") if not os.path.exists(neg_dest_folder): ...
The main task of the code is to organize and split labeled data (Positive/Negative) into train/val/test directories, execute vector generation (`run_c2v`), and process/segregate vectors (`segregate_vectors`). It repeatedly renames folders to rotate data splits and ensures structured preparation for downstream tasks lik...
def generate_c2v(): for sample_type in ["Positive", "Negative"]: cur_src_folder = os.path.join(src_folder, sample_type) train_dest_folder = os.path.join(TRAIN_DIR, sample_type) val_dest_folder = os.path.join(VAL_DIR, sample_type) test_dest_folder = os.path.join(TEST_DIR, sample_type)...
def createSimMatrix(q, X): r = {} i = 0 for p in X: d = euclidean_distance_square(q,p) r[i] = 1/(1+d) i = i + 1 return r def swap(X,recitems,k,ub): global swapnumber SortedRecItems = sorted(recitems.items(), key=lambda x: x[1], reverse=True) retlist = topkitems(Sorted...
The main task of the code is to evaluate and compare two clustering algorithms, 'swap' and 'AugSwap', by generating synthetic data, constructing hierarchical cluster structures, and measuring their execution time and results. It creates similarity matrices, builds clustering trees, and validates outputs against each ot...
def run(numberOfSamples,numberofCluster,numberofLevel,k): X, Y = make_blobs(n_samples=numberOfSamples, centers=1, n_features=3, random_state=2) # X = X.tolist() query = [0, 0,0] r = createSimMatrix(query, X) ub = 1000000 start = timeit.default_timer() res = swap(X, r, k, ub) stop = tim...
def createSimMatrix(q, X): r = {} i = 0 for p in X: d = euclidean_distance_square(q, p) r[i] = 1 / (1 + d) i = i + 1 return r def swap(X,SortedRecItems, recitems,k, ub): global swapnumber,inArrayTime #SortedRecItems = sorted(recitems.items(), key=lambda x: x[1], reverse=T...
The main task of the code is to process a dataset by normalizing features, clustering data into hierarchical structures, and evaluating two recommendation algorithms (swap and AugSwap) for top-k item retrieval. It loads data from 'ratings.csv', computes similarity matrices, and benchmarks the time efficiency of both me...
def run(datasetname, numberOfSamples, numberofCluster, numberofLevel, k): global inArrayTime print('datasetname', datasetname, 'dataset size: ', numberOfSamples, 'k:', k, 'number of cluster: ', numberofCluster, 'number of level: ', numberofLevel) # X, Y = make_blobs(n_samples=numberOfSamples, cen...
def update(self): for i in self.l_cart: db.q_update(i[0], i[2]) if cu.c_check_cridit(self.name) >= 1000: cu.cridit_update(self.name, -1000) else: cu.cridit_update(self.name, self.total) def add_card(self): self.card_number = int(input("Enter Your Card ...
The code processes card payments by verifying existing card details (name, number, CVV), handling successful transactions, and offering options to retry, add new cards, switch to cash, or return to the main menu if validation fails.
def card_payment(self): if cu.card_name(self.name): # Checks if card exists or not self.card_number = int( input("Enter your last 4 digit of your card:")) self.card_cvv = int(input("Enter your card cvv:")) if cu.check_card_no(self.name, self.card_number, self....
def display(self, l_cart, name): date = datetime.now() # Current time and date print(f'Username:{name}\t Date:{date.strftime("%d/%m/%Y")}\t time:{date.strftime("%H:%M:%S")}') self.total = 0 self.l_cart = l_cart self.name = name print("MedicinName\tPrice\t\tQuantity\tTotal...
The code presents a payment selection menu, allowing users to choose between cash or card payment. It displays the shopping cart and triggers corresponding payment methods based on user input. If an invalid option is chosen, it shows an error message. The primary task is to handle payment method selection and execute r...
def p_menu(self, name, l_cart): n = int(input("1.For Cash Payment\n2.For Card Payment\n")) if n == 1: self.display(l_cart, name) self.cash() elif n == 2: self.display(l_cart, name) self.card_payment() else: print("\nInvalid Choi...
def split_data(self, test_size=0.33, random_state=42): self.x_train, self.x_test, self.y_train, self.y_test = train_test_split(self.X, self.Y, test_size = test_size, random_state = 42) self.x_train = np.array(self.x_train.T) self.x_test = np.array(self.x_test.T) self.y_train = np.array(s...
The main task of the code is to train a machine learning model using gradient descent by splitting the dataset, initializing weights, optimizing parameters, and evaluating model performance. It calculates train/test accuracy via mean absolute error, printing scores to assess model effectiveness on both training and tes...
def fit(self): # initializing variables and splitting data set self.split_data() self.initialize_weights(self.x_train.shape[0]) self.costs = [] # Applying gradient descent self.optimize() # Printing test/train accuracy ...
def initialize_layers(self, layer_dims): L = len(layer_dims) self.parameters = {} for l in range(1, L): self.parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) * 0.01 self.parameters['b' + str(l)] = np.zeros((layer_dims[l], 1)) def split_data(self, test_size=0.33, random_...
The code trains a neural network by initializing layers, splitting data, and iterating through forward/backward propagation to update parameters. It calculates and logs costs periodically, then evaluates and prints training and test accuracies after completion.
def fit(self): costs = [] self.initialize_layers(self.layer_dims) self.split_data() for i in range (self.iterations): self.forward_propogation(self.x_train) cost = self.calculate_cost() self.backward_propogation() self.update_parameters() if i % 30000 == 0 or i == self.ite...
def runPrediction(self, test_data, model): predictions = [] #Run predictions for each observation for row in test_data.index: predictions.append(self.predict(test_data.loc[row], model)) return predictions def buildConfusionMatrix(self, predictions, train_labels): tp...
This code evaluates a decision tree model on test data by generating predictions, computing a confusion matrix, calculating basic statistics (e.g., accuracy, precision), and optionally visualizing results. It loads the model and test data, runs predictions, constructs performance metrics, and returns the confusion matr...
def testModel(self, tree_file, test_data_file, plot=False, title="Model"): test_set = pd.read_csv(test_data_file) dtree = pd.read_pickle(tree_file) self.pos_class = dtree.statistics["pos_class"] self.neg_class = dtree.statistics["neg_class"] predictions = self.runPrediction(tes...
def nodeStatistics(self, dataset): # Mask to filter by class class_mask = dataset['class'] == self.pos_class # Count positive and negative ocurrances p = dataset.loc[class_mask, 'class'].agg('count') n = dataset['class'].agg('count') - p return p, n, class_mask def plural...
The main task of the code is to recursively construct a decision tree by splitting data based on the best attribute until base cases are met, returning nodes with classifications or splits. It handles empty data, uniform class data, single-attribute data, and splits on the best attribute, recursively building subtrees ...
def decisionTreeLearning(self, data, parent_data): if data.empty: # Return its parent's plurality value # print("RETURNING") p, n, _ = self.nodeStatistics(parent_data) return Node(self.pluralityValue(parent_data), p, n, self.pos_class, self.neg_class) elif...
def SingularOrMany(t): return Union[t, SequenceOf(t)] def SequenceOf(t): return Union[Tuple[t, ...], List[t]] def forward_augments( self, prompt: Tensor, prompt_mask: Optional[SingularOrMany(SequenceOf(Tensor))] = None ): # if only one prompt is given with multiple augmentati...
The main task of the code is to generate text sequences using an anchor language model, applying cross-attention masks from augmentation models and top-p sampling. It processes prompts, manages attention contexts, and returns generated tokens with specified sequence lengths and filtering parameters.
def generate( self, prompt: Tensor, seq_len: int, prompt_mask: Optional[SingularOrMany(SequenceOf(Tensor))] = None, filter_fn: Callable = top_p, filter_kwargs: dict = dict( thres = 0.9 ) ): batch, device = prompt.shape[0], next(self.cross_a...
def SingularOrMany(t): return Union[t, SequenceOf(t)] def forward_augments( self, prompt: Tensor, prompt_mask: Optional[SingularOrMany(SequenceOf(Tensor))] = None ): # if only one prompt is given with multiple augmentation llms, then just feed that one prompt into all augment llm...
This code implements a forward pass for a neural network model that processes input sequences with augmented prompts, using cross-attention mechanisms. It computes logits via an anchor language model (anchor_llm) and optionally calculates a cross-entropy loss for training, incorporating prompt masking and handling both...
def forward( self, seq: Tensor, *, prompt: SingularOrMany(Tensor), prompt_mask: Optional[SingularOrMany(Tensor)] = None, mask: Optional[Tensor] = None, return_loss = True, anchor_llm_in_train_mode = True # unsure about this ): if return_loss: ...
def am_i_next(self, reqid): client_id = self.redis.get('cm:' + reqid) if not client_id: client_id = self.add_new_client(reqid) else: self.redis.expire('cm:' + reqid, self.queue_expire_secs) client_id = int(client_id) next_client = int(self.redis.get('nex...
This function initializes a new browser container by retrieving request data from Redis, configuring environment variables (URL, browser, VNC password, proxy settings), creating a container with timed_new_container, updating Redis with container info, and returning the container details including queue status and TTL. ...
def init_new_browser(self, reqid, host, width=None, height=None): req_key = 'req:' + reqid container_data = self.redis.hgetall(req_key) if not container_data: return None # already started, attempt to reconnect if 'queue' in container_data: container_da...
def name_entry_funct(self): self.NameEntry_TK = tk.Tk() self.NameEntry_TK.title("New Dice") self.NameEntryWindow = tk.Canvas(self.NameEntry_TK, width=300, height=200, bd = 15, bg = 'green') self.NameEntryWindow.grid(columnspan=4, rowspan = 5) self.UE_dice_label = tk.Label(text = "Dice Set Name:") self.UE_d...
The main task of the code is to handle user name input validation. It first calls a function to process name entry, checks if a valid name was provided (`self.setname`), and exits the program if none is set. If a name is provided, it proceeds to initialize dice choice buttons for further interaction.
def main(self): self.name_entry_funct() if self.setname == None: print("Window closed, exiting...") self.quit_funct() return self.dice_choice_buttons()
def parse_args(): return create_argparser().parse_args() def list_files(args): if args.recurse: return glob.glob(os.path.join(args.path, "**/*.dir"), recursive=True) return [args.path] def extract_pakfile(file, convert_tx): pakfile = pakfiles.open_pakfile(file) pakfile.log = True print(f...
The main task of the code is to process multiple files by extracting their contents using the `extract_pakfile` function. It first parses command-line arguments, lists target files with `list_files`, and iterates over each file to extract data, applying texture conversion if specified via `args.convert_tx`. The functio...
def main(args=None): if args is None: args = parse_args() files = list_files(args) for file in files: extract_pakfile(file, args.convert_tx)
def read_u8(self): return self.read_struct0("<B") def append_current(self, nextchar): self.current.append(nextchar) def push_current(self): self.stack.append(bytes(self.current)) def finalize_entry(self): offset = self.read_u32() length = self.read_u32() path = bytes(self...
This function processes directory tree nodes by reading command bytes to determine actions: appending characters, pushing current state, or finalizing entries. It uses 0x40/0xC0 for appending with context, 0x08/0x88 for appending and finalizing, and raises an error for unknown commands.
def read_next_char(self): nextchar = self.read_u8() cmd = self.read_u8() if cmd == 0x40: self.append_current(nextchar) elif cmd == 0xC0: self.push_current() self.append_current(nextchar) elif cmd == 0x08: self.append_current(nextcha...
def trailing_buy(self, pair, reinit=False): # returns trailing buy info for pair (init if necessary) if not pair in self.custom_info_trail_buy: self.custom_info_trail_buy[pair] = dict() if reinit or not 'trailing_buy' in self.custom_info_trail_buy[pair]: self.custom_info_...
This function manages trailing buy orders in a trading strategy. It modifies the DataFrame to indicate buy signals based on dynamic price conditions, updates trailing buy parameters (like uplimit and offset), and handles initiation, updates, or termination of trailing buys. The logic checks for open trades, current pri...
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: dataframe = super().populate_buy_trend(dataframe, metadata) if not self.trailing_buy_order_enabled or not self.config['runmode'].value in ('live', 'dry_run'): # no buy trailing return dataframe datafra...
def count_transitions(walk): """ Get the number of transitions in a walk """ return np.sum(get_transitions(walk)) def get_transitions(walk): """ Get a boolean array of transitions """ clusters = get_clusters(walk) transitions = np.append([0], np.diff(clusters)) transitions = (tra...
The function checks if a walk has more than 8 transitions between clusters, excluding switchbacks, by subtracting switchback counts from total transitions and verifying the result exceeds 8.
def enough_transitions(walk): """ Check that a walk transitions between clusters at least 9 times Does not include switchbacks """ n_transitions = count_transitions(walk) t = get_transitions(walk) n_switchbacks = count_switchbacks(t) return n_transitions - n_switchbacks > 8
def get_good_randomlattice_walk(graph, n): """ Finds a walk that: visits every node at least 3 times """ walk = np.array(walks.random_walk(graph, n)) while not enough_node_vists(walk): walk = np.array(walks.random_walk(graph, n)) return walk def get_randomlattice_SOAs(walk): n_tr...
This code initializes an experiment setup for a subject by configuring visual and graph conditions, organizing trial blocks based on order parameters, and predefining random walks and stimulus onset asynchronies (SOAs) for different graph types (random, modular, lattice, demo). It structures trials into two days with o...
def __init__(self, subject_id, block_order, visual_condition, n_trials): """ block_order: 0 = MLML/LMLM 1 = LMLM/MLML visual_condition: 0-3 (cue=x%2, color=x//2) n_trials: number of trials per block """ self.subject_id = subject_id self.bloc...
def get_good_modular_walk(graph, n): """ Finds a modular graph walk that: visits every node at least 3 times transitions between clsuters at least 9 times """ walk = np.array(walks.random_walk(graph, n)) while not (enough_node_vists(walk) and enough_transitions(walk)): walk = np.arra...
The main task of the code is to test the generation of modular walks on a graph. It verifies that each generated walk has sufficient transitions (excluding switchbacks) and ensures all nodes are visited at least 3 times. The test runs 10 iterations, asserting that transitions minus switchbacks exceed 8 and minimum node...
def test_modular_walk(): print("Testing modular walk generation") graph = graphs.modular for i in range(10): walk = get_good_modular_walk(graph, 100) n_transitions = count_transitions(walk) t = get_transitions(walk) n_switchbacks = count_switchbacks(t) c = Counte...
def get_good_modular_walk(graph, n): """ Finds a modular graph walk that: visits every node at least 3 times transitions between clsuters at least 9 times """ walk = np.array(walks.random_walk(graph, n)) while not (enough_node_vists(walk) and enough_transitions(walk)): walk = np.arra...
This code tests the generation and evaluation of modular Service-Oriented Architectures (SOAs) by iterating 10 times. It uses a predefined modular graph to create a walk, derives SOAs and transitions from the walk, calculates modular efficiency with a threshold of 1.1, and prints results. The goal is to validate the co...
def test_modular_SOAs(): print("Testing modular SOA generation") graph = graphs.modular walk = get_good_modular_walk(graph, 100) for i in range(10): SOAs = get_modular_SOAs(walk) transitions = get_transitions(walk) eff = calculate_modular_efficiency(transitions, SOAs, 1.1) ...
def test_modular_walk(): print("Testing modular walk generation") graph = graphs.modular for i in range(10): walk = get_good_modular_walk(graph, 100) n_transitions = count_transitions(walk) t = get_transitions(walk) n_switchbacks = count_switchbacks(t) c = Counte...
The main task of the code is to execute multiple test functions, including modular and random walk simulations, SOA (Service-Oriented Architecture) testing, subject generation validation, and block creation verification, to ensure the correctness and functionality of various system components.
def run_all_tests(): test_modular_walk() test_modular_SOAs() test_random_walk() test_random_SOAs() test_subject_generation() test_block_creation()