dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def connect() -> socket: """ Creates a socket obj that will use to communicate between two ip address with TCP protocol, and connects to the pre-defined SERVER_IP and SERVER_PORT """ print(f"connecting to {SERVER_IP} port {SERVER_PORT}") c_socket = socket.socket(socket.AF_INET, socket.SOCK_STREA...
The main task of the code is to launch a Trivia Client by connecting to a server, handling user authentication (signup/login), and providing a menu for actions like viewing scores, high scores, and playing trivia questions. It maintains a loop for user interactions until they choose to quit, ensuring proper connection ...
def main(): """ The main function to start the Trivia Client. - Establishes a connection to the server using 'connect'. - Prompts the user to sign up or log in. - If the user chooses to sign up, calls the 'signup' function to create a new user. - Calls the 'login' function to log in (either aft...
def set_theta(self, angle): """Sets the theta angle. Used for animating plots""" self.angle_deg = angle def set_noise(self, noise_val): """Sets the noise value. Used for animating plots""" self.noise = noise_val def gen_readout(self, calibration_func, param_set, distortion_dial=0, verbos...
The code animates cross-correlation plots by varying either the angle ('theta') or noise level ('noise'), updating four subplots: mask, resampled mask, detector readout, and cross-correlation results. It calculates cross-correlation, determines lag, and dynamically updates visualizations for each parameter change, disp...
def animate(self, range_vals, mode): """Plots cross correlation but animates either the change in angle or change in noise""" figure, ax = plt.subplots(4, constrained_layout=True, figsize=(20, 10)) if mode == 'theta': range_nums = range(range_vals[0], range_vals[1]) ...
def gen_metric(mask, count): """Generates our metric which is ratio of xcor peak to the second highest peak Using this metric gives relatively precise results, though not accurate""" try: #print(mask, count) xcor = np.correlate(mask, count, 'full') #print(xcor) #print(xcor)...
The code optimizes parameters (a, b, c, d) to improve a metric derived from a mask and naive values. It iteratively generates candidate solutions, evaluates their metrics, and updates the parameters if a better solution is found, repeating until no further improvement is possible. The goal is to converge on optimal par...
def optimize(mask): #Actual answer, use for reference #a, b, c, d = 1.573374532385897, 4.019185691943018, -4.00502684639661, 1.359444812728886 current_metric = gen_metric(mask, naive_vals) #print(current_metric) current_arr, a, b, c, d = gen_random(naive_vals) parameters = [a, b, c, d] ...
def gen_readout(mask, angle_deg): """Given a mask and an incidence angle, simulate photons hitting the detector through that mask and at that angle """ # #Contains our extrapolated mask readout = np.zeros(n_det_pix) # simulate a bunch of photons hitting the detector for i in range(n_photons)...
The code calculates a detector readout for a given angle, resamples a mask to match the detector's pixel count, performs cross-correlation between the resampled mask and detector readout to determine alignment lag, optimizes mask parameters using a sigmoid function, and generates plots comparing original and optimized ...
def main(): # find the detector readout for a given angle theta_deg = 0 # incidence angle, 0 if perpendicular det_readout = gen_readout(mask, theta_deg) if verbose: print(det_readout) # to do cross-correlation we must resample the mask to have as # many pixels as the detecto...
def clean_file(name): print("clean_file", name) id = "" # graph id c = "" # n clusters e = 0 # n edges pm = 0. plm = 0. pdi = 0. pdbi = 0. count = 1 with open("{}-stats.csv".format(name)) as fin: with open("{}-stats-clean.csv".format(name), mode=...
The code processes and predicts cluster assignments from cleaned data. It loads a dataset, converts column types, and applies a prediction function with specified clusters and error tolerance, then saves results.
def process_results(name, nclusters, e=ERR): clean_file(name) # return df = pdx.load_data("{}-stats-clean.csv".format(name), dtype=[float] * 8 + [enumerate] * 2 + [float] * 42) # print(df.dtypes) df = df[COLUMNS].astype({"c": int, "id": int, "r": int, "e": int, "numClusters": int}) save_resul...
def on_start(self): """ Hook for doing any setup that should be done *after* the actor is started, but *before* it starts processing messages. For :class:`ThreadingActor`, this method is executed in the actor's own thread, while :meth:`__init__` is executed in the thread that cr...
The main task of the code is to manage an actor's event loop by processing incoming messages from the actor inbox, handling exceptions during message processing, and coordinating actor lifecycle events. It initializes the actor, processes each message by invoking _handle_receive, sends responses to reply_to if specifie...
def _actor_loop(self): """ The actor's event loop. This is the method that will be executed by the thread or greenlet. """ try: self.on_start() except Exception: self._handle_failure(*sys.exc_info()) while not self.actor_stopped.is_set():...
def set_cling_compile_options(add_defaults = False): # extra optimization flags for Cling if not 'EXTRA_CLING_ARGS' in os.environ: CURRENT_ARGS = '' add_defaults = True else: CURRENT_ARGS = os.environ['EXTRA_CLING_ARGS'] enable_cuda = os.environ.get('CLING_ENABLE_CUDA', '0') i...
The function `load_cpp_backend` loads the C++ backend library for `cppyy`, handling dynamic linking. It ensures precompiled headers, constructs possible library filenames (using environment variables or defaults with platform-specific extensions), and attempts to load the library. If unsuccessful, it aggregates errors ...
def load_cpp_backend(): set_cling_compile_options() if not _precompiled_header_ensured: # the precompiled header of standard and system headers is not part of the # distribution as there are too many varieties; create it now if needed ensure_precompiled_header() names = list() try: ...
def open_w_gdal(self, path: str) -> gdal.Dataset: ds = gdal.OpenEx(path) if not ds: logging.warning(f'Could not open {path}. Is this a valid file?') return ds def get_ds_extent(self, ds: gdal.Dataset) -> Tuple[float, ...]: geo = ds.GetGeoTransform() minx = geo[0] ...
This function creates a buffered version of a Digital Elevation Model (DEM) by expanding its geographic extent using a predefined buffer distance. It adjusts the DEM's boundaries, ensures valid coordinate ranges, and generates a new Virtual Raster (VRT) file combining overlapping DEMs within the expanded extent. The bu...
def buffer_dem(self, dem: str) -> str: ds = self.open_w_gdal(dem) if not ds: return projection = ds.GetProjection() no_data_value = ds.GetRasterBand(1).GetNoDataValue() # try: # srs = osr.SpatialReference(wkt=ds.GetProjection()) # if srs.IsProjected(): ...
def get_joint_angles(self): ''' Getting the (theta) variable in the Denavit-Hartenberg parameters ''' return [self.link_list[i].dh_params_[0] for i in range(len(self.link_list))] def forward_kinematics(self): trans = self.transformation_matrix() # getting the end effector position ...
This code performs inverse kinematics using an iterative numerical method. It calculates the difference between the desired end-effector pose and the current pose, computes the Jacobian matrix, applies an Euler angle transformation matrix (K_zyz), and updates joint angles via pseudo-inverse of the Jacobian. The process...
def inverse_kinematics(self, ref_ee_pose): goal_joint_angles = None # saving the initial joint angle values initial_joint_angles = self.get_joint_angles() # iterative solution to the inverse kinematics ee_pose = None for cnt in range(1000): # getting the ...
def get_y(model, results, x): return model({i: results.params[i].value for i in results.params}, x) def log_likelihood(N_data, y_true, y_model, x, logscaled=False): return -(N_data / 2) * np.log(RSS(y_true, y_model, x, logscaled) / N_data) def likelihood_ratio(llmin, llmax): return(2*(llmax-llmin))
The function `LRT` performs a likelihood ratio test (LRT) to compare two statistical models (`model1` and `model2`) using their fitted results (`results1` and `results2`). It calculates log-likelihoods for both models based on predicted values and observed data (`y`), computes the likelihood ratio statistic, and return...
def LRT(y, results1, model1, results2, model2, distances, logscaled = False): """ performs a likelihood ratio test for two lmfit models """ # n samples n = len(distances) # n parameters for each k1 = len(results1.params) k2 = len(results2.params) # get model y y1 = get_y(mo...
def get_y(model, results, x): return model({i: results.params[i].value for i in results.params}, x) def r2(y_true, y_model, x, logscaled=False): ss_res = RSS(y_true, y_model, x, logscaled=logscaled) ss_tot = RSS(y_true, np.mean(y_true), x, logscaled=logscaled) return 1 - ss_res / ss_tot def AICc(N_data,...
The function evaluates model fit metrics (R² and AICc) for three decay models—exponential, power law, and combined—using input data and model parameters. It applies optional masking to exclude non-positive signal values and computes log-scaled metrics if enabled. Results include R² scores and AICc values for each model...
def fit_results( sig, distances, results_exp, results_power, results_pow_exp, mask=True, logscaled=True, ): if mask: mask = sig > 0 distances = distances[mask] sig = sig[mask] """ Get model fit results""" y_exp = get_y(exp_decay, results_exp, distances) ...
def res_to_matrix(res): all_keys = set() l = [res['point']] + res['environs'] for env in l: all_keys |= keys(env) reference = np.array(list(all_keys)) idxer = np.ones(len(l), dtype = bool) vs = [] for it, env in enumerate(l): v = np.zeros(len(reference)) try: ...
Your returnThe code generates a Bokeh scatter plot visualizing data points with colors indicating their "fringiness" (s values). The first row is highlighted in red. It processes input coordinates (x, y) and fringiness values (s), maps s to a color gradient using viridis (or defaults to position-based colors if s is em...
def embedding_plot_bokeh(x, y, s, res): """ Draws a Bokeh scatter plot with the color indicating the fringiness. The first row is indicated in red. Parameters ---------- x : array_like x coordinates of the points. y : array_like y coordinates of the points. s : array_li...
def r_auth_token(): resp = requests.get('https://commerce.reuters.com/rmd/rest/xml/login?username=HackZurichAPI&password=8XtQb447') xml = ET.fromstring(resp.text) global auth_token auth_token = xml.text def load_cache(): global cache cache = {} try: with open('cache', 'rb') as cachef...
The code analyzes input text to extract key entities, identifies main actors, searches for related articles, processes article content, and generates environmental analyses. It returns a dictionary containing the original analysis and derived environmental insights, while managing authentication, caching, and asynchron...
def run(text, limit=15): r_auth_token() #In case it timed out load_cache() point = analyze(text) entities = point['entities'] main_actors = sorted(entities, key=entities.get)[-6:] related_articles = r_search(main_actors, limit) fut_article_bodies = (r_body_fut(id) for id in related_articles)...
def r_auth_token(): resp = requests.get('https://commerce.reuters.com/rmd/rest/xml/login?username=HackZurichAPI&password=8XtQb447') xml = ET.fromstring(resp.text) global auth_token auth_token = xml.text def load_cache(): global cache cache = {} try: with open('cache', 'rb') as cachef...
The code analyzes input text to identify key entities, retrieves related articles, extracts their entities, and compiles a structured response with the analysis and enriched article data, using caching for efficiency.
def fastrun(text, limit=300): r_auth_token() #In case it timed out load_cache() point = analyze(text) entities = point['entities'] main_actors = sorted(entities, key=entities.get) related_articles = r_search(main_actors, limit) fut_article_entities = (r_entities_fut(id) for id in related_art...
def WaitUntilVisible(self, locator): LoggerUtil.getLogger(self).info("{} {}".format("Wait until element is Visible ", locator)) element = self.driver.find_element(*locator) self.SteadyWait(locator) try: self.waiter.until(EC.visibility_of(element)) except Exception as ...
The main task of the code is to select an option from a dropdown menu by its visible text using Selenium. It locates the dropdown element, ensures it is visible and clickable, moves to the element, and uses the Select class to choose the specified value. If an error occurs during selection, it logs a soft assertion fai...
def SelectFromDropdownByText(self, dropdownLocator, Value): LoggerUtil.getLogger(self).info("{} {} {} {}".format("select ", Value, "from dropdown", dropdownLocator)) dropdownelement = self.driver.find_element(*dropdownLocator) self.WaitUntilVisible(dropdownLocator) self.WaitUntilClickabl...
def WaitUntilVisible(self, locator): LoggerUtil.getLogger(self).info("{} {}".format("Wait until element is Visible ", locator)) element = self.driver.find_element(*locator) self.SteadyWait(locator) try: self.waiter.until(EC.visibility_of(element)) except Exception as ...
The main task of the code is to input specified text into a text box located by a given locator. It logs the action, waits for the element to be visible, clears the textbox using backspace, clicks the element, and enters the provided text. If an error occurs during execution, it triggers a soft assertion failure to han...
def SetTextBox(self, locator, textToAdd): LoggerUtil.getLogger(self).info("{} {} {} {}".format("Fill text Box", locator, ": ", textToAdd)) element = self.driver.find_element(*locator) self.WaitUntilVisible(locator) self.MoveToElement(locator).clear() try: element.clic...
def binarize_data(pixel_values): ''' Binarize the data by thresholding around 0.5 ''' return np.where(pixel_values > 0.5, 1.0, 0.0) def compute_parameters(train_data, train_labels): ''' Compute the eta MAP estimate/MLE with augmented data You should return a numpy array of shape (10, 64) ...
The main task of the code is to train a model using binarized training data, compute model parameters (eta), evaluate its performance via average conditional log probabilities on train/test sets, generate synthetic data, and report classification accuracy on both train and test sets using the learned parameters.
def main(): train_data, train_labels, test_data, test_labels = data.load_all_data('data') train_data, test_data = binarize_data(train_data), binarize_data(test_data) # Fit the model eta = compute_parameters(train_data, train_labels) # Evaluation plot_images(eta) generate_new_data(eta) ...
def compute_mean_mles(train_data, train_labels): ''' Compute the mean estimate for each digit class Should return a numpy array of size (10,64) The ith row will correspond to the mean estimate for digit class i ''' means = np.zeros((10, 64)) for i in range(0, 10): #i_labels = [trai...
The code's main task is to load training and test data, compute mean and covariance matrices for each class using MLE, visualize covariance diagonals, evaluate average log likelihoods on train/test data, classify data using computed parameters, and report accuracy on both train and test sets.
def main(): train_data, train_labels, test_data, test_labels = data.load_all_data('data') # Fit the model means = compute_mean_mles(train_data, train_labels) covariances = compute_sigma_mles(train_data, train_labels) # plot covariance plot_cov_diagonal(covariances) # Evaluation print(...
def _get_storage_obj(self): return self._data_storage def _is_layered_aux(self): # determine if this is the special aux variable case if ( self.structure.name.lower() == "aux" and self._get_storage_obj().layered ): return True else: ...
This function generates a file entry string for data storage, handling both scalar and layered data structures. It checks storage validity, formats scalar data with indentation, processes layered data by iterating through specified layers, and constructs entries using helper methods. It returns a concatenated string re...
def _get_file_entry( self, layer=None, ext_file_action=ExtFileAction.copy_relative_paths ): if isinstance(layer, int): layer = (layer,) data_storage = self._get_storage_obj() if ( data_storage is None or data_storage.layer_storage.get_total_size() ...
def eval_wic(args,trainer_mim=None): with torch.no_grad(): data_scores=produce_wic_data(args.test_data_dir,args.base_embed) wicdata={} wicdata['train_1'],wicdata['train_2'],train_scores,_,_,_,_=data_scores['train'] wicdata['dev_1'],wicdata['dev_2'],dev_scores,_,_,_,_=data_sc...
The code evaluates model performance on various tasks (WIC, SCWS, USIM, SimLex) in two scenarios: original setup and after adjustment using `trainer_mim`. It first runs baseline evaluations, then re-tests with the adjusted model to compare results.
def evaluation(trainer_mim,args): print ('==========original space===========') eval_wic(args) eval_sim('scws',args) eval_sim('usim',args) eval_context_simlex(args) print ('=============after adjustiment=============') eval_wic(args,trainer_mim) eval_sim('scws',args,trainer_mim) eva...
def is_complete(board): return all(all(val is not EMPTY for val in row) for row in board) def find_first_empty(board): for i, row in enumerate(board): for j, val in enumerate(row): if val == EMPTY: return i,j; return False def valid_so_far(board): if not row...
This code solves a Sudoku puzzle using backtracking. It recursively fills empty cells with numbers 1-9, checking validity at each step. If a number leads to a complete solution, it returns the solved board; otherwise, it backtracks and tries the next value. The algorithm ensures all constraints (rows, columns, 3x3 grid...
def sudoku(board): if is_complete(board): return board r, c = find_first_empty(board) #set values 1 to 9 and check; for i in range(1, 10): board[r][c] = i #print(board) if valid_so_far(board): #print(board) result = sudok...
def get_registration_info(self, term: str): self.term = term data = self.__get_registration_info(term) if len(data) < 6: raise ValueError() waitlist_data = { 'seats': data[3], 'taken': data[4], 'vacant': data[5] } load = { ...
The code generates a string representation of an object's registration details, including its name, specific data fields (excluding 'waitlist'), waitlist availability status, and prerequisites. It formats the information with line breaks and tabs for readability, returning a structured summary of the object's attribute...
def __str__(self) -> str: data = self.get_registration_info(self.term) res = "{}\n".format(self.name) for name in data: if name == 'waitlist': continue res += "{}:\t{}\n".format(name, data[name]) res += "waitlist open: {}\n".format('yes' if self.waitlist_available...
def gather_coordinates(filepath, simulation_sets): results = [] for simulation in simulation_sets: simulation_directories = simulation[1] simulation_name = simulation[0] coordinates_set = [] for directory in simulation_directories: base_name = os.path.basename(directo...
The function `create_graphic` processes simulation data by gathering coordinates from a file, computing averages and errors, then generating a visual graph with specified labels and title.
def create_graphic(simulation_sets, filepath, xlabel, graph_title): coordinates = gather_coordinates(filepath, simulation_sets) graph_values = create_averages_and_errors(coordinates) generate_graphic_file(graph_values, xlabel, graph_title)
def handle_arguments(): quick = False debug = False if "quick" in sys.argv: quick = True sys.argv.remove("quick") if "debug" in sys.argv: debug = True sys.argv.remove("debug") if "print-algorithms" in sys.argv: print_integration_algorithms("all-integration...
The main task of the code is to configure and execute a molecular dynamics simulation with adjustable parameters (e.g., temperature, time steps, simulation lengths) based on input arguments. It sets simulation settings for different modes (quick, GAMD-CMD base, or default), initializes performance metrics, runs the sim...
def main(): [boost_type, output_directory, device, platform, debug, quick] = handle_arguments() temperature = 300 dt = 2.0 * femtoseconds if quick: ntcmdprep = 2000 ntcmd = 10000 ntebprep = 2000 nteb = 20000 nstlim = 60000 ntave = 250 frame_size =...
def write_out_phi_cpptraj_command(output_directory, starting_frame, boost_type_str): paths = write_out_1d_rc_cpptraj_command(output_directory, starting_frame, "phi", ":1@C :2@N :2@CA :2@C out ", ...
The function generates and executes CPPtraj command files to compute phi/psi dihedral angles and their 2D distributions from molecular dynamics trajectories. It writes individual command files for phi, psi, and combined phi-psi analyses, runs them using the provided topology file, and returns structured results contain...
def write_out_and_run_cpptraj_command_files(output_directory, starting_frame, topology_filepath, boost_type_str=None): phi_paths = write_out_phi_cpptraj_command(output_directory, starting_frame, boost_type_str) psi_paths ...
def write_out_and_run_cpptraj_command_files(output_directory, starting_frame, topology_filepath, boost_type_str=None): phi_paths = write_out_phi_cpptraj_command(output_directory, starting_frame, boost_type_str) psi_paths ...
The function prepares data for CPPtraj analysis by generating input files, executing commands, and processing 1D/2D trajectory data. It writes command files, runs simulations, and organizes output paths for subsequent analysis.
def perform_data_prep(output_directory, starting_frame, topology_filepath, boost_type_str=None): data_files = write_out_and_run_cpptraj_command_files(output_directory, starting_frame, ...
def data_processing(y, tx): """ Data processing applied to all our data before running algorithms. Several steps are better described in the code : - Feature correlations scores. - Outliers and missing values processing. - Data normalization. - Value assignation to missing values. Param...
The main task of the code is to train a Higgs boson dataset by performing polynomial feature expansion, splitting data by jet categories, and applying ridge regression for each category to compute weights and minimized losses. It processes input data, expands features, categorizes samples based on jet types, and iterat...
def train(y, tx, best_lambda, best_degree): """ Train Higgs boson data following multiple steps detailed in code such as data processing, polynomial feature expansion and data splitting based on categories of jet Parameters ---------- tx : ndarray, samples and features best_lambda : float, regu...
def data_processing_test(tx): """ Data processing applied to testing data before running algorithms. Several steps are better described in the code : - Feature correlations scores. - Outliers and missing values processing. - Data normalization. - Value assignation to missing values. Par...
The main task of the code is to predict Higgs boson data by processing test samples, applying polynomial feature expansion, splitting data by jet categories, and aggregating predictions using precomputed weights for each category. It returns the summed predictions across all categories before applying final classificat...
def test(tx_test, best_lambda, best_degree, weights): """ Test Higgs boson data with calculated weights following multiple steps detailed in code such as data processing, polynomial feature expansion and data splitting based on categories of jet Parameters ---------- tx : ndarray, samples and featu...
def get_default_device(): return torch.device('cuda') if torch.cuda.is_available() \ else torch.device('cpu') def batches_to_device(data_loader, device): for batch in data_loader: yield to_device(batch, device) def to_device(data, device): return [to_device(x, device) for x in data] if isinsta...
The main task of the code is to train a baseline ResNet101 model for 5 epochs using provided data loaders. It first configures the default device (GPU/TPU), transfers training/validation/test data batches to the device, initializes the model on the device, and executes the training process with the specified model and ...
def train_baseline(): device = get_default_device() batches_to_device(train_loader, device) batches_to_device(val_loader, device) batches_to_device(test_loader, device) model = to_device(resnet101, device) train(5, model, train_loader, val_loader)
def update_labeled_data(self, sample_ids): print("update_labeled_data") # check if sample_ids are in unlabeled_ids if not (set(sample_ids) <= set(self.unlabeled_ids)): raise Exception( "Some ids ({}) in sample_ids are not contained in unlabeled data pool: {}".format( ...
The code initializes an active learning setup by loading datasets, selecting initial unlabeled samples, and preparing labeled/unlabeled data structures. It uses config parameters to set initial/incremental sample sizes, seeds randomness, and randomly selects the first batch of samples to label, enabling iterative activ...
def __init__(self, cfg): """ """ self.cfg = cfg register_datasets() # get ids of all images self.unlabeled_jsons = DatasetCatalog.get(cfg.AL.DATASETS.TRAIN_UNLABELED) self.unlabeled_ids = [ image["image_id"] for image in self.unlabeled_jsons if image["file_...
def getRenewalTime( zo_mag, ustar_mag, density, cp, alpha, Qnet, viscosity ): Rfcr = -2.0e-04 if(density < 50): Rfcr = -2.0e-01 if(density < 50): Cshear = 53.32 else: Cshear = 209 # from Wick thesis if(density < 50): Cconv = 0.80 else: Cconv = 3.13 # from ...
The code solves for atmospheric boundary layer parameters, including friction velocity (ustar), temperature flux (tstar), moisture flux (qstar), and Monin-Obukhov length (1/L), under varying stability conditions. It iteratively adjusts these values using stability functions (phi_T, phi_Q), turbulent flux models (Stanto...
def solve( fixedcp, fixedwa, fixed_hsig, fixed_uen, fixed_ustar, neutral, CON_P, cp, CRIT, denwat, nu, qmixa, qmixw, sfcten, ss_prm, ss_val, ta, tskin, Qnet, zref, zreft, zrefq, ww, ww_eql, betag_set, betac_set, betas_set, z0_prm, warn ): global betac_prime, betag, betac, betas, betag_prime, betas_prim...
def pmix_( dyn_in_prm, dyn_in_val, dyn_in_val2, CONVECT, CONV_CRIT, pressure, air_moist_prm, air_moist_val_dum, sfc_moist_prm, sfc_moist_val_dum, salinity, ss_prm, ss_val_dum, t_air, sst_prm, t_skin, ref_ht_wind, ref_ht_tq, astab, Qnet, warn, flux_model, z0_mom_prm, z0_TQ_prm, ...
This function calculates atmospheric fluxes and height adjustments for wind, temperature, and moisture under various stability conditions. It adjusts parameters for neutral or specified conditions, computes equivalent neutral roughness lengths, and corrects fluxes to the desired height (z_wanted). It handles zero wind ...
def ht_adj_( dyn_in_prm, dyn_in_val, dyn_in_val2, CONVECT, CONV_CRIT, pressure, air_moist_prm, air_moist_val, sfc_moist_prm, sfc_moist_val, salinity, ss_prm, ss_val, t_air, sst_prm, t_skin, ref_ht_wind, ref_ht_tq, z_wanted, astab, eqv_neut_prm, Qnet, warn, flux_model, z0_mom_prm, z0_TQ_prm, stable_prm, ...
def int_or_none(params, name): text = param_as_str(params, name, "") if text.isdigit(): return int(text) else: return None def get_shopping_trip(tripid): st = db.query(db.ShoppingTrip).filter_by(uid=tripid).all() return None if len(st) != 1 else st[0] def editable_table(title, column...
This code generates an editable table for item types, either for a specific shopping trip or all item types. It retrieves item data from the database, filters based on trip context, and prepares rows with checkboxes, item details, and aisle information. The table allows edits and new entries if write access is granted,...
def item_types_edit(user, write_access, params): tripid = int_or_none(params, "trip") if tripid is not None: trip = get_shopping_trip(tripid) if trip is None: return {"template": "error.html", "message": "unrecognized trip ID"} requests = db.query(db.Request).filter(db.Reque...
def int_or_none(params, name): text = param_as_str(params, name, "") if text.isdigit(): return int(text) else: return None def get_shopping_trip(tripid): st = db.query(db.ShoppingTrip).filter_by(uid=tripid).all() return None if len(st) != 1 else st[0] def param_as_str(params, name, d...
This code generates a review list for shopping trip requests, either for viewing or editing. It retrieves trip data, filters requests by state if specified, prepares dropdown options, constructs table columns/rows with request details, and returns an editable table interface with actions for modification or review, bas...
def requests(user, write_access, params): tripid = int_or_none(params, "trip") if tripid is None: return {"template": "error.html", "message": "invalid trip ID"} trip = get_shopping_trip(tripid) if trip is None: return {"template": "error.html", "message": "unrecognized trip ID"} edi...
def primary_shopping_trip(): st = db.query(db.ShoppingTrip).filter_by(primary=True).all() return None if len(st) != 1 else st[0] def allowable_cost_object_uids(user): # TODO: make this simpler uids = [co.uid for co in db.query(db.CostObject).filter_by(kerberos=None).all()] user_uids = [co.uid for co...
The code generates an editable form for managing shopping trip requests, populating fields like item names, cost objects, quantities, and dates from a database. It retrieves user-specific data, prepares dropdown options, sets defaults, and constructs a table for editing existing entries or adding new ones, returning a ...
def request_entry(user, write_access, params): trip = primary_shopping_trip() if trip is None: return {"template": "error.html", "message": "no shopping trip was marked as primary"} trip_date = str(trip.date) allowable_cost_ids = allowable_cost_object_uids(user) if allowable_cost_ids is None...
def int_or_none(params, name): text = param_as_str(params, name, "") if text.isdigit(): return int(text) else: return None def get_shopping_trip(tripid): st = db.query(db.ShoppingTrip).filter_by(uid=tripid).all() return None if len(st) != 1 else st[0] def item_names_by_uids(): re...
This function generates an editable procurement dispositioning table for a shopping trip, displaying accepted requests with details like item names, quantities, locations, and cost objects. It validates user access, retrieves trip data, processes inventory locations, and structures a table with edit options, dropdowns,...
def request_procurement_dispatching(user, write_access, params): if not write_access: return {"template": "error.html", "message": "no QM access"} tripid = int_or_none(params, "trip") if tripid is None: return {"template": "error.html", "message": "invalid trip ID"} trip = get_shopping_...
def int_or_none(params, name): text = param_as_str(params, name, "") if text.isdigit(): return int(text) else: return None def get_shopping_trip(tripid): st = db.query(db.ShoppingTrip).filter_by(uid=tripid).all() return None if len(st) != 1 else st[0] def item_names_by_uids(): re...
The code generates an editable table for unloading processing, validating user access and trip data. It retrieves shopping trip details, item/cost data, and location options, then constructs a table with columns for editing requests, including item names, quantities, states, and procurement details. The table includes ...
def unload_processing(user, write_access, params): if not write_access: return {"template": "error.html", "message": "no QM access"} tripid = int_or_none(params, "trip") if tripid is None: return {"template": "error.html", "message": "invalid trip ID"} trip = get_shopping_trip(tripid) ...
def locations_by_uids(): return {loc.uid: loc.name for loc in db.query(db.Location).all()} def item_names_by_uids(): return {it.uid: it.name for it in db.query(db.ItemType).all()} def render_quantity(quantity, unit): fq = float(quantity) if str(quantity).endswith(".00"): fq = int(fq) textual...
The function generates an editable inventory retirement form to retire purchased items. It queries relevant requests, compiles details (ID, item name, comments, quantity, location, date), and creates a sortable table with checkboxes for retirement. It includes warnings about substituted items and ensures only 'purchase...
def purchase_retirement_list(user, write_access, params): communal_costids = [co.uid for co in db.query(db.CostObject).filter_by(kerberos=None).all()] requests = db.query(db.Request).filter(db.Request.itemid != None, db.Request.state == db.RequestState.purchased, db.Request.costid.in_(communal_costids), db.Requ...
def int_or_none(params, name): text = param_as_str(params, name, "") if text.isdigit(): return int(text) else: return None def get_shopping_trip(tripid): st = db.query(db.ShoppingTrip).filter_by(uid=tripid).all() return None if len(st) != 1 else st[0] def item_names_by_uids(): re...
The main task of the code is to generate an editable shopping list table for a specific trip, retrieving and sorting items by aisle, name, quantity, and other details, then returning the formatted data for display. It validates the trip ID, fetches related items and costs, constructs structured rows, sorts them, and ou...
def shopping_list(user, write_access, params): tripid = int_or_none(params, "trip") if tripid is None: return {"template": "error.html", "message": "invalid trip ID"} trip = get_shopping_trip(tripid) if trip is None: return {"template": "error.html", "message": "unrecognized trip ID"} ...
def item_names_by_uids(): return {it.uid: it.name for it in db.query(db.ItemType).all()} def cost_objects_by_uids(): return {co.uid: co.description for co in db.query(db.CostObject).all()} def build_table(objects, *columns): return [[(getattr(obj, col) if type(col) == str else col(obj)) for col in columns] ...
This function generates an editable table displaying transaction details (credit, debit, amount, dates, etc.) for review. It retrieves transaction data, formats it into rows with associated cost/object names, and prepares a dynamic creation form for adding new transactions if write access is enabled. The table includes...
def review_transactions(user, write_access, params): items = item_names_by_uids() costs = cost_objects_by_uids() transactions = db.query(db.Transaction).all() date_by_trip = {st.uid: st.date for st in db.query(db.ShoppingTrip).all()} requests = db.query(db.Request).all() formal_names = {req.uid:...
def cost_objects_by_uids(): return {co.uid: co.description for co in db.query(db.CostObject).all()} def allowable_cost_object_uids(user): # TODO: make this simpler uids = [co.uid for co in db.query(db.CostObject).filter_by(kerberos=None).all()] user_uids = [co.uid for co in db.query(db.CostObject).filte...
This function processes request updates for a trip, validating user permissions, request existence, and state/procurement changes. It updates existing requests or creates new ones based on parameters, ensuring allowable states and cost objects, then commits changes if edits occur.
def handle_request_updates(user, write_access, params, trip, require_edit=False, state_only=False, procurement_only=False): if write_access: allowable_cost_ids = cost_objects_by_uids().keys() else: allowable_cost_ids = allowable_cost_object_uids(user) if allowable_cost_ids is None: ...
def item_names_by_uids(): return {it.uid: it.name for it in db.query(db.ItemType).all()} def locations_by_uids(): return {loc.uid: loc.name for loc in db.query(db.Location).all()} def build_latest_inventory(*filter_queries): inventory = db.query(db.Inventory).filter(*filter_queries).order_by(db.Inventory.me...
The code generates a sorted inventory table for a user, retrieving item names, quantities, locations, and inventory status. It formats data into a structured table with columns for item name, quantity, location, last update timestamp, and full re-inventory status, then returns this table with a count of entries.
def inventory(user, write_access, params): items = item_names_by_uids() locations = locations_by_uids() objects = build_latest_inventory() rows = build_table(objects, lambda i: i.item.name, lambda i: render_quantity(i.quantity, i.unit), lambda i: locations.get(i.locationid, "#REF?"), "measurement", lamb...
def item_names_by_uids(): return {it.uid: it.name for it in db.query(db.ItemType).all()} def cost_objects_by_uids(): return {co.uid: co.description for co in db.query(db.CostObject).all()} def locations_by_uids(): return {loc.uid: loc.name for loc in db.query(db.Location).all()} def int_or_none(params, name...
The code retrieves and displays previous request results for a user, filtering by trip ID if provided. It fetches item, cost, and location data, queries database requests, and formats them into a table with fields like item name, quantity, cost, and status. It also generates a trip selection dropdown and returns an HTM...
def request_results(user, write_access, params): items = item_names_by_uids() costs = cost_objects_by_uids() locations = locations_by_uids() trip_dates = {t.uid: t.date for t in db.query(db.ShoppingTrip).all()} tripid = int_or_none(params, "trip") if tripid is not None and tripid not in trip_da...
def item_names_by_uids(): return {it.uid: it.name for it in db.query(db.ItemType).all()} def cost_objects_by_uids(): return {co.uid: co.description for co in db.query(db.CostObject).all()} def build_table(objects, *columns): return [[(getattr(obj, col) if type(col) == str else col(obj)) for col in columns] ...
The code generates a table of personal transactions for a user, calculating their net financial balance (owed or owed to them) from transactions where they are involved as a credit or debit party. It retrieves related data like item names, trip dates, and request details, formats the transactions into a structured tabl...
def personal_transactions(user, write_access, params): items = item_names_by_uids() costs = cost_objects_by_uids() user_uids = [co.uid for co in db.query(db.CostObject).filter_by(kerberos=user).all()] if not user_uids: return {"template": "error.html", "message": "no cost object found for user"...
def item_names_by_uids(): return {it.uid: it.name for it in db.query(db.ItemType).all()} def cost_objects_by_uids(): return {co.uid: co.description for co in db.query(db.CostObject).all()} def get_by_id(items, uid): if uid is None: return None return items.get(uid, "#REF?") def render_quantity(q...
This code generates a table listing communal requests with specific filters, excluding certain states, and dynamically adjusts the table structure by removing the cost ID column if all entries share the same cost ID.
def all_communal_requests(user, write_access, params): items = item_names_by_uids() costs = cost_objects_by_uids() communal_costids = [co.uid for co in db.query(db.CostObject).filter_by(kerberos=None).all()] locations = {l.uid: l.name for l in db.query(db.Location).all()} objects = db.query(db.Requ...
def int_or_none(params, name): text = param_as_str(params, name, "") if text.isdigit(): return int(text) else: return None def get_shopping_trip(tripid): st = db.query(db.ShoppingTrip).filter_by(uid=tripid).all() return None if len(st) != 1 else st[0] def requests(user, write_access,...
The function submits all draft requests associated with a specified trip by updating their state to "submitted" if the user has write access. It validates the trip ID and checks for trip existence, returning error messages for invalid inputs. After updating request states, it delegates further processing to the `reques...
def submit_drafts_confirmed(user, write_access, params): if not write_access: return {"template": "error.html", "message": "no QM access"} trip_id = int_or_none(params, "trip") if trip_id is None: return {"template": "error.html", "message": "invalid trip ID"} trip = get_shopping_trip(t...
def cost_objects_by_uids(): return {co.uid: co.description for co in db.query(db.CostObject).all()} def int_or_none(params, name): text = param_as_str(params, name, "") if text.isdigit(): return int(text) else: return None def get_shopping_trip(tripid): st = db.query(db.ShoppingTrip)...
The code validates transaction parameters, checks trip/request IDs, ensures valid cost IDs, verifies description/amount, and creates a new transaction if all criteria are met, returning error templates for invalid inputs or mismatches.
def add_transaction(user, write_access, params): if not write_access: return {"template": "error.html", "message": "no QM access"} allowable_cost_ids = cost_objects_by_uids().keys() trip_id = int_or_none(params, "trip_id") if trip_id is not None and get_shopping_trip(trip_id) is None: ...
def int_or_none(params, name): text = param_as_str(params, name, "") if text.isdigit(): return int(text) else: return None def get_shopping_trip(tripid): st = db.query(db.ShoppingTrip).filter_by(uid=tripid).all() return None if len(st) != 1 else st[0] def review_transactions(user, wr...
The code splits a cost object's total amount into equal parts among selected cost objects, creating transactions for each. It validates user access, checks parameters, ensures valid selections, calculates per-person shares, and commits new transactions while handling errors.
def split_costs_do(user, write_access, params): if not write_access: return {"template": "error.html", "message": "no QM access"} if not write_access: return {"template": "error.html", "message": "no QM access"} objid = int_or_none(params, "object") if objid is None: return {"t...
def primary_shopping_trip(): st = db.query(db.ShoppingTrip).filter_by(primary=True).all() return None if len(st) != 1 else st[0] def handle_request_updates(user, write_access, params, trip, require_edit=False, state_only=False, procurement_only=False): if write_access: allowable_cost_ids = cost_obje...
The function processes a form submission for a shopping trip. It validates the trip ID from parameters against the current primary trip, handles request updates if valid, and returns either an error or the next request entry.
def request_submit(user, write_access, params): trip = primary_shopping_trip() if trip is None or params.get("trip","") != str(trip.uid): return {"template": "error.html", "message": "primary shopping trip changed between page load and form submit"} res = handle_request_updates(user, False, params,...
def int_or_none(params, name): text = param_as_str(params, name, "") if text.isdigit(): return int(text) else: return None def get_shopping_trip(tripid): st = db.query(db.ShoppingTrip).filter_by(uid=tripid).all() return None if len(st) != 1 else st[0] def handle_request_updates(user,...
This function processes a request to modify a shopping trip. It checks write access, validates the trip ID, retrieves the trip, handles update requests, and redirects with parameters if updates fail. It returns error responses for invalid access, trip IDs, or unrecognized trips, or forwards to the requests function wit...
def request_modify(user, write_access, params): if not write_access: return {"template": "error.html", "message": "no QM access"} tripid = int_or_none(params, "trip") if tripid is None: return {"template": "error.html", "message": "invalid trip ID"} trip = get_shopping_trip(tripid) i...
def int_or_none(params, name): text = param_as_str(params, name, "") if text.isdigit(): return int(text) else: return None def get_shopping_trip(tripid): st = db.query(db.ShoppingTrip).filter_by(uid=tripid).all() return None if len(st) != 1 else st[0] def handle_request_updates(user,...
This function processes a procurement update request by validating user access, trip ID, and handling updates. If valid, it either returns an update result or delegates to dispatching logic.
def request_procurement_update(user, write_access, params): if not write_access: return {"template": "error.html", "message": "no QM access"} tripid = int_or_none(params, "trip") if tripid is None: return {"template": "error.html", "message": "invalid trip ID"} trip = get_shopping_trip(t...
def int_or_none(params, name): text = param_as_str(params, name, "") if text.isdigit(): return int(text) else: return None def get_shopping_trip(tripid): st = db.query(db.ShoppingTrip).filter_by(uid=tripid).all() return None if len(st) != 1 else st[0] def handle_request_updates(user,...
This function handles an update request for unloading a shopping trip. It verifies user write access, validates the trip ID, retrieves the trip data, processes update requests with specific constraints (edit and procurement-only), and delegates to unload processing if initial handling fails. The main task is to securel...
def request_unload_update(user, write_access, params): if not write_access: return {"template": "error.html", "message": "no QM access"} tripid = int_or_none(params, "trip") if tripid is None: return {"template": "error.html", "message": "invalid trip ID"} trip = get_shopping_trip(tripid...
def read_gpio(self, gpio_name): """Will read a corresponding GPIO pin after a value and index is given.""" (mcp_idx, pin) = self.INPUT_PINS[gpio_name] return self.mcp[mcp_idx].input(pin) def update_temp(self): """Will pdate all of the basic temp values.""" self.temp_healthy = sel...
The code updates system status by reading GPIO pins to determine armed/tripped states, calculates overall health based on component statuses, checks latched conditions, and triggers individual component and fan updates.
def update(self): """Will update all of the values taken from the IO pins.""" self.armed = self.read_gpio("armed") self.tripped = not self.read_gpio("tripped") self.overall = ( self.temp_healthy and self.humid_healthy and self.leak_healthy and self.pump_healthy ) ...
def findSequence(header, aln): sequence = "" found = False for line in open(aln).readlines(): if line.find(header) != -1: found = True continue if found: if line[0] == ">": break else: sequence += line[:-1] ...
The main task of the code is to process biological data (MSA, PDB, contact maps, conservation scores) by parsing command-line arguments, extracting sequence/structure information from configuration files, analyzing residue contacts, mapping secondary structures, and generating a formatted table linking alignment positi...
def main(): # We build an argument parser to parse the command line arguments parser = argparse.ArgumentParser() parser.add_argument('config', type=str, help='Path to the config file') parser.add_argument('conservation_scores', type=str, help='Path to the file with conservation scores') parser.add_a...
def extractImportantContacts(contact, threshold): contacts = set() i = 0 for line in (open(contact)).readlines(): linelist = line.split() if i == 0: i = 1 continue res_1 = int(linelist[0]) res_2 = int(linelist[1]) conf = float(linelist[2]) ...
The main task of the code is to generate 1000 perturbed protein sequences by combining conservation scores, contact information, and configuration parameters. It parses input files, extracts thresholds and sequence data, computes conserved positions and contacts, and iteratively creates new sequences using a consensus ...
def main(): # Build an argument parser to parse the command line arguments parser = argparse.ArgumentParser() parser.add_argument('config', type=str, help='Path to the config file') parser.add_argument('scores', type=str, help='Path to the file with conservation scores') parser.add_argument('contact...
def extract(proteins, idx, l): motif = [] for (i,j) in idx: motif.append(proteins[i][j:j+l]) return motif def get_ball_size(motifs): ball_sizes = [] for motif in motifs: x = max([dim[0] for dim in motif])- min([dim[0] for dim in motif]) y = max([dim[1] for dim in motif])- min...
The function `impose_step` processes structural data to find the optimal alignment (lowest TRMSD) among feasible motifs. It iterates over sample ranges, extracts motifs, calculates their "ball size," and filters those below a threshold `b`. For valid motifs, it superimposes them, computes feasibility and occupancy, and...
def impose_step(data): sample_ranges = data[0] centered_structs = data[1] min_trmsd = data[2] length = data[3] b = data[4] ID = data[5] count = 0 min_feasible = None min_consensus = None min_occ = None min_ball_size = None min_sample = None for sample_range in t...
def initialize_with_zeros(dim): w = np.zeros(dim).reshape(dim, 1) b = 0 assert(w.shape == (dim, 1)) assert(isinstance(b, float) or isinstance(b, int)) return w, b def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): costs = [] for i in range(num_iterations)...
The code trains a logistic regression model using gradient descent on training data, evaluates it on training and test sets, and returns model parameters, predictions, and training costs. It initializes weights, optimizes them via gradient descent, predicts class labels, and compiles results into a dictionary for outpu...
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False): w, b = initialize_with_zeros(len(X_train)) parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost = False) w = parameters["w"] b = ...
def get_init_data(self, init_data): if self.folder_path: path = get_first_file_path(self.folder_path) type = export_type(path) return fileLoader.Factory_fileLoader().get_file_loader(type)().load(self.folder_path, path_type='folder') if self.file_path: type...
The main task of the code is to process input data through a series of steps: initializing data, applying modeling operations (with progress tracking), dimensionality reduction if enabled, and cascading to subsequent processing stages. It filters out invalid results, tracks success/failure counts, and returns the final...
def process_all(self, init_data=None): init_data = self.get_init_data(init_data) if self.apply: processed_data = [i for i in (self.handle_process(data, idx, folder_base=self.folder_path) for idx, data in enumerate(tqdm(init_data, desc='[dataProcessing] now applying modeling for each data')))...
def copyState( state1, state2): for i in range(N): state1[i] = state2[i]; def generateBoard( board, state): fill(board, 0); for i in range(N): board[state[i]][i] = 1; def getNeighbour(board, state): # Declaring and initializing the # optimal board and state with # the current board and the state # as the s...
The main task of the code is to implement a hill-climbing algorithm to optimize a board configuration. It iteratively generates neighboring states, evaluates their objective values, and transitions to better neighbors. If a plateau or local optimum is detected (equal objective values but different states), it introduce...
def hillClimbing(board, state): # Declaring and initializing the # neighbour board and state with # the current board and the state # as the starting point. neighbourBoard = [[0 for _ in range(N)] for _ in range(N)] neighbourState = [0 for _ in range(N)] copyState(neighbourState, state); generateBoard(neighb...
def log_state(self, str): return self.log( str + f" state: '{self.get_state(self.entity)}'" + f" is_blocked: '{self.is_blocked()}'" + f" need_illumination: '{self.need_illumination()}'" + f" turn_on_enabled: '{self.turn_on_enabled}'" + f" i...
This function handles motion-triggered lighting control. It logs motion events, checks if the system is blocked, sets a timer to turn off lights after motion stops, and conditionally turns on lights only if they are off, illumination is needed, and activation is enabled. The function ensures lights are not unnecessaril...
def motion_recent(self, entity, attribute, old, new, kwargs): self.log_state("motion_recent") if self.is_blocked(): return # we do this before the illumination and turn_on_enabled checks, # because regardless of their policy, we want to (potentially) # turn off the ...
def log_state(self, str): return self.log( str + f" state: '{self.get_state(self.entity)}'" + f" is_blocked: '{self.is_blocked()}'" + f" need_illumination: '{self.need_illumination()}'" + f" turn_on_enabled: '{self.turn_on_enabled}'" + f" i...
This method handles an entity's "on" state change by logging the event, checking if the system is blocked (to prevent unintended actions), and initiating an off-timer to manage the entity's state, ensuring proper control flow and timing when manually activated.
def entity_on(self, entity, attribute, old, new, kwargs): self.log_state("entity_on") if self.is_blocked(): return # kick off the timer when manually turned on too self.set_off_timer()
def insert_admin(db: MongoClient): admin_data = { "username": "a-" + settings.admin_username, "password": utils.hash(settings.admin_password), "email": settings.admin_email } db["admins"].insert_one(admin_data) def insert_users(db: MongoClient): users_data = [] with open('e...
The function initializes a MongoDB database by dropping the existing database and inserting predefined data (admin, users, service providers, categories, services, bookings) into it. It uses a dependency-injected MongoClient to connect to the database specified in settings, ensuring a fresh start with initialized data ...
def initializeDB(db: MongoClient = Depends(get_db)): client = MongoClient(f"{settings.mongo_url}") client.drop_database(f"{settings.mongo_db}") insert_admin(db) insert_users(db) insert_service_providers(db) insert_categories(db) insert_services(db) insert_bookings(db) return {"...
def identify(a): ''' Identify method determines if 'a' is an operator or operand @param 'a' is an element in the array (reg_expr) @returns '1' for an operator or '0' for an operand ''' if a == '*' or a == '|' or a == '(' or a == ')': return 1 # operator else: return 0 def che...
The function `check_type` handles implicit concatenation ('@') in a regex parser by checking when to add '@' to the operator stack based on current and previous symbols, stack precedence, and context (e.g., after ')', operands, or '*'). It ensures correct operator precedence, updates the NFA, and appends '@' when neces...
def check_type(a, previous, operator_stack, operand_stack): ''' check_type: adds implied concat when necessary checks the type of the operator that is to be put on the stack handles concat operator and add in '@' for char or ')' followed by another char, '(', or star @param a is the current s...
def identify(a): ''' Identify method determines if 'a' is an operator or operand @param 'a' is an element in the array (reg_expr) @returns '1' for an operator or '0' for an operand ''' if a == '*' or a == '|' or a == '(' or a == ')': return 1 # operator else: return 0 def che...
The code parses a regular expression into a syntax tree (NFA) using two stacks. It processes each character, managing operator precedence by pushing operators and operands onto stacks, and constructs the NFA by popping and combining elements. Parentheses and implied concatenations are handled, ensuring correct operator...
def parse(reg_expr): ''' Parse method goes through and adds operators to the operator stack, keeping in mind order of precedence, and adds operands to the operand stack. Once you have gone through the whole reg_expr array, pop from the operator stack and pop twice from the operand stack, creating a ...
def validate_expr(str, alphabet): ''' validate_expr: takes in a string and the alphabet to make sure that the string is formatted properly @param str is the regular expression @param alphabet is the valid symbols in the language @returns check which is 1 if invalid and 0 if valid ''' re...
The code processes a regular expression and input strings to determine if each string is accepted by the corresponding DFA. It reads an alphabet, validates the regex, constructs an NFA using two stacks, converts it to a DFA, and simulates the DFA on each input string, writing "accept" or "reject" to the output file.
def main(argv=sys.argv): input_file = sys.argv[1] output_file = sys.argv[2] # try to open file try: ifp = open(input_file, 'r') except IOError: print("File not found. Please check to make sure that the file exists/path is correct") exit(1) # read in alphabet alphab...
def ReqBucketName(req_dict): keyStrArray = req_dict['Key'].split('/') return keyStrArray[0] def ReqFileName(req_dict): keyStrArray = req_dict['Key'].split('/') return keyStrArray[1] def SetMC(): ipaddress = LOCAL_IP mc = Minio(f"{ipaddress}:9000", access_key='minioadmin', secret_...
The code processes data from a MinIO bucket by parsing a JSON request to extract bucket and file names, retrieving the data using a MinIO client, processing it, and returning the original request.
def handle(req): reqJson = json.loads(req) minioBucketName=ReqBucketName(reqJson) minioFileName=ReqFileName(reqJson) mc = SetMC() data = GetDataFromBucketFile(minioBucketName, minioFileName, mc) ProcessData(data, minioFileName, mc) return req
def GetMinioInfos(req_dict): keyStrArray = req_dict['Key'].split('/') return keyStrArray[0], keyStrArray[1] def GetDataFromBucketFile(minioBucketName, minioFileName): mc.fget_object(minioBucketName, minioFileName, "/tmp/" + minioFileName) with open("/tmp/" + minioFileName) as json_file: data = j...
The code processes a request by parsing JSON input to extract MinIO bucket and file information, retrieves data from the specified MinIO bucket/file, processes the data, and returns the processed result.
def handle(req): req_dict = json.loads(req) minioBucketName, minioFileName = GetMinioInfos(req_dict) data = GetDataFromBucketFile(minioBucketName, minioFileName) response = ProcessData(data, minioFileName) return response
def GetMinioInfos(req_dict): keyStrArray = req_dict['Key'].split('/') return keyStrArray[0], keyStrArray[1] def GetDataFromBucketFile(minioBucketName, minioFileName): mc.fget_object(minioBucketName, minioFileName, "/tmp/" + minioFileName) with open("/tmp/" + minioFileName) as json_file: data = j...
The code processes data retrieved from a MinIO bucket by parsing the input request, fetching the specified file, and returning the processed result.
def handle(req): req_dict = json.loads(req) minioBucketName, minioFileName = GetMinioInfos(req_dict) data = GetDataFromBucketFile(minioBucketName, minioFileName) response = ProcessData(data, minioFileName) return response
def _extract_global_statement(buffer, row): buffer_str = "\n".join(buffer[:]) module = ast.parse(buffer_str) for node in ast.iter_child_nodes(module): first_line = node.lineno last_line = node.end_lineno if row >= first_line and row <= last_line: return "\n".join(buffer[f...
The function `eval_global_statement` extracts a global statement from the current Vim buffer at the cursor's row, evaluates it if found, or prints a message if no statement is selected.
def eval_global_statement(): row = vim.current.window.cursor[0] statement_code = _extract_global_statement(vim.current.buffer, row) if statement_code is not None: eval_code(statement_code) else: _print("No global statement selected")
def _update(self): self._forward() self._critical_path_length = max(nx.get_node_attributes(self, 'EF').values()) self._backward() self._compute_critical_path() self._dirty = False def _add_tasks(self, critical_path): final_task_time = self._node[critical_path[-1]]["ES"] +...
The code identifies and returns the critical path of a project network by first updating the network if necessary, sorting nodes by their earliest start time, adding tasks to the path, and connecting any hanging nodes to ensure continuity.
def critical_path(self): if self._dirty: self._update() critical_path = sorted(self._criticalPath, key=lambda x: self._node[x]['ES']) self._add_tasks(critical_path) self._connect_hanging_nodes() return critical_path
def on_click_start(processor, event): """Records the starting coordinates of a mouse drag for selecting an area.""" processor.variables.start_x = processor.viewer_controller.current_viewer.canvasx(event.x) processor.variables.start_y = processor.viewer_controller.current_viewer.canvasy(event.y) def on_dragg...
The function initiates or toggles an entity operation (add/delete/merge) by activating/deactivating the corresponding status, binding/unbinding mouse/keyboard events for user interaction, and ensuring only one operation is active at a time. It sets focus on the viewer, manages status indicators, and links events to han...
def start_operating(processor, operation_type): """Initiates an entity operation (add, delete, or merge) and sets up event bindings.""" processor.variables.slice_type.set(SLICE_TYPES[2]) current_viewer = processor.viewer_controller.current_viewer merge_status, delete_status, add_status = processor.varia...
def find_first_small_bounding_box(self, minimum_box_size): """Finds the first bounding box in the set that has a size smaller than the given minimum size.""" for bbox in self.bounding_boxes: if bbox.size()[0] < minimum_box_size[0] or bbox.size()[1] < minimum_box_size[1]: retu...
The code merges small bounding boxes by iteratively identifying the closest pair, combining them into a larger box, and repeating until all remaining boxes meet the specified minimum size. It removes the original small boxes and replaces them with merged boxes, updating the set of bounding boxes accordingly.
def fix_merged_bounding_boxes(self, minimum_box_size): """ Merges small bounding boxes by iteratively finding the closest pair and merging them. Args: minimum_box_size (tuple): A tuple representing the minimum width and height for a bounding box. Returns: set: T...
def print_table(self, n): # Stack 1-D arrays as columns into a 2-D array. particle_xy = np.column_stack((self.particle_x, self.particle_y)) pBest_xy = np.column_stack((self.pBest_x, self.pBest_y)) velocity_xy = np.column_stack((self.velocity_x, self.velocity_y)) # Rounded value ...
The code performs iterative optimization by updating particle velocities and tracking personal/global best solutions. It runs 'n' iterations, printing progress at each step, and finally outputs the minimum value of the fitness function achieved using the global best solution (gBest_x, gBest_y).
def iterate(self, n) -> None: self.print_table("Beginning") print() for j in range(n): self.findGbest() self.findPbest() self.updateV() self.print_table(j + 1) print() print(f"Minimum value of f(x) = {fitness_function(self.gBe...
def print_table(self, n): # Rounded value rounded_particle = np.round(self.particle, 3) rounded_determine_fx = np.round(self.determineFunction(), 3) rounded_fx_pBest = np.round(self.evaluatePbestFitness(), 3) if self.gBest is not None: rounded_fx_gBest = np.round(fitn...
The code performs optimization iterations by updating global and particle best positions, velocities, and tracking progress. It runs 'n' iterations, printing intermediate results, then outputs the minimum function value using the final global best solution.
def iterate(self, n) -> None: self.print_table("Beginning") print() for j in range(n): self.findGbest() self.findPbest() self.updateV() self.print_table(j + 1) print() print(f"Minimum value of f(x) = {fitness_function(self.gBe...
def determineFunction(self) -> list[float]: return [ fitness_function(x, y) for x, y in zip(self.particle_x, self.particle_y) ] def evaluatePbestFitness(self) -> list[float]: return [fitness_function(p, q) for p, q in zip(self.pBest_x, self.pBest_y)] def fitness_function(x, y): r...
The code implements a Particle Swarm Optimization (PSO) algorithm, iterating `n` times to update particle positions, velocities, and best solutions (pBest and gBest). It initializes and prints particle states, evaluates fitness functions, and updates positions based on velocity adjustments, aiming to converge toward th...
def iterate(self, n) -> None: # Matrix of particle, pBest, and velocity particle_xy = np.column_stack((self.particle_x, self.particle_y)) pBest_xy = np.column_stack((self.pBest_x, self.pBest_y)) velocity_xy = np.column_stack((self.velocity_x, self.velocity_y)) print(f"Beginning ...
def determineFunction(self) -> list[float]: return [fitness_function(x) for x in self.particle] def evaluatePbestFitness(self) -> list[float]: return [fitness_function(p) for p in self.pBest] def fitness_function(x): return x**3 + 3 * x**2 - 12 def findGbest(self) -> None: if not self.gBest:...
The code implements an iterative optimization process using Particle Swarm Optimization (PSO). It initializes and updates a particle's position, velocity, personal best (pBest), and global best (gBest) over `n` iterations. Each iteration evaluates the fitness function, updates the particle's movement, and prints interm...
def iterate(self, n) -> None: print(f"Beginning Value") print(f"Particle (x) = {self.particle}") print(f"Determine fx = {self.determineFunction()}") print(f"fx(pBest) = {self.evaluatePbestFitness()}") print( f"fx(gBest) = {fitness_function(self.gBest) if self.gBest is...
def findPbest(self) -> None: if len(self.pBest) < len(self.particle): self.pBest.extend([np.copy(p) for p in self.particle[len(self.pBest) :]]) for i in range(len(self.particle)): if fitness_function(self.particle[i]) < fitness_function(self.pBest[i]): self.pBest[...
The code animates a Particle Swarm Optimization (PSO) process by updating particle velocities, positions, personal/global bests, and visualizing iterations. It prints iteration details, clears the plot, redraws particle positions and fitness landscape, and updates the plot title/labels for each iteration to track the o...
def animate(self, i, ax): if self.first_iteration: self.first_iteration = False else: # Print informasi untuk iterasi selanjutnya self.findPbest() self.findGbest() self.updateV() print(f"Iterasi {i+1}") print("Initializ...
def feedforward(self, X): """Produces output from the input 2D array (X)""" self.inputs = np.copy(X) self.hidden.activations = X @ self.hidden.weights self.hidden.activations += self.hidden.biases self.hidden.activations = self.hidden.actfn(self.hidden.activations) self...
This code trains a neural network using mini-batch gradient descent. It iterates over epochs, shuffles data, processes batches with forward/backward passes, accumulates costs, and evaluates validation accuracy if provided.
def fit(self, X, Y, no_epochs, batch_size, validation=()): """This method coordinates the learning process""" N = X.shape[0] # nuber of total learning samples for epoch in range(1, no_epochs + 1): print("Epoch:", epoch) X, Y = shuffle_data(X, Y) costs = [] ...
def create_temp_table(bq_client, gcs_file_path: str): table_schema = infer_schema_from_csv(gcs_file_path) print('-'*80) print(f'schema_inferred : \n {table_schema}') print('-'*80) table_id = f"{PROJECT_ID}.{STG_DATASET_ID}.{CP_TEMP_TABLE}" query = f'DROP TABLE IF EXISTS {table_id}' quer...
(The main task of the code is to process multiple CSV files by loading them into a Google BigQuery table, handling exceptions, and archiving/rejecting files based on success/failure. It creates temporary tables, transfers data to a final table, executes post-processing procedures, and logs results. The function iterate...
def csv_to_BigQuery(logging,project_id:str,dataset_id:str,table_name:str,file_list:list, path:str,header_rows:int,log_checker,bucket_name): sucess_list,excpt_lis= [],{} bq_client = bigquery.Client() table_id = f'{project_id}.{dataset_id}.{table_name}' final_table_name = CP_FINAL_TABLE csv_path_rege...
def CLAddedMass(omega, A, t): return np.pi *1.0/2.0 * HeaveAcceleration(omega, A, t) def HeaveVelocity(omega, A, t): return A*omega*np.cos(omega*t) def CLCirc(omega, A, t, k): # The minus sign here is debatable. In other derivations it is not present. But I think it should be # out of phase with the heave vel...
The main task of the code is to calculate the total lift coefficient (CLTotal) by summing the added mass contribution (CLAddedMass) and the product of heave velocity (HeaveVelocity) and circulation-based lift (CLCirc). The function combines these components using input parameters omega (angular frequency), A (amplitude...
def CLTotal(omega, A, t, t_cir, k): return CLAddedMass(omega, A, t_cir) + HeaveVelocity(omega, A, t)*CLCirc(omega, A, t, k)
def TheoPhase(k, T): theo = theo_fun(k) theor = np.real(theo) theoi = np.imag(theo) return np.arctan(theoi/theor)/(2*np.pi)*T def CLAddedMass(omega, A, t): return np.pi *1.0/2.0 * HeaveAcceleration(omega, A, t) def CLCirc(omega, A, t, k): # The minus sign here is debatable. In other derivations it ...
The function calculates the total force by combining added mass force (CLAddedMass) and circulatory force (CLCirc), using heave period $ T $, amplitude $ A $, and $ n $ evaluation points. It computes time steps, angular frequency $ \omega $, and a phase-shifted time array $ t_{\text{cir}} $ for circulatory force, then ...
def CLTotalSimple(T, A, n): """ Requires: Heave period T Heave amplitude A Number of evaluation points n Returns total force """ t = np.linspace(0,T,n) k = np.pi/T t_cir = t + TheoPhase(k, T) # phase --> frame of reference thing omega = 2*np.pi/T return CLAddedMass(omega, A, t) + CLCirc...
def prepare_loaders(df, fold, img_size, stage='NOT_TRAIN'): df_train = df[df.kfold != fold].reset_index(drop=True) df_valid = df[df.kfold == fold].reset_index(drop=True) if stage == 'train': train_dataset = HappyWhaleDataset(df_train, img_size, train_flag=True) else: train_dataset =...
This function trains and validates a machine learning model (HappyWhaleModel) using specified configurations. It supports two modes: single-fold validation (mode=0) for a specific fold or full-fold training (mode=1). For each fold, it initializes the model, sets up optimizer/scheduler, loads data, trains the model, and...
def Training_and_Validation(mode=1, val_fold=0): if mode == 0: print(f"Running_mode=🌘SINGLE_FOLD👉 \"{val_fold}\", image_size={CONFIG['train_img_size']}, model=\"{CONFIG['model_name']}\"") logger.info(f"Running_mode=🌘SINGLE_FOLD👉 \"{val_fold}\", image_size={CONFIG['train_img_size']}, model=\"{CO...
def SendDiscover(): s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) IP_Header = IPHead(SrcIP = socket.inet_aton('0.0.0.0').decode('latin-1'), DstIP=socket.inet_aton('255.255.255.255').decode('latin-1')) Packet = DHCPDiscover() Packet.ca...
This code monitors DHCP traffic by sniffing network packets, identifies DHCP responses (using UDP port 67), extracts client IP addresses, and processes them with the `ParseDHCPCode` function alongside a provided DNS. It prints relevant DHCP event messages when detected.
def DHCP(DHCP_DNS): s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW) s.bind((Interface, 0x0800)) SendDiscover() while True: data = s.recvfrom(65535) if data[0][23:24] == b"\x11":# is udp? SrcIP, SrcPort, DstIP, DstPort = ParseSrcDSTAddr(data) i...
def check_configuration(mssql, option, value): try: res = mssql.batch("SELECT cast(value as INT) as v FROM sys.configurations where name = '%s'" % option)[0]['v'] return res == value except: return False def do_enable_ole(self, line): try: if set_configuration...
The main task of the code is to upload a local file to a remote destination using SQL Server's Ole Automation Procedures. It converts the file to hexadecimal format, creates an ADODB.Stream object via SQL commands, writes the data, saves it to the specified remote path, and verifies the upload's success. Error handling...
def do_upload(self, params): try: local, remote = params.split(' ') except: logging.error("upload: invalid params") return if check_configuration(self.sql, 'Ole Automation Procedures', 0): if self.do_enable_...
def change_background(img, mask, bg): # oh = img.height # ow = img.width ow, oh = img.size bg = bg.resize((ow, oh)).convert('RGB') imcs = list(img.split()) bgcs = list(bg.split()) maskcs = list(mask.split()) fics = list(Image.new(img.mode, img.size).split()) for c in rang...
This function loads images and associated labels/masks for object detection, applies data augmentation (background replacement, geometric transformations, color adjustments), and generates updated labels accounting for image transformations. It returns the augmented image and corresponding adjusted detection labels.
def load_data_detection(imgpath, shape, jitter, hue, saturation, exposure, bgpath): labpath = imgpath.replace('images', 'labels').replace('JPEGImages', 'labels').replace('.jpg', '.txt').replace('.png','.txt') maskpath = imgpath.replace('JPEGImages', 'mask').replace('.jpg','.png') #maskpath = imgpath.replace...
def status_check(): global hash,allowed_regions,antibot_triggered,lpt,user_id,lrje if antibot_triggered or args.a: d = {'v':3,'client_id':'Cordova:iOS','client_version':'1.135.2','login_token':cookie} r = requests.post('https://www.mousehuntgame.com/api/action/passiveturn',d,headers=api_headers)...
The code automates performing a game action ("horn") in Mouse Hunt by sending API requests to execute turns, handling antibot mechanisms, updating game state variables (gold, points, bait), and processing journal entries. It retries on failures, manages waiting periods, and adjusts strategies based on success/failure, ...
def horn(): global lpt,lrje,hash,user_id,antibot_triggered fail = 0 try: assert lpt except: lpt = int(time.time()) - 15*60 while 1: if not args.a: wait_time = status_check() while wait_time: print('[%s] horn not ready'%(datetime.datetime.now().replac...
def random_state(self): """Returns a random initial state.""" result = np.zeros(3) result[-1] = np.random.rand() * twoPi return result def sense(self, state): """Returns a vector of sensor reading values for a particular agent state (position and orientation). No...
This function simulates agent-environment interactions over a specified time interval, generating time-series data of agent poses, sensory inputs, motor outputs, and internal controller states. It initializes with a random state, iteratively computes sensations, applies the controller to generate actions, updates agent...
def simulate(self, controller, interval=500.0): """Simulates the agent-environment system for the specified interval (in simulated time units) starting from a random state. Returns a (poses, sensations, actions, states) tuple where poses is a time array of agent poses (position and orien...
def random_state(self): """Returns a random initial state.""" result = np.zeros(3) result[-1] = np.random.rand() * twoPi return result def sense(self, state): """Returns a vector of sensor reading values for a particular agent state (position and orientation). No...
This function simulates an agent-environment interaction over a specified time interval. It initializes random starting states, iteratively senses the environment, uses a controller to generate actions, updates the agent's pose, and records all poses, sensations, actions, and internal states. The controller function pr...
def simulateNN(self, controller, net, interval=500.0): """Simulates the agent-environment system for the specified interval (in simulated time units) starting from a random state. Returns a (poses, sensations, actions, states) tuple where poses is a time array of agent poses (position an...
def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) def load_and_cache_examples(args, tokenizer, labels, pad_token_label_id, mode, lang, lang2id=LANG2ID, few_shot=-1): # Make sure only the first process ...
The code trains a multilingual model for NER/POS tasks using Hugging Face's transformers, with adapter configurations for language-specific and task-specific layers. It handles distributed training, logging, debugging, and model saving. Adapters are loaded for specified languages, fused with a task adapter, and the mod...
def main(): parser = argparse.ArgumentParser() parser = HfArgumentParser((ModelArguments, MultiLingAdapterArguments)) args, adapter_args = parser.parse_args_into_dataclasses() if os.path.exists(args.output_dir) and os.listdir( args.output_dir) and args.do_train and not args.overwrite_output_dir: rai...
def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) def evaluate(args, model, tokenizer, labels, pad_token_label_id, mode, prefix="", lang="en", adap_ids=None, lang2id=None, print_result=True, adapter_weig...
The main task of the code is to evaluate a multilingual token classification model (e.g., NER/POS) using adapter-based fine-tuning. It loads a pre-trained model, configures language adapters, and evaluates performance across specified languages, saving results and predictions. The code handles distributed training, log...
def main(): parser = argparse.ArgumentParser() parser = HfArgumentParser((ModelArguments, MultiLingAdapterArguments)) args, adapter_args = parser.parse_args_into_dataclasses() if os.path.exists(args.output_dir) and os.listdir( args.output_dir) and args.do_train and not args.overwrite_output_dir: ra...
def playerchoose(): #decides player 1 and player 2 player1 = '' while player1 != 'X' and player1 != 'O': player1 = input('Which do you want to be? X or O? ').upper() #define player 2 based on player 1 if player1 == 'X': player2 = 'O' else: player2 = 'X' ret...
The function `playing(board)` manages a two-player game on a board, alternating turns between Player 1 and Player 2 for up to 10 moves. It initializes player choices, displays the board, and uses the `turn` function to handle each player's move. The loop ensures players take turns sequentially, with Player 1 starting f...
def playing(board): #the total number of turns is chosen here, the game will be performed in this function player1, player2 = playerchoose() boardlayout(board) for i in range(10): if i%2 == 0: print('Player 1, do your move. ') turn(board, (player1, player2), player1)...
def _get_all_tasks(self): """Gets all tasks from Ticktick.""" self._get_ticktick_data() raw_active_tasks = self.ticktick_data["syncTaskBean"]["update"] if raw_active_tasks == self._cached_raw_active_tasks: return self._cached_raw_active_tasks = raw_active_tasks ...
This function processes daily tasks by retrieving all tasks, moving inbox tasks to day logs, completing tasks older than 3 days, adding relevant tags to recent tasks, and appending processed tasks to day_logs.
def _process_daily_logs(self): """Processes the daily logs.""" self._get_all_tasks() for task in self.all_day_logs.copy(): if task.project_id == get_ticktick_ids()[tik.LIST_IDS.value][tfK.INBOX_TASKS.value]: self._replace_tags_in_highlight_log(task) s...
def get_baseline(self, image_bytes): ggl = self.get_ggl_ocr_data(image_bytes) tes = self.get_tes_ocr_data(image_bytes)[['text', 'poly']].copy() should_restart = True while should_restart: should_restart = False for i, trow in tes.iterrows(): for j,...
The function processes OCR data from two sources (GGL and TES) by aligning their detected text polygons with a baseline, filtering out mismatches, merging results with baseline data, and applying character filtering to text fields before returning the consolidated dataset.
def get_iter_data(self, image_bytes): base = (self.baseline if self.baseline is not None else self.get_baseline(self.img_bytes)) ggl_iter = self.get_ggl_ocr_data(image_bytes) tes_iter = self.get_tes_ocr_data(image_bytes)[['text', 'poly']].copy() ggl_iter, tes_iter = [df.a...
def bytes_to_image(image_bytes): img_BGR = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_COLOR) img_RGB = cv2.cvtColor(img_BGR, cv2.COLOR_BGR2RGB) return img_RGB, img_BGR def get_white_color_ratio(self, image_bytes): img = self.bytes_to_imag...
The code processes an image iteratively by applying different image manipulation functions (blurring, polluting, watermarking) with varying parameters. For each iteration, it computes text length metrics, generates visualizations, and returns aggregated results and visual outputs.
def do_iter(self, iter_range, fun, fun_type, image_bytes): iter_res = {} iter_viz = [] for i in iter_range: try: if fun_type == 'blurring': pic = fun(self.bytes_to_image(image_bytes)[0], (i, i), 0) elif fun_type == 'polluting': ...
def get_fluid_properties(self, T): vap_frac = self.n2o.vap_mass_frac(T) # mass fraction of vapor for mass averaged density and Cp rho = (1 - vap_frac) * self.n2o.rho_V(T) + vap_frac * self.n2o.rho_L(T) cp = (1 - vap_frac) * self.n2o.cp_V(T) + vap_frac * self.n2o.cp_L(T) return rho, ...
This code simulates heating dynamics by iteratively calculating temperature changes in carbon fiber, aluminum, and N2O gas using a forward Euler method. It updates temperatures based on heat transfer resistances, gas properties, and power input, while monitoring pressure against a cutoff threshold. Upon exceeding the c...
def simulate(self, cutoff): """ Conduct heating simulation """ self.t = np.arange(0, self.T, self.dt) # Temperatures self.T_cf0 = self.T_amb * np.ones(len(self.t)) self.T_alu0 = self.n2o.T0 * np.ones(len(self.t)) self.T_alu1 = self.n2o.T0 *...
def h_V(self, T): T_r = T / self.T_c a = 1 - T_r b = [-200., 440.055, -459.701, 434.081, -485.338] n = [0, 1./3., 2./3., 3./3., 4./3.] h = 0 for i in range(len(b)): h += b[i]*a**n[i] return h def h_L(self, T): T_r = T / self.T_c a = 1 -...
The function calculates the heat of vaporization (Q_vap) at temperature T by subtracting the enthalpy difference between vapor and liquid phases, adjusting for pressure differences and mass changes between T_last and T. It uses enthalpy (h), pressure (p), and density (rho) values of the phases, along with liquid mass (...
def Q_vap(self, T, T_last): # Not the fastest but quite compact return (self.h_V(T)-self.h_L(T) - (self.p(T_last) - self.p(T))/self.rho_V(T_last)) * (self.m_L(T_last)-self.m_L(T))
def select_unassigned_variable(assignment,csp,arc_dic,binary_equal,binary_n_equal,binary_n_sim): unassigned_var=list(csp.keys()) for var in assignment: unassigned_var.remove(var[0]) remaining_value=[] for var in unassigned_var: remaining=check_availability(var,assignment,csp) rem...
The code implements a backtracking algorithm for solving a Constraint Satisfaction Problem (CSP). It recursively assigns values to variables while checking consistency with constraints. If an assignment is valid, it proceeds; otherwise, it backtracks. The algorithm uses arc consistency (ARC) inference to prune invalid ...
def BACKTRACK(assignment,csp,values_ls,arc_dic,binary_equal,binary_n_equal,binary_n_sim): if len(assignment)==len(csp): return assignment var=select_unassigned_variable(assignment,csp,arc_dic,binary_equal,binary_n_equal,binary_n_sim) print('we selected variable',var) for value in order_doma...
def read_file(filename): fl = open(filename) flg = 0 #graph = Graph() arc_dic = {} var_time = {} values_ls = [] ddl_constraint = 0 unary_inclusive ={} unary_exclusive = {} binary_equal = {} binary_n_equal = {} binary_n_sim = [] for line in fl: line = line.rstrip() if "#" in line and "variables" in line...
The code solves a Constraint Satisfaction Problem (CSP) using backtracking search. It reads input data, constructs a constraint matrix, applies backtracking to find a valid solution, and converts numerical results to human-readable values. The main task is to determine a feasible assignment of values to variables that ...
def main(): fn = "input2.txt" values_ls,var_time,arc_dic,deadline,binary_equal,binary_n_equal,binary_n_sim = read_file(fn) csp=build_constrain_mtx(values_ls,arc_dic,binary_equal,binary_n_equal,binary_n_sim) #BACKTRACKING_SEARCH(csp) result=BACKTRACKING_SEARCH(csp,values_ls,arc_dic,binary_equal,binar...
def Data_finder(data_addr:str): """Loads data from a given address. '.ndf' & '.tif' files are expected to be in the folder. Args: data_addr (str): Address of data folder. In this folder should be pairs of images and masks. images format: 'image_name.tif' masks format: 'mask_name.ndf' ...
The main task of the code is to preprocess neuron image and mask data by loading image-mask pairs from a specified directory, extracting trace information, and saving processed results (including colorized images and masks) to an output folder. It supports customizable parameters for resizing, colorization, image quali...
def NeuronJ(data_addr:str, output_dir:str, image_dir_name:str = 'images', mask_dir_name:str = 'masks', image_ext:str = '.tif', mask_ext:str = '.tif', colorize:bool = False, save_data_dpi:int = 300, resize_mask_to_image_s...
def convert_df_dict(): vic_path = '/media/nimashiri/DATA/vsprojects/ICSE23/data/vuldata.csv' data = pd.read_csv(vic_path, sep=',', encoding='utf-8') x = {} for index, rows in data.iterrows(): x[rows[2].split('/')[-1]] = rows[1] return x def read_txt(fname): with open(fname, 'r') as fileR...
The code processes software repositories to detect vulnerabilities using static analysis tools (flawfinder, rats, cppcheck) via diff-based matching. It iterates through commits, clones repositories, analyzes modified files, runs tool detections, and logs results (vulnerability frequencies, execution times, change detai...
def main(): vic_path = '/media/nimashiri/DATA/vsprojects/ICSE23/data/vic_vfs' full_check = True _id = 0 label_dict = convert_df_dict() comp = read_txt('/media/nimashiri/DATA/vsprojects/ICSE23/data/valid_commits.txt') for tool in ['flawfinder', 'rats', 'cppcheck']: for mapping_ in...