dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def _get_reward(self, state, action): [row, col] = self.ind2coord(self.state) reward = self.reward_matrix[row,col] if self.at_border() and reward == 0: if row == 0 and action == UP: reward = -1.0 if row == self.n-1 and action == DOWN: rewar...
This code simulates a single step in a grid-based reinforcement learning environment. It updates the agent's position based on the action, enforces grid boundaries, calculates rewards, and handles specific state transitions. The main task is to model environment dynamics by processing actions, updating the state, track...
def step(self, action): assert self.action_space.contains(action) self.steps +=1 if self.steps >= self.upper_steps: self.done = True return self.state, self._get_reward(self.state, action), self.done, None [row, col] = self.ind2coord(self.state) reward = ...
def get_document(docx_path: str) -> Document: """Read the word doc, returning a parsed Document instance.""" with open(docx_path, "rb") as f: return Document(f) def get_cities(doc: Document) -> list[str]: """Get the list of cities in the word doc. In these documents, Heading 1 is only used to de...
The main task of the code is to process a Word document containing cancer data by city. It extracts tables and associated city names, validates their count, and processes each city's data using the `process_city` function.
def process_doc(year_range: str, docx_path: str): """Process a word doc containing cancer data broken down by city. Parse out the tables and associated city names, and process by city.""" doc = get_document(docx_path) tables = doc.tables cities = get_cities(doc) if len(tables) != len(cities): ...
def chi(x1, x2, rmin): t1 = np.abs(x1) <= rmin t2 = np.abs(x2) <= rmin t3 = np.logical_and(t1, t2) p = np.where(t3 == True, 0, 1) return p def G(u,x1,x2,rmin,rmax): sq_len = np.abs(np.max(x1[0])-np.min(x1[0])) w = u*zeta(x1,x2,rmin,rmax) return return_lapu(w,sq_len) def phi(x1,x2): n...
The function performs a 2D convolution-like operation on grids X1 and X2, computing a matrix `conv_arr` where each element is the sum of products between a kernel `g` (derived from `phi`) and a function `f` (computed via `chi` and `G`). The result is scaled by `dx²`, with `dx` being the spacing in X1. The nested loops ...
def convol_quad(rmin,rmax,X1,X2,u): x1_dim = np.shape(X1)[0] x2_dim = np.shape(X2)[0] conv_arr = np.zeros((x1_dim,x2_dim)) dx = X1[0][1]-X1[0][0] f = chi(X1,X2,rmin)*G(u,X1,X2,rmin,rmax) for i in range(1,x1_dim): for j in range(1,x2_dim): g = phi(X1[i,j]-X1,X2[i,j]-X2) ...
def chi(x1, x2, rmin): t1 = np.abs(x1) <= rmin t2 = np.abs(x2) <= rmin t3 = np.logical_and(t1, t2) p = np.where(t3 == True, 0, 1) return p def G(u,x1,x2,rmin,rmax): sq_len = np.abs(np.max(x1[0])-np.min(x1[0])) w = u*zeta(x1,x2,rmin,rmax) return return_lapu(w,sq_len) def phi(x1,x2): n...
The code performs a 2D convolution between an image `im` (generated via `phi` on a meshgrid derived from coordinates in `X1`/`X2`) and a kernel `ker` (computed using `chi` and `G` functions). The kernel is scaled by `dx²`, where `dx` is the spacing between grid points in `X1`. The convolution uses FFT for efficiency, o...
def convol(rmin,rmax,X1,X2,u): ker = chi(X1,X2,rmin)*G(u,X1,X2,rmin,rmax) k_start = X1[0][0] k_end = -k_start k_size = np.shape(X1)[0] im_start = int(2*k_start) im_end = int(2*k_end) im_len = int(2*k_size-1) im_sp = np.linspace(im_start,im_end,im_len) IM1, IM2 = np.meshgrid(im_sp,im_...
def chi(x1, x2, rmin): t1 = np.abs(x1) <= rmin t2 = np.abs(x2) <= rmin t3 = np.logical_and(t1, t2) p = np.where(t3 == True, 0, 1) return p def G(u,x1,x2,rmin,rmax): sq_len = np.abs(np.max(x1[0])-np.min(x1[0])) w = u*zeta(x1,x2,rmin,rmax) return return_lapu(w,sq_len) def phi(x1,x2): n...
The main task of the code is to compute a 2D convolution of a kernel and an image using Fast Fourier Transform (FFT). It prepares a kernel and image grids, pads them for convolution, applies FFT to their product, performs inverse FFT to obtain the result, and returns the central portion of the convolution scaled by $dx...
def convol2(rmin,rmax,X1,X2,u): # set scaling for continuous conversion dx = X1[0][1] - X1[0][0] # get kernel on [-a,a]^2 ker = chi(X1, X2, rmin) * G(u, X1, X2, rmin, rmax) utils.ndwrite(ker,"XG.d") # make meshgrid on [-2a,2a]^2 k_start = X1[0][0] k_end = -k_start k_size = np.shape(X...
def download_10k_update(path, company_ticker, File_Type, year): # global path # path = input('Please input the path:') # global company_ticker # company_ticker = input('Please input the Company Ticker:') # File_Type = input('Please input the File Type:') # year = input('Please input the Year:')...
The function updates financial data (revenue growth, gross margin, net sales) for a specified company and year by either appending new data or modifying existing entries in pickle files. It downloads and extracts 10-K filings, processes metrics, checks for existing years, and updates DataFrames accordingly before savin...
def update_10_k(year,comapny_name,form_type): path_10k = DIR_PATH+"10k_downlod_extraction/" with open(DIR_PATH+'revenue_growth.pkl', 'rb') as f: revenue_growth_df = pickle.load(f) with open(DIR_PATH+'gross_margin.pkl', 'rb') as f: gross_margin_df = pickle.load(f) with open(DIR_PATH+'net_...
def get_fbref_league_team_data(self, season_name, league_id, league_name): """Function used to grab league tables for a specific league e.g Premier league""" year1, year2 = season_name.split("_") league_data = pd.read_html( f"https://fbref.com/en/comps/{league_id}/{year1}-{y...
The main task of the code is to aggregate team statistics and fixtures data for multiple sports seasons into a structured dictionary. It processes each season in the input list, retrieves team data and fixtures using helper methods, and organizes them under their respective season names in a nested dictionary structure...
def get_seasons_dict(self, season_name_list, league_id, league_name): """Function used to get multiple seasons worth of data for a chosen competition""" seasons_dict = {} for season_name in season_name_list: season_dict = {} # team season statistics league_tea...
def term_to_array(term): '''Converts abcd to [1,1,1,1]''' i = 0 L = [] while i < len(term) - 1: if term[i + 1] == '\'': L.append(0) i += 2 else: L.append(1) i += 1 if term[-1] != "'": L.append(1) return L def find(v, w): ...
The function `comb_function_expansion` processes K-map terms to determine their maximum legal regions. It converts input terms (`func_TRUE` for '1's and `func_DC` for don't cares) into arrays, combines them, and identifies valid regions. If all combined terms are don't cares (['x', 'x']), it returns a list of `None` va...
def comb_function_expansion(func_TRUE, func_DC): """ determines the maximum legal region for each term in the K-map function Arguments: func_TRUE: list containing the terms for which the output is '1' func_DC: list containing the terms for which the output is 'x' Return: a list of terms: exp...
def read_dataset(filename): """ Reads the dataset with given filename. """ df = pd.read_csv(filename, sep=',', header = 0) return df def get_histogram(dataset, chosen_anime_id="199"): df=(dataset) anime_map = np.zeros((len(df.columns),13)) skip = 0 for (columnName, columnData) ...
The code evaluates differential privacy mechanisms (Laplace and exponential) on an anime dataset by measuring average error, mean squared error, and accuracy across varying epsilon (ε) values. It reads the dataset, computes histograms, and runs experiments to analyze privacy-utility trade-offs for different ε levels, p...
def main(): filename = "anime-dp.csv" dataset = read_dataset(filename) counts = get_histogram(dataset) print("**** LAPLACE EXPERIMENT RESULTS ****") eps_values = [0.0001, 0.001, 0.005, 0.01, 0.05, 0.1, 1.0] error_avg, error_mse = epsilon_experiment(counts, eps_values) print("**** AVERAGE E...
def info(self, data: str, counter: str = str(datetime.now()), end: str = "\n") -> None: self.__log(LEVEL.INFO, data, counter, end) def warning(self, data: str, counter: str = str(datetime.now()), end: str = "\n") -> None: self.__log(LEVEL.WARNING, data, counter, end) def error(self, data: str, counter: ...
The code defines a log method that routes logging tasks to specific handler methods (info, warning, error, header, debug) based on the provided level parameter, using default values for counter and end.
def log(self, level: LEVEL, data: str, counter: str = str(datetime.now()), end: str = "\n") -> None: if level == LEVEL.INFO: self.info(data, counter, end) elif level == LEVEL.WARNING: self.warning(data, counter, end) elif level == LEVEL.ERROR: self.error(data,...
def getAllPossibleMoves(self): moves = [] for r in range(len(self.board)): for c in range(len(self.board[r])): turn = self.board[r][c][0] if (turn == "w" and self.whiteToMove) or (turn == "b" and not self.whiteToMove): piece = self.board[r]...
This function generates valid chess moves by simulating each possible move, checking if it leaves the king in check, and removing invalid moves. It handles en passant temporarily, determines checkmate/stalemate if no valid moves remain, and restores original game state before returning the filtered list of valid moves.
def getValidMoves(self): tempEnpassantPossible = self.enPassantPossible # Generate all possible moves moves = self.getAllPossibleMoves() # When removing from list, move backward through list for i in range(len(moves) - 1, -1, -1): # For each move, make the move ...
def _init_cmd_info(self): self._cmd_type = C_ERROR self._arg1 = '' self._arg2 = 0 def _nullary_command(self, id): self._set_cmd_type(id) if self._command_type[id] == C_ARITHMETIC: self._arg1 = id def _unary_command(self, id): self._nullary_command(id) ...
This code advances the parser by retrieving the next command token, checks its type (nullary, unary, or binary), and executes the corresponding command handler based on the token's value.
def advance(self): self._init_cmd_info() self.lex.next_command() tok, val = self.lex.cur_token if tok != Lex.ID: pass # error if val in self._nullary: self._nullary_command(val) elif val in self._unary: self._unary_command(...
def cosine_sim(self, vectors): return cosine_similarity(vectors) def asort(self): mm = self.sim_matrix > self.ignore_similarity mask = np.zeros_like(mm, dtype=np.bool) mm[np.triu_indices_from(mask)] = False indcs = list(zip(*np.where(mm))) pos = self.sim_matrix[mm].argsor...
The code clusters input vectors using cosine similarity, sorts and groups similar items, forms initial clusters, and optionally merges clusters based on similarity thresholds. It returns a model with cluster labels assigned to each input vector, optimizing groupings by merging if similarity meets predefined criteria.
def fit(self, vec): self.sim_matrix = self.cosine_sim(vec) t0 = t.time() itrun = self.asort() print('finished sorting in {:.3f} s'.format(t.time() - t0)) # print ("'sorted -", itrun [:, -1]) t1 = t.time() print('looping through {} items for groupby_per'.format(l...
def init_league() -> ff_espn_api.League: """Initialize a League object from the command line arguments.""" parser = argparse.ArgumentParser(description="Determine the fantasy Coach and GM of the Year.") parser.add_argument("league_id", type=int, help="ESPN FF league ID, from the URL") parser.add_argumen...
The main task of the code is to determine the Coach and GM of the Year by initializing a league, processing season data to calculate suboptimality and optimal points, then printing awards based on these metrics. It fetches league data, analyzes performance outcomes, ranks candidates using derived statistics, and output...
def main(): """Fetch data and run our algorithm to determine Coach and GM of the Year.""" league = init_league() results = process_season(league) sorted_suboptimals = get_suboptimality(results) sorted_totals = get_optimal_points_for(results) print_awards(league, sorted_suboptimals, sorted_tot...
def prepare_source(source: Source) -> Path: if source.path: return source.path.resolve() if source.url: # assume this is a git repo tmp = TemporaryDirectory(prefix="dotlink.") atexit.register(tmp.cleanup) repo = Path(tmp.name).resolve() run("git", "clone", "--dep...
The main task of the code is to generate a `Plan` object that links a `source` to a `target` using a specified `method`. It logs debug information, prepares the source, generates a configuration, resolves required actions based on the target and method, and constructs a `Plan` with these actions. The function returns t...
def dotlink(source: Source, target: Target, method: Method) -> Plan: LOG.debug("source = %r", source) LOG.debug("target = %r", target) LOG.debug("method = %r", method) root = prepare_source(source) config = generate_config(root) LOG.debug("config = %s", pformat(config, indent=2)) plan = Pl...
def __on_event(self, event): (symbols, action, version, ts) = event self.publish_event( {"event_type": EventType.RPA_ALERT, "tickers": symbols, "action": action, "version": version, "ts": ts}) next_move = self.next_move(action) source = f'#B4#{version}#' ...
The code's main task is to monitor and process events from a queue during trading hours, repeatedly checking for new events, handling them via `__on_event`, and pausing for 5 seconds between checks. Once the trading end time is reached, it executes end-of-day processing (`eod_process`) and generates reports (`gen_repor...
def work(self): print('Start working ...') logger.info('Start working ...') while datetime.datetime.now().timestamp() < self.trading_end_time.timestamp(): while not self.__event_q.empty(): event = self.__event_q.get() self.__on_event(event) ...
def load_model_from_checkpoint(config, checkpoint_number=None, path=None): """ - checkpoint_number: Number of checkpoint to load. If none given, will load the last checkpoint saved. - path: Path to the saved model. If nothing is given, will load from config.path . - ...
The code evaluates two models by having them play against each other in a specified game, using configurable settings like solvers or Monte Carlo steps. It initializes models, sets up bots, runs multiple games, handles exceptions for infinite games (e.g., Oware), records results in a buffer, and sends outcomes to a que...
def two_player_evaluator(*, game, config, logger, queue, num): """Adapted from alpha_zero.evaluator(), this process generates games of two different models playing against one another.""" results = az_lib.Buffer(config.evaluation_window) logger.print("Initializing models") if config.checkpoint_numbe...
def get_last_chat_id_and_text(self, updates): num_updates = len(updates["result"]) last_update = num_updates - 1 text = updates["result"][last_update]["message"]["text"] chat_id = updates["result"][last_update]["message"]["chat"]["id"] return (text, chat_id) def get_updates(self,...
This code handles a movie bot's chat loop, detecting new/existing users, sending personalized greetings, and using sentiment analysis to respond to user messages. It tracks conversation state via flags and intent variables, updating user data in a database and maintaining continuous interaction through an infinite loop...
def chat(self): last_textchat = (None, None) flag = False intent = -1 while True: text, chat = self.get_last_chat_id_and_text(self.get_updates()) if (text, chat) != last_textchat: if text.lower() == "hello": flag = False ...
def _check_done(self): if self.offset == len(self.rosary): wait_for_key() console.print("Amen.", style="bold green") self.config["prayed"].append( {"date": todaycode(), "mysteries": DAY_TO_ROSARIES_NAME[dayofweek()]}) self.reset() sys.e...
This function processes a rosary prayer step by iterating through its elements. It checks completion status, retrieves the current prayer, generates a description if needed, prints the prayer name and description, increments the offset, and updates the state.
def step(self): self._check_done() current = self.rosary[self.offset] desc = None if current not in [_("Hail Mary"), _("Credo"), _("Glory to the Father"), _("Our Father")]: with console.status(_("Generating mystery's description..."),spinner="squish"): desc =...
def loadKeras(self): imdb = keras.datasets.imdb (self.train_data, self.train_labels), (self.test_data, self.test_labels) = imdb.load_data(num_words=self.NUM_WORDS) def _alterBulkData(self): self.train_data = self._alterData(self.train_data) self.test_data = self._alterData(self.test_data...
The code initializes a class by loading either IMDb dataset or user-provided data, processes the data with _alterBulkData(), loads a model, and retrieves word index mappings. It sets up training/test data, labels, and linguistic resources for text processing or NLP tasks.
def __init__(self, imdb=True, tain_data=None, train_labels=None, test_data=None, test_labels=None, model=None, loadData=True): if imdb: self.loadKeras() self._alterBulkData() elif loadData: self.train_data = tain_data self.train_labels = train_labels ...
def read_annotations_train(self, dir): with open(dir, 'r') as input_json: train_annotation = json.load(input_json) test_annotation_split = train_annotation['image'][:self.val_split_number] train_annotation_split = train_annotation['image'][self.val_split_number:] query_ids ...
The code initializes a dataset class for a person re-identification task, loading training, query, and gallery data from specified directories. It reads annotations from JSON files, splits data into train/validation/test sets, computes statistics (e.g., number of persons, images, cameras), and organizes them for use in...
def __init__(self, root='/home/hzr/bag_of_tricks/reid-strong-baseline/data/', verbose=True, **kwargs): super(MVBdataset, self).__init__() self.root = root self.dataset_dir = osp.join(root, self.dataset_dir) self.train_dir = osp.join(self.dataset_dir, 'MVB_train') self.query_dir =...
def takecommand(): r = sr.Recognizer() with sr.Microphone() as source: print("Listening..........") r.pause_threshold = 1 audio = r.listen(source, timeout=10, phrase_time_limit=5) try: print("Recognizing") query = r.recognize_google(audio, language='en-in') p...
This code handles user requests for voice or video calls by prompting the user to specify the call type, capturing the name of the contact, and initiating the corresponding call functions (VoiceCall/VedioCall) along with their internal processes. If the input is unclear or invalid, it requests the user to retry.
def call(): Speak("Which call do you want to Voice call or Video call") tk = takecommand().lower() if(tk!="none"): if "voicecall" in tk or "voice call" in tk or "voice" in tk: Speak("Please Tell Me Name You want to call") name = takecommand().lower() ...
def load_data(dataset): if dataset == "cifar100": (x_train, y_train), (x_test, y_test) = load_cifar100() else: # dataset in [mnist, cifar10] (x_train, y_train), (x_test, y_test), min_, max_ = load_dataset(dataset) # label must be one hot encoded n_train = np.shape(y_train)[0] shuff...
The function `get_loaders` loads training and test datasets, initializes a backdoor attack pattern, and generates clean and poisoned data loaders for training and testing. It conditionally loads data based on the `plotting` flag and returns train loaders, a standard test loader, and a poisoned test loader for backdoor ...
def get_loaders(args, plotting = False): if plotting: x_train, y_train, x_test, y_test = load_data(args['dataset']) else: x_train, y_train, x_test, y_test = load_data(args.dataset) # Init backdoor pattern backdoor = PoisoningAttackBackdoor(add_pattern_bd) example_target = np.zeros(...
def transformText(txt, screen_width, emoji_dict = None, scramble=False): # How many characters can we fit inside a line (-1 for border, -1 for cursor) max_line_width = screen_width - (2 * PADDING) - 3 lines = txt.split('\n') new_lines = [] for line in lines: # If new line (empty) ...
This code creates an interactive text entry interface using curses, allowing users to input text with mood selection, emoji autocomplete, and privacy toggling. It handles keyboard input for text editing, displays a mood bar, enforces character limits, and submits entries while dynamically updating the screen with effic...
def main(screen): # Text entry txt_entry = '' # Mood current_mood = len(MOODS) // 2 # Program state done = False # Initialize curses stuff screen = screen curses.curs_set(0) height, width = screen.getmaxyx() overflow_flag = False prev_transform_txt_height = 0 tra...
def edit_config(graph_id='', name='', unit=''): return {'id': graph_id, 'name': name, 'unit': unit, 'type': 'float', 'color': 'ichou'} def new_user(self): num_names = len(self.users) layout = [ [sg.Frame("Create New User?", layout=[ [sg.Text("Username:"), sg.Input(k='-use...
This code initializes a class instance by loading user data from a JSON file, handling errors by creating a new user if needed, setting up authentication headers with a selected user's token, and preparing graph configurations. It ensures user data is either loaded or generated, configures API headers, and initializes ...
def __init__(self): self.data_variables = [] self.graph_config = edit_config() self.chosen = None try: with open('./users.json', 'r') as f_users: u_dict = json.load(f_users) except ValueError: self.users = {} added_user...
def gen_lambda(n, b): _lambda = np.zeros((n, n)) z = univariate_gaussian_data_generator(0, 1/b) for i in range(n): _lambda[i][i] = z return _lambda def inv(arr): return np.linalg.inv(arr) def polynomial_basis_linear_model_data_generator(n, a, w): """ Polynomial basis linear model dat...
The code performs Bayesian linear regression iteratively, updating parameters μ (mean) and Λ (precision matrix) using polynomial basis data. It generates synthetic data points, updates μ and Λ via matrix operations, checks for convergence, and records parameter states at iterations 10, 50, and final. The goal is to est...
def Baysian_linear_regression(b, n, a, w): _lambda = gen_lambda(n, b) # initial lambda (nXn) _mu = np.zeros((n, 1)) # initial mu (nX1) samples = {'10':[], '50':[], 'final':[]} data_points = [] a = 1/a # the fornmula denotes a^-1 as var _lambda = inv(_lambda) ...
def mul(arr_A, arr_B): return np.matmul(arr_A, arr_B) def sigmoid_fun(x): return 1 / (1 + math.exp(-1 * x)) def output(A, w, y, method): print("\n{:s}:\n".format(method)) print("w:\n") for w_i in w: print("\t%f" %w_i) print("\nConfusion Matrix:\n") print("\t\tPredict cluster 1 ...
This code implements gradient descent for logistic regression. It initializes weights, iteratively computes gradients using the sigmoid function and input matrix A, updates weights with a learning rate, and stops when convergence is reached or after 2000 iterations. The final prediction is evaluated and returned.
def gradient_descent(A, y): w = np.zeros((3, 1)) # initialize w iter = 0 lr = 0.02 while True: g = mul(A, w) for i in range(len(g)): g[i] = sigmoid_fun(g[i]) - y[i] g = mul(A.T, g) new_w = w - lr * g iter += 1 if sum(abs(new_w - w)) < ...
def mul(arr_A, arr_B): return np.matmul(arr_A, arr_B) def sigmoid_fun(x): return 1 / (1 + math.exp(-1 * x)) def inv(arr): return np.linalg.inv(arr) def output(A, w, y, method): print("\n{:s}:\n".format(method)) print("w:\n") for w_i in w: print("\t%f" %w_i) print("\nConfusion M...
This code implements Newton's method for optimizing logistic regression parameters. It iteratively updates weight vector w using the Hessian matrix (computed from second derivatives of the sigmoid function) and gradient of the loss function, with a learning rate. If the Hessian is singular, it defaults to gradient desc...
def newton_method(A, y): w = np.zeros((3, 1)) # initialize w iter = 0 lr = 0.02 n = len(y) while True: g = mul(A, w) for i in range(n): g[i] = sigmoid_fun(g[i]) - y[i] g = mul(A.T, g) H = np.zeros((n, n)) for i in range(n): H[i][i]...
def bar_chart(df, system): return dcc.Graph( id='bar-chart', figure=bar_figure(df, system) ) def date_picker(df): return dcc.DatePickerSingle( min_date_allowed=df['date'].min(), max_date_allowed=df['date'].max(), display_format='YYYY.MM.DD', date=df['date'].ma...
The main task of the code is to create a Dash web dashboard layout using Plotly/Flask components. It constructs a container with a bar chart (for 'BEDAS' data), a date picker component, and a table (for 'BEDAS' data), arranging them in a responsive grid layout with specified padding and alignment. The function returns ...
def home(df): return html.Div(id="home", style={}, children=[ dbc.Row([ bar_chart(df, 'BEDAS') ], justify="start", id='bar-chart-container'), dbc.Row([date_picker(df)], className='ml-4'), html.Div([ lp_table(df, 'BEDAS') ], style={ 'padding...
def read_dataset(): x = [] y = [] file = open("rectangle.txt", "r") for line in file: x1, y2, val = line.split() p = Point(float(x1), float(y2)) x.append(p) y.append(float(val)) return x, y def get_ht_line(train, w, truth): error = np.inf rule = Rule(None, Non...
The code implements the Adaboost algorithm for classification. It trains weak classifiers iteratively, updates their weights based on prediction errors, and tracks training/test accuracy. The main task is to compute weighted ensemble predictions, adjust classifier weights, and evaluate performance across multiple round...
def adaboost(rounds): X, Y = read_dataset() X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.5) w = np.ones(len(X_train)) / len(X_train) test_acc = np.zeros(8) train_acc = np.zeros(8) Hs = [] As = [] for i in range(rounds): total_sum = 0 rule = get_ht...
def populate_source(self): global y_top_left,x_top_left,y_btm_right,x_btm_right,grid y_top_left = 0 x_top_left = 0 y_btm_right = resolution*bot_len_Y x_btm_right = resolution*bot_len_X self.populate_grid(x_top_left,y_top_left,x_btm_right,y_btm_right,"Green") def set_move_...
This function switches the application to "Add Source" mode by checking the button text, validating map existence, updating UI elements (headers, button text), and triggering source population. If no map exists, it warns the user. When the button text is "Save Source," it calls save_source() to finalize the source data...
def start_source_mode(self): global mode if(self.button_add_source.cget("text") == "Add Source"): if(mapName is not None): mode = "addSource" self.populate_source() self.set_move_btn_names("Source") self.update_map_header(mapNam...
def move_forward(self): global x_top_left, y_top_left, x_btm_right, y_btm_right, direction,path_list if direction == "up": if(y_top_left>0): x_top_left = x_top_left y_top_left = y_top_left - 1 x_btm_right = x_btm_right y_btm_r...
This code initializes a GUI for an autonomous robot navigator, creating a full-screen window with multiple tabs for configuration, map settings, path planning, and UI adjustments. It includes controls for robot movement, map creation, obstacle/destination placement, speed/sensor settings, and path saving. The interface...
def __init__(self): super().__init__() #Create an instance of tkinter frame screen_width = self.winfo_screenwidth() screen_height = self.winfo_screenheight() # configure window self.title("Autonomous Robot Navigator") self.geometry("{0}x{1}+0+0".format(s...
def resize_grid_on_map_select(self,map_data): global resolution_factor, GRID_HEIGHT, GRID_WIDTH resolution=1 try: if(float(resolution_factor) == 0.5): resolution = 2 elif(float(resolution_factor) == 0.25): resolution = 4 ...
The main task of the code is to initialize a new path by resetting the path list, setting the mode to "path," retrieving map and destination data from a database, adjusting the grid based on the map data, and configuring destination values. It prepares the environment for path creation by fetching necessary data and up...
def start_new_path(self): global mapName, mode, path_list path_list = [] mode = "path" print("start New Path") db_obj = DatabaseOperations(db_file_path) map_data = db_obj.get_map_data(mapName) #print(map_data) self.resize_grid_on_map_select(map_da...
def populate_destination(self): global y_top_left,x_top_left,y_btm_right,x_btm_right,grid #print(grid) result = self.find_nearest_fit(grid, bot_len_X*resolution, bot_len_Y*resolution) if result is not None: y_top_left, x_top_left = result y_btm_right = y_top_left+...
This function switches the application to "addDestination" mode, enabling destination editing features. It checks if a map is loaded, updates the UI (header, button labels, and button states), and prepares to save a new destination. If no map is loaded, it shows an error.
def start_destination_mode(self): global mode, dest_count if("Add Dest" in self.button_add_destination.cget("text")): if(mapName is not None): mode = "addDestination" self.populate_destination() self.update_map_header(mapName + " map : Mode - A...
def set_map_values(self, data): global resolution_factor, GRID_WIDTH, GRID_HEIGHT self.set_map_items_state("normal") for map_data in data: self.entry_x_coordinate.delete(0, tkinter.END) # Remove the placeholder text self.entry_x_coordinate.insert(0, map_d...
The code retrieves map and destination data from a database based on user selection, updates UI elements with the fetched map data, resizes the grid, and populates dropdowns for paths and destinations.
def set_map(self, event: str): global mapName,map_data mapName = self.button_map_collection.get() db_obj = DatabaseOperations(db_file_path) map_data = db_obj.get_map_data(mapName) #print(map_data) self.set_map_values(map_data) self.resize_grid_on_map_select(map_da...
def start_new_path(self): global mapName, mode, path_list path_list = [] mode = "path" print("start New Path") db_obj = DatabaseOperations(db_file_path) map_data = db_obj.get_map_data(mapName) #print(map_data) self.resize_grid_on_map_select(map_da...
This function retrieves map and destination data from a database, visualizes the destination color on a canvas, and simulates a robot's path by executing movement commands (forward, left, right) with delays. It fetches destination details, identifies matching entries, renders color indicators, retrieves path instructio...
def set_destination_color_main(self, event: str): global mapName mapName = self.button_map_collection.get() dest_name = self.button_dest_collection.get() db_obj = DatabaseOperations(db_file_path) dest_data = db_obj.get_dest_data(mapName) for row in dest_data: ...
def compute_statistics_of_path(path, path_prefix, model, batch_size, dims, device, num_workers=8, max_count=None, count=None, im_size=None): if isinstance(path, str) and path.endswith('.npz'): print('Loaded from ', path) with np.load(path) as f: m, s, act = f['mu'][:], f['sigma'][:], f['...
This function calculates the Fréchet Inception Distance (FID) between two image datasets by loading model features (InceptionV3 or CLIP), processing file paths, computing statistical features, and returning FID along with PID/UID metrics and dataset lengths. It handles shared files, path filtering, and batch processing...
def calculate_fid_given_paths(path1, path_prefix1, file_list1, path2, path_prefix2, file_list2, batch_size, device, dims, net='inception', num_workers=8, max_count1=No...
def binary_parser(self): binary_list = [] platform_cmd = 'sh %s/../../build/get_PlatForm_str.sh' % (self.local_dir) platform_list = os.popen(platform_cmd).read().split('\n') platform_str = platform_list[0] if platform_str == 'euleros2.0_sp5_x86_64': binary_list.append...
The code defines a `build_mode` method that executes platform-specific build operations based on the `self.mode` value. It first parses binary data, then branches into actions like building, shrinking, cleaning, or distributing components. If the mode is unrecognized, it raises an error. The core task is to orchestrate...
def build_mode(self): # check if support platform self.binary_parser() # build mode if self.mode == 'build': self.build_component() elif self.mode == 'all': self.build_all() elif self.mode == 'shrink': self.shrink_component() el...
def combine(x, y): root = Node() root.left = x root.right = y x.parent = root y.parent = root return root def who_to_explode(x, depth = 0): if x == None: return if depth >= 4: epic_explosions(x) else: who_to_explode(x.left, depth + 1) who_to_explode(x.right, depth + 1) def split_them_values(x): global...
The main task of the code is to iteratively combine elements from the input list `trees` into a single result (`final`), with each combination followed by a sequence of operations involving `who_to_explode` and `split_them_values`. The global flags `gvd` and `fml` control nested loops that likely handle side effects li...
def fuckMyLife(trees): global gvd final = trees[0] for i in range(1, len(trees)): final = combine(final, trees[i]) gvd = True while gvd == True: fml = True while fml == True: fml = False who_to_explode(final) gvd = False split_them_values(final) return final
def reconstruction_loss(self, x_dic, x_hat_dic): """Within-view Reconstruction loss Parameters: ----------- x_dic: dictionary, float tensor, $\tilde{X}^{(v)}$: (sample_num, feature_dim_v). Rebuilding input dictionary {$\tilde{X}^{(1)}$, $\tilde{X}^{(2)}$, ..., $\tilde{X}^{(V)}$}. x_hat_dic: dict...
The code computes a multi-component loss for a multi-view model, combining reconstruction, cross-instance contrastive, category contrastive, and classification losses. It returns the total loss and individual components, with optional dual prediction loss based on mode. In 'with_dual' mode, an additional dual predictio...
def forward(self, output_dic, gt_label, label_mask, classes=2, mode='without_dual', device=None): if mode == 'with_dual': """ icl + ccl + recon_loss + classification_loss (+ dual_pre_loss if completion method is 'no_complete', 'average_complete', or 'random_complete') """ # Make suitable dictionary ...
def create_random_loss_fcn(num_ppl=NUM_PPL, num_outcomes=NUM_OUTCOMES): def random_loss_fcn(): out_dict = {} ppl = get_individuals(num_ppl) for person in ppl: outcomes = get_outcome_variables(person, num_outcomes) for outcome in outcomes: out_dict[outcome] = -1 * random.random() re...
The code defines a function `run_exp` that solves a linear programming (LP) optimization problem. It generates a random loss function, constructs LP constraints and objectives, and uses `optimize.linprog` to find the optimal solution. The result includes optimized weights and feature names, which are printed and return...
def run_exp(num_ppl=NUM_PPL, num_outcomes=NUM_OUTCOMES): loss_fcn = create_random_loss_fcn(num_ppl, num_outcomes) # print(len(loss_fcn()), loss_fcn()) loss_vect, constraints_matrix, b, feature_names = generate_lp( loss_fcn, num_ppl, num_outcomes, CONSTANT_METRIC, generate_distribution_tv_constraints)...
def init_data_tab(self): """ Method that initialize the tab :return: """ self.clear() self.tab_info = QWidget() self.tab_exif = QWidget() self.addTab(self.tab_info, "Info") self.addTab(self.tab_exif, "EXIF") def __update_info(self, info): ...
The main task of the code is to update the data tab with the currently selected image's metadata. It initializes the data tab, retrieves image information and EXIF data from the controller, then updates the interface's info and EXIF sections accordingly.
def update_tab_value(self): """ Method that update the data tab with the selected image data :return: """ self.init_data_tab() info, exif = self.controller.get_current_data() self.__update_info(info) self.__update_exif(exif)
def locate_endpoints(edge_image, locations='all'): """ Locates edge endpoints Args: edge_image (2d array) locations (Optional[str]): Choices are ['all', 'small', 'broken']. Returns: Image endpoints, where endpoints = 1. """ # Setup the endpoint structuring elements fo...
The function performs morphological cleaning on binary edge images by removing small objects, thinning edges, extending endpoints along gradient directions, linking broken edges, trimming endpoints, and filling gaps to produce cleaned, continuous edge structures.
def morphological_cleanup(cr, min_line_size, theta_45_iters=0, theta_90_iters=0, theta_180_iters=0, pre_thin=False, endpoint_iterations=0, ...
def init_distance(egm_array, threshold): """ Initializes a euclidean distance transform array Args: egm_array (2d array) threshold (float or int) """ # Threshold the EGM into a binary edge/no edge array. binary_array = np.uint8(np.where(egm_array < threshold, 1, 0)) # Get...
The function `multiscale_threshold` applies multi-scale adaptive thresholding to a 2D input array (`egm_array`) using various methods (e.g., Gaussian, mean, Sauvola) across different window sizes. It then performs morphological cleaning (e.g., removing small objects, linking ends) to refine detected edges, ensuring obj...
def multiscale_threshold(egm_array, min_object_size, windows=None, link_ends=False, theta_180_iters=1, theta_90_iters=1, theta_45_iters=1, skelet...
def divide(buckets): stBuckets = {} hardBucketsHigh = {} softBuckets = {} hardBucketsLow = {} doubleBuckets = {} splitBuckets = {} for key in buckets: h = buckets[key].hand if h.canSplit: splitBuckets[key] = buckets[key] elif h.canDouble: do...
The main task of the code is to process input data (`buckets`) by dividing it into distinct categories (stand, high, soft, low, double, split) and then generating expectations for each category using specialized functions. These functions sequentially compute expectations for standing, high, soft, low, doubling, and sp...
def makeExpectations(buckets): stand, high, soft, low, double, split = divide(buckets) standExpectations(stand) highExpectations(high, stand) softExpectations(soft, high, stand) lowExpectations(low, soft, high, stand) doubleExpectations(double, low, soft, high, stand) splitExpectations(split...
def takeBets(player, shoe): prop = BETTING_UNIT/BANKROLL bet = prop*player.money # if shoe.getTrue() > 1: # bet *= shoe.getTrue() bet = round(bet) player.changeMoney(-bet) return bet def dealCards(shoe, player, dealer, bet): player.addHandtoFront([shoe.deal(), shoe.deal()], bet) ...
The code simulates a blackjack game, creating a shuffled card shoe, initializing player and dealer, and running up to 1000 rounds. It handles betting, card dealing, player and dealer actions, insurance checks, debt settlement, and reshuffling the deck when low on cards. The function returns the player's remaining money...
def newGame(): # Create and shuffle the shoe of cards suits = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] deck = 4*suits shoeList = NUM_DECKS*deck random.shuffle(shoeList) shoe = Shoe(shoeList, 0) # create the player and the dealer p1 = Player("auto") dealer = Player(True) # b...
def valid_placement(board, cell, cell_type): # If potential cell type is a white cell, continue - no verification needed if cell_type == 0: return True # If potential cell type is changing from white cell to light bulb, determine if # its placement will interfere with beams and numbered boxes (w...
The code implements a backtracking algorithm to solve a puzzle by placing bulbs on a grid. It iteratively attempts to assign bulbs to white cells, validates placements, updates the board's light beams, and recursively solves the puzzle. If a placement leads to an invalid state, it backtracks by removing the bulb and ad...
def solver(board, cells_to_try): for white_cell in cells_to_try: # Set up x and y board coordinate values x = white_cell[0] y = white_cell[1] assignment = 1 # Check bulb placement if valid_placement(board, white_cell, assignment): # Assign cell new state ...
def is_token(obj): return isinstance(obj, tuple) and len(obj) > 0 and token_key_part(obj).startswith("TOKEN:") def evaluate_token(evaluate, tokens, key, args): for func in tokens[key]: res = func(evaluate, *args) if res: return res raise ValueError("No evaluators work") def token...
This method evaluates an object by checking if it is a token. If so, it uses `evaluate_token` with extracted token details; otherwise, it serializes the object. The function acts as a dispatcher for handling different object types during evaluation, ensuring proper processing based on the input's nature.
def evaluate(cls, obj, inst=None): if is_token(obj): return evaluate_token(cls.evaluate, tokens, token_key(obj), token_arguments(obj)) else: return cls.serialize(obj)
def createFolderIfNonexistent(path): existingFile = Path(path) if not existingFile.is_dir(): os.makedirs(path) def traverseBookmarks(item): return traverseBookmarksHelper([], item) def downloadMusic(url, title): actuallyDownloadedFile = downloadMusicOrUseCache(url, title) if actuallyDownload...
The main task of the code is to download music files from YouTube bookmarks stored in a JSON file, up to a limit of 100 downloads. It creates necessary output and ignore directories, reads bookmark data, processes each bookmark to extract music, and stops when the download limit is reached, printing "Downloads complete...
def main(): createFolderIfNonexistent("./output/") createFolderIfNonexistent("./ignore/") downloadLimit = 100 data = {} with open(chosenBookmarkFileName, encoding="utf8") as bookmarkFile: data = json.load(bookmarkFile) #print(str(data).encode("utf-8")) ytBookmarks = traverse...
def readGrid(filename): #print('In readGrid') grid = [] with open(filename) as f: for l in f.readlines(): grid.append([int(x) for x in l.split()]) f.close() #print 'Exiting readGrid' return grid def informedSearch(grid, start, goal, searchType): if searchType ==...
The code performs an informed search (A* or greedy) on a grid to find a path from a start location to a goal location. It reads a grid from a file, prompts the user for a search algorithm, calculates the path using Euclidean distance as the heuristic, and outputs the resulting grid with the computed path.
def main(): # ---TEST--- # startLocationList = [7,1] goalLocationList = [1,8] test = readGrid('grid.txt') node = Node([1,0], [0,0], 0, 0, 0) clist = [] olist = [] search_type = input("Enter your preffered search type (a*/greedy): ") path = informedSearch(test,startLocationList,goa...
def tile_from_id_ex(_id_ex): _id, axis, angle = _id_ex.split('_') return rotate(flip(tiles[_id], axis), int(angle)) def rotate(tile, angle): #clockwise if angle == 0: return [l for l in tile] if angle == 90: return [''.join(l) for l in list(zip(*tile[::-1]))] if angle == 180: return rotate(rotat...
The function identifies a tile from a list that, when rotated and/or flipped, matches the edge of a reference tile. It checks each candidate tile's transformations (rotations 0°–270°, horizontal flip) against the reference tile's edge alignment (right/left or bottom/top), depending on the input list's length modulo 12....
def find_right_candidate(id_list): if len(id_list)%12 != 0: _id_ex = id_list[-1] else: _id_ex = id_list[-12] tile = tile_from_id_ex(_id_ex) for _id_ot in tiles: if _id_ot not in [l.split('_')[0] for l in id_list]: for angle in [0, 90, 180, 270]: for axis in ['no', ...
def generate_key_values(self, num_keys): # Generate a dictionary of N key-value pairs return_dict = {} for i in range(num_keys): key = "a" + str(i) value = str(i) return_dict[key] = value return return_dict def automated_load(self, sensors_dict): # Insert many key value pairs into the DHT for key,v...
This code benchmarks the performance of inserting and randomly checking key-value pairs in a data structure. It generates `num_keys` pairs, measures insertion time, then shuffles and looks up each key to assess retrieval speed, printing both durations before exiting.
def automated_script(self, num_keys): sensors_dict = self.generate_key_values(num_keys) current_time = time.time() # Insert key-value pairs from dictionary self.automated_load(sensors_dict) surpassed_time = time.time() - current_time print(f"Inserting {num_keys} key-value pairs took {surpassed_time} seconds...
def log(self, infoData): file_ = open("./logs/chord.log", "a+") file_.write(str(self.getIdentifier()) + " : " + infoData + "\n") file_.close() def getIdentifier(self, offset=0): return (self._address.__hash__() + offset) % SIZE def successor(self): return self._finger[0] def clos...
The function `findSuccessor` determines the responsible node for a given key in a distributed network. It checks if the key lies within the current node's range; if so, it returns the direct successor. Otherwise, it identifies the closest preceding node and recursively delegates the query, ensuring efficient key lookup...
def findSuccessor(self, id): # check paper for implementation timeStamp = datetime.now().strftime('%Y/%m/%d %H:%M:%S.%f')[:-3] self.log( "findSuccessor called at: Node[" + str(self.getIdentifier()) + "] for key: " + str(id) + " :: " + timeStamp) if (inrange(id, self.getIdenti...
def log(self, infoData): file_ = open("./logs/chord.log", "a+") file_.write(str(self.getIdentifier()) + " : " + infoData + "\n") file_.close() def findSuccessor(self, id): # check paper for implementation timeStamp = datetime.now().strftime('%Y/%m/%d %H:%M:%S.%f')[:-3] se...
The main task of the code is to periodically update a finger table in a distributed system. It iterates through each entry in the table, calculates the successor of a specific identifier using bit-shifting, and updates the corresponding finger entry. This ensures accurate routing information for efficient data location...
def fixFingers(self): nxt = 0 while system_running: # print(str(self.getIdentifier()) + " :: " + "called fixFingers") self.log("fixFingers") nxt = nxt + 1 if nxt > NBITS: # self.printFingerable() nxt = 1 self._fi...
def choose_coordinates_to_attack(self): """ Method used to choose coordinates for a shot @ return row The row coordinate of the attacked square @ return col The column coordinate of the attacked square @ return layer The layer coordinate of the attacked square ...
This function manages a player's turn in a turn-based game, handling the attacking phase. It displays the current player, shows ally and enemy boards, selects attack coordinates, processes the shot, updates the enemy board, and checks if the game has ended after the attack.
def one_turn(self, current_player): """ Manage a player turn @param current_player the current player """ # Display the current player self.view.display_player_to_play(current_player) # Display that the player is in the attacking phase print("You are attacking ...
def reload_saved_sbm(self, player_number, row, col, layer, size, direction): """ Method used to reload a submarine @param player_number The number of the player who owns the submarine @param row The row coordinate of the head of the submarine @param col The ...
The code's main task is to manage a game by either reloading saved submarine placements and shots from a CSV file or initiating a new game with fresh submarine placements. It displays player boards, handles user input to progress through phases, alternates turns between players until the game ends, and finally displays...
def launch_game(self): """ Manage the game """ # If players want to reload an old game if self.is_old_game_to_be_reload: # Reload the selected game boards with open(self.backup_file_path) as file: reader = csv.reader(file) for row ...
def Start_User_Data_Stream(self): params = dict() obj = self.sendCmd(type='POST', url = '/fapi/v1/listenKey', params = params) return obj def connect(self, param): def on_open(ws): print('open connection') def on_message(ws, message): ...
The main task of the code is to initiate a connection to a user data stream using a listen key obtained from `Start_User_Data_Stream`, then immediately close the stream via `Close_User_Data_Stream`, returning `None`. The method essentially establishes and terminates a connection in sequence, likely for stream managemen...
def Connect_To_User_Data_Stream(self): listenKey = self.Start_User_Data_Stream()['listenKey'] self.connect(listenKey) self.Close_User_Data_Stream() return None
def _merge_attributes(dest, elem, int_attributes = None, float_attributes = None, forbidden_attributes = None): for attrib_name in elem.attrib: if forbidden_attributes is not None and attrib_name in forbidden_attributes: raise Exception('attribute "{}" on <{}> is not supported: conflict with internal format'.form...
The main task of the code is to read an ORA file (a ZIP archive) containing an Open Raster image, parse its XML structure into a Python dictionary for manipulation, validate the file format, extract layer data, and load raster images. It initializes metadata, checks for required files, parses the stack tree, and popula...
def read_ora(ora_file): """ Read an ORA file and convert it to a dict for easy manipulation """ # Normalize between different kind of parameters ora_filename = None if isinstance(ora_file, str): ora_filename = ora_file if not zipfile.is_zipfile(ora_file): raise Exception('"{}" is not an Open Raster file: n...
def hhblits(inp,a3mout,hhmout,ncpu,db): a3m = a3mout hhm = hhmout query = inp cmd = "hhblits -cpu %d -id 99 -diff inf -cov 50 -n 3 -maxmem 16.0 "\ "-i %s -d %s -maxres 65535 "\ "-oa3m %s -ohhm %s"%(ncpu,query,database[db],a3m,hhm) ## Let's do it using sbatch ## sba...
The code builds a custom HHBLITS database from HMMER search results by fetching sequences, clustering them with MMseqs, generating an MSA, and using cstranslate_mpi. It handles database-specific logic, such as replacing previous results for 'uniref' based on Nf values or combining/filtering alignments for 'metaclust'/'...
def build_and_search_custom_db(prefix,previous_db,db): ## fetch sequence from hmmer search table ## tbl = '%s.%s.tbl'%(prefix,db) fseqs = '%s.%s.fseqs'%(prefix,db) time = datetime.datetime.now().time() cmd = "esl-sfetch -f %s %s | sed 's/*//g' > %s"%(database[db],tbl,fseqs) sys.stdout.write("...
def search_uniclust30(self,db,skip_search): hhblits_on_db(self.prefix,self.ncpu,db,skip_search=skip_search) def enough_msa(self,db): time = datetime.datetime.now().time() sys.stdout.write("-%s Checking if result msa "\ "from %s has enough Nf\n"%(time,db)) return ...
The code builds a final multiple sequence alignment (MSA) by sequentially using up to four databases (db1–db4) if prior alignments are insufficient, then copies the final a3m file and optionally removes intermediate files and temporary directories.
def build(self,db1,db2,db3,db4,remove_intermediate=True): self.search_uniclust30(db1,skip_search=False) final_db = db1 if not self.enough_msa(db1): jackhmmer_on_db(self.prefix,db1,db2,skip_search=False) final_db = db2 if not self.enough_msa(db2): ...
def _allow_analysis(printer, settings): """Returns true if we can analayze files currently, assuming that we are printing. This is run frequently so it shouldn't be too CPU intensive. Returns true if allowAnalysisWhilePrinting is set. Also returns true if allowAnalysisWhileHeating is set and there is a hea...
This code performs 3D print analysis by executing built-in and external analyzers, aggregating results, handling errors, and compensating estimates based on historical data to refine print time and filament timing predictions.
def _do_analysis(self, high_priority=False): self._aborted = False logger = self._plugin._logger results = {'analysisPending': True} self._finished_callback(self._current, results) if self._plugin._settings.get(["enableOctoPrintAnalyzer"]): logger.info("Running built-in analysis.") try: ...
def start_dice_round(self): self._saved_dice = [] self._current_dice_roll = 0 dice_count = 5 while self._current_dice_roll < self._max_dice_roll: self._current_dice_roll += 1 if len(self._saved_dice) < 5: self.print_output("") out...
The main task of the code is to manage a game loop that iterates through a predefined number of rounds, cycling through each player to take turns rolling dice, updating scores, and progressing the game state. The loop increments the round counter, assigns the current player, executes dice rolls, records scores, and con...
def start_game(self): while self._current_game_round < self._total_game_rounds: self._current_game_round += 1 for i, p in enumerate(range(len(self.players))): self._current_player_index = i self.start_dice_round() self.set_score() ...
def generate_tests(): src_path = self_path / "specs" / "generate_tests.py" dst_path = self_path / "tests" / "test_generated.py" spec_paths = list(self_path.joinpath("specs").glob("*.toml")) if ( not dst_path.exists() or src_path.stat().st_mtime > dst_path.stat().st_mtime or any(...
The main task of the code is to execute a pre-commit workflow by generating tests, formatting code, running linters, executing tests with optional backtrace details, and updating documentation to ensure code quality and consistency before committing changes.
def precommit(backtrace=False): generate_tests() format() lint() test(backtrace=backtrace) update_docs()
def debug(*args, debug_filename=DEFAULT_DEBUG_PATH, sep=' ', end='\n'): """ print()-like function for debugging """ with open(debug_filename, 'a') as file: for arg in args: file.write(str(arg) + sep) file.write(end) def set_centers(centers: list, filename=__OLD_CENTERS_PATH)...
The code performs iterative center updates until convergence or a specified step limit, using initial centers from a file. It handles debugging outputs, manages temporary files, and returns the total steps taken.
def full_run(self, max_steps_count=0, start_centers_path=DEFAULT_CENTERS_PATH, is_debug=False): """ Full running with several steps """ if max_steps_count < 0: raise ValueError("max_steps_count must be >= 0") if is_debug: debug("-- Metric is " + self.met...
def compress_multirowplayers(df): """ This function removes extra rows for players with more than one row (because they switched teams during the season): For players with more than one row, keep only row with 'Tm' == 'TOT' and replace 'Tm' value with most recent team id: """ indices_of_rows_toberemove...
This function loads and processes NBA player statistics for a specific year by merging basic and advanced stats from CSV files, cleaning data, adding derived metrics (efficiency, game score), team info, scaled stats, and target-specific awards (e.g., All-Star, MVP). It reorders columns and returns a structured DataFram...
def loaddata_singleyear(year, target): """ Function that loads NBA data from csv-files for one particular year """ NBA_playerstats_csvfilename = NBAanalysisdir + 'data/NBA_totals_{}-{}.csv'.format(year-1, year) if not os.path.isfile(NBA_playerstats_csvfilename): print("--- ERROR: {...
def arxiv2bib(id_list): """Returns a list of references, corresponding to elts of id_list""" d = arxiv2bib_dict(id_list) l = [] for id in id_list: try: l.append(d[id]) except: l.append(ReferenceErrorInfo("Not found", id)) return l def create_output(self, bib)...
The main task of the code is to fetch a BibTeX entry from arXiv using a given ID, handle HTTP errors (especially 403 Forbidden for rate-limiting), generate output files, and tally errors. It ensures robust error handling for network issues and enforces proper usage to avoid arXiv.org's restrictions.
def run(self): """Produce output and error messages""" try: bib = arxiv2bib(self.args.id) except HTTPError as error: if error.getcode() == 403: raise FatalError("""\ 403 Forbidden error. This usually happens when you make many rapid fire requests i...
def require_registered(self, user_id: str): """ Check if a user is registered """ if user_id not in self._graph or user_id not in self._balances: raise ValueError(f"{user_id} is not registered") def remaining_capacity(self, user_id: str, recipient_id: str) -> int: sel...
This function determines the maximum credit limit a creditor can extend to a debtor by returning the minimum value between the creditor's remaining capacity for the debtor and the creditor's available balance. It first verifies the creditor's registration, then calculates the limiting factor between these two financial...
def edge_credit_limit(self, creditor_id: str, debtor_id: str) -> int: self.require_registered(creditor_id) return min(self.remaining_capacity(creditor_id, debtor_id), self.available_balance(creditor_id))
def require_all_registered(self, users: Iterable[str]): """ Check if all users are registered """ for user_id in users: self.require_registered(user_id) def withdraw(self, user_id: str, amount: int): self.require_registered(user_id) if amount <= self.available...
This function transfers a specified amount from a user's account to a recipient's account. It first verifies both parties are registered, then deducts the amount from the user's balance and adds it to the recipient's balance.
def transfer(self, user_id: str, amount: int, recipient_id: str): self.require_all_registered((user_id, recipient_id)) self.withdraw(user_id, amount) self.deposit(recipient_id, amount)
def debug_print(arg): global debug if debug: print(("[%4d] %s"%(inspect.currentframe().f_back.f_lineno, arg))) def is_namespace(nameStack): """Determines if a namespace is being specified""" if len(nameStack) == 0: return False if nameStack[0] == "namespace": return True return F...
(The code parses C++ header files (from a file or string) to build a structured parse tree, tracking classes, functions, variables, namespaces, and access specifiers. It processes templates, macros, and preprocessing directives, using a lexer to tokenize input and handle nested constructs. The parser manages state for ...
def __init__(self, headerFileName, argType="file", **kwargs): """Create the parsed C++ header file parse tree headerFileName - Name of the file to parse OR actual file contents (depends on argType) argType - Indicates how to interpret headerFileName as a file string or file name ...
def gsheet( self, spreadsheet_id: str, worksheet_name: str | None = None, *, create_ws: bool = False ) -> Worksheet | Spreadsheet: """Retrieve a Google sheet by its id and the name Open a Google sheet in your browser and check the URL to retrieve the id, e.g.: https://docs.google.co...
(The function saves a pandas DataFrame to a specified Google Sheet worksheet by either retrieving an existing worksheet or creating a new one. It clears existing data, writes the DataFrame with optional formatting, and handles API errors. Key parameters include the spreadsheet ID, worksheet name, creation flag, formatt...
def save_df_as_gsheet( self, df: pd.DataFrame, spreadsheet_id: str, worksheet_name: str, *, create_ws: bool = False, default_fmt: bool = True, **kwargs: str | (bool | int), ): """Save the given dataframe as worksheet in a spreadsheet M...
def get_current_location(address): location = geopy.geocoders.Nominatim(user_agent="spotsum").geocode(address) return [location.latitude, location.longitude] def get_place_info(place_id): # Define the Places API endpoint url = f"https://maps.googleapis.com/maps/api/place/details/json?place_id={place_id}...
This function searches for nearby places of a specified type (e.g., restaurants) using the Google Maps API, retrieves detailed information about each location, filters results based on a search query, and returns a summarized list of relevant spots within a given radius of a provided address.
def search_places(address, search, radius=500, place_type="restaurant"): location = get_current_location(address) location = ",".join([str(i) for i in location]) # Define the Places API endpoint url = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={location}&radius={radius}&type...
def get_e(self, x): prime = [] for i in range(2, x): if self.gcd(i, x): prime.append(i) return random.choice(prime) def get_d(self, n, phi): for i in range(1, n): if ((self.e * i) % phi) == 1: return i def encrypt(self, pt, e, n): ...
This code implements RSA encryption by taking user input for a message and two prime numbers, computing RSA keys (n, e, d), and encrypting the message by converting each character to its ASCII value, then applying RSA encryption to produce an encrypted text string.
def __init__(self): # Taking the plain text and getting their ascii value self.plain_text = [ord(x) for x in input("Enter the text to be encrypted: ")] #Taking two primes as inputs. self.p, self.q = int(input("Enter a prime number(p): ")), int(input("Enter a prime number(q): ")) ...
def get_best_split(self, x_data, num_features): """function to find the best split""" # dictionary to store the best split best_split = {} max_info_gain = -float("inf") # loop over all the features for feature_index in range(num_features): feature_values = x...
This code recursively builds a decision tree by splitting data based on information gain. It checks stopping conditions (min samples, max depth), computes the best split, and creates child nodes if the split is valid. If no valid split, it returns a leaf node with the calculated value.
def build(self, x_data, y_data, curr_depth=0): """ Build decision tree """ num_samples, num_features = np.shape(x_data) if num_samples >= self.min_size and curr_depth <= self.max_depth: best_split = self.get_best_split(x_data, num_features) if best_split[...
def get_params(self, q: str) -> dict: """Generate request params""" params = { 'q': q, 'type': 'link', 'cId': str(uuid.uuid4()), 'iId': str(uuid.uuid4()), } return params def get_request(self, link: str, params: dict = None) -> str: ...
The main task of the code is to fetch paginated Reddit search results based on a query (q), either for a specified subreddit or the main Reddit site. It constructs URLs, retrieves data using `get_request`, processes results, and iterates through pages until no more results exist, compiling the data into a dictionary.
def update_data(self, q: str, subreddit_name: str = None) -> dict: domain = 'https://www.reddit.com' if subreddit_name: # subreddit_name must be like "https://www.reddit.com/r/europe" link = subreddit_name + '/search/' else: link = domain + '/search/' ...
def _compute_gradients(self, input_vector, target): layer_1 = np.dot(input_vector, self.weights) + self.bias layer_2 = self._sigmoid(layer_1) prediction = layer_2 derror_dprediction = 2 * (prediction - target) dprediction_dlayer1 = self._sigmoid_deriv(layer_1) dlayer1_db...
The code trains a model using stochastic gradient descent by iteratively selecting random data points, computing gradients, updating weights, and periodically calculating cumulative errors across all data instances to monitor performance.
def train(self, input_vectors, targets, iterations): cumulative_errors = [] for current_iteration in range(iterations): # Pick a data instance at random random_data_index = np.random.randint(len(input_vectors)) input_vector = input_vectors[random_data_index] ...
def process(board_size, train_data_cnt, test_data_cnt,learning_rate,epochs): setBoardSize(board_size) print("*" * 30) print("Creating Train Dataset") createTrainDataset(train_data_cnt) print("Train Dataset Created") print("*" * 30) print("Creating Test Dataset") createTestDataset(te...
The code simulates a board game (likely Snakes and Ladders) with two AI players: one using a neural network (NN) and the other a tree-based model. It runs 100 simulations, tracking each player's scores, checking for wins, and generating plots/histograms to compare their performance across iterations. The goal is to eva...
def simulate_game(game_size): #Requirement 8 and 9 model = process(board_size=game_size,train_data_cnt=500,test_data_cnt=200,learning_rate=0.0001,epochs=500) #Requirement 10 and 5 simulation_steps = 100 player1_scorelist = [] player2_scorelist = [] for i in range(simulation_steps): ...
def _compute_gradients(self, input_vector, target): layer_1 = np.dot(input_vector, self.weights) + self.bias layer_2 = np.dot(layer_1, self.weights) + self.bias layer_3 = self._sigmoid(layer_2) prediction = layer_3 derror_dprediction = 2 * (prediction - target) dpredicti...
This code trains a model using stochastic gradient descent by randomly selecting data points, computing gradients, updating weights, and tracking cumulative and test errors over iterations. It iterates through the dataset, measures prediction errors against targets, and appends cumulative and test error values to lists...
def train(self, input_vectors, targets,test_input,test_output,iterations): cumulative_errors = [] test_errors = [] for current_iteration in range(iterations): # Pick a data instance at random random_data_index = np.random.randint(len(input_vectors)) input_vec...
def get_filename(): filename = input("Enter the filename: ") return filename def get_initial_data(filename): D = [] with open(f'{DIR_PATH}/{filename}', 'r') as f: f_row = f.readline().strip().split(' ') int(f_row[0]) int(f_row[1]) for line in f: number = [int(...
The code processes user data to find and sort favorite items of a specified user, then writes the results. It retrieves data from a file, prompts for a user number, generates a list of favorites, sorts it, and outputs the sorted list with the user's number.
def main(): filename = get_filename() data = get_initial_data(filename) X = int(input("Enter the user number for comparison: ")) favourites_list = users_and_inv(data, X) sort_favourites_list(favourites_list) write_result(favourites_list, X)
def take_action(self,action): """ SEE CONSTRUCTOR FOR FULL DETAILS Important remark: when the agent takes action, it has not seen the closing value. The closing value determines the portfolio value after the action is took. Translate to the action made by the agent. It mo...
This method defines the environment's evolution after an agent's action. It increments the step count, executes the action, checks termination conditions (net worth ≤0, invalid portfolio positions, or step limit), calculates rewards, and returns the next observation, reward, done flag, and empty info.
def step(self, action): """ Define the evolution of the environment after the action:action has been taken by the agent. This is the action took at the begining of the session. Override from the gym.Env class' method. :param action: :return: obs,reward,done, {} ""...
def drive(self, way): if way == 1: if self.speed < self.max_speed / 3: self.speed = min(self.speed + self.acceleration, self.max_speed) elif self.speed < self.max_speed / 2: self.speed = min(self.speed + self.acceleration / 5, self.max_speed) e...
This code processes movement commands by checking each element of the 'move' list. If any element is not 'False', it sets 'moved' to True and triggers corresponding drive or rotate actions. If no movement occurs, it calls 'reduce()' to handle idle state.
def onServer(self, move): moved = False if move[0] != 'False': moved = True self.drive(1) if move[1] != 'False': moved = True self.drive(0) if move[2] != 'False': self.rotate(1) if move[3] != 'False': sel...
def add_data_tab(self): self.data_tab = self.add_tab('Data') self.data_selection_btn = widgets.Button(description='Load Data', icon='refresh') self.data_selection_btn.on_click(self.filter_data_on_request) self.data_tab.add_child(self.data_selection_btn) # Initialize data ...
Your return The code initializes a GUI interface with multiple tabs, including data, dimensionality reduction, autoencoder, and a dedicated logs tab. It sets up a container using `widgets.Tab()`, adds specialized tabs via methods like `add_data_tab()` and `add_dim_reduction_tab()`, and creates a logs tab with a child w...
def __init__(self): self.container = widgets.Tab() self.add_data_tab() self.add_dim_reduction_tab() self.add_autoencoder_tab() self.log_tab = self.add_tab('Logs') self.log_context = self.log_tab.add_child()
def get_simulated_data(doubling_type, densities, max_real_area, coord_spacing, mult): # Import relevant modules import numpy as np import pandas as pd # Warn if we're doubling up the data if doubling_type != 0: print('NOTE: DOUBLING UP THE SIMULATED DATA!!!!') # Specify the columns th...
This code initializes a class to handle data processing, either generating simulated data or loading real data from a CSV. It preprocesses the data, extracts metadata (species, slides, plotting info), and stores results in a pickle file for future use. If the pickle already exists, it loads data directly from it, avoid...
def __init__(self, pickle_dir, simulate_data, allow_compound_species, mapping_dict, **kwargs): # Import relevant module import os # These next two blocks aren't technically needed but it helps to set these here to help for linting purposes # These are set in this method but not saved i...
def roi_checks_and_output(x_roi, y_roi): import numpy as np coord_spacing_check = 0.5 x_roi2 = x_roi.copy() y_roi2 = y_roi.copy() x_roi2.sort() y_roi2.sort() unique_spacing_x = np.unique(x_roi2[1:]-x_roi2[0:-1])[0:2] unique_spacing_y = np.unique(y_roi2[1:]-y_roi2[0:-1])[0:2] expected...
This code processes slide data to count neighboring cells within defined parameters (k_max, dr) for each ROI, identifying valid centers and species. It saves results in a pickle file for reuse, avoiding redundant calculations. If the file exists, it loads precomputed data. Finally, it computes basic slide properties li...
def count_neighbors(self, k_max=10, dr=8, min_nvalid_centers=50): # Import relevant modules import os import numpy as np # Set variables already defined as attributes unique_slides = self.unique_slides pickle_dir = self.pickle_dir # Constant pickle_fil...
def get_descriptive_cell_label(phenotype_list, mapping_dict): # Note: CD163+/CD4+ REALLY ISN'T ANYTHING COMPOUND --> MAKE IT OVERLAPPING SPECIES (i.e., it shouldn't be in the dictionary below)!!!! phenotype_string = phenotypes_to_string(phenotype_list) descriptive_name = mapping_dict.get(phenotype_string) ...
The main task of the code is to generate and save visualizations of ROI data, density heatmaps, PDFs, and null distribution comparisons for each slide and ROI, compiling them into an HTML report. It processes input data, applies plotting parameters, creates figures for density and PDF analysis, computes z-scores relati...
def plot_results(self, marker_size_step, resultsdir, dpi, myfontscale, dens_range, dens_demeaned_range, pdf_range, pdf_demeaned_range, z_score_range, alpha, mapping_dict): # Antonio's fix to enable plot generation in SLURM's batch mode import matplotlib matplotlib.use('Agg') ...
def traverse_nodes(node, board, state, identity): """ Traverses the tree until the end criterion are met. Args: node: A tree node from which the search is traversing. board: The game setup. state: The state of the game. identity: The bot's identity, either 'red...
The code implements Monte Carlo Tree Search (MCTS) to determine the optimal action in a game. It constructs a game tree by iteratively selecting nodes, expanding the tree with new states, simulating outcomes through rollouts, and backpropagating results to update node values. The process evaluates legal actions, priori...
def think(board, state): """ Performs MCTS by sampling games and calling the appropriate functions to construct the game tree. Args: board: The game setup. state: The state of the game. Returns: The action to be taken. """ identity_of_bot = board.current_player(state) #r...
def traverse_nodes(node, board, state, identity): """ Traverses the tree until the end criterion are met. Args: node: A tree node from which the search is traversing. board: The game setup. state: The state of the game. identity: The bot's identity, either 'red...
The code implements Monte Carlo Tree Search (MCTS) to determine the optimal action by iteratively selecting, expanding, simulating, and backpropagating game states. It constructs a tree of possible moves, evaluates outcomes through rollouts, and selects the action with the highest win rate from the root node's children...
def think(board, state): """ Performs MCTS by sampling games and calling the appropriate functions to construct the game tree. Args: board: The game setup. state: The state of the game. Returns: The action to be taken. """ identity_of_bot = board.current_player(state) roo...
def isFlush(self): """ returns true if the hand is a flush """ cards = self.tableBothCards('suit') for card in cards.values(): if card >= 5: return True return False def isStraight(self, cards = None): """ cards- a dict ...
The main task of the code is to determine if a poker hand is a straight flush by checking if it is both a flush (all cards of the same suit) and a straight (five consecutive ranks). It filters cards to the dominant suit, extracts their ranks, and verifies if these ranks form a consecutive sequence.
def isStraightFlush(self): """ returns true if the hand is a straight flush """ if not self.isFlush() or not self.isStraight(): return False check = self.tableBothCards('suit') for i in check.keys(): if check[i] >= 5: suit ...
def generate_icosphere(radius, center, refinement_order=3): """ Generate icosphere (subdivision surface of a regular `icosahedron`_). Args: radius (``float``): Radius of icosphere. # center (``numpy.ndarray``): Sphere center. refinement_order (``int``): (optional) Number of refinement. ...
The main task of the code is to generate a 3D mesh model of a molecule, including atoms and bonds, by creating geometric shapes (icospheres for atoms and cylinders for bonds) scaled according to parameters like bond order, radii, and segmentation. It combines these elements into a unified mesh, with support for single,...
def create_mol_model(mol: Molecule, atom_size=1, bond1_radius=1, bond2_radius=0.65, bond3_radius=0.45, bond_num_segments=64, sphere_refinement_order=3, all_bonds_single=False, bd2=0.14, bd3=0.17, mode: int = PrintMode.All, **kwargs): """ Creates the mesh for the whole ...
def print_board(board): for row in board: print(" ".join(row)) print() def get_best_move(board): best_move = None best_score = -math.inf empty_cells = get_empty_cells(board) for cell in empty_cells: board[cell[0]][cell[1]] = 'X' score = minimax(board, 0, False) bo...
This code implements a tic-tac-toe game where a human player ('X') competes against an AI ('O'). It manages the game loop, validates moves, checks for wins/ties, and alternates turns. The AI uses a 'get_best_move' function to determine its strategy. The game ends when a player wins or the board is full, with results di...
def play_game(): board = [[' ' for _ in range(3)] for _ in range(3)] current_player = 'X' while True: print_board(board) if current_player == 'X': row, col = map(int, input("Enter row (0-2) and column (0-2) separated by space: ").split()) if board[row][col] != ' ': ...
def register_dangers(self, data): board = get_board(data) self.dangers = [] self.dangers.extend(board.bounds) for snake in board.snakes: self.dangers.extend(snake.body) def register_food(self, data): board = get_board(data) self.winners = [] self.win...
The main task of the code is to determine the optimal movement for an agent by analyzing environmental data (dangers and food), generating possible moves, evaluating their priorities, selecting the highest-weighted options, and randomly choosing one to execute while recording the decision in history.
def move(self, data): self.register_dangers(data) self.register_food(data) moves = self.probable_moves() moves = self.weigh(moves) print(moves) moves = self.max_moves(moves) moves = random.choice(moves) self.history.append(move) return moves
def update_text_fields(self, who, what, amount): self.who_text = who self.reset_who() self.what_text = what self.reset_what() self.amount.config(text=amount) def enable_buttons(self, enable: bool): state = "normal" if enable else "disabled" self.add_filter_button....
This function assigns a tag to a table row based on filter rules. It checks if 'who' or 'what' parameters match filter criteria. If no match, it waits for user input to assign a tag. If no user input, it defaults to "Other" and updates the table with the determined tag.
def process_row(self, row_index: int, who, what, amount): tag_for_row = "" for _, filter_row in self.filters.iterrows(): filter_who = str(filter_row[Constants.FILTER_WHO_STR]) filter_what = str(filter_row[Constants.FILTER_WHAT_STR]) tag = filter_row[Constants.FILTER_T...
def process_row(self, row_index: int, who, what, amount): tag_for_row = "" for _, filter_row in self.filters.iterrows(): filter_who = str(filter_row[Constants.FILTER_WHO_STR]) filter_what = str(filter_row[Constants.FILTER_WHAT_STR]) tag = filter_row[Constants.FILTER_T...
The main task of the code is to process each row of a table by extracting 'who', 'what', and 'amount' data, then calling `process_row` for each entry while updating progress. After processing all rows, it saves the updated table and filters to CSV files specified in the configuration, finally displaying a "Done" status...
def start_data_processing(self): self.rows_processed = 0 for row_index, row in self.table.iterrows(): who, what, amount = csv_helpers.get_entries( row, [Constants.WHO_STR, Constants.WHAT_STR, Constants.AMOUNT_STR]) self.process_row(row_index, who, what, amount) ...
def omnipotent(num_of_intersections: int, matrix_representations: list, graph): """ :param num_of_intersections: number of intersections :param matrix_representations: matrix representation of intersections :param graph: Intersections class objects for current input.txt file :return: None """ out_edges = [0] * n...
The main task of the code is to read an adjacency matrix from "input.txt", construct a graph with vertices, edges, and weights based on the matrix, and execute graph-related operations like checking strong connectivity and outputting circuits. It processes the matrix data, populates the graph structure, and triggers fu...
def getIntersections(): """ Opens the input.txt file to retrieve intersection and matrices Adds vertices, edges, and weights to graph Calls omnipotent function with needed parameters :return: None """ with open("input.txt") as file: intersections = int(file.readline()) graph = Intersection(intersections) c...
def get_data(): now = datetime.now() date_time = now.strftime("%Y/%m/%d %H:%M:%S") pymc3e = pymcprotocol.Type3E() pymc3e.connect("192.168.1.2", 10000) press_mode = pymc3e.batchread_bitunits(headdevice="M310", readsize=1) all_pump_on = pymc3e.batchread_bitunits(headdevice="M3292", readsize=1...
The main task of the code is to periodically retrieve PLC data, compare the current data with the latest historical data from a database, and insert concatenated data into a web log if the "press_mode" changes. It runs indefinitely with a 30-second interval, querying the latest record, filtering by die name and date, c...
def main(): interval = 30 new_data = get_data() while True: now = datetime.now() date_now = now.strftime("%Y/%m/%d %H:%M:%S") time.sleep(interval) new_data = get_data() insert_data_to_log(new_data) sql1 = "SELECT DATE_FORMAT(date_time, '%Y-%m-%d %H:%i') as dat...
def importVideo(filename): print('Reading Video File') filename = 'final_clip' return VideoFileClip(VIDEO_OUTPUT_PATH + filename + '.MP4') def importTranscription(filename): print('Reading Transcription') return json.load(open('transcriptions/' + filename + '.json')) def createSectionsToKeep(transcr...
The main task of the code is to process a video by importing it and its transcription, identifying relevant sections, refining them, and generating subclips with zoom effects using face detection. If text is enabled, it overlays text graphics from the transcription. Finally, it creates a final video from the subclips, ...
def main(filename, FACE_DETECTION_FRAME_NAME, BUCKET_NAME, hasText=False): print('Video Creation Started') video = importVideo(filename) transcription = importTranscription(filename) sectionsToKeep = createSectionsToKeep(transcription) sectionsToKeep = refineSections(sectionsToKeep, video) subC...
def check_algorithm(self): """Checks that the algorithm asked for is one of the options""" if self.algorithm not in self.algorithm_options: raise ParameterException('Algorithm {0} is not valid. Pick from {1}'.format(self.algorithm, self.algorithm_options)) if self.algorithm in ['Bran...
The main task of the code is to validate parameters for consistency, assign default values to missing parameters (e.g., mutation generator, mutation rate, figure size), collect warnings for overridden defaults, and handle exceptions. It checks algorithm, population, timing, and sample configurations, ensuring prerequis...
def check_parameters(self): """Check parameters for consistency. Defines any missing parameters which can be calculated from others.""" try: if self.mutation_generator is None: self.warnings.append('Using the default mutation generator: {0}'.format(self.default_mutation_gener...
def biopsies_samples(grid, ancestors, biopsies): if biopsies is None or type(biopsies) == dict: vaf_arr = biopsy_sample(grid, ancestors, biopsies) else: all_biopsy_samples = [biopsy_sample(grid, ancestors, biopsy) for biopsy in biopsies] try: vaf_arr = np.concatenate([s for s...
The function generates variant allele frequency (VAF) arrays from biopsy data by first sampling based on grid and ancestor relationships. It adjusts VAFs for coverage and detection limits if specified, then optionally subsamples the data. The result is a modified VAF array for analysis.
def get_vafs(grid, ancestors, biopsies, coverage, detection_limit, subsample=None): vaf_arr = biopsies_samples(grid, ancestors, biopsies) if coverage is not None: vaf_arr = small_detection_limit(vaf_arr, coverage, detection_limit) if subsample is not None: vaf_arr = random_sample_vafs(vaf_...
def get_vafs(grid, ancestors, biopsies, coverage, detection_limit, subsample=None): vaf_arr = biopsies_samples(grid, ancestors, biopsies) if coverage is not None: vaf_arr = small_detection_limit(vaf_arr, coverage, detection_limit) if subsample is not None: vaf_arr = random_sample_vafs(vaf_...
The function computes and returns variant allele frequency (VAF) data and statistical results (R² values) for full data, biopsy-informed data, and matched-sample-size scenarios. It processes simulation data to generate X/Y values, R² metrics, sample sizes, and raw VAFs for recalculating statistics. Adjustments account ...
def get_results_for_sim(sim_file, biopsies, coverage, detection_limit, fixed_interval): """ Get the vafs for full data, biopsies and matched sample size full data. Return the sample size and for each of (full data points, fixed num points, fixed interval points): Full x and y for incomplete mome...
def get_active_pid(): wid = get_active_window() return get_field(get_window_info(wid, '_NET_WM_PID')) def get_child_pid(pid): return get_field(Popen(['pgrep', '-P', pid], stdout=PIPE)) def get_wd(pid): symlink = Path('/proc/') / pid / 'cwd' if symlink.exists(): return get_field(Popen(['readl...
The main task of the code is to retrieve the working directory of the first child process of the active window, assuming it is a terminal. It achieves this by obtaining the active window's process ID, identifying its child process, and then fetching the working directory of that child process.
def get_active_wd(): '''gets the active windows first child process's working directory (hopefully the terminal)''' pid = get_active_pid() child_pid = get_child_pid(pid) return(get_wd(child_pid))
def isInsufficient(): if len(wp.piecelist) > 0 or len(bp.piecelist) > 0: return False elif len(wq.piecelist) > 0 or len(bq.piecelist) > 0: return False elif len(wr.piecelist) > 0 or len(br.piecelist) > 0: return False elif len(wb.piecelist) > 1 or len(bb.piecelist) > 1: r...
The function checks if a chess game is a draw by evaluating three conditions: insufficient material, repetition, and the 50-move rule. It returns specific draw reasons if any condition is met; otherwise, it returns False.
def isDraw(): if isInsufficient(): return "INSUFFICIENT MATERIAL" if isRepitition(): return "DRAW BY REPITITION" if isDrawByFifty(): return "DRAW BY 50 MOVE RULE" return False