dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_gen_image(self, batch): images=batch['images'] depths=batch['depths'] poses=batch['poses'] K=batch['K'] mask=batch['mask'] prompt=batch['prompt'] depth_inv_norm=batch['depth_inv_norm'] depth_inv_norm_small=batch['depth_inv_norm_small'] ...
The main task of the code is to generate predicted images from input batches using a model, combine generated and input predictions via masking, and save the results (including images, depths, poses, and camera matrices) to disk for evaluation. It processes batches, applies inference, merges outputs, and stores them in...
def test_step(self, batch, batch_idx): batch_gen=self.get_gen_image(batch) images_gen_pred = self.inference_gen(batch_gen) batches_inp=self.get_inp_image(batch, images_gen_pred) images_pred=np.zeros_like(batch['images'].cpu().numpy()).astype(np.uint8) mask=batch['mask']...
def sift(array, sortedList=0, cols = ncols): tmpArray = array.copy() cont= removeEmpty(array) containers = cont.copy() cont[:,2:4] = ['00000','UNUSED'] filterArray = ((array[:,:,3] != 'UNUSED') == (array[:,:,3] != 'NAN')) (tmpArray[filterArray]) = cont #make empty ship whi...
The function `siftPick` determines a selection from a ship array based on comparisons with a `siftState`. It calculates the stack height at a given column, identifies the corresponding ship element, and checks if it matches the `siftState` at the same position. If they match, it returns `20`. Otherwise, it iterates thr...
def siftPick(state, col, siftState=[]): array = state.state.ship if(siftState==[]): siftState = sift(array) h = stackHeight(array,col) chosen = array[h,col] if((chosen == siftState[h,col])).all(): return(20) for i in removeEmpty(siftState): # print((chosen, "vs...
def unloadTop(state, unload, cols=ncols): #Shows us cols of states to pick from which have exposed unload container top = np.array((updateTop(state.state.ship, cols=cols))) filterTop = top[((top[:,3] != 'NONAME') == (top[:,3] != 'NAN'))] # print(filterTop) unloadable = [] for i in filt...
The code implements a priority-based search algorithm to find the optimal sequence of container loading/unloading/moving operations on a ship, minimizing cost. It explores states using a priority queue, prioritizing unloading, then loading (if crane is free), and finally moving containers. It tracks duplicate states to...
def LoadingBranch(testManifestArray, unloadIn, load): # unloadIn = [] # load = [] #tracking how many duplicate states old=100 #cost of going to truck costBetweenPink = 2 #duplicate states checker duplicateState = [] #legal final states finalState = [] #Create PriorityQu...
def build_heap(self): for i in range(self.heapsize // 2 - 1, -1, -1): self.heapify(i) def update_size(self): self.heapsize = self.heapsize - 1 def heapify(self, i): # Set left-child with respect to node i self.left(i) # Set right-child with respect to node i ...
The main task of the code is to implement the heapsort algorithm. It first builds a max-heap using `build_heap()`, then repeatedly extracts the maximum element by swapping the root with the last element in the heap, reducing the heap size, and re-heapifying the root to maintain the heap property, ultimately sorting the...
def heapsort(self): # Invoke build_heap method self.build_heap() for i in range(self.heapsize - 1, 0, -1): # Swap root and node i self.A[0], self.A[i] = self.A[i], self.A[0] self.update_size() # subtract 1 from heapsize self.heapify(0)
def optimal_weights(n_points, er, cov): """ Returns a list of weights that represent a grid of n_points on the efficient frontier """ target_rs = np.linspace(er.min(), er.max(), n_points) weights = [minimize_vol(target_return, er, cov) for target_return in target_rs] return weights def portfolio...
The code plots the multi-asset efficient frontier by generating optimal portfolio weights, calculating their returns and volatilities, and visualizing them as a line graph. It optionally adds the Capital Market Line (CML), equal-weighted (EW), and Global Minimum Variance (GMV) portfolios as key points. The function ret...
def plot_ef(n_points, er, cov, rf=0, style='.-', legend=False, show_cml=False, show_ew=False, show_gmv=False): """ Plots the multi-asset efficient frontier """ weights = optimal_weights(n_points, er, cov) rets = [portfolio_return(w, er) for w in weights] vols = [portfolio_vol(w, cov) for w in we...
def createKnowledge(file_path_in): read_data_lines = list(); try: file_in_stream = open(file_path_in, mode="r", encoding="utf-8") lines = file_in_stream.read().splitlines(); lines.append(""); line_idx = 0; current_line = TranslationLine(); nb = 0; while line_idx < len(lines): if not lines[line_idx].s...
The code reads configuration settings, processes data files to build a translation datastore, merges and translates text strings from source and UI files, and generates output files like databases, TODO lists, and .po files while handling duplicates and case sensitivity according to specified parameters.
def main(): global datastore, datastore_trim, regex_only_letters, allow_msgctxt, ignore_case, remove_comment; global percent_error_similar, language, language_code, max_similar, database_out; data_files = list(); # list of file paths ui_dir = ""; operations = list(); # list of TranslationFiles settings_stream = o...
def _extract_screen_names(argv): return _extract_argument_array_after_key(_AcceptedArgumentKeys.screen_names.value,argv) def _extract_categories(argv): return _extract_argument_array_after_key(_AcceptedArgumentKeys.append_categories.value,argv) def _validate_argument_dict(dict): if not _valid_screen_names_c...
The function `extract_arguments` parses command-line arguments into a structured dictionary. It extracts screen names, checks for optional flags like `append_categories`, `weka_friendly`, and `include_retweets`, and processes the `output_format` argument, validating it against supported formats. If `output_format` is m...
def extract_arguments(argv=None): """ Extract arguments for this call """ dict = {} # extract screen names or fail dict[_AcceptedArgumentKeys.screen_names.value] = _extract_screen_names(argv) if _AcceptedArgumentKeys.append_categories in argv: dict[_AcceptedArgumentKeys.append_cate...
def __extract__(self, folder_path: str, if_exists: str="append") -> dict[str, pd.DataFrame]: """ Extract data from CSV or JSON files and returns a Pandas DataFrame per file into a dictionary. Parameters ---------- folder_path : str The path to the folder containing t...
The code executes an ETL (Extract, Transform, Load) process. It prompts the user for a data folder path and whether to overwrite existing data, then calls private methods to extract data, transform it, and load the results, returning the outcome of the load operation as a boolean.
def run(self) -> bool: """Run the ETL.""" data_folder = input('Enter the path to the data folder: ') if_exists = input('Do you want to overwrite the existing data? (y/[n]): ') if_exists = "replace" if if_exists == "y" else "append" data = self.__extract__(data_folder, if_exists...
def load_base_table(filename: str) -> Trie: root = Trie() with open(filename, 'r') as f: reader = csv.reader(line_with_tab(f), delimiter='\t') for line in reader: token = line[0] code = line[1] priority = None if len(line) == 2 else line[2] if len(...
The main task of the code is to convert a pinyin input method table from Luna format to Flypy format. It loads a base dictionary, applies rule-based patches, then exports two Flypy-compatible YAML files: one for symbols and another for phrases, using specific filtering functions to separate entries into main and phrase...
def luna_to_flypy(): luna_table = load_base_table('./luna_pinyin.dict.yaml') patch_table_with_rules(luna_table) with open('flypy_self_main.dict.yaml', 'w+') as f: dump_table(luna_table, [], is_a_symbol, f) with open('flypy_self_phrase.dict.yaml', 'w+') as f: dump_table(luna_table, [], ...
def is_image(path): if path.endswith('.png') or path.endswith('.jpg'): return True return False def get_duplicate_images(at_path, original_image, other_files): duplicates = [] for other_file in other_files: if is_candidate(original_image, other_file): if are_dublicates(at_pat...
The code removes duplicate images from a specified directory path. It walks through the directory, identifies image files, detects duplicates using `get_duplicate_images`, and deletes them while logging the process. Duplicates are stored in `discarded_files` and removed with `discard()`, ensuring no redundant files rem...
def remove_duplicates_at_path(path): discarded_files = [] for _root, _dirs, files in os.walk(path): for target_file in files: if not is_image(target_file) or target_file in discarded_files: continue print("Searching for duplicates of " + target_file) ...
def create_readme(project: upsilon_workshop_client.api.project.Project, path: str) -> None: """Create the README.md file.""" readme = f"# {project.name}\n\n" readme += f"{project.description}\n" # If the path is a file, don't write the readme if os.path.isfile(path): retu...
The main task of the code is to save a project's data into a specified directory by creating necessary files and structure. It first resolves the input path to its real path, creates the directory if it doesn't exist, generates a README.md file, creates project files, and saves project information. The function organiz...
def save_project_to_directory(project: upsilon_workshop_client.api.project.Project, path: str) -> None: """Save a project to a directory to apply the clone.""" # Get the real path realpath = os.path.realpath(path) # Create the directory os...
def actions(board, player, user_pieces, ai_pieces): """ Returns set of all possible actions (i, j) available on the board. """ if player == USER and user_pieces > 0: positions = board_positions(board) return [positions[position][0] for position in positions ...
The code implements a minimax algorithm for an AI to choose the optimal move in a game based on difficulty levels. For beginner mode, it selects a random move. For intermediate, it picks the move with the minimum utility value. For hard mode, it evaluates two turns ahead by simulating user and AI moves, calculating uti...
def minimax(board, difficulty, player, user_pieces, ai_pieces): """ Returns the optimal action (i,j) for the AI. """ # beginner difficulty, make a random move if difficulty == BEGINNER: moves = actions(board, player, user_pieces, ai_pieces) print(f"\nOptimal moves to be made: {moves}...
def initial_state(): """ Returns starting state of the board """ return [[EMPTY, "$", "$", EMPTY, "$", "$", EMPTY], ["$", EMPTY, "$", EMPTY, "$", EMPTY, "$"], ["$", "$", EMPTY, EMPTY, EMPTY, "$", "$"], [EMPTY, EMPTY, EMPTY, "$", EMPTY, EMPTY, EMPTY], ["$"...
The main task of the code is to simulate a game state by applying predefined moves to an initial board, then use the minimax algorithm with HARD difficulty and a depth limit of 7-8 to determine the AI's optimal move. The code evaluates the game state after user and AI moves, leveraging minimax for strategic decision-ma...
def main(): board = initial_state() board = result(board, (0, 0), USER) board = result(board, (0, 6), AI) board = result(board, (3, 0), USER) print(minimax(board, HARD, AI, 7, 8))
def read(Fname): f = open(f"Files/{Fname}.txt", "r+") x = int(f.read()) f.close() return x def div3(n): result = sum(int(digit) for digit in str(n)) if result > 9: result = div3(result) else: return result in (3, 6, 9) return result def div3mod(n): result = sum(int(d...
The code benchmarks seven division-by-3 functions (div3, div3mod, etc.) by running each `loopn` times, measuring execution time per iteration. It calculates and prints average durations, identifies the fastest function, and returns results based on `printAll` flag.
def testFunctions(loopn, printAll=True): t = [0, 0, 0, 0, 0, 0,0] s = [0, 0, 0, 0, 0, 0,0] t0 = [] t1 = [] t2 = [] t3 = [] t4 = [] t5 = [] t6 = [] n = read("x") for i in range(loopn): # n = random.getrandbits(192) s[0] = timer() div3(n) t[0] =...
def read(Fname, b=0): dirname = f"{os.path.dirname(__file__)}\\Files" if not os.path.exists(dirname): os.mkdir(dirname) if not os.path.exists(f"Files\\{Fname}.txt"): f = open(f"Files\\{Fname}.txt", "w+") f.write("1" if b else "2") f.close() f = open(f"Files\\{Fname}.txt"...
The code's main task is to generate numbers by appending incrementing digits to a base number, check each generated number for primality using a predefined list, and print the result of each check. It saves the current number and iteration count after each step, looping indefinitely.
def main(): x = read("x", 1) i = read("i") temp = i primes = [] primes = readPrime(primes) while True: x = int(f"{x}{i}") i += 1 print( f"Iteration number {i - 1} is not prime because: {Test(x, i - 1, primes)}") save("x", x) save("i", i)
def read(Fname): f = open(f"Files/{Fname}.txt", "r+") x = int(f.read()) f.close() return x def isPrime(n): if (n <= 1 or n == 4): return False if (n <= 3): return True d = n - 1 while (d % 2 == 0): d //= 2 for i in range(40): if (millerTest(d, n) == Fa...
The code compares the performance of two primality testing functions, `isPrime()` and `miller_rabin()`, over `loopn` iterations. It measures execution time for each, calculates average durations, and prints results if `printAll` is True. Finally, it identifies and reports the faster function based on the average time.
def testFunctions(loopn, printAll=True): t = [0, 0] s = [0, 0] t0 = [] t1 = [] n = read("TESTX") for i in range(loopn): #n = random.getrandbits(128) s[0] = timer() isPrime(n) t[0] = timer()-s[0] t0.append(t[0]) s[1] = timer() miller_rabin...
def close_first_phase(self): self.phase += 1 self.soundManager.play_sound_break() self.start_second_phase() def close_second_phase(self): self.phase += 1 self.soundManager.play_sound_work() self.start_third_phase() def close_third_phase(self): self.phase += 1 ...
The code transitions to the next phase by invoking the corresponding closure method based on the current phase value, ensuring sequential phase completion in a state machine or process workflow.
def next_phase(self): if self.phase == 1: self.close_first_phase() elif self.phase == 2: self.close_second_phase() elif self.phase == 3: self.close_third_phase() elif self.phase == 4: self.close_fourth_phase()
def createBoardMemory(size): board = [['' for j in range(size)]for i in range(size)] return board def createBoardGUI(board,window,SIZE): boardGUI = [] for rowIndex , row in enumerate(board): # loop through rows boardGUI.append([]) for columnIndex , column in enumerate(row): # loop ...
The code initializes a 2048 game window, creates a 4x4 game board structure, generates its graphical interface, and adds initial tiles to the board. It sets up the game environment by configuring the board data, linking it to the GUI, and preparing the game for user interaction.
def runGame(root): global board global boardGUI boardWindow = tk.Toplevel(root) boardWindow.title('2048') SIZE =4 board = createBoardMemory(SIZE) boardGUI = createBoardGUI(board,boardWindow,SIZE) board , boardGUI = addBlockToBoard(board,boardGUI)
def display_board(board): print(board) def get_user_move(board): while True: move_str = input("Enter your move (in algebraic notation, e.g., e2e4): ") try: move = chess.Move.from_uci(move_str) if move in board.legal_moves: return move else: ...
The code allows a user to play chess against an AI opponent. It prompts the user to set the AI's decision depth (1-3), initializes a chess board, and alternates turns between the user and AI until the game ends. The AI uses the specified depth to calculate moves, and the board state is displayed after each move. The fi...
def play_vs_ai(): depth = int(input("Enter AI depth level (1-3): ")) board = chess.Board() display_board(board) while not board.is_game_over(): # Get user's move move = get_user_move(board) board.push(move) display_board(board) if not board.is_game_over(): ...
def tr(data): data['previous_close'] = data['close'].shift(1) data['high-low'] = abs(data['high'] - data['low']) data['high-pc'] = abs(data['high'] - data['previous_close']) data['low-pc'] = abs(data['low'] - data['previous_close']) tr = data[['high-low', 'high-pc', 'low-pc']].max(axis=1) retu...
The function processes a list of trading markets by fetching historical OHLCV data, calculating technical indicators (TR, ATR, Supertrend), and storing the results in a pickled file. It either creates a new file or updates an existing one with the latest market data and indicators, returning the updated dictionary of t...
def tradable_markets(list2): if not os.path.exists('trading.p'): print('no file creating...') with open('trading.p', 'wb') as fp: tradable_market = {} print('getting tradable markets') for market in list2: bars = exchange.fetch_ohl...
def tradable_markets(list2): if not os.path.exists('trading.p'): print('no file creating...') with open('trading.p', 'wb') as fp: tradable_market = {} print('getting tradable markets') for market in list2: bars = exchange.fetch_ohl...
The code's main task is to manage a trading bot that selects tradable cryptocurrency pairs (testnet/mainnet-specific), filters out downtrend markets, allocates investment resources, executes buy/sell strategies via portfolio management, and saves trading results. It processes market data, applies trend analysis, and ma...
def run_bot(): if config.IS_TESTNET: trade = ['BTC/USDT', 'ETH/USDT'] else: trade = ['BTC/USDT', 'ETH/USDT', 'BNB/USDT', 'NEO/USDT', 'LTC/USDT', 'QTUM/USDT', 'ADA/USDT', 'XRP/USDT', 'EOS/USDT','LINK/USDT','VET/USDT','MATIC/USDT','DOGE/USDT','DOT/USDT', 'LUNA/U...
def find_split(self, entries, class_values, class_name): list_one = list() list_two = list() label = "" split = 0 info_gains = 0 labels = list(entries[0].keys()) labels.pop(0) labels.pop() for key in labels: for diction in entries: ...
The code recursively builds a decision tree by splitting data based on information gain. If the gain is below a threshold or leaf nodes have insufficient samples, it returns a leaf node with the majority class. Otherwise, it creates decision nodes with split parameters and child nodes, prioritizing larger child subsets...
def help_tree(self, parent, class_values): split = self.find_split(parent, class_values, self.class_name) children = [split[2], split[3]] split_col = split[0] threshold = split[1] if info_gain(parent, children, class_values, self.class_name) < .005 or get_majority(children[0], se...
def dir2data(data_dir): data_dict = {} for state in os.listdir(data_dir): state_dir = os.path.join(data_dir, state) if os.path.isdir(state_dir): data_dict[state] = {} for city in os.listdir(state_dir): city_dir = os.path.join(sta...
The main task of the code is to process city data from a CSV file using a Google Maps API key. It loads existing data from a directory, checks for new cities not present in the existing data, and retrieves missing information via the `ycg_zip` function. The script parses the API key, iterates through cities, and update...
def main(): parser = argparse.ArgumentParser(description="Run ycg_zip function with Google Maps API key") parser.add_argument("api_key", help="Google Maps API key") args = parser.parse_args() # Load existing data from the data directory existing_data = dir2data("data") # Read cities.csv ci...
def pr_log(log_message): """Print log message alongside a timestamp :param log_message: The message to log """ print(f'[{BullyGroupMember.pr_now()}] {log_message}') def set_leader(self, new_leader): """Updates the current bully :param new_leader: The PID of the new bully """ ...
This function declares a process as the leader in a distributed system by logging the victory reason, updating its state to WAITING_FOR_ANY_MESSAGE, and sending victory messages to all peers with lower IDs to coordinate leadership transition.
def declare_victory(self, reason): """Declare self as bully by sending coordinate messages to all other peers :param reason: The reason for declaring victory """ self.pr_log(f'Victory by {self.pid}: {reason}') self.set_leader(self.pid) self.set_state(State.WAITING_FOR_ANY_MESSAGE, swit...
def pr_log(log_message): """Print log message alongside a timestamp :param log_message: The message to log """ print(f'[{BullyGroupMember.pr_now()}] {log_message}') def get_connection(self, member): """Establishes a connection for a particular member w/ their address :param member...
The main task of the code is to initiate a bully election algorithm by contacting members with higher PID values. If no such members exist, the current node declares itself the leader. It logs the election reason, attempts connections to higher-PID members, and transitions states to coordinate the election process.
def start_election(self, reason): """Starts an election amongst members with higher PID values :param reason: The reason for starting an election """ self.pr_log(f'Starting an election: {reason}') has_connected_to_bully = False for member in self.members.items(): if member[0] > self....
def pr_log(log_message): """Print log message alongside a timestamp :param log_message: The message to log """ print(f'[{BullyGroupMember.pr_now()}] {log_message}') def pr_sock(self, sock): """Printing helper for given socket.""" if sock is None or sock == self or sock == self.listene...
This function processes an ELECTION message by logging receipt, updating member information, sending an OK response, and initiating a new election or declaring victory based on member ID comparisons. It checks if the current node is the highest ID to determine if it should start an election or claim leadership.
def handle_election(self, peer, message_data): """Decides what to do after receiving an ELECTION message :param peer: The peer socket that sent the ELECTION message :param message_data: The dictionary of members within the ELECTION message """ self.pr_log(f'{self.pr_sock(peer)}: received ELECT...
def is_expired(self, peer=None, threshold=ASSUME_FAILURE_TIMEOUT): """Determines whether a peer has expired through timeout :param peer: A member's designated socket to check for timeout :param threshold: The alloted time before timeout occurs :return: True if timeout occured, False otherwise "...
This function identifies expired peers and handles timeout scenarios. It marks expired peers as quiescent and checks the listener's state. If the listener has expired, it declares victory if waiting for confirmation or initiates an election if awaiting a victor, ensuring proper protocol transitions during timeouts.
def check_timeouts(self): """Check all peers for timeout""" expired = [peer for peer in self.states if not self.listener == peer and self.is_expired(peer)] for peer in expired: self.set_quiescent(peer) if self.is_expired(self.listener): state = self.get_state(self.listener) if state =...
def is_time_to_probe(self): """Determines if it's a proper time to send a probe message to the leader :return: True if proper time to probe, False otherwise """ probe_time = rng(0.5, 3.0) last_probe = dt.strptime(self.last_probe, '%H:%M:%S.%f') is_time_to_probe = (dt.now() - last_probe).se...
The function `probe_leader` sends a PROBE message to the leader node to check its status. If the probe succeeds (receiving an "OK" response), it logs the success; otherwise, it logs the failure and initiates an election assuming leader failure. The function uses a connection to the leader, handles exceptions, and sets ...
def probe_leader(self): """Sends a PROBE message to the leader""" if self.is_time_to_probe(): leader = (self.bully, self.members[self.bully]) peer = self.get_connection(leader) is_successful_probe = True if peer: self.pr_log(f'{self.pr_sock(peer)}: sending PROBE') try: ...
def receive(peer, buffer_size=BUF_SZ): """Receives a message through a provided peer :param peer: The member socket to receive a message through :param buffer_size: The size of the byte stream to receive :return: The unpickled message """ message = peer.recv(buffer_size) return pickle....
The main task of the code is to receive and process asynchronous messages from a specific peer. It attempts to retrieve a message, parses its name and data, and handles it by calling corresponding methods for election, OK, victory, or probe messages. On errors, it logs the failure, transitions the system state, and mar...
def receive_message(self, peer): """Receive an asynchronous message from a particular peer :param peer: The member socket to receive a message from """ try: message = self.receive(peer) message_name, message_data = message if type(message) is tuple else (message, self.members) ...
def get_ledger_csv(): """Get income/expense ledger csv as a StringIO.""" return io.StringIO(subprocess.check_output(LEDGER_CSV_CMD, shell=True, text=True)) def get_toshl_income_dataframe(): """Get historical data from Toshl export.""" dataframe = pd.read_csv( TOSHL_INCOME_FILENAME, index...
The main task of the code is to aggregate and process financial ledger data from multiple sources (CSV and Toshl), clean and categorize transaction details, and generate visualizations (charts) for yearly and monthly income/expenses summaries, categorized insights, and average trends, outputting them into an HTML file ...
def main(): """Main.""" ledger_df = pd.read_csv( get_ledger_csv(), index_col=0, parse_dates=True, infer_datetime_format=True, names=[ "date", "skip", "payee", "category", "currency", "amount", ...
def get_home_estimate(filename): """Get home average price.""" return round( statistics.mean( [ get_redfin_estimate(REDFIN_URLS[filename]), get_zillow_estimate(ZILLOW_URLS[filename]), ] ) ) def write_csv(filename, value): """Write C...
The main task of the code is to fetch home value estimates from Redfin and rent estimates from Zillow for multiple properties, then save these data as CSV files. It iterates through URLs in REDFIN_URLS, retrieves home values, writes them to temporary files, and generates CSV outputs. For each property, it also fetches ...
def main(): """Main.""" for filename in REDFIN_URLS: # Home value value = get_home_estimate(filename) output = common.PREFIX + filename if not value: continue with common.temporary_file_move(output) as output_file: output_file.write(str(value)) ...
def sf1_mf1(self, src="zh"): num_predict = num_label = num_intersection = 0 num_major_predict = num_major = num_major_intersection = 0 for sample in self.df.itertuples(): span_labels, label_length = span_label(sample) major_label_spans, major_length = span_label(sample, m...
The code's main task is to evaluate model performance by running a series of tests: it prints the result file name, calculates F1 scores (sf1_mf1) for source language, computes Matthews Correlation Coefficient (mcc) for target language, assesses score errors, and checks major count discrepancies. This comprehensive eva...
def test_all(self, src="zh", tgt="en"): print() print(os.path.basename(self.result_path)) self.sf1_mf1(src) self.mcc(tgt) self.score_error() self.major_count_error()
def load_iris(self, to_preprocess=True): df = datasets.load_iris(as_frame=True).frame # rename columns df.columns = ["f0","f1","f2","f3","class"] self.ground_truth = df['class'] # drop class column df = df.drop('class', axis=1) df = df.drop('f1', axis=1) ...
The code loads a specified dataset (e.g., iris, diabetes, blobs) based on the `dataset_name` parameter, applying preprocessing if `to_preprocess` is True. It returns the resulting DataFrame or exits with an error if the dataset name is invalid.
def load_dataset(self, dataset_name, to_preprocess=True): if dataset_name == 'iris': df = self.load_iris(to_preprocess) elif dataset_name == 'diabetes': df = self.load_diabetes(to_preprocess) elif dataset_name == 'wine': df = self.load_wine(to_preprocess) ...
def _create_cells(self): self._cells = [[[None] for _ in range(self.num_rows)] for _ in range(self.num_cols)] start = self.x1 for i in range(len(self._cells)): for j in range(len(self._cells[i])): self.node_p1 = Point(self.x1,self.y1) self.node_p2 = P...
This code initializes a maze with specified dimensions and parameters, sets a random seed for reproducibility, generates the maze structure by breaking walls recursively, resets cell visitation status, and determines if the maze is solvable. It creates a grid of cells, configures maze properties, and prepares the maze ...
def __init__(self, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, win = None, seed = None): self.x1 = x1 self.y1 = y1 self.num_rows = num_rows self.num_cols = num_cols self.cell_size_x = cell_size_x self.cell_size_y = cell_size_y self.win = win #see...
def map_target(data,column): data.loc[:,column] = data[column].map({'sms':0,'click':1}) def handle_nan(data,strategy='mean',fillna='mode',drop_outliers=False): """ Function handles NaN values in a dataset for both categorical and numerical variables Args: strategy: Method of filli...
The function preprocesses input data for training or validation. For training, it filters rows with missing 'customer_class', maps 'event_type', handles NaNs by filling with 'missing' and removing outliers, drops 'msisdn.1', and saves to a training pickle file. For validation, it loads data from a specified path, appli...
def preprocess(dataframe=None,train=True,validation_path=None): if train: dataframe = dataframe[~dataframe['customer_class'].isnull()] # data = data.dropna(thresh=data.shape[1]*0.8) map_target(dataframe,'event_type') dataframe = handle_nan(dataframe,fillna='missing',drop_outliers=Tru...
def start(): """Defines and initiates all the values""" global selected_word, word_length, lives, missed_letters, blanks #Selects a random word from hangman_data.py file selected_word = random.choice(word_list) word_length = len(selected_word) missed_letters = [] lives = 6 # Matching th...
The main task of the code is to run a Hangman game loop, handling user guesses, updating the game state (blanks, lives, missed letters), checking for win/loss conditions, displaying appropriate feedback, and offering replay functionality after game completion.
def main(): global lives global missed_letters #First thing is defining the variables with the function start() so we can use them later start() end_of_game = False #Loop for the main game while not end_of_game: #Uses the delimeter ' ' to put a space between the blanks that we define...
def build_network(self): # layers of network be 3 or more, will it works? x = tf.placeholder(tf.float32, shape=[None,self.state_dim]) dense1 = tf.layers.dense(inputs=x, units=128, activation=tf.nn.relu) # dense2 = tf.layers.dense(inputs=dense1, units=128, activation=tf.nn.relu) ...
This code initializes a Q-learning agent for the CartPole-v1 environment using TensorFlow. It sets up a neural network for Q-value estimation, implements experience replay via a memory buffer, and trains the agent over 800 episodes. The agent interacts with the environment, stores experiences, and updates its policy us...
def __init__(self): self.env = gym.make("CartPole-v1") self.state_dim = 4 self.action_dim = 2 self.memory = MEMORY(10000, self.state_dim, self.action_dim) self.state_in, self.q_out = self.build_network() self.action_in, self.y_label, self.train_opt = self.create_train_...
def getBizDetails(id): details = asyncio.run(getBizInfo(id)) return { "name": details['name'], "address": " ".join(details['location']['display_address']), "image_url": details['image_url'], "url": details['url'], "phone": details['display_phone'], "alias": detail...
The function retrieves business details and reviews, merges them, processes categories via a pipeline, and returns the combined data with categorized information.
def getBizDetailsAndReviews(id): details = getBizDetails(id) alias = details['alias'] reviews = getBizReviewsAsync(alias) details.update(reviews) p = Pipeline() # cats = {'categories': {'appetizers': {'stars': 2.0, 'count': 1, 'items': {'starter kielbasa sausage': {'stars': 2.0, 'count': 1}}}, '...
def setup_logging(): logging.basicConfig(format='[%(relativeCreated)20.4f][%(levelname)s] %(message)s', level=logging.INFO) def get_crashes() -> Tuple[pd.DataFrame, pd.DataFrame]: return read_epf_crashes(), read_aflnet_crashes() def add_stack_trace_hash_to(df: pd.DataFrame) -> pd.DataFrame: logging.info('Ca...
The main task of the code is to process crash data from EPF and AFLNet by deduplicating entries using stack trace hashes, calculating metrics like p^discov and E^trigger, and saving results to CSV files. It logs progress, ensures data uniqueness, and outputs statistical analyses for both datasets, returning a success s...
def main() -> int: setup_logging() logging.info('Calculating crash statistics...') epf, aflnet = get_crashes() add_stack_trace_hash_to(epf) add_stack_trace_hash_to(aflnet) logging.info(f'Writing deduplicated crash results to {str(EPF_DEDUP_RESULTS_PATH)}') epf.drop_duplicates(subset=['h...
def setup_logging(): logging.basicConfig(format='[%(relativeCreated)20.4f][%(levelname)s] %(message)s', level=logging.INFO) def read_results() -> Tuple[pd.DataFrame, pd.DataFrame]: return read_epf_coverage(), read_aflnet_coverage() def plot_coverage(epf: pd.DataFrame, aflnet: pd.DataFrame, destination: pathlib....
The main task of the code is to evaluate and visualize coverage results from two methods (epf and aflnet). It sets up logging, reads input data, generates coverage plots and statistics, saves them to specified paths, and logs completion. The function returns a success status code upon completion.
def main() -> int: setup_logging() logging.info('Creating coverage evaluation results...') epf, aflnet = read_results() plot_coverage(epf, aflnet, destination=COVERAGE_PLOT_PATH) stats_coverage(epf, aflnet, destination=COVERAGE_STATS_PATH) logging.info('Done!') return os.EX_OK
def initNodes(grid, algo, goal): nodeList = [] if algo == "dijkstra": for i in range(len(grid)): cols = [] for j in range(len(grid[0])): cols.append(Node(i, j, grid[i][j], None, 0 , float('inf'), None)) nodeList.append(cols) if algo == "A*": for i in range(len(grid)): cols ...
The code implements **Dijkstra's algorithm** to find the shortest path from a `start` node to a `goal` node in a 2D grid, where `0` represents free space and `1` represents obstacles. It returns the path as a list of coordinates and the number of steps (nodes visited) to reach the goal. The algorithm initializes nodes,...
def dijkstra(grid, start, goal): '''Return a path found by Dijkstra alogirhm and the number of steps it takes to find it. arguments: grid - A nested list with datatype int. 0 represents free space while 1 is obstacle. e.g. a 3x3 2D map: [[0, 0, 0], [0, 1, 0], [0, 0, 0]] start - The s...
def initNodes(grid, algo, goal): nodeList = [] if algo == "dijkstra": for i in range(len(grid)): cols = [] for j in range(len(grid[0])): cols.append(Node(i, j, grid[i][j], None, 0 , float('inf'), None)) nodeList.append(cols) if algo == "A*": for i in range(len(grid)): cols ...
The code implements the A* algorithm to find a path from a start node to a goal node in a grid-based environment. It navigates through free spaces (0s) while avoiding obstacles (1s), returning the path as a list of coordinates and the number of steps taken. The algorithm initializes nodes, searches for the goal using h...
def astar(grid, start, goal): '''Return a path found by A* alogirhm and the number of steps it takes to find it. arguments: grid - A nested list with datatype int. 0 represents free space while 1 is obstacle. e.g. a 3x3 2D map: [[0, 0, 0], [0, 1, 0], [0, 0, 0]] start - The start node...
def sq_under_attack(self, row, col): self.whiteMove = (not self.whiteMove) opponent_moves = self.all_possible_moves() self.whiteMove = (not self.whiteMove) for move in opponent_moves: if move._end_row == row and move._end_col == col: return True return...
This function generates legal castling moves for a chess king. It checks if the current square is under attack, then verifies if king-side or queen-side castling is permitted based on the player's turn and castling rights. If valid, it calls respective methods to add castling moves to the list, ensuring only permitted ...
def get_castle_moves(self, row, col, moves, ally_color): if self.sq_under_attack(row, col): return if (self.whiteMove and self.current_castling_rights.wks) or (not self.whiteMove and self.current_castling_rights.bks): self.get_king_side_castle_moves(row, col, moves, ally_color) ...
def check_for_pins_and_checks(self): pins = [] checks = [] inCheck = False if self.whiteMove: enemy_color = "b" ally_color = "w" start_row = self.white_king_loc[0] start_col = self.white_king_loc[1] else: enemy_color = "...
This function determines valid chess moves by checking for pins, checks, and castling. It identifies the king's position, filters moves to avoid leaving the king in check, and adds castling options. If in check, it restricts moves to those that remove the threat, either by blocking, capturing the attacker, or moving th...
def get_valid_moves(self): moves = [] self.in_check, self.pins, self.checks = self.check_for_pins_and_checks() if self.whiteMove: king_row = self.white_king_loc[0] king_col = self.white_king_loc[1] else: king_row = self.black_king_loc[0] k...
def command_case_match(self): match self.commands: case [first]: pass case [first,"init"]: self.init_repo() case [first,'remote']: print('remote') case _: pass def environ_lookup(self): if 'AN...
The code initializes an object with `commands` and optional `options`, setting the current working directory (`cwd`) to the first command. It processes commands and options by matching cases, looking up environment variables, parsing notes, and handling case-sensitive options, preparing the object for further operation...
def __init__(self, commands,options=None): self.commands = commands self.cwd = self.commands[0] self.options = options self.command_case_match() self.environ_lookup() self.parse_notes() self.options_case_match()
def initial_position(yf,zf,alpha,beta): y0=-yf*np.sqrt(yf**2+l1**2)/l1 z0=-(zf*l1-l2*(hr-zf))/(np.sqrt((hr-zf)**2+l1**2)) p0temp=roll(beta)@np.array([0,y0,z0]) return p0temp[1], p0temp[2]/np.cos(alpha) def initial_velocity(yf,zf,alpha,beta): s_vec=s_vector(yf,zf,alpha,beta) s_mag=np.linalg.norm...
This code implements a 4th-order Runge-Kutta numerical integration to simulate the trajectory of an object under acceleration, tracking position, velocity, and line-of-sight (LOS) values. It calculates cumulative error using specified methods (NEM, SEM, TEM) by comparing actual positions to the LOS, returning trajector...
def runge_kutta_4th_order(yf, zf, alpha, beta, r = 300, error_method = "NEM"): dt=.001 y0,z0=initial_position(yf, zf, alpha, beta) v0_vec=initial_velocity(yf, zf, alpha, beta) x_values = [0] y_values = [y0] z_values = [z0] vx_values = [v0_vec[0]] vy_values = [v0_vec[1]] vz_values = [...
def initial_position(yf,zf,alpha,beta): y0=-yf*np.sqrt(yf**2+l1**2)/l1 z0=-(zf*l1-l2*(hr-zf))/(np.sqrt((hr-zf)**2+l1**2)) p0temp=roll(beta)@np.array([0,y0,z0]) return p0temp[1], p0temp[2]/np.cos(alpha) def initial_velocity(yf,zf,alpha,beta): s_vec=s_vector(yf,zf,alpha,beta) s_mag=np.linalg.norm...
This function numerically integrates a particle's trajectory using the 4th-order Runge-Kutta method, updating position and velocity at each time step. It calculates trajectory data (x, y, z, velocities) and computes position and line-of-sight (LOS) errors based on the specified error method (SEM, TEM, or NEM). The loop...
def mess_with_runge_kutta_4th_order(yf, zf, alpha, beta, r = 300, error_method = "NEM"): dt=.001 y0,z0=initial_position(yf, zf, alpha, beta) v0_vec=initial_velocity(yf, zf, alpha, beta) x_values = [0] y_values = [y0] z_values = [z0] vx_values = [v0_vec[0]] vy_values = [v0_vec[1]] vz_...
def get_los(seeker, evader_loc): if evader_in_blindspot(seeker, evader_loc): # print("blindspot") return 0 [seeker_x, seeker_y, seeker_elevation, orient_left, orient_right] = seeker seeker_loc=np.array([seeker_x, seeker_y, seeker_elevation]) "Create vector function r(t) from see...
This function calculates the maximum visual detection probability for an evader based on seeker positions, movement mode, travel time, and perpendicular movement flags. It checks immediate visibility, computes line-of-sight (LOS), trajectory ratios, and detection probabilities for each seeker group, returning the highe...
def get_visual_detection_2(position_i, mode_of_travel, travel_time, seeker_groups, perpendicular): for seeker in seekers: [seeker_coord, z, orient, orient_uncert] = seekers[seeker] distance_position_i=np.linalg.norm(np.array(seeker_coord)-position_i[:2]) if distance_position_i <=z*np.sqrt(2...
def get_los(seeker, evader_loc): if evader_in_blindspot(seeker, evader_loc): # print("blindspot") return 0 [seeker_x, seeker_y, seeker_elevation, orient_left, orient_right] = seeker seeker_loc=np.array([seeker_x, seeker_y, seeker_elevation]) "Create vector function r(t) from see...
Your return The function calculates the probability of visual detection by evaluating line-of-sight (LOS) between seekers and target positions, adjusting for elevation and obstacles. It computes LOS for each seeker, averages it, and applies a detection formula involving alpha/beta ratios and a time-adjusted probabili...
def get_visual_detection(position_i, position_j, mode_of_travel, travel_time, seeker_groups): """ This function should get the probability of visual detection Tasks: o Determine line of sight to start and end positions (seperate function that checks if evader is in deadspace or is blocked by foliage...
def get_seeker_group(templated_seeker): """ takes a templated seeker location and creates a list of worst case seeker information. Assumes seeker is 2m tall Parameters ---------- templated_seeker : list [seeker_loc, loc_uncertainty, theta_orientation, theta_uncertainty]. node_field_...
This code computes and visualizes 2D detection probability maps across a grid, using both visual and audio detection methods for different travel modes. It processes seeker groups, calculates elevation data, and generates heatmaps with color bars, while optionally plotting seeker positions, orientation circles, and nod...
def detection_fields(mode_of_travel, perpendicular, plot_node_field, seekers=seekers): seeker_groups={templated_seeker : get_seeker_group(seekers[templated_seeker]) for templated_seeker in seekers} xvals=np.linspace(0, desired_map_width,2*nodes_wide-1) yvals=np.linspace(0, desired_map_length,2*nodes_long-1)...
def create_node_field(): """ Creates node field Parameters (All Universal) ---------- nodes_wide : Integer width of node field measured in nodes. nodes_long : Integer length of node field measured in nodes. step_size : Float desired birds eye distance between N-S or ...
The function generates a dictionary of arcs between nodes in a grid-based field, calculating travel modes (crawling, sneaking, walking), travel times, and detection risks based on terrain elevation, vegetation, and seeker presence. It creates bidirectional arcs with positions, movement type, time, and risk levels, excl...
def get_arcs(nodes_wide=nodes_wide, nodes_long=nodes_long, step_size=step_size, file_name=file_name, max_elevation=max_elevation, seekers=seekers): """ gets arcs and node field Parameters ---------- nodes_wide : Integer width of node field measured in nodes. nodes_long : Integer ...
def cast_net(center,d): cx,cy=center net=[] dy=d for i in range(3): net.append([[cx-d,cy+dy],[cx,cy+dy],[cx+d,cy+dy]]) dy-=d return net def get_errors(net,alpha,beta,r,error_method): min_error=99999 errors=[] for i in range(3): errors.append([]) for j in r...
This code animates the iterative search for an optimal point (yf, zf) by adjusting grid resolution (d) and tracking errors, visualizing the path of the center point over iterations in a scatter plot saved as a GIF. It reduces grid spacing by 60% each iteration until the error meets an acceptable threshold, updating the...
def second_vis_fishing(alpha,beta,r,error_method): plt.clf() fig, ax = plt.subplots() center=[0,.065] xs=[center[0]] ys=[center[1]] d=.001 accepteable_error=10**-8 net=cast_net(center,d) errors,i,j,min_error=get_errors(net,alpha,beta,r,error_method) error=[min_error] iters=[1...
def cast_net(center,d): cx,cy=center net=[] dy=d for i in range(3): net.append([[cx-d,cy+dy],[cx,cy+dy],[cx+d,cy+dy]]) dy-=d return net def get_errors(net,alpha,beta,r,error_method): min_error=99999 errors=[] for i in range(3): errors.append([]) for j in r...
The function `vis_go_fishing` iteratively adjusts a center point to minimize an error metric defined by `error_method`, using a grid-based search (cast_net). It visualizes the center's trajectory and error reduction over iterations. The process continues until the error falls below a threshold (`accepteable_error`). Th...
def vis_go_fishing(alpha,beta,r,error_method): center=[0,.065] xs=[center[0]] ys=[center[1]] d=.001 accepteable_error=10**-8 net=cast_net(center,d) errors,i,j,min_error=get_errors(net,alpha,beta,r,error_method) error=[min_error] iters=[1] while objective(error_method,error[-...
def cast_net(center,d): cx,cy=center net=[] dy=d for i in range(3): net.append([[cx-d,cy+dy],[cx,cy+dy],[cx+d,cy+dy]]) dy-=d return net def get_errors(net,alpha,beta,r,error_method): min_error=99999 errors=[] for i in range(3): errors.append([]) for j in r...
The function `go_fishing` iteratively refines a grid (net) centered at a starting point to minimize error between the grid and parameters α, β, and r. It adjusts the grid's resolution (d) and updates the center based on computed errors until the error falls below a threshold. If plotting is enabled, it visualizes the r...
def go_fishing(alpha,beta,r=300,plot = None,error_method="NEM"): center=[0,.065] d=.001 accepteable_error=10**-8 net=cast_net(center,d) errors,i,j,min_error=get_errors(net,alpha,beta,r,error_method) error=[min_error] while objective(error_method,abs(error[-1]),accepteable_error,d): ...
def __user_entry(self): adult = Adult() self.__inner_print('') self.__inner_print('Program made by Yaroslav Oliinyk, 2019') self.__inner_print('NAIVE BAYES ALGORITHM') self.__inner_print('') self.__inner_print('You will get to know if a person makes >50K a year or <=50K a...
This code initializes a classifier to predict income categories (more/less than $50k) by processing probability and class distribution dictionaries. It removes irrelevant features (e.g., workclass, age) from input data, calculates user input probabilities, and computes prediction results. The __calculate() method likel...
def __init__(self, prob_d, class_d, more50k, less50k): # Probability dictionary. # Dictionary in which: number of entries is divided by # number of >50K earnings and <=50K earnings respectively # e.g. There are 6000 males who earn >50K, and overall 7000 people make >50K, # which ...
def get_info(): with open("PicturePairsKey.txt") as file: global USERNAME USERNAME = file.readline() global P1 P1 = file.readline() global P2 P2 = file.readline() global MODE MODE = file.readline() def login(): driver.implicitly_wait(20) driver...
The main task of the code is to automate logging into a website, navigate to a game, play it, and then close the session. It sequentially retrieves information, accesses a URL, logs in, initiates gameplay, confirms completion, and terminates the browser driver.
def main(): get_info() driver.get("https://teach.speakagent.com/#/") login() play_game() print("Test Complete -- Game Finished") driver.close()
def get_info(): with open("MatchingKey.txt") as file: global USERNAME USERNAME = file.readline() global P1 P1 = file.readline() global P2 P2 = file.readline() global MODE MODE = file.readline() def login(): driver.implicitly_wait(20) driver.fin...
The main task of the code is to automate a sequence of actions: retrieving information, navigating to a specific website, logging in, and initiating a game session. The `main()` function orchestrates these steps by calling `get_info()` to gather data, using a web driver to access the target URL, executing the `login()`...
def main(): get_info() driver.get("https://teach.speakagent.com/#/") login() play_game()
def parse_line(self, line: str): tokens = shlex.split(line, posix=False) for token in tokens: if token.startswith('//'): break self.add_token(token) def execute_all(self, debug=False, cmd=False): while self.scope_stack[-1].has_next(): self.exec...
This code implements an interactive Read-Eval-Print Loop (REPL) that continuously accepts user input, parses and executes commands, handles specific exceptions by printing error messages, displays stack contents when stack_max is exceeded, and resets state upon keyboard interrupts while maintaining debugging capabiliti...
def run_repl(self, stack_max=16, debug=False): while True: try: try: print(self.console_prefix + ('..' * self.tokening_indent) + ' ', end='') inp = input() self.parse_line(inp) self.execute_all(debug=debu...
def parse_with_global_required(self, arg, value): path, entry = self.find_param(arg, self.global_required) mode = self.global_required['mode'] syntax = self.get_syntax(self.global_required, path, mode) prefix = self.get_prefix(self.global_required, path) if entry: sel...
This function parses input elements into parameters by checking global requirements, determining parsing modes (field/prototype), validating parameters, and either adding arguments or processing prototypes based on the specified syntax and structure. It handles exceptions for invalid parameters and structures parsed da...
def parse_input_elements(self): self.query_elements['field'] = [] for elements in self.input_elements: arg = elements[:-1] value = [elements[-1],][0] if self.params is None: self.add_field_arg('', value) conti...
def get_source(self, source): if source in self.sources: return copy.deepcopy(self.sources[source]) elif source is not None and source not in self.sources: return self.load_source(source) else: raise Exception('Invalid source \'' + str(source) + '\'') def crea...
The code performs a search by constructing a query from input parameters, parsing elements and options, determining output format, and executing the query via an API. It fetches results, converts them to the specified format, and returns them, optionally pretty-printing the output.
def search(self, input_string, source=None, api='default', return_format='', inherit_from=None, pretty_print=False): search_source = self.get_source(source) query_object = self.create_query_object(input_string, search_source, api) query_object.parse_input_elements() query...
def nms(dets, scores, thresh, max_dets=1000): """Non-maximum suppression. Args: dets: [N, 4] scores: [N,] thresh: iou threshold. Float max_dets: int. """ y1 = dets[:, 0] x1 = dets[:, 1] y2 = dets[:, 2] x2 = dets[:, 3] areas = (x2 - x1) * (y2 - y1) order = scores.argsort()[::-1] kee...
The function performs object detection using the ViLD model, processing input images to identify and classify objects based on specified categories. It preprocesses category names, runs inference to obtain detection boxes and scores, applies non-max suppression, filters results by thresholds, computes text embeddings f...
def vild(session, image_path, category_name_string, params, plot_on=True, prompt_swaps=[]): ################################################################# # Preprocessing categories and get params for a, b in prompt_swaps: category_name_string = category_name_string.replace(a, b) category_names = [x.stri...
def wait_for_deployment_to_complete( k8s_name, k8s_namespace, primary_resource_kind, timeout=300 ): start = time.time() logger.info(f"Waiting for deployment '{k8s_name}' to succeed...") logger.info(f"Resource kind is : {primary_resource_kind}") while time.time() - start < timeout: sleep(...
The function processes Kubernetes resource deployment based on the primary_resource_kind. For "deployment", it sets k8s_name, waits for completion, updates asset/service status, and triggers tests if successful; otherwise, it logs failures and checks previous deployments. For "job/cronjob", it directly updates asset/se...
def process_primary_resource_kind( primary_resource_kind, has_multiple_components, component_name, k8s_name, k8s_namespace, k8s_image_version, assets_url, asset_restaurant_id, previous_deployment, k8s_pv_name, k8s_pvc_name, ...
def loop_through_messages_1(attribute_value, k8s_kind, k8s_name): if isinstance(attribute_value["StringValue"], dict): k8s_message = attribute_value["StringValue"] else: k8s_message = json.loads(attribute_value["StringValue"]) k8s_kind, k8s_name, has_multiple_components = check_for_multiple_...
This function processes Kubernetes resources from incoming messages, identifies their types (e.g., CronJob, Deployment, Certificate), extracts metadata like image versions, namespaces, and names, and triggers specific handling logic (e.g., certificate notifications, firmware processing). It updates resource tracking va...
def loop_through_messages( messages, asset_restaurant_id, assets_url, component_name, k8s_name, k8s_namespace ): # set to None by default so we can recognize cases where a SQS message does not change a primary resource primary_resource_kind = None k8s_pv_name = None k8s_pvc_name = None k8s_i...
def get_message_data_from_response(response): messages = {} message_payload = {} logger.info("Message Response: " + str(response)) try: message = response["Messages"][0] message_id = message["MessageId"] receipt_handle = message["ReceiptHandle"] # try to get the payload i...
The code retrieves restaurant data from an API, constructs an SQS queue URL, receives and processes a message, extracts Kubernetes metadata, identifies the primary resource kind, and triggers an open test if the resource is a statefulset or daemonset.
def get_sqs_message(): asset_restaurant_id_response = requests.get( f"https://{config['assetsUrl']}/restaurant_assets/restaurants?filter[name]={config['restaurantId']}", auth=config["awsAuth"], ) asset_restaurant_id_response_json_file = asset_restaurant_id_response.text asset_restaurant_...
def load_dataset(): df = pd.read_csv('fintech_data.csv') return df def preprocessing(): df=load_dataset() #menghitung ulang isi dari kolom screen_litst karena tidak pas di kolom num screens df['screen_list'] = df.screen_list.astype(str) + ',' df['num_screens'] = df.screen_list.astype(str).str.count(',') r...
The code's main task is to load a CSV dataset via a Streamlit app, either from user upload or a predefined file, preprocess it by modifying columns like 'numscreens' and 'hour', and generate visualizations. It calculates correlations and mutual information between features and the target variable 'enrolled' to assess f...
def app(): dataset = st.sidebar.file_uploader("Unggah File CSV", type=['csv']) if dataset is not None: df = load_dataset(dataset) st.dataframe(df) else: load = st.button('load data') #initialize session state if "load_state" not in st.session_state: st.session_state.load_state = False ...
def gradient_loss(self, G): """The 'loss' of the neural network. Corresponds to the function on which the gradient should be computed.""" p_zax = self.get_p_zax(G) # Sample z using the reparametrization trick. z = p_zax.rsample((self.K,)) p_az = self.get_p_az(z) log_p_z...
This code trains a model using gradient descent and the EM algorithm to estimate parameters of a mixture distribution over latent variables. It initializes cluster centers via KMeans on sampled embeddings, then iteratively updates mixture weights (pi), means (mu), and covariances (sigma) using EM steps. The model learn...
def train_em(self, G, n_epochs=47000, lr=0.01, N=500): optimizer = torch.optim.Adam(self.parameters(), lr=lr) for e in range(n_epochs): loss = self.gradient_loss(G) # Backward optimizer.zero_grad() loss.backward() optimizer.step() ...
def _get_error_message_from_exception(self, e): """ Get appropriate error message from the exception. :param e: Exception object :return: error message """ error_code = None err_msg = KOODOUS_ERR_MSG_UNAVAILABLE try: if hasattr(e, "args"): ...
This function handles detonating an APK file by validating parameters, uploading the file if necessary, triggering specified analysis types (dynamic/static/yara), and retrieving the analysis report. It ensures proper error handling, checks for existing analyses, and executes required API calls to process the file.
def _handle_detonate_file(self, param): action_result = self.add_action_result(ActionResult(dict(param))) try: attempts = int(param.get('attempts', 1)) if attempts < 1: attempts = 1 except Exception as e: error_message = self._get_error_messa...
def _get_error_message_from_exception(self, e): """ Get appropriate error message from the exception. :param e: Exception object :return: error message """ error_code = None err_msg = KOODOUS_ERR_MSG_UNAVAILABLE try: if hasattr(e, "args"): ...
This code handles retrieving a report by validating parameters like 'attempts', checking if a provided 'vault_id' corresponds to an APK file, ensuring 'sha256' is present, and then calling _get_report with these parameters. It returns errors for invalid inputs or missing APK files.
def _handle_get_report(self, param): action_result = self.add_action_result(ActionResult(dict(param))) try: attempts = int(param.get('attempts', 1)) if attempts < 1: attempts = 1 except Exception as e: error_message = self._get_error_message_fr...
def _handle_test_connectivity(self, param): action_result = self.add_action_result(ActionResult(dict(param))) self.save_progress("Making call to validate API key...") params = { 'search': 'Whatsapp' } ret_val, _ = self._make_rest_call(KOODOUS_APKS_ENDPOINT, action_...
The code defines a method `handle_action` that determines and executes the appropriate action based on the action identifier. It retrieves the action ID, debug-prints it, and routes to specific handler methods (`_handle_test_connectivity`, `_handle_detonate_file`, or `_handle_get_report`) depending on the ID. The resul...
def handle_action(self, param): ret_val = phantom.APP_SUCCESS # Get the action that we are supposed to execute for this App Run action_id = self.get_action_identifier() self.debug_print("action_id", self.get_action_identifier()) if action_id == 'test_connectivity': ...
def get_user_games_from_boardgamegeek(username): collection = get_users_collection(username) collection_et = get_xml_string_from_response(collection) print(collection_et.text.strip()) try: if collection_et.find(".//message").text == "Invalid username specified": return "invalid usern...
The function adds a user's game collection from BoardGameGeek to a database, handling retries for API waiting. It identifies new games not in the database, inserts them, and updates the user's record. If the user exists, it synchronizes their collection by adding new games and removing outdated ones from the database.
def add_new_users_collection_to_db(username, user_exists=False): num_tries = 5 for try_ in range(num_tries): user_games = get_user_games_from_boardgamegeek(username) if user_games == "invalid username": return "invalid username" elif user_games == "waiting": time....
def place_limit_order(self, order): """Place a limit order on the exchange.""" print( f"You have placed a limit {order.direction.lower()} order for {order.quantity} {order.ticker} shares at ${order.price:.2f} each.") self.resolve_order(order) return order def place_market_ord...
This code processes user trading commands by parsing actions like limit/market orders, quotes, and portfolio views. It uses regex to identify order details, creates order objects, verifies them, and executes trades or retrieves market data. It also handles viewing orders, portfolios, and displaying help information.
def execute(self, user, action): """Execute an action on the exchange An action is a string that would be parsed before being executed. """ limit_order_re = r"^(BUY|SELL) (\w+) LMT \$([0-9]*[.]?[0-9]+) (\d+)$" match = re.match(limit_order_re, action) if match: ...
def getIdentifiers(filename): identifiers = OrderedDict() lexemes, tokens = Lexer.getLexemesWithTokens(filename) for i in range(len(lexemes)): if(tokens[i] == "Identifier"): identifiers[lexemes[i]] = None return list(identifiers.keys()) def getDataTypes(filename, identifiers): da...
The code generates and prints a symbol table for identifiers in a given file, listing each variable's name, memory reference, data type, declaration line, and reference lines. It sorts identifiers if specified, calculates memory space based on data types, and formats the output in a structured table with columns for co...
def printSymoblTable(filename, isOrdered): refrence = 0 identifiers = getIdentifiers(filename) if(isOrdered): identifiers.sort() dataTypes = getDataTypes(filename, identifiers) lines = getLines(filename) print('counter\t variable_name\tobject_refrence \t data_type \tdimenson\tline_d...
def loss(): print("You lose!") ok = False tt = True def Hit1(): print('--------------------------------') rand1 = random.randrange(0, 53) player.append(deck[rand1]) print("you pulled a" , player[3].value, "of" , player[3].suit ) h1 = values.get(player[0].value) h2 = values.get(playe...
This function calculates the total value of a player's three cards in a game, checks if it exceeds 21 (resulting in a loss), displays the current hand and total, then prompts the player to "Hit" or "Stand" to continue the game.
def Move1(): m1 = values.get(player[0].value) m2 = values.get(player[1].value) m3 = values.get(player[2].value) total = m1 + m2 + m3 if total > 21: loss() else: print("Your cards are the" , player[0].value, "of" , player[0].suit , "," , player[1].value, "of" , player[1].suit, "an...
def handle_site_event(self, point): if self.beach_line is None: self.beach_line = Arc(point) else: arc = self.beach_line while arc is not None: flag, vertex = self.check_intersection(point, arc) if flag: flag, temp =...
The code computes a Voronoi diagram using Fortune's algorithm by processing site and circle events from a queue, completing edges, extracting edge coordinates, and displaying the result with input points and boundaries.
def compute(self): while not self.queue.empty(): next_event = self.queue.get()[1] if next_event.is_site: self.handle_site_event(next_event.point) else: self.handle_circle_event(next_event) self.complete_edges() edges = [] ...
def gen_train_pair(batch_size=1): while True: arrays = np.asarray([generate_train_pair() for _ in range(batch_size)]) img1, img2 = arrays[:,0,:,:].reshape((batch_size,1,128,128)), arrays[:,1,:,:].reshape((batch_size,1,128,128)) seg1, seg2 = arrays[:,2,:,:].reshape((batch_size,1,128,128)), a...
The code trains a neural network model for image registration using a combination of reconstruction loss (MSE) and gradient regularization. It iteratively optimizes the model to align moving images with fixed images, computes dice scores for segmentation accuracy, and validates performance on distant data pairs. The fu...
def circle_train(mod, n_iter, batch_size, gpu='0', lr=1e-4, data_loss='mse', reg_param=0.01, train_module=None): os.environ["CUDA_VISIBLE_DEVICES"] = gpu device = "cuda" mod.to(device) # Set optimizer and losses opt = A...
def get_args(): """ Get Saruman args. Args: None Returns: args: Argparse args object. """ parser = argparse.ArgumentParser(prog="saruman") parser.add_argument('-r', '--red_file', type=str, required=True, help="TIF file containing red signal.") pars...
The main task of the code is to analyze a Z-stack image by extracting cellular features, calculating radial intensity profiles, determining half-max radii and shell widths for each cell, and saving the results in a CSV file while generating visualizations. It processes a specified z-slice, identifies cells, computes st...
def main(): """ Main entry point """ args = get_args() print("[INFO] Saruman is searching for the rings.", file=sys.stderr) # Read the Z-stack files print("[INFO] Reading zstack ... ", end="", file=sys.stderr) zstack = read_stack(args.red_file, args.green_file) if args.iz < 0 or args.iz > ...
def sold_search_url(query): return FMT_SOLD_SEARCH_URL.format(urllib.parse.quote(query)) def adjust_options(driver): # Open listing options menu driver.find_element(by=By.XPATH, value='//button[contains(@aria-label, "Listing options")]').click() driver.find_element(by=By.XPATH, value='//li/button[contai...
The code automates web scraping of sold iPhone listings by navigating a site, handling GDPR prompts, and updating data from an input file. It processes scraped data, serializes results, and saves them to 'data_update.jsonl', requiring manual CAPTCHA resolution before proceeding.
def main(argv): driver = webdriver.Firefox() driver.implicitly_wait(0.5) driver.get(sold_search_url('iphone')) time.sleep(5) driver.find_element(by=By.XPATH, value='//button[@id = "gdpr-banner-decline"]').click() adjust_options(driver) input('Press ENTER after captcha...') print(argv) ...
def check_emb_exists(location, target): path = os.path.join(location, target.replace(' ', '_') + '.npy') if os.path.isfile(path): LOG('debug', f'embedding exist: {path}') return path return None def extract_word_emb(word, model=None): global W2V_MODEL if not model: if not W2...
The function retrieves a word's embedding by either loading it from a specified directory if it exists, or generating it using a provided model and saving it to the directory for future use.
def get_word_emb(word, model=None, emb_dir=None): if emb_dir: path = check_emb_exists(emb_dir, word) if path: return np.load(path, allow_pickle=True) emb = extract_word_emb(word, model) if emb_dir: save_emb(emb_dir, word, emb) return emb
def check_emb_exists(location, target): path = os.path.join(location, target.replace(' ', '_') + '.npy') if os.path.isfile(path): LOG('debug', f'embedding exist: {path}') return path return None def get_all_word_emb(words, model=None, emb_dir=None): embs = [] for word in words: ...
The function `get_bundle_emb` retrieves or generates embeddings for a given text bundle. It prioritizes loading precomputed embeddings from a directory if specified. If not found, it splits the bundle into words, extracts word embeddings using a model (or from a directory), and combines them. It also checks for BOS/EOS...
def get_bundle_emb(bundle, infersent_model=None, w2v_model=None, emb_dir=None): if emb_dir: path = check_emb_exists(emb_dir, bundle) if path: return np.load(path) # extract words = bundle.split(' ') words_emb = get_all_word_emb(words, model=w2v_model, emb_dir=emb_dir) # ...
def load_infersent_model(model_path, config): LOG('info', f'loading infersent model: {model_path}...') import torch from infersent import InferSent model = InferSent(config) model.load_state_dict(torch.load(model_path)) LOG('info', f'infersent model loaded') return model def LOG(tag, content...
This function generates embeddings for input bundles using an InferSent model and word2vec. It processes batches of bundle data, computes embeddings via the model, and optionally saves individual embeddings to disk. The core task involves transforming textual bundles into dense vector representations for downstream tas...
def get_bundles_embedding(bundles, infersent_model, w2v_model, emb_dir, output_dir=None): import torch config = {'bsize': 64, 'word_emb_dim': 300, 'enc_lstm_dim': 2048, 'pool_type': 'max', 'dpout_model': 0.0, 'version': 2} model = loa...
def create_bound(min, max): return (min - BOUND_NOISE, max + BOUND_NOISE) def get_days_between_infections_in_begin( date_begin, date_end, days_to_recovery, df, date_column, effective_reproduction_number_column): df_outbreak = df[(df[date_column] >= date_begin) & (df[date_...
The function `get_bounds_and_arguments` processes outbreak data from a DataFrame to define parameter bounds and arguments for an epidemiological model. It identifies outbreak intervals, calculates bounds for initial infections, recovery periods, case fatality rates, and transition days between outbreaks. It adjusts bou...
def get_bounds_and_arguments(df, date_column, death_column, effective_reproduction_number_column, case_column, outbreak_column, days_to_recovery, ...
def find_holes(points, max_circumradius=0.4, max_ratio_radius_area=0.2, height_clustering=False, kde_bandwidth=0.05, suppress_qhull_errors=False): """ Find holes in a point cloud. Parameters ---------- points : (Mx3) array The coordinates of the points. max...
The function generates synthetic points to fill holes in 3D point clouds by identifying triangular gaps based on circumradius and area ratios, then interpolating Z-values from neighboring points. It uses parameters like distance, percentile, and bounding shapes to control synthetic point placement, ensuring they fit wi...
def fill_holes(points, max_circumradius=0.4, max_ratio_radius_area=0.2, distance=0.4, percentile=50, normals_z=None, min_norm_z=0, bounding_shape=None, height_clustering=False, kde_bandwidth=0.05, suppress_qhull_errors=False): """ Generate synthetic points to fill ho...
def _show_item_list(collection, show_all=False): if len(collection)<=5 or show_all: return '<' + ','.join([str(item) for item in collection]) + '>' else: return '<' + ','.join([str(item) for item in collection[:2]])+ '...' + ','.join([str(item) for item in collection[-2:]]) + '>' def _remove_fro...
The main task of the code is to handle post-processing after each iteration of a semi-supervised active learning (SCAL) pipeline. It updates labeled/unlabeled data collections, tracks label changes, computes model thresholds (tj), updates precision estimates (Rhat), adjusts batch sizes (B), and persists model states. I...
def after_loop(self): new_labels = list(self.annotations["label"]) logging.info(f"NEW LABELS. {';'.join(new_labels[-self.b:])}") assert len(new_labels[:-self.b]) == len(self.all_labels) count=0 for ix, item, old, new in zip(range(len(self.all_labels)),list(self.labeled_collectio...
def PolarCoordinates(a, pos): """ Returns a grid of r and phi polar coordinate values corresponding to each pixel, with the origin position provided as a parameter Parameters ----------- a - 2D array, array of pixels to be mapped onto polar coordinates pos - 1D array, shape(2...
The function generates a search cone along a ridge line and a check cone to determine an endpoint, using polar coordinates and masking to avoid self-intersections. It returns masked arrays for the new search area and endpoint validation, based on angular ranges derived from maxima positions and ridge direction.
def GetRidgeCone(area_fluxes, maxima_array, ridge_point, ridge_phi, chain_mask, dphi): """ Returns a new search cone along the ridge with an end point check cone. WARNING: FUNCTION UNDER DEVELOPMENT. Issues to be fixed - finding the source end point to avoid swirly ridges. Directly connected to...
def ErodedMaxima(area_fluxes): """ Returns a numpy array with local maxima locations found from eroding the original image as well as the the eroded structure, to be used in weighted angle averaging Parameters ----------- area_fluxes - 2D array, raw image array convolved...
The function `RetryDirections` computes new directional angles (NewAngle3, NewAngle4) and a new point (new_ip) from a modified input array (`new_iparray`). It masks local maxima, initializes a new point, calculates initial directions, and handles NaN values by falling back to a masked center calculation. The task invol...
def RetryDirections(new_iparray, init_point, CompTable, n_comp, source_name, hdu): """ """ #new_ip = np.empty(2) new_iparray[int(init_point[1]),int(init_point[0])] = np.nan #print(new_iparray) maskedmaxima2, maskedmaxima_array2, maskederoded2 = ErodedMaxima(new_iparray) #n...
def ErodedMaxima(area_fluxes): """ Returns a numpy array with local maxima locations found from eroding the original image as well as the the eroded structure, to be used in weighted angle averaging Parameters ----------- area_fluxes - 2D array, raw image array convolved...
The function initializes search parameters for ridge detection in an astronomical image by determining initial directional angles and creating masked regions (cones) around a starting point. It checks if the initial position is within the image bounds, computes search directions, and generates two cones for subsequent ...
def InitCones(area_fluxes, init_point, dphi, lmsize, CompTable, \ n_comp, source_name, hdu): """ Returns initial position, search directions and search cones ready for ridge detection. Parameters ----------- area_fluxes - 2D array, raw image array convolved wit...
def ErodedMaxima(area_fluxes): """ Returns a numpy array with local maxima locations found from eroding the original image as well as the the eroded structure, to be used in weighted angle averaging Parameters ----------- area_fluxes - 2D array, raw image array convolved...
The code identifies and traces two ridge lines in an image starting from a given point, returning their coordinates, angular directions, and cumulative lengths. It uses cone-shaped search regions to detect ridge directions, iteratively extending the ridges while accumulating step sizes to compute their lengths. If init...
def FindRidges(area_fluxes, init_point, R, dphi, lmsize, \ CompTable, n_comp, source_name, hdu): """ Returns numpy arrays with point coordinates along 2 ridge lines and seperate numpy arrays containing the angular directions and length along the ridgeline associated with these points. Th...
def get_matrix_lu(matrix_a, matrix_b): """Function returns matrix L, matrix U and new matrix B AX = B A = LU""" size_a = matrix_a.shape[0] size_b = matrix_b.shape[1] # Number of columns matrix_l = np.identity(size_a, dtype = 'float') for k in range(size_a - 1): set_max_value(...
The main task of the code is to compare custom implementations of LU decomposition, determinant calculation, linear system solving, and matrix inversion with NumPy/SciPy functions. It constructs matrices, applies user-defined functions, and prints results alongside standard library outputs to validate accuracy and corr...
def lab1_1(): matrix_a = np.array([ [1, -1, 1, -2], [-9, -1, 1, 8], [-7, 0, 8, -6], [3, -5, 1, -6], ], dtype = 'float') matrix_b = np.array([ [-20], [60], [-60], [-44], ], dtype = 'float') matrix_l, matrix_u, matrix_b_aft = get_matrix_l...
def _handle_keydown_event(self, event: pygame.event.Event) -> None: """Handle the specified KeyDown event. Acts based on the key that triggered the event""" match event.key: # On escape, quit game (TODO determine if a pause menu should be on escape) case pygame.K_ESCAPE: ...
This method checks for pygame events like window closure, keyboard, and mouse inputs. It processes each event by calling corresponding handler methods, such as handling key presses, releases, and mouse clicks, to update game state or trigger actions.
def _check_events(self) -> None: """Checks for events from pygame, eg keyboard or mouse input. Called constantly""" # Go over all pygame events that happened last frame for event in pygame.event.get(): match event.type: # Close window event, quit cas...
def _check_alien_fleet_edges(self): """Check if the edge of the alien fleet is at/near the horizontal edge of the screen""" for alien in self.aliens.sprites(): if alien.is_at_hor_screen_edge(): self._change_alien_fleet_direction() break def _player_lost(self):...
This method updates the alien fleet's position, checks for collisions between aliens and the player's ship (triggering game loss if detected), and verifies if any aliens have reached the screen's bottom (also causing game loss). It ensures proper alien movement, collision detection, and game state management during gam...
def _update_aliens(self): """Update the fleet of aliens""" self._check_alien_fleet_edges() self.aliens.update() # Check if any aliens have collided with the player ship, meaning this game is lost if pygame.sprite.spritecollideany(self.ship, self.aliens): self._player...
def _update_ship(self) -> None: """Update the player ship""" self.ship.update_pos() def _update_bullets(self) -> None: """Update the bullets fired by player""" self.bullets.update() # Loop over all bullets, delete those that are out-of-bounds (python expects the list of bullets t...
The main task of the code is to continuously update game elements by calling three methods: updating the player's ship, bullets, and aliens. This method is part of a game loop, ensuring dynamic interactions and movements of game components in real-time.
def _update_elements(self) -> None: """Update elements of the game. Called constantly""" self._update_ship() self._update_bullets() self._update_aliens()
def _check_events(self) -> None: """Checks for events from pygame, eg keyboard or mouse input. Called constantly""" # Go over all pygame events that happened last frame for event in pygame.event.get(): match event.type: # Close window event, quit cas...
The main task of the code is to run the game's main loop continuously, handling events, updating game elements when the game is active, and refreshing the screen to maintain gameplay and rendering.
def run_game(self) -> None: """Run the main game loop""" # On a continous loop while True: self._check_events() if self.stats.game_active: self._update_elements() self._update_screen()
def ABVReference(interval): allCodes = pd.DataFrame() for i in include: this_year = getSeasonSummary(i)[['Conference']] this_year['Year'] = i allCodes = pd.concat([allCodes,this_year]) allCodes = allCodes.groupby(by='Conference')['Year'].max().reset_index(drop=False) allCodes['AB...
The function retrieves and returns the list of NCAA tournament teams for a given season, using cached data if available. If not, it fetches conference abbreviations, checks each conference's teams, and compiles the results, then caches them for future use.
def NCAA_Tourney_Teams(season): if os.path.exists('.\\pklSupport\\knownTourney.pkl'): known = DataHandling.importPKL('knownTourney','.\\pklSupport') else: known = {} if season in known: return known[season] else: abvDict = ABVReference([season])[['Conference','ABV']] ...
def ApplySpatialCorrelation(self, sampleName, measure, method): self.currentSampleName = sampleName network = self.getDataOfSample(sampleName, "network") tensorMeasure = self.getTensorMeasureOfSample(sampleName, measure) self.removedNotOccuringNodes(network, list(tensorMeasure.keys())) ...
The main task of the code is to compute spatial correlation measures for multiple samples using a specified method, organize results by groups if provided, generate statistical tables, calculate p-values, and save outputs to CSV files. It processes each sample, applies the correlation method, sorts results by groups, f...
def ApplySpatialCorMethod(self, measure, method, groups, filenameToSave=None, printOut=False): allSampleCorrelations = {} assert method in self.allowedMethodNames, "The method {} is not exisiting in the allowed method names. {} not in {}".forma...
def calcRowsToSelect(self, table, timePoint=0, getAllTimePointsData=False): if getAllTimePointsData: selectedRows = np.arange(len(table)) allGroups = table.iloc[:, 1].to_numpy() allSampleNames = table.iloc[:, 2].to_numpy() else: selectedRows = [] ...
The main task of this code is to initialize an object that processes microtubule tensor data, either by loading precomputed values from pickle files or calculating them (connectivity networks, contours, and average angular changes) from a table. It standardizes sample names, handles data persistence, and saves computed...
def __init__(self, table, timePointTxt="", loadFromPkl=False, dumpData=True, baseFolder="FibrilJ Tensors/"): # ----- allows creation and saving of networks and average changes of microtubule tensors ----- self.table = table self.table.iloc[:, 2] = ["".join(sampleName.split(".tif...
def summedWeightedDeviationsOfAllIAndJ(self): weightedCov = 0 for i in range(self.weightMatrix.shape[0]): for j in range(self.weightMatrix.shape[1]): weightedCov += self.weightMatrix[i, j] * self.valueDifFromMean[i] * self.valueDifFromMean[j] return weightedCov def ca...
This function calculates Moran's I, a measure of spatial autocorrelation, by computing weighted covariance and variance. It then determines the expected Moran's I value and calculates a p-value to assess statistical significance, returning both the Moran's I statistic and its associated p-value.
def calcMoransI(self): self.weightedCovariance = self.summedWeightedDeviationsOfAllIAndJ() moransI = (self.numberOfValues * self.weightedCovariance) / (self.sumOfWeightMatrix * self.summedVariance) expectedMoaransI = self.calcExpectedMoransI() pValue = self.calcPValue(moransI, expectedMo...
def calcSumWeightedMultipliedValues(self): sumWeightedMultipliedValues = 0 for i in range(self.weightMatrix.shape[0]): for j in range(self.weightMatrix.shape[1]): if i != j: sumWeightedMultipliedValues += self.weightMatrix[i, j] * self.value[i] * self.valu...
This function calculates the Getis-Ord General G statistic and its associated p-value to assess spatial autocorrelation. It computes the ratio of weighted summed products to unweighted summed products, compares this to an expected value, and returns both the statistic and its significance level.
def calcGetisOrdGeneralG(self): sumWeightedMultipliedValues = self.calcSumWeightedMultipliedValues() sumMultipliedValues = self.calcSumMultipliedValues() generalG = sumWeightedMultipliedValues / sumMultipliedValues expectedGeneralG = self.calcExpectedGeneralG() pValue = self.calc...
def calcLocalMoransI(self, i): summedWeightedDifOfMean = self.calcSummedWeightedDifOfMean(i) SiSquared = self.calcSummedSquaredDifOfMean(i) / (self.numberOfValues - 1) Ii = (self.value[i]-self.meanValue) * summedWeightedDifOfMean / SiSquared return Ii def calcLocalMoransIZScore(self, i, ...
This function calculates local Moran's I statistics, z-scores, and p-values for each data point. It iterates through all values, computes local Moran's I using calcLocalMoransI, derives z-scores via calcLocalMoransIZScore, converts them to p-values, and stores results in arrays for return.
def calcAnselinLocalMoransI(self): allLocalIs = np.zeros(self.numberOfValues) allZScores = np.zeros(self.numberOfValues) allPValues = np.zeros(self.numberOfValues) for i in range(self.numberOfValues): localI = self.calcLocalMoransI(i) allLocalIs[i] = localI ...
def setNeededValues(self): self.meanValue = np.mean(self.value) self.valueDifFromMean = self.value - self.meanValue self.numberOfValues = len(self.value) self.sumOfWeightMatrix = np.sum(self.weightMatrix) self.summedVariance = np.sum((self.value - self.meanValue)**2) def calcMora...
This code initializes a spatial analysis tool to compute various spatial autocorrelation measures (e.g., Moran's I, Geary's C) on a given network and value array. It constructs a weight matrix from the network, processes selected cells if specified, and calculates requested statistics based on the provided method. If n...
def __init__(self, network, value, method=None, selectedCells=None): self.network = network if not selectedCells is None: if len(selectedCells) != len(list(self.network.nodes())): self.network = self.network.subgraph(selectedCells) self.weightMatrix =...
def find_closest_z(block, potential_blocks): max_z = 1 for potential_block in potential_blocks: if not can_be_supported(block, potential_block): continue max_z = max(max_z, potential_block["to"][2] + 1) return max_z def get_support_blocks(blocks): block_1_support_block_2 = ...
The code simulates stacking blocks by adjusting each block's vertical position to align with the highest z-coordinate of previous blocks, ensuring proper stacking. After processing all blocks, it determines the supporting blocks by sorting them by z-coordinate and identifying stable foundations.
def simulate(blocks): for i in range(len(blocks)): block = blocks[i] other_blocks = blocks[:i] max_z = find_closest_z(block, other_blocks) diff = block["from"][2] - max_z block["to"][2] -= diff block["from"][2] = max_z return get_support_blocks(sort_by_z(blocks)...