dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def sho_hamiltonian_over_psi(psi, x, a): x = x[0] return (a + (a ** 2 - 1) * (x ** 2)) / (2 * a ** 2) def sho_psi(x, a): x = x[0] return np.exp(- x ** 2 / (2 * a)) def qmc(hamiltonian_over_psi, psi, initial, steps, delta_t, starting): x = np.array(initial) average = 0 steps_count = 0 ...
The code defines a Quantum Monte Carlo (QMC) simulation for a quantum harmonic oscillator (SHO). It sets up the Hamiltonian and wavefunction functions using lambda expressions, then calls a `qmc` solver with parameters like time steps (`steps`), time interval (`delta_t`), and initial state (`starting`). The task is to ...
def sho_qmc(a, steps, delta_t, starting): hamiltonian_over_psi = lambda psi, x: sho_hamiltonian_over_psi(psi, x, a) psi = lambda x: sho_psi(x, a) return qmc(hamiltonian_over_psi, psi, [0], steps, delta_t, starting)
def check_if_db_exists(self): sqlConf = self.conf.get('mysql') try: df = self.get_df_from_server(f'''show databases like '{sqlConf["database"]}' ''') if len(df)>0: return True return False except: return False def initialize...
The code initializes a database if it doesn't exist, using provided topics, and creates any missing tables related to those topics. It ensures the database structure is properly set up for the specified topics.
def init_if_new(self,topics): if not self.check_if_db_exists(): self.initialize_db(topics) self.generate_missing_tables(topics)
def generate(self) -> List[TestCase]: raise UnexpectedError('Can\'t create tests: override "generate" method') def create_files(files: Dict[str, str]): for file, content in files.items(): with open(file, 'w') as f: f.write(content) def _run_test(self, test: TestCase) -> str: ...
This method runs a series of tests by generating them, executing each with setup/cleanup, checking outputs against expected results, and returning pass/fail status. It handles errors, tracks test progress, manages temporary files, and ensures proper system state restoration after testing.
def run_tests(self) -> Tuple[int, str]: if self.module_to_test.startswith('tests.'): import hstest.utils as hs hs.failed_msg_start = '' hs.failed_msg_continue = '' hs.success_msg = '' curr_test: int = 0 try: SystemHandler.set_up() ...
def train_model(df): store_all = pd.DataFrame(df) store_errors = store_k_errors(df) for i in df.index.to_list(): sorted_df = knn_model(df, df.at[i,'x'], df.at[i,'y']) if (sorted_df['class'].iloc[:k].to_list().count(0) > k//2): store_all.at[i, 'prediction'] = 0 if(so...
The code performs k-fold cross-validation on a dataset by splitting it into 'partition_num' parts. For each fold, it trains a model on the combined data excluding the current partition (test set), evaluates accuracy on both training and test data, accumulates results, and returns average accuracy metrics across all fol...
def cross_validation(partition_num, df): df['prediction'] = np.nan data_split = [] df_len = df.shape[0] test_acc = [0,0] #[all, error] train_acc = [0,0] #[all, error] model_train = [] for i in range(partition_num): start = round((i/partition_num) * df_len) s...
def train_model(df): # create empty data frames to sstore model data and errors store_all = pd.DataFrame() store_errors = store_k_errors(df) # iterate over the index list of the input data for i in df.index.to_list(): # use kNN model to get sorted data for each index in the data sort...
This code performs k-fold cross-validation by partitioning data into 'partition_num' subsets, using each subset as a test set while training on the remaining data. It evaluates model accuracy on both training and test sets, accumulates results across partitions, and computes average accuracy metrics. The trained models...
def cross_validation(partition_num, df): # add empty prediction column to data frame df['prediction'] = np.nan # list to store partitioned data frames data_split = [] # number of rows in data frame df_len = df.shape[0] # list to store accuracy of model predictions for test data and train dat...
def is_connected(self): return not (self.connection == None) def query_result_list(self,data): jobs=[] for job in data: jobdict=dict(job) job_result = jobdict['decision_result'] jobdict = self.substitute_markdown_result(jobdict, job_result) jobs.ap...
The function retrieves a list of jobs by querying a database, checks for connection status, handles exceptions by returning an empty list, processes each job's decision result using a substitution method, and returns the modified job list.
def get_jobs_list(self): if not self.is_connected(): return [] try: jobs = self.query_result_list(self.connection.execute(JOB_QUERY)) except: return [] for job in jobs: job_result = job['decision_result'] job = self.substitute_m...
def find_user_id(username): url = "https://api.twitter.com/2/users/by/username/{}".format(username) url += "?user.fields={}".format(USER_FIELDS) response = requests.get(url, auth=bearer_oauth) return response.json()["data"]["id"] def get_followers(user_id): followers = [] next_token = None n...
The main task of the code is to scrape and save followers for multiple Instagram accounts. It iterates through a list of usernames, retrieves each user's ID, fetches their followers, and stores the data. The function logs progress with print statements, indicating completion for each username and the overall task.
def pre_compute_followers(usernames): print("Initiating scraping of followers") # get the followers for each account for username in usernames: user_id = find_user_id(username) followers = get_followers(user_id) save_followers(followers, username) print("Completed scraping {}...
def get_ns_instance(): # To set your environment variables in your terminal run the following line: # export 'PROVIDER_URL'='<your_http_provider_url>' provider_url = os.environ.get("PROVIDER_URL") w3 = Web3(Web3.HTTPProvider(provider_url, request_kwargs={"timeout": 60})) ns = ENS.fromWeb3(w3) r...
The code extracts wallet addresses from followers of given usernames and saves them into a CSV file. It initializes a CSV with headers, iterates through each username to retrieve followers, and uses a function to store wallet addresses alongside account details. The process is logged with start and completion messages.
def extract_wallet_addresses(usernames): ns = get_ns_instance() with open("out/wallet.csv", "a") as f: f.write("Account,Follower Account,Wallet Address\n") print("Initiating extracting wallet addresses") for username in usernames: followers = get_followers(username) # Extract w...
def Rvir_sim(snapdir, simname=None, useNoAGNFb=True): # Load redshift of each snapshot redshifts = redshifts_snapshots(snapdir) simname = os.path.basename(snapdir.rstrip('/')) if simname is None else simname fname = f'data/Rvir/Rvir_{simname}.h5' if os.path.exists(fname) and (not useNoAGNFb or '_no...
The function `profiles_zbins` computes density profiles for galaxy snapshots within specified redshift bins. It divides the redshift range [zmin, zmax) into bins of width zbinwidth, processes each bin by selecting snapshots within the bin, and uses the virial radius from the median snapshot in the bin to calculate prof...
def profiles_zbins(snapdir, redshifts=None, Rvir_allsnaps=None, zmin=1, zmax=4, zbinwidth=0.5, outfile=None): '''Compute profiles for all snapshots in each redshift bin. In each redshift bin, the virial radius at the median (center) snapshot is used. Parameters: `snapdir`: directory with snapshots ...
def assign_samples_to_clusters(X, K, centroids): """ :param X: data for clustering, shape: (N, D), with N - number of data points, D - dimension :param K: number of clusters :param centroids: means of clusters, K vectors of dimension D, shape: (K, D) :return: ind_samples_clusters: indicator variable...
The code implements K-means clustering to group data points into K clusters. It initializes centroids randomly, iteratively assigns data points to the nearest centroid, recomputes centroids based on cluster memberships, and tracks the cost (sum of squared distances) at each iteration. The algorithm stops early if the c...
def kmeans(X, K, max_iter): """ :param X: data for clustering, shape: (N, D), with N - number of data points, D - dimension :param K: number of clusters :param max_iter: :return: ind_samples_clusters - indicator variables for all data points, shape: (N, K) centroids - means of clusters, ...
def _gallery_fetch_helper(self, username, offset=0, display_num=24): self._validate_token() # only do this to check if the cache has to be updated... response = requests.get( f"{API_URL}gallery/all?username={username}&limit=24&access_token=" f"{self.access_token}&offset={...
The main task of the code is to retrieve and return a user's entire gallery (deviations) from a database, either using cached data if available or fetching all results in batches. It checks cache validity, executes a query for deviations, handles pagination with offsets, caches results if needed, and filters the final ...
def fetch_entire_user_gallery(self, username, version): if self.db_actions.user_last_cache_update(username): self._gallery_fetch_helper(username) deviant_row_id = self.db_actions.fetch_user_row_id(username) # use cache query = f""" SELECT * from deviations where d...
def fetch_entire_user_gallery(self, username, version): if self.db_actions.user_last_cache_update(username): self._gallery_fetch_helper(username) deviant_row_id = self.db_actions.fetch_user_row_id(username) # use cache query = f""" SELECT * from deviations where d...
This function retrieves a user's gallery images. It checks if cached data is up-to-date; if so, it fetches the entire gallery. Otherwise, it fetches and filters images, then returns a subset based on offset and display_num parameters.
def fetch_user_gallery(self, username, version, offset=0, display_num=10): if self.db_actions.user_last_cache_update(username): response = self.fetch_entire_user_gallery(username, version) else: display_num = 10 response = self._filter_api_image_results( ...
def _check_play_button(self,mouse_pos): """Start a new game when the player clicks Play""" # We use collidepoint() to check whether the point of the mouse click overlaps the region defined by the Play button's rect. # If it does, we set game_active to True, and the game will start. butto...
The method `_check_events` handles user inputs by processing Pygame events: exiting the game on quit, detecting mouse clicks to trigger the play button, and responding to keyboard presses for movement. It delegates keydown/up events to specialized methods, ensuring interactive control over the game state and player act...
def _check_events(self): """Respond to keypresses and mouse events""" for event in pygame.event.get(): """If click Quit, game exit""" if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: # get_pos() retur...
def _check_fleet_edges(self): """Respond appropriately if any aliens have reached an edge""" for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _ship_hit(self): """Respond to the ship being hit by a...
The code updates alien positions, checks for collisions between aliens and the ship, and detects if aliens reach the screen bottom. If a collision occurs, it triggers a ship-hit response, removing aliens/bullets and resetting the fleet.
def _update_aliens(self): """Check if the fleet is at an edge, then Update the positions of all aliens in the fleet""" self._check_fleet_edges() self.aliens.update() # Look for alien-ship collisions.If no collisions, the method returns None. If there is a collision, it returns the alien...
def _check_events(self): """Respond to keypresses and mouse events""" for event in pygame.event.get(): """If click Quit, game exit""" if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: # get_pos() retur...
The code's main task is to run the game loop, handling user input events continuously, updating game elements (ship, bullets, aliens) only when the game is active, and rendering the screen. It ensures real-time responsiveness to user actions like quitting, while maintaining game state and visuals.
def run_game(self): """Start the main loop for the game""" """The game is controlled by run_game(). A event is an action that the user performs while playing the game such as pressing a key or moving the mouse """ while True: # Watch for keyboard and mouse events. ...
def validate_a_value(self): value = self.ui.gainInput.text() if value in self.user_inputs_values: self.show_error( self.ui.value_error, "Filter was already added", self.ui.gainInput, ) return True elif value == ...
This function processes user input for a custom all-pass filter by validating the input, creating a ProcessButton with the entered value, updating cascaded filter lists, and organizing UI elements. It appends the value to user inputs, generates a uniquely named button, adds it to the filter chain, updates phase respons...
def customize_all_pass_filter(self): # Get the value entered in the text field value = self.ui.gainInput.text() if not self.validate_a_value(): self.user_inputs_values.append(value) self.ui.gainInput.clear() # Instantiate a library button button_n...
def add_target_item(self, pos, movable, symbol, color): """ It just add A ZERO OR POLE TO THE UNIT CIRCLE. """ item = TargetItem( pos=pos, size=10, movable=movable, symbol=symbol, pen=pg.mkPen(color), ) self.ui.u...
This code handles mouse clicks on a unit circle plot to add/remove poles/zeros. Left-click adds a pole (red 'x') or zero (green 'o') based on flags, stores their positions, and draws conjugates if enabled. Right-click triggers removal via context menu. It maps click positions, checks mouse buttons, and manages dynamic ...
def handle_unit_circle_click(self, event): # Get the clicked position by mouse pos = self.ui.unitCirclePlot.mapToView(event.scenePos()) # Check which button is clicked to determine whether to add or remove if event.button() == QtCore.Qt.LeftButton: if self.is_pole: ...
def reset_design(self): self.remove( self.poles + self.poles_conjugates + self.zeros + self.zeros_conjugates, ) # Empty all lists self.poles.clear() self.poles_positions.clear() self.poles_conjugates.clear() self.poles_conjugates_positions.clear() ...
This code imports and visualizes filter components (zeros/poles) by resetting existing design data, removing old all-pass elements, plotting new zeros/poles with specific markers, handling conjugate pairs for symmetry, and updating frequency responses.
def import_filter(self, zeros, poles, allpass_zeros, allpass_poles): # Reset everything self.reset_design() for filter in self.cascaded_filters: self.remove_all_pass_zeros_and_poles( self.all_pass_zeros, filter.zero.real, filter.zero.imag ) sel...
def team_name(module): ''' Accepts a module that has been imported Returns the name of the module as a string ''' return str(module).split(' ')[1].replace('\'','') def playoff(player1, player2, number_of_rounds=60): ''' player1 and player2 are functions that accept two ints and return an int...
The main task of the code is to simulate a round-robin tournament among multiple player functions, tracking their win-loss-tie records and generating detailed reports. It initializes player data, conducts pairwise matches using their strategies, updates scores and zero-round counts, and compiles a summary report with N...
def round_robin(number_of_rounds, *argv): '''number_of_rounds is an int = 1 or more The remaining arguments become a list: argv argv is a list of functions, one per player ''' # Create report and scores[player1][player2] array scores = {} #scores[team_name] = [(W,L,T), (W,L,T), etc.] report ...
def optimal_portfolio(return_vec, N = 1000): import cvxopt as opt from cvxopt import blas, solvers # Turn off progress printing solvers.options['show_progress'] = False n = len(return_vec) log_returns = np.asmatrix(return_vec) mus = [10 ** (5.0 * t / N - 2.0) for t in range(N)] # Conv...
The code retrieves Bitcoin price data from 2019, calculates log returns, computes optimal portfolios using mean-variance optimization, plots the efficient frontier, selects a portfolio, generates diversified portfolios, and evaluates their monthly returns for performance analysis.
def new_run(): df = data.get_data(choice='BTC') df = df[df.index > pd.to_datetime(datetime.date(2019, 1, 1))] log_returns = df.pct_change().apply(lambda x: np.log(1 + x)).dropna() return_vec = log_returns.T # returns.T # Get Optimal PFolios: opt_weights, opt_returns, opt_risks, res = optimal_po...
def initialize_solution(self, y: measurements): """ Initialize solution with an all-zero vector or the LS solution """ batch_size = y.shape[0] if self.use_LS_initialization == True: h_init = torch.matmul(self.W_pinv,y.unsqueeze(-1)).squeeze(-1) else: ...
This code performs forward propagation in an FPN-OAMP neural network, iteratively finding a fixed point via detached gradients. During training, it reattaches gradients for one final iteration to compute gradients, while testing stops at the fixed point. It includes safeguards against excessive depth and contractive ma...
def forward(self, y: measurements, depth_warning=False): ''' FPN-OAMP forward propagation Training process: With gradients *detached*, find the fixed point. Then attach gradient and perform one additional iteration to calculate the gradient. Testing process: Wi...
def update_node_fig(x_range, top_n_node): return generate_node_fig(x_range, top_n_node) def update_river_fig(x_range, relayoutData): if x_range is not None: river_fig.update_layout(xaxis_range=x_range) elif 'xaxis.autorange' in relayoutData: river_fig.update_layout(xaxis_range=None, yaxis_ra...
The function updates multiple visualizations (node, river, race, bar figures) and click data based on user interactions (relayoutData) and x-axis range adjustments. It processes relayoutData to determine the x-axis range, updates node_fig accordingly, and refreshes river_fig, race_fig, and bar_fig with the new range an...
def update_figure(relayoutData, top_n_bar, click_data, top_n_words, top_n_node, bar_fig, node_fig): x_range = None if relayoutData is not None: if 'xaxis.range[0]' in relayoutData: x_range = [relayoutData['xaxis.range[0]'], relayoutData['xaxis.range[1]']] node_fig = update_node_...
def update_node_fig(x_range, top_n_node): return generate_node_fig(x_range, top_n_node) def update_river_fig(x_range, relayoutData): if x_range is not None: river_fig.update_layout(xaxis_range=x_range) elif 'xaxis.autorange' in relayoutData: river_fig.update_layout(xaxis_range=None, yaxis_ra...
This function updates multiple visualizations (node, river, race, bar charts) and related data based on relayoutData, top_n parameters, and click events. It adjusts x-axis ranges, refreshes figures, updates click data, and toggles a modal. The output includes updated figures, click data, a URL, and the modal's open sta...
def update_figure(relayoutData, top_n_bar, click_data, top_n_node, top_n_words, bar_fig, is_open, n1, n2): x_range = None if relayoutData is not None: if 'xaxis.range[0]' in relayoutData: x_range = [relayoutData['xaxis.range[0]'], relayoutData['xaxis.range[1]']] elif 'xaxis.autorange...
def session_new(timeout,multiplayer): global firestoreClient global SESSION_START_TIME global MESSAGE_TRACK global STACK_TRACK global SESSION_DONE global SESSION_ID global SESSION_USER global SANDBOX_TYPE global API_KEY global SHELL2_CLIENT global FOLDER_STATE_7Z global F...
The main task of the code is to parse CLI arguments for managing sandbox sessions or sequences, validate API keys for LLM services, handle voice/text input modes, and execute session actions (new, resume, join) or sequence runs based on user-provided parameters, ensuring proper setup and error handling for required res...
def main(): global FOLDER_STATE_NOSYNC global USER_INPUT_MODE # is called from main cli, ~like this # shell2_cli_live --sandbox session --action new --timeout 600 --multiplayer # shell2_cli_live --sandbox session --action resume --sessionId "someId" --timeout 600 --multiplayer # shell2...
def extract_features(self, data, sr): mfcc = librosa.feature.mfcc(y=data, sr=sr, n_mfcc=30) delta = librosa.feature.delta(mfcc) delta_2 = librosa.feature.delta(delta) combined_feat = np.concatenate((mfcc, delta, delta_2)) self.features.append(combined_feat.T) self.plot_...
The code performs speaker and word recognition from an audio file using GMM models. It loads pre-trained GMMs for four words and five speakers, extracts audio features, calculates log-likelihoods, and applies softmax to determine the most probable word and speaker. It checks if the detected speaker is selected in a UI ...
def predict_speaker(self): #self.current_mode = "Fingerprint" y_word = [] y_speaker = [] audio, sr = librosa.load('output.wav') # Prediction code for word recognition model_folder2 = r'F:\task\2' gmm_files_word = [f'{model_folder2}/{i}.jo...
def on_connection_init(self, op_id, payload): self.send_message(op_type=GQL_CONNECTION_ACK) def on_connection_terminate(self, op_id): self.close(code=1011) def get_graphql_params(self, payload): return { "request_string": payload.get("query"), "variable_values": payload.g...
This code processes incoming messages by parsing JSON data, determining the operation type (e.g., connection initialization, termination, GraphQL start/stop), and routing them to appropriate handler methods. It validates payloads, handles errors for invalid types, and ensures proper delegation of operations like starti...
def on_message(self, message): parsed_message = json_decode(message) op_id = parsed_message.get("id") op_type = parsed_message.get("type") payload = parsed_message.get("payload") if op_type == GQL_CONNECTION_INIT: return self.on_connection_init(op_id, payload) ...
def isWin(self): '''Return is the current player is winning''' return self.winning(self.get_piece_player()) def isLose(self): '''Return is the opponent player is winning''' return self.winning(self.get_opp_piece(self.get_piece_player())) def getLegalActions(self, agentIndex=0): "...
The code checks if a state is terminal by verifying if the current state is a win, a loss, or if there are no legal actions remaining. It returns a boolean indicating whether the state is terminal.
def is_terminal(self): ''' Return whether or not that state is terminal ''' return self.isWin() or self.isLose() or len(self.getLegalActions()) == 0
def getLegalActions(self, agentIndex=0): """ Returns the legal actions for the agent specified. """ actions = [] if not self.isWin() and not self.isLose(): for col in range(u.COLUMN_COUNT): if(self.is_valid_location(col)): actions.a...
This function identifies the optimal move by evaluating all valid actions, generating successor states for each, and selecting the move with the highest score. It initializes with a random valid move, iterates through each option, updates the best move based on the highest score found, and returns the column correspond...
def pick_best_move(self): best_score = -10000 valid_location = self.getLegalActions() best_col = random.choice(valid_location) for col in valid_location: temp_state = self.generateSuccessor(self.get_piece_player(), col) score = temp_state.getScore() i...
def parse_model(xbrl_facts): k = 0 # create a new Filing object with null properties filing = Filing(None) # create empty arrays facts = [] facts_mapped = [] # traverse the xbrlfacts for fact in enumerate(xbrl_facts): k += 1 # make the fact string for parsing fact...
The code processes input 'facts' by parsing them into structured data, checking and resetting a matched table for the associated entity, then exporting the processed facts and mapped data into a CSV file.
def process(facts): facts, facts_mapped, filing = parse_model(facts) check_matched_table(filing.entity) reset_matched_table() to_csv(facts_mapped=facts_mapped, facts=facts)
def validate_datetime(date_string): try: return datetime.datetime.strptime( date_string, '%d-%m-%Y' ) except ValueError: raise ValueError( "The date you have entered is incorrect, likely misformatted." ) def _calculate_value...
This code initializes an object with bonus data, date ranges, and salary information, then calculates value-based, percentage-based, and total bonuses by calling private methods. It validates dates and stores inputs for later use in bonus computations.
def __init__( self, bonus_list: list[Bonus], start_date: str, end_date: str, salaries: list[Salary] = [], *args, **kwargs ): self._bonus_list = bonus_list self._salaries = salaries self.start_date = validate_...
def formula(data, c, co, o, v, apply_data): global _c, _co, _o, _v ajusted_confidences = [] for i in range(len(data[0])): ajusted_confidences.append(apply_data(data, i, c, co, o, v)) ajusted_confidences = minmax_scale(ajusted_confidences) return ajusted_confidences def evaluate(confidences, ...
The function `calc_o` recursively optimizes parameters (c, co, o, v) by adjusting `o` (either doubling or reducing) at each depth level, comparing results to find the best configuration. It uses similarity metrics from `evaluate` and updates global variables for tracking progress, ultimately returning the optimal param...
def calc_o(data, c, co, o, v, depth, best, aply_data): if depth == 0: return best, c, co, o, v else: ajusted_confidences = formula(data, c, co, o, v, aply_data) similarity = evaluate(ajusted_confidences, verification_data) global last, _c, _co, _o, _v if similarity >= la...
def formula(data, c, co, o, v, apply_data): global _c, _co, _o, _v ajusted_confidences = [] for i in range(len(data[0])): ajusted_confidences.append(apply_data(data, i, c, co, o, v)) ajusted_confidences = minmax_scale(ajusted_confidences) return ajusted_confidences def evaluate(confidences, ...
This function recursively optimizes parameters (c, co, o, v) by adjusting 'co' values (doubling or reducing) at each depth level, comparing similarity scores from adjusted confidences against verification data, and returning the best configuration of parameters that maximizes performance. It uses global tracking to ret...
def calc_co(data, c, co, o, v, depth, best, aply_data): if depth == 0: return best, c, co, o, v else: ajusted_confidences = formula(data, c, co, o, v, aply_data) similarity = evaluate(ajusted_confidences, verification_data) global last, _c, _co, _o, _v if similarity >= l...
def formula(data, c, co, o, v, apply_data): global _c, _co, _o, _v ajusted_confidences = [] for i in range(len(data[0])): ajusted_confidences.append(apply_data(data, i, c, co, o, v)) ajusted_confidences = minmax_scale(ajusted_confidences) return ajusted_confidences def evaluate(confidences, ...
The function recursively optimizes parameters (c, co, o, v) by adjusting confidence values through depth-limited exploration. It calculates adjusted confidences, evaluates similarity, and compares outcomes of recursive calls with modified c-values (doubled or reduced). The best result is selected iteratively, updating ...
def calc_c(data, c, co, o, v, depth, best, apply_data): if depth == 0: return best, c, co, o, v else: ajusted_confidences = formula(data, c, co, o, v, apply_data) similarity = evaluate(ajusted_confidences, verification_data) global last, _c, _co, _o, _v if simila...
def init_fonts(self): ''' Initializes consistent fonts for GUI usage. ''' self.btn_font = tkfont.Font(family="Helvetica", size=36) self.txt_font = tkfont.Font(family="Helvetica", size=24) self.inp_font = tkfont.Font(family="Helvetica", size=22) self.reading_font =...
This code initializes a GUI for Ozone control, setting up the interface with fonts, buttons, and labels. It configures the layout using grid geometry, linking frames to the main window. The class accepts serial connections for ion gauge and leak valve control, enabling interaction with hardware components through the g...
def __init__(self, root, other): ''' Creates GUI and relevant control scheme for Ozone control :param ion_com: serial connection to the ion gauge :param leak_com: serial connection to the leak valve ''' self.root = root self.CRLR = other self.init_fonts(...
def timer(theme: str, work_time: int, break_time: int, ext_break_time: int): # Audio files work_done_audio = f"pomodoro_audio/{theme}/work_done.wav" break_done_audio = f"pomodoro_audio/{theme}/break_done.wav" cnt = 1 while True: print(f"Round {cnt}!") print("Work:") countdow...
The code's main task is to handle command-line arguments for a Pomodoro timer, allowing users to select themes, custom settings, or specify work/break times. It uses default values when no arguments are provided, displays help information for "help", loads custom configurations, and validates inputs, exiting with error...
def main(): try: # Default if len(sys.argv) == 1: timer(DEFAULT_THEME, DEFAULT_WORK_TIME, DEFAULT_BREAK_TIME, DEFAULT_EXT_BREAK_TIME) elif len(sys.argv) == 2: arg = sys.argv[1].lower() # User asking for help if sys.argv[1].lower() == "help": ...
def do_search(self, value:str) -> None: self.search_results = search_cards(value, self.cards) self.search_names = [card['name'] for card in self.search_results] self.search_box.delete(0, 'end') for name in self.search_names: self.search_box.insert('end', name) return ...
This code initializes a GUI application for building and managing card combos. It sets up a window with search functionality, listboxes for selecting starters/end cards, buttons to add/remove items, and tools to finalize combos, render images, and edit existing pairs. The interface allows users to search cards, organiz...
def __init__(self, card_data:list[dict[str, str]], combos:ComboWrapper): self.root = tk.Tk() self.root.title('Combo Builder') self.root.geometry('500x600') self.cards = card_data self.combos = combos self.temp_combos = [] #search/add frame self.search_fr...
def delete_path(self): for id in self.path_object_ids: self.canvas.delete(id) self.path_object_ids = [] def get_start_position(self) : x,y = self.get_center(2) # Purple block has id 2 yaw = self.get_yaw(2) return x,y,yaw def get_a_star_path(self, path, cost_f...
The code generates a path using A* algorithm in two stages: first finding an initial path from a start position, then extending it with modified parameters. It combines both paths and visualizes the result by drawing the complete path.
def go(self, event): self.delete_path() start_pos = self.get_start_position() path = self.get_a_star_path([start_pos], self.cost_function, 60, 0., 700, 600) path2 = self.get_a_star_path(path, self.cost_function, 20, 350., 0, 50) path = path + path2 self.path_obje...
def normalize_url(self, raw_url): url = urllib.parse.urlparse(urllib.parse.urljoin(self.source_url_root, raw_url)) if url.path == '': url = url._replace(path = '/') if url.path == '/rss': url = url._replace(path = '/rss/') return urllib.parse.urlunparse(url) def get_urls_for_retrieval_from_img_srcset(self...
This function extracts all URLs from HTML content by parsing anchor tags, links, images, scripts, and styles. It normalizes URLs from href, src, and srcset attributes, handling CSS and image source sets separately. The result is a list of normalized URLs for retrieval.
def get_urls_for_retrieval_from_html(self, data): urls = [] soup = BeautifulSoup(data, features='html.parser') for link in soup.findAll('a'): if link.has_attr('href'): urls.append(self.normalize_url(link['href'])) for link in soup.findAll('link'): if link.has_attr('href'): urls.append(self.normali...
def handle_tcp(self, pkt: bytes) -> None: pass def handle_udp(self, pkt: bytes) -> None: pass def not_my_packet(self, pkt: bytes, intf: str) -> None: if self._ip_forward: self.forward_packet(pkt) else: pass
This function processes an incoming IP packet by checking if it is destined for the host. It collects all destination IP addresses from network interfaces, checks if the packet's destination matches (including broadcast), and routes it to TCP/UDP handlers if applicable. If not, it passes the packet to a method for furt...
def handle_ip(self, pkt: bytes, intf: str) -> None: ip = IP(pkt) all_addrs = [] #Parse out all destination IP address in the packet for intf1 in self.int_to_info: all_addrs += self.int_to_info[intf1].ipv4_addrs #Determine if this host is the final destination for the packet, based on the d...
def handle_ip(self, pkt: bytes, intf: str) -> None: ip = IP(pkt) all_addrs = [] #Parse out all destination IP address in the packet for intf1 in self.int_to_info: all_addrs += self.int_to_info[intf1].ipv4_addrs #Determine if this host is the final destination for the packet, based on the d...
This function processes an Ethernet frame by checking if it is destined for the local interface or broadcast. If so, it handles IP or ARP packets by calling respective methods; otherwise, it delegates the frame to a different handler.
def _handle_frame(self, frame: bytes, intf: str) -> None: eth = Ether(frame) if eth.dst == 'ff:ff:ff:ff:ff:ff' or eth.dst == self.int_to_info[intf].mac_addr: if eth.type == ETH_P_IP: self.handle_ip(bytes(eth.payload), intf) elif eth.type == ETH_P_ARP: self.handle_arp(byte...
def parse_rule(rule): # Shunting-yard precedence = { "(": 3, ")": 3, "+": 2, "|": 1, } output_queue = [] operator_stack = [] for token in rule.split(): if token in ["+", "|"]: while ( operator_stack and precedenc...
The function checks if the input text matches grammar rules 8 and 11 by parsing their ASTs, dividing text into chunks of fixed lengths, and testing all valid distributions of repeated "42" and "31" patterns. It returns True if any distribution perfectly matches the text structure, otherwise False.
def match_8_11(text, resolved_rules): # rule 8: 42 | 42 8 # rule 11: 42 31 | 42 11 31 # rules 8 and 11 simplify to 42 n times followd by 42 k times followed by 31 k times asts = dict() for name in ["42", "31"]: asts[name] = parse_rule(resolved_rules[name]) # input(message) length_...
def get_graph(self): return self._G def get_root(self): """ Returns the root of the Neuron which is typically the soma with node id = 1. :return: int, node id of the soma. """ try: root = np.min(self.nodes(type_ix=1)) except (ValueError, KeyError): ...
This function calculates distances from the soma (root node) in a neuronal graph using either 'path_from_soma' (Dijkstra's algorithm with specified edge weights) or 'branch_order' metrics. It returns distances as a dictionary of {node_id: distance} or numpy array, depending on 'as_dict' parameter. The 'weight' paramete...
def _get_distance(self, dist='path_from_soma', weight='euclidean_dist', as_dict=False): """ Returns the distance :param dist: String, defines the distance measure to be used (default is 'path_from_soma'), Options are 'path_from_soma' and 'branch_order'. :param weight: String. Def...
def _make_tree(self): """ Forces the networkx.DiGraph to be a tree. This routine was needed because the networkx.dfs_tree() function looses the original node and edge attributes. Manipulation done inplace. """ G = self._G r = self.get_root() T = nx.dfs_tree(G, r)...
The code's main task is to simplify a tree structure by pruning nodes (e.g., removing intermediate nodes like B in A→B→C) based on a specified method. It reduces the number of nodes in-place, either by creating a minimal spanning tree (MST), removing nodes that don’t significantly alter edge lengths (via `dist` with to...
def reduce(self, method='mst', e=0.01): """ Reduces the number of nodes in the given tree by pruning nodes on paths like A-->B-->C. B is pruned and the resulting edge A-->C is inserted under circumstances defined by the keyword 'method'. :param method: (default 'mst') Defines the method ...
def get_graph(self): return self._G def _get_distance(self, dist='path_from_soma', weight='euclidean_dist', as_dict=False): """ Returns the distance :param dist: String, defines the distance measure to be used (default is 'path_from_soma'), Options are 'path_from_soma' and 'branc...
The function computes a Gaussian kernel density estimate (KDE) for a specified graph measure (e.g., thickness, path/branch angles, branch order, or distance) as a 1D or 2D distribution, depending on whether a distance metric is provided. It extracts relevant data for each measure, combines it with distance values if ap...
def get_kde_distribution(self, key, dist=None): """ Returns a Gaussian kernel density estimate of the distribution of the measure defined by _key_. :param key: String, measure to calculate the kernel density estimate from. Options are: 'thickness', 'path_angle', 'branch_angle', 'branch_o...
def get_graph(self): return self._G def get_root(self): """ Returns the root of the Neuron which is typically the soma with node id = 1. :return: int, node id of the soma. """ try: root = np.min(self.nodes(type_ix=1)) except (ValueError, KeyError): ...
The function `get_thickness_dist` calculates and returns the distribution of neuronal thickness (in microns) as a histogram. It optionally uses a distance measure ('path_from_soma' or 'branch_order') to generate a 2D histogram (with distance and thickness) or a 1D histogram (thickness only). The soma's thickness is exc...
def get_thickness_dist(self, dist_measure=None, **kwargs): """ Returns the distribution of the neurons thickness in microns in form of a histogram. The distribution can be calculated against a distance measure, namely 'path_from_soma' or 'branch_order'. :param dist_measure: ...
def get_graph(self): return self._G def edges(self, start=None, type_ix=None, data=False): """ Wrapper function to the networkx.edges() function. It returns a list of edges. :param start: int, node id, determines the starting edge within the neuron :param type_ix: int, optional, ...
The main task of the code is to compute the distribution of path angles between consecutive segments in a graph, either as a 1D histogram of angles or a 2D histogram combining angles with a specified distance measure (e.g., 'path_from_soma' or 'branch_order'). It calculates angles between vectors of consecutive edges, ...
def get_path_angle_dist(self, dist_measure=None, **kwargs): """ Returns the distribution of the path angle, so the angles that are made between two consecutive segments. The distribution can be calculated against a distance measure, namely 'path_from_soma' or 'branch_order'. ...
def get_branch_angles(self): """ Returns the list of branch angles. :return: branch_angles list of branch angles. """ from itertools import combinations branch_angles = [] branchpoints = self.get_branchpoints() for bp in branchpoints: ...
The function calculates the distribution of branch angles (in degrees) between branching segments, using a specified distance measure ('path_from_soma' or 'branch_order'). It returns a 2D histogram and bin edges, either pairing angles with distances or directly histogramming angles if no distance measure is provided.
def get_branch_angle_dist(self, dist_measure=None, **kwargs): """ Returns the distribution of the branch angles, so the angles that are made between two branching segments. The distribution is calculated against a distance measure, namely 'path_from_soma' or 'branch_order'. T...
def _remove_redundant_nodes(self): """ Remove redundant nodes from the NeuronTree. A node is considered redundant if the edge between two nodes has a euclidean distance = 0, so the node has the same 3D position as its predecessor. """ # get the nodes whose edge between them has d...
The main task of the code is to initialize a NeuronTree object containing a networkx.DiGraph with node attributes (position, type, radius) and edge attributes (distance, path length). It constructs the graph from SWC data, node/edge lists, or an existing graph, scales coordinates, processes node types, and optionally p...
def __init__(self, swc=None, scaling=1., soma_rad=1., node_data=[], edge_data=[], graph=None, post_process=True): """ Creates a NeuronTree object that contains a networkx.DiGraph with node attributes 'pos' [x,y,z], 'type' [1:soma,2:axon,3: dendrite], 'radius' and edge attributes 'euclidean_dist'...
def get_tile_indices(self, x, flex): self.masks = [] # Masks of input data corresponding to each weight tile for each layer self.tile_indices = [] self.n_data = x.shape[0] # Get weight indices of all layers for each entry of x self.indices = self.get_indices(x, self.tile_dims...
This code processes input data through a neural network by tiling the input into smaller segments, applying modular operations to each tile, and recombining them. It uses flexible tiling based on the 'flex' flag, normalizes input with positional encoding, and handles dynamic data shapes by recalculating tile indices wh...
def forward(self, x, flex=False, labels=None): # Weight tile indices and masks for input data are only calculated once per model initialization if self.indices is None or x.shape[0] != self.n_data: self.get_tile_indices(x, flex) # x should be normalized to be within [-1, 1] ...
def get_file_path(): """ This method is used to get the absolute path of config file from User. """ return input("Enter absolute file path:") def read_conf(file_path, retry=0): """ Reads the config files of type .conf, .cfg and .ini. Params: file_path = Path to the file ret...
The main task of the code is to load a configuration file based on its extension, validate its supported type, and pass it to the menu_options function. It retrieves the file path, extracts the name and extension, uses read_conf or load_yaml depending on the format, logs errors for unsupported files, and exits if inval...
def main(): """ Main driver function """ file_path = get_file_path() logger.info("Finfding File {}".format(file_path)) config_name = (file_path.split("/")[-1]).split(".")[0] file_extension = pathlib.Path(file_path).suffix[1:] if file_extension in supported_file_types[:3]: config ...
def lock_intf_track_file(self): self.logger.info("Lock interface track file from S3 bucket.") self.lock_id = str(uuid.uuid1()) b_succ = False # Get tagging max_loop = 60 go_next = False for i in range(max_loop): try: b_exist = self.chec...
The code's main task is to save the current VM's interface information into a track file. It locks the file, retrieves the interface track dictionary, updates it with the VM's interfaces using its ID as a key, writes the updated data back to the file, and then unlocks the file. Exceptions during this process are logged...
def save_intf(self): self.lock_intf_track_file() try: intf_track_dict = self.get_intf_track_dict() if intf_track_dict != None: intf_track_dict[self.fgt_vm_id] = self.fgt_vm_intfs self.update_intf_track_file(intf_track_dict) except Exception...
def lock_intf_track_file(self): self.logger.info("Lock interface track file from S3 bucket.") self.lock_id = str(uuid.uuid1()) b_succ = False # Get tagging max_loop = 60 go_next = False for i in range(max_loop): try: b_exist = self.chec...
The main task of the code is to remove a specific instance's record from an interface tracking file. It locks the file, retrieves the tracking dictionary, removes the entry associated with `self.fgt_vm_id`, updates the file with the modified dictionary, handles exceptions during the process, and ensures the file is unl...
def remove_intf(self): self.lock_intf_track_file() try: intf_track_dict = self.get_intf_track_dict() if intf_track_dict != None: intf_track_dict.pop(self.fgt_vm_id, None) self.update_intf_track_file(intf_track_dict) except Exception as e: ...
def lock_intf_track_file(self): self.logger.info("Lock interface track file from S3 bucket.") self.lock_id = str(uuid.uuid1()) b_succ = False # Get tagging max_loop = 60 go_next = False for i in range(max_loop): try: b_exist = self.chec...
The main task of the code is to safely retrieve or initialize an interface tracking dictionary. It locks a file, attempts to fetch the dictionary, initializes it as empty if null, logs errors if exceptions occur, then unlocks the file before returning the dictionary.
def get_intf(self): self.lock_intf_track_file() try: intf_track_dict = self.get_intf_track_dict() if intf_track_dict == None: intf_track_dict = {} except Exception as e: self.logger.error(f"Exception when get interface track file: {e}") ...
def lock_lic_track_file(self): self.logger.info("Lock license track file from S3 bucket.") self.lock_id = str(uuid.uuid1()) b_succ = False # Get tagging max_loop = 60 go_next = False for i in range(max_loop): try: b_exist = self.check_o...
This code releases a license by moving a specified VM instance from the 'used' list to the 'available' list in a license track file. It locks the file to prevent conflicts, updates the license status if the VM ID is found in the 'used' list, uploads the updated file to S3, and handles errors. The function returns wheth...
def release_lic(self, fgt_vm_id): b_locked = self.lock_lic_track_file() if not b_locked: return False b_updated = False try: # Get license track file lic_track_dict = self.get_lic_track_dict() if lic_track_dict: # Update lic...
def get_item_from_dydb(self, category, attributes): rst = None try: response = self.dynamodb_client.get_item( TableName=self.dynamodb_table_name, Key={ 'Category': { 'S': category, } ...
The main task of the code is to retrieve and return the next available serial number from a DynamoDB list. It fetches the "available_sn_list" from the "fortiflex" table, converts it to a standard format, extracts the first item, removes it from the list, and returns it. If no items are available or data is missing, it ...
def get_next_available_sn(self): self.logger.info("Get next available serial number.") dydb_items = self.get_item_from_dydb("fortiflex", ["available_sn_list"]) if dydb_items: if "available_sn_list" in dydb_items: available_sn_list = self.convert_aws_dydb_to_normal_for...
def change_password(self, fgt_vm_id): self.logger.info("Change password for FortiGate instance.") b_succ = False session_key = "" max_loop = 10 for i in range(max_loop): url = f"https://{self.fgt_private_ip}{self.fgt_login_port}/api/v2/authentication" ...
The main task of the code is to handle operations like changing a password, uploading a license, or uploading a configuration to a FortiGate instance based on the `operation` parameter in the event. It validates required parameters, executes the corresponding method, and returns success or error status codes with descr...
def main(self, event): self.logger.info(f"Start internal lambda function.") self.fgt_private_ip = event["private_ip"] operation = event["operation"] parameters = event["parameters"] if operation == "change_password": if "fgt_vm_id" not in parameters: s...
def get_intf(self): self.lock_intf_track_file() try: intf_track_dict = self.get_intf_track_dict() if intf_track_dict == None: intf_track_dict = {} except Exception as e: self.logger.error(f"Exception when get interface track file: {e}") ...
The main task of the code is to terminate an FGT VM instance by cleaning up its network interfaces. It logs the termination, retrieves current interface data, merges them into a tracking structure, skips index "0", and cleans/cleans up non-zero interfaces. Finally, it removes all interfaces. The code ensures proper res...
def do_terminate(self): self.logger.info(f"Do terminate fgt vm instance: {self.fgt_vm_id}") intf_track_dict = self.get_intf() cur_fgt_intf_dict = intf_track_dict.get(self.fgt_vm_id, {}) # Merge intfs info for d_index, intf in cur_fgt_intf_dict.items(): if d_index not ...
def do_launch(self): self.logger.info(f"Do launch fgt vm instance: {self.fgt_vm_id}") intf_setting = json.loads(os.getenv('network_interfaces')) fgt_az = self.instance_detail['Reservations'][0]['Instances'][0]['Placement']['AvailabilityZone'] for intf_name, intf_conf in intf_setting.item...
This code handles EC2 lifecycle events by retrieving instance network interfaces and triggering actions (launch/terminate) based on event type. It logs details, maps interfaces by device index, and calls methods to complete lifecycle actions or save interface data when the instance launches successfully.
def main(self, event): self.logger.info(f"Do interface config") self.fgt_vm_id = event["detail"]["EC2InstanceId"] detail_type = event["detail-type"] self.instance_detail = self.ec2_client.describe_instances(InstanceIds=[self.fgt_vm_id]) self.fgt_vm_intfs = {} for intf in ...
def get_item_from_dydb(self, category, attributes): rst = None try: response = self.dynamodb_client.get_item( TableName=self.dynamodb_table_name, Key={ 'Category': { 'S': category, } ...
The function retrieves or generates a valid Fortiflex OAuth token by checking an existing token's validity, refreshing it if needed, or creating a new one using a refresh token or credentials if no valid token exists. It ensures the token is not expired and returns the valid OAuth token for authentication.
def get_fortiflex_oauth_token(self): dydb_items = self.get_item_from_dydb("fortiflex", ["oauth_token"]) oauth_token = "" if dydb_items: if "oauth_token" in dydb_items: oauth_token = self.convert_aws_dydb_to_normal_format(dydb_items["oauth_token"]) if oauth_tok...
def stdConv(g): absorbing = [] transient = [] # print(d) # printMatrix(g) for i in range(len(g)): if sum(g[i]) == 0: absorbing.append(i) else: transient.append(i) matrixKey = absorbing + transient standardM = [] for val in matrixKey: standa...
The code solves a system of linear equations represented by matrix `m`. It first checks if the first row is all zeros, returning `[1,1]` if true. Otherwise, it converts the matrix into fractions, partitions it into submatrices, computes an inverse of a modified identity matrix, multiplies it with another submatrix, and...
def solution(m): if sum(m[0]) == 0: return [1,1] MM, abs, trans = stdConv(m) M1, D1 = convertToFrac(MM) # print(M1) RQ = M1[abs:] R = [] Q = [] for row in RQ: R.append(row[:abs]) Q.append(row[abs:]) I = generateIdentityMatrix(trans) F = inverse(subtract...
def initialize_db(db_filename): db = sqlite3.connect(db_filename) cpes_create_command = "create table cpes ( uri text, part text, vendor text, product text, version text, update_number text, edition text, language text, sw_edition text, target_sw text, target_hw text, other text, cve_id text, start_version tex...
The code initializes a database, downloads CPE match data and yearly CVE data, then creates a 'cve_match' table by joining CPE and match records on overlapping fields to link CVEs with specific product versions.
def main(): db_filename = "nvd.db" db = initialize_db(db_filename) download_cpe_match_data(db) for year in range(2002, 2022): download_year_data(year, db) # now join these two tables together print("Creating cve match table...", end='', flush=True) db.execute("create table cve_mat...
def hello_screen(sock): show_screen(sock, " VeritaWall Firewall ", ">>> veritawall.com") def version_screen(sock): version = get_version() show_screen(sock, " VeritaWall Firewall ", f"Ver: {version}") def cpu_screen(sock): for _ in range(5): show_screen(sock, " VeritaWall Firewall ", ...
The code connects to a local server on port 13666, sends a "hello" message, and continuously displays system information (CPU, RAM, IPs) and version details via socket communication, conditional on the absence of a specific configuration file.
def main(): sock = socket.create_connection(("localhost", 13666)) sock.sendall("hello\n".encode()) while True: hello_screen(sock) version_screen(sock) if not os.path.exists('/usr/local/etc/veritawall-lcd-simple'): cpu_screen(sock) ram_screen(sock) ...
def preorder_print(self, start, traversal): """Root => Left => Right""" if start: traversal += (str(start.value) + "-") traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) return traversal def inorder_print(self,start, traversal):...
The code defines a method `print_tree` that performs tree traversal based on the specified type (`preorder`, `inorder`, or `postorder`). It delegates to corresponding private methods (`preorder_print`, `inorder_print`, `postorder_print`), passing the tree's root node and an empty string. If an invalid traversal type is...
def print_tree(self, traversal_type): if traversal_type == 'preorder': return self.preorder_print(tree.root, "") elif traversal_type == 'inorder': return self.inorder_print(tree.root, "") elif traversal_type == 'postorder': return self.postorder_print(tree.root, "") else: ...
def transform_Board(sudoku): board = np.ones((9, 9, 9), dtype=int) # Initialize a 3D array with all possibilities set to 1 for x in range(9): for y in range(9): if sudoku[x][y] != '?': # If a value is given in the Sudoku puzzle, set the corresponding possibility array to all...
The code implements a backtracking algorithm to solve a constraint satisfaction problem (e.g., Sudoku) on a board. It recursively attempts values in empty cells, checks validity, and tracks steps taken (numSteps) and backtracking instances (backTrackSteps). If a solution is found, it returns True with updated parameter...
def solve_backtrack_FC(board, numSteps, backTrackSteps): if numSteps == 0: # print('Transforming...') board = transform_Board(board) if not check_Init_Board(board): print("Check Init") return (False, numSteps, backTrackSteps, board) print_board(board) ...
def augment(self, root: Optional[TreeNode]) -> TreeNode: if root == None: return root root.val = [root.val,self.nodeCount] self.nodeCount += 1 if root.left != None: root.left = self.augment(root.left) if root.right != None: root.right = self.au...
The code computes the maximum path sum in a binary tree. It uses dynamic programming with two arrays (`maxSumDown` and `maxSumTouch`) to track the maximum sum of paths extending downward from each node and the maximum sum of paths passing through each node, respectively. After augmenting the tree nodes and performing p...
def maxPathSum(self, root: Optional[TreeNode]) -> int: self.nodeCount = 0 self.maxSumTouch = [-10000 for i in range(30005)] self.maxSumDown = [-10000 for i in range(30005)] root = self.augment(root) self.maxsumdown(root) self.maxsum(root) # print(self.maxSumDown...
def initialize(): global model global intents global lemmatizer global words global classes words=pickle.load(open('words.pk1','rb')) classes=pickle.load(open('classes.pk1','rb')) lemmatizer=WordNetLemmatizer() model=load_model('chatbot_modecrush.h5') intents=pickle.load(open('sa...
The code processes an input question by initializing a system, predicting its intent class, and retrieving a corresponding response based on predefined intents. The main task is to classify user input and generate an appropriate reply using a pre-trained model and response mapping.
def getReplyForInputQuest(inputquest): initialize() ints=predict_class(inputquest) res=get_response(ints,intents) return res
def initialize(): global model global intents global lemmatizer global words global classes words=pickle.load(open('words.pk1','rb')) classes=pickle.load(open('classes.pk1','rb')) lemmatizer=WordNetLemmatizer() model=load_model('chatbot_modecrush.h5') intents=pickle.load(open('sa...
This code processes user input by initializing a model, predicting the intent of the input question, and generating a response based on the predicted intent using predefined intents and responses.
def getReplyForInputQuest(inputquest): initialize() ints=predict_class(inputquest) res=get_response(ints,intents) return res
def can_place(self,row,col): for i in self.get_consecutive((row,col)): if i > 0: return True return False def get_consecutive(self, pos): consec = [] for dir in EIGHT_DIRECTIONS: consec.append(self.go_in_direction(pos,dir)) return consec de...
This function places a piece at (row, col) if valid, updates scores by flipping opponent's pieces in all directions, and switches the current player. It calculates consecutive pieces in eight directions, adjusts scores accordingly, and executes flips.
def place(self, row, col): if self.can_place(row,col): dictionary = dict(zip(EIGHT_DIRECTIONS, self.get_consecutive((row,col)))) self.score[self.get_other_player()] -= sum(dictionary.values()) self.score[self.get_current_player()] += sum(dictionary.values())+1 for...
def remove_subs(data): ndata = {} for key, value in data.items(): if isinstance(value, list):continue if isinstance(value, dict):continue ndata[key]=value return ndata def add_relationships(parent_data, child_data, parent_label, child_label): global global_cnt parent_node = c...
This function recursively processes JSON data to create nodes and relationships by traversing nested dictionaries and lists. It modifies labels based on key names, handles plural/singular forms, and establishes connections between parent and child nodes using predefined rules. Relationships are added when valid data an...
def process_json(label, data, parent_label=None, parent_data=None): """Recursively process JSON to create nodes and relationships.""" only_data = None doit = False if isinstance(data, dict): if 'id' in data: only_data = remove_subs(data) #create_or_update_node(label, only...
def _contains_sub_select(item): """ check whether an parsed item is a query DML statement :param item: the parsed item :param ctx: the context object :return: True or False """ if not item.is_group: return item.ttype is DML and item.value.upper() == 'SELECT' for sub_token in item...
The function parses a SQL SELECT statement into a sequence of operators representing query components like projections, joins, filters, and sorting. It extracts clauses (SELECT, FROM, WHERE, GROUP BY, etc.), validates the statement structure, and constructs an operator list for data processing. The result is a structur...
def _parse_select(stmt: Statement): """ parse the select query to get the result dataframe :param stmt: the query statement :return: the result dataframe """ assert _contains_sub_select(stmt), 'only the select statement is supported' pos = 0 proj_columns, pos = _parse_select_clause(stmt...
def combine_bib(self, folder): db = BibDatabase() db.entries = self.prune_bib(self.read_bib(folder)) writer = BibTexWriter() writer.indent = ' ' # indent entries with 4 spaces instead of one # writer.comma_first = True # place the comma at the beginning of the line ...
This code processes academic documents by unzipping files, organizing content, modifying LaTeX structures, and cleaning up files. It converts individual papers into chapters, adjusts references and paths, extracts abstracts, and ensures only necessary files remain for compilation into a cohesive document.
def __init__(self, root_folder, mode=None): self.root = root_folder self.chapters = [] self.folders = [] self.types = {'plots': ['.png', '.jpg'], 'tex': ['.tex'], } if mode == 'clear_folder': # remove all non-zip folders for f in os.scandir(root_folder):...
def sent_tokenize(text): sents = nlkt_sent_tokenize(text) sents_filtered = [] for s in sents: sents_filtered.append(s) return sents_filtered def cleanup_sentences(text): stop_words = set(stopwords.words('english')) sentences = sent_tokenize(text) sentences_cleaned = [] for sent i...
This code generates a summary by selecting top sentences from the input text based on their similarity to a centroid embedding derived from TF-IDF keywords. It calculates sentence embeddings, scores them against the centroid, sorts them, and filters redundant sentences to ensure diversity, ultimately combining the top ...
def summarize(text, emdedding_model, tokenizer, layers): raw_sentences = sent_tokenize(text) clean_sentences = cleanup_sentences(text) centroid_words = get_tf_idf(clean_sentences) word_vectors = word_vectors_cache(clean_sentences, emdedding_model, tokenizer, layers) # Centroid embedding representati...
def partition_data(documents, summaries): return shuffle(documents, summaries, random_state=0)[:100] def cleanup_sentences(text): stop_words = set(stopwords.words('english')) sentences = sent_tokenize(text) sentences_cleaned = [] for sent in sentences: words = nlkt_word_tokenize(sent) ...
The code validates a summarizer by evaluating ROUGE-1 and ROUGE-L scores across different threshold values (0.75, 0.85, 0.95). It partitions documents and summaries, generates summaries using Word2Vec, computes scores for each threshold, and returns average metrics. The goal is to assess summarizer performance based on...
def perform_validation(documents, summaries): document_subsets, summary_subsets = partition_data(documents, summaries) rouge_1_scores = {} rouge_l_scores = {} thresholds = [0.75, 0.85, 0.95] for threshold in thresholds: rouge_1s = [] rouge_Ls = [] print('Performing validation...
def make_triangle(self: Matrix) -> Matrix: current = 0 for col in range(self.width): for row in range(current + 1, self.height): self.gcd_rows(current, row, col) if self.data[current][col] == 0: continue current += 1 if curr...
This code transforms a matrix into the identity matrix using Gaussian elimination. It first creates a triangular form, then scales rows to make leading entries 1, and eliminates other entries in the same column via row operations.
def make_perfect(self: Matrix) -> Matrix: self.make_triangle() for i in range(self.height): for col in range(self.width): if self.data[i][col] == 0: continue self.multiply_row(i, Fraction(1, self.data[i][col])) for j in rang...
def __command_up_key(self): with self.write_lock: if self.history_tail_index > 0: self.history_tail_index -= 1 self.update_input_buffer(self.history[self.history_tail_index]) def __command_down_key(self): with self.write_lock: if len(self.history) ...
This function handles keyboard stroke events by mapping specific key inputs (UP, DOWN, LEFT, RIGHT, DELETE) to corresponding command methods. It uses a read lock to safely process input and logs unhandled characters with their UTF-8 encoding.
def handle_stroke(self, char): with self.buffer_lock.for_read(): if char == key.UP: # up self.__command_up_key() elif char == key.DOWN: # bottom self.__command_down_key() elif char == key.LEFT: # left self.__command_left_key(...
def __write_input(self, append=''): with self.write_lock: self.__clear_input() with self.buffer_lock.for_read(): self.last_line = self.label_colored + self.read_buffer + append sys.stdout.write(self.last_line) self.__move_cursor(self.last_l...
This function handles real-time input processing in a thread, reading characters, managing a buffer with locking, handling deletions, line feeds, and interruptions. It updates the buffer, cursor position, and display, while capturing errors and handling keyboard interrupts to clear input or signal interruptions.
def thread_read(self): self.__write_input() try: while True: try: char = readkey() except KeyboardInterrupt: with self.buffer_lock.for_read(): self.read_interrupted_buffer = self.read_buffer ...
def predict(self, neighbors): if self.classification: px = self.classify(neighbors) # classify based on neighbors else: px = self.regression(neighbors) # gets regression estimate return px def correct(self, prediction, actual): if self.classification: ...
The code evaluates a model's performance by calculating distances between test and training data (using VDM for discrete or Euclidean for continuous), identifying k nearest neighbors, predicting outcomes, and returning accuracy/error metrics. It iterates through test data, computes distances, sorts neighbors, predicts,...
def performance(self, test, train): # initializes testing and training vectors and list to capture performance of each element testV = np.array(test.to_numpy()) trainV = np.array(train.to_numpy()) tPerf = [] # goes through all elements of test data if self.discrete: ...
def predict(self, neighbors): if self.classification: px = self.classify(neighbors) # classify based on neighbors else: px = self.regression(neighbors) # gets regression estimate return px def correct(self, prediction, actual): if self.classification: ...
The code implements a k-Nearest Neighbors (k-NN) classifier. It prepares training and test data, computes distances (Euclidean for continuous, VDM for discrete), identifies k nearest neighbors, predicts class labels, and evaluates performance (accuracy/MSE). It supports tuning, mean-based training, and visualization vi...
def KNN(self, tune=False, means=False, video=False): if tune: # uses tuning sample if tuning test = self.tune else: # uses 10th sample for test if being run normally test = self.samples[9] self.train = pd.concat(self.samples[0:9]) # intializes global training data ...
def tuneK(self): tune = {} self.train = pd.concat(self.samples) for k in range(1,50,5): # range to try self.k = k # setting k performance = self.KNN(tune=True) # getting perf tune[k] = performance # adding result kk = max(tune, key=tune.get) # ge...
This function tunes hyperparameters (K, bandwidth, epsilon) for different datasets. It sets specific values for 'abalone.data' and 'forestfires.data', defaults to K=1 otherwise. If classification is enabled, it tunes only K; otherwise, it adjusts K, bandwidth, and epsilon, returning tuned values and performance metrics...
def tuneit(self,test=False): if self.name == 'abalone.data': self.k = 68 self.bandwith = 10 self.eps = 0.01 return "K, Bandwith: ",self.k,self.bandwith," epsilon: " + str(self.eps) #elif self.name == 'machine.data': # self.k = 27 # se...
def getWebpageContent(url): driver=configSelenium() try: driver.get(url) driver.implicitly_wait(0.5) except exceptions.StaleElementReferenceException as e: print(e) pass title = driver.title pageHtmlContent = driver.page_source #pageTextualContetnts = get_text(p...
The main task of the code is to extract and process structured data from a webpage (Oracle Cloud Functions) by fetching its content, filtering tags, traversing and cleaning the JSON structure, collecting relevant items into a list, generating a summary from context, and saving the processed JSON data to a file. The wor...
def main(): result_list=[] context="" #url="https://www.ah.nl/producten/product/wi495314/chiquita-bananen-family-pack" #url = "https://www.jumbo.com/producten/jumbo-carpaccio-roast-met-italiaanse-kruiden-pesto-en-kaas-ca-600g-572312KGR" #url= "https://aws.amazon.com/athena/?nc2=h_ql_prod_an_ath" ...
def load_data(train_path, labels_map): np.random.seed(1) train_images = [] train_labels = [] shape = (40, 40) for filename in os.listdir(train_path): name, res = filename.split(".")[0], filename.split(".")[1] if res == "jpg": img = cv2.imread(os.path.join(train_path, fi...
The code prepares datasets for training and evaluating multiple machine learning models on a classification task. It loads training and test data, splits them into training/validation sets, combines additional training data with the original, and iterates through models to run them on the prepared datasets for evaluati...
def run(): labels = { "banana": 1, "apple": 0, #"mixed": 2, "orange": 2, } X, Y = load_data("classification/data/train", labels) x_train, x_val, y_train, y_val = train_test_split(X, Y, random_state=1) X, Y = load_data("classification/data/test", labels) x_trai...
def initial_fireflies(swarm_size=10, dim=dimension): position = pd.DataFrame(np.zeros((swarm_size, dim))) position['Fitness'] = 0.0 temp = weights temp.append(0.0) p = pd.DataFrame(np.array(temp)) for i in range(0, swarm_size): position.iloc[i] = p[0] position.iloc[i, - ...
The code implements the Firefly Algorithm for optimization, where a swarm of fireflies iteratively updates their positions based on light intensity (fitness) comparisons. It aims to find the optimal solution by moving fireflies toward brighter ones, adjusting positions using parameters alpha_0, beta_0, and gamma over a...
def firefly_algorithm(swarm_size=10, dim=dimension, generations=50, alpha_0=0.2, beta_0=1, gama=1): count = 1 position = initial_fireflies(swarm_size=swarm_size, dim=dim) best_firefly = destination_position(dimension=dim) while (count <= generations): print(count) for i in range(0, swarm...
def cost_function(P, x, t): Nx = np.size(x) # Number of elements in x array. Nt = np.size(t) # Number of elements in t array. # Initialize cost function with 0. cost_sum = 0 # function that computes jacobian matrix, constructed from the cost fucntion # (matrix with all possible partial deriva...
The code trains a deep neural network (DNN) to approximate solutions to a partial differential equation (PDE) using gradient descent. It initializes network parameters, computes the cost function, and iteratively updates weights/biases to minimize the mean squared error (MSE) between the DNN's predictions and an analyt...
def solve_pde_deep_neural_network(x,t, num_neurons, num_iter, lmb, mse): Nx = np.size(x) # Number of elements in x array. Nt = np.size(t) # Number of elements in t array. # Number of hidden layers. N_hidden = np.size(num_neurons) # Set up initial weigths and biases # Initialize the list of p...
def get_page_obj(url): error_count = 0 error = True page_obj = None while error and error_count < 3: try: r = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=30) r.encoding = "utf-8" page = r.text page_obj = BeautifulSoup(page, "lx...
The code scrapes product data from a webpage, extracting title, categories, tags, images, description, weight, and price. It writes this information into an Excel file while handling exceptions for missing elements. The function tracks progress using a counter and ensures data is properly formatted and stored.
def scrape_product(link, counterr): page_obj = get_page_obj(link) if page_obj is None: return try: prod_title = page_obj.find("h1", attrs={"id": "itemTitle"}) #.text.strip() prod_title.find("span").decompose() prod_title = prod_title.text.strip() categories_list, tags...
def get_most_specific_types(types, type_hierarchy): """Filters a set of input types to most specific types w.r.t the type hierarchy; i.e., super-types are removed.""" filtered_types = set(types) for type in types: type_path = get_type_path(type, type_hierarchy) for supertype in type_path...
The code evaluates a system's predicted outputs against ground truth by calculating accuracy for category predictions and NDCG@5/NDCG@10 scores for type rankings, with special handling for resource types using a type hierarchy to assess specificity and relevance. It aggregates results across questions and prints overal...
def evaluate(system_output, ground_truth, type_hierarchy, max_depth): """Evaluates a system's predicted output against the ground truth. Args: system_output: Dict with the system's predictions. ground_truth: Dict with the ground truth. type_hierarchy: Dict with the type hierarchy. ...
def load_type_hierarchy(filename): """Reads the type hierarchy from a TSV file. Note: The TSV file is assumed to have a header row. Args: filename: Name of TSV file. Returns: A tuple with a types dict and the max hierarchy depth. """ print('Loading type hierarchy from {}... '....
The main task of the code is to evaluate a system's performance by comparing its output against ground truth data using a type hierarchy. It loads the type hierarchy, ground truth labels, and the system's predictions, then assesses accuracy based on type relationships and depth constraints.
def main(): type_hierarchy, max_depth = load_type_hierarchy('Evaluation/dbpedia_types.tsv') ground_truth = load_ground_truth('data/smarttask_dbpedia_test.json', type_hierarchy) system_output = load_system_output('Results/system_output_json.json') evaluate(system_output, ground_truth, type_hierarchy, max...
def _input(self): if self.is_taking_damage: return keys = pygame.key.get_pressed() if keys[self.keyboard.up] and self.jumps < self.max_jumps and not self.shooting and not self.is_sliding: self._jump() if not self.is_sliding: idleShooting = self.status == (('lef...
This code updates a game entity's state by handling input, updating cooldowns/timers, animating, applying horizontal and vertical movement to objects, and adjusting direction if the entity is taking damage.
def update(self, objects:pygame.sprite.Group): self._input() self._update_cooldowns_and_timers() self._animate() self._apply_horizontal_movement(objects) self._apply_vertical_movement(objects) if self.is_taking_damage: self.direction.x -= self.direction.x ...
def reconstruct_path(previous, current, max_path=10000): """ Reconstruct the steps in an A* path Keyword Arguments: previous -- dictionary matching a node to the node before it : tuple dictionary current -- tuple with (x,y) : tuple max_path -- length of the maximum path : int """ total_path = [current]...
The code implements the A* pathfinding algorithm to find the shortest path from a start point to a goal on a grid. It uses a heuristic function to estimate costs, maintains open and closed sets for node exploration, and updates path costs (g_score and f_score). The algorithm reconstructs the path if the goal is reached...
def astar(start, goal, h_score, grid, max_iterations = 1000, trtl = None, cell_scale = 0.5, offset = 100): """ Find a path from start to goal Keyword Arguments: start -- start point (tuple with x y coordinates) : tuple goal -- end point (tuple with x y coordinates) : tuple h -- heuristic function : functio...
def _gini_impurity(self, data): if data.empty: return 0 p = data.value_counts().apply(lambda x: x/len(self.data)).tolist() # binary classification means two resultant probabilities whose sum is 1; p*(1-p) is identical for both cases # therefore, we can simply double the va...
This method trains a decision tree model by assigning input data and target variable, computing Gini impurity, identifying optimal splits, and creating branches if depth constraints allow. It stores data, target, independent features, and split criteria, halting further branching when maximum depth is reached.
def fit(self, data, target): """ Derive and self-assign (training) data, target attribute, and independent attribute names. data: pandas.core.frame.DataFrame target: string """ if self.depth <= self.max_depth: print(f'processing at depth: {self.depth}') ...
def abs_sobel_thresh(self, img, orient='x', sobel_kernel=3, thresh=(0,255), method='gray'): """ Edge detection in x or y direction with according color transformation in certain threshold region Input: RGB image 'img', the detection direction 'orient', filter size 'sobel_kernel', ...
The code applies gradient and color-based filters to an RGB image using HLS, HSV, and LAB color spaces to detect lane lines. It combines Sobel thresholds, magnitude/direction gradients, and color masks for white/yellow lanes, producing a binary image highlighting potential lane regions. The function returns the combine...
def grad_color_filter (self, image, imagenorm): """ Filter and color transformation showing most promising results Input: RGB Image 'image' Output: Binary filtered image 'combined' """ ### First filter definition based upon the l-layer of hls transformation ...
def populate_celltype_composition_data(result_dict, df): dict_cc = result_dict['celltype_composition'] dict_cc['title'] = ' - '.join(df.columns.values) edges = set([]) stacks = [] all_elems = set([]) for row in df.values: prev_item = None stack_idx = 0 for item in row: ...
This function populates visualization data into `result_dict` based on the `config_key`, using specific helper functions to process the input dataframe (`df`). It initializes entries for each visualization type in `VIZZES`, updates `result_dict` with processed data, and adds the dataframe to `file_name2df` for certain ...
def populate_data4viz(config_key, result_dict, df, separator, file_name2df): for viz in VIZZES: if viz not in result_dict: result_dict[viz] = {} if config_key == 'celltype_composition': populate_celltype_composition_data(result_dict, df) elif config_key == 'microenvironments': ...
def get_forecast(bank_branch): path='../src/Datasets/'+bank_branch+'_forecasts.xlsx' df=pd.read_excel(path) arr= df.to_numpy() return arr def get_drain_out_day(forecast): drain_out_map=[] temp=curr_money for i in range(0,7): temp=np.subtract(temp,forecast[i]) em_list=[] ...
The code retrieves a forecast for a bank branch, calculates daily drain values, gathers combination days, and executes an optimization process using these data. The main task involves analyzing forecasted data and optimizing operations based on drain values and combination days.
def main(args): forecast=get_forecast(args.bank_branch) drain_arr=get_drain_out_day(forecast) mega_set=get_all_comb_days() print(forecast) print( " drain value ", drain_arr) # total_rep_amount(1,4,drain_arr,forecast) solve_mega_optimisation(forecast,drain_arr,mega_set)
def build_dataset_dir(dataset): return "/flownote/input/{}".format(dataset["slug"]) def run_cmd(cmd, err = "Unknown"): exit_code = os.system(cmd) if exit_code != 0: eprint("FLOWNOTE-ERROR: {}\n".format(err)) if exit_code > 127: exit_code = 1 sys.exit(exit_code) return exit_code def unzip(files): ...
The code downloads a dataset specified in `ds` using either HTTP or Git protocol. For HTTP, it downloads a ZIP file, extracts it, and removes the ZIP. For Git, it clones the repository and runs `dvc pull`. It returns the dataset directory path after processing.
def download(ds): downloadOption = ds["downloadOption"] dataset_dir = build_dataset_dir(ds) dataset_file = "{}/{}.zip".format(dataset_dir, ds["id"]) if downloadOption["protocol"] == "HTTP": run_cmd("mkdir -p {} && wget '{}' -O '{}'".format(dataset_dir, downloadOption["url"], dataset_file)) unzip([datas...
def find_datasource_by_id(datasource_id): query = ''' query datasourceById($id: ID!) { datasource(id: $id) { id title type defaultUser defaultPassword databaseName secretName host port bigQueryProject bigQueryDataset ...
This function retrieves a datasource by ID and returns either its JSON description or connection string based on the 'cmd' parameter, then exits the program.
def datasources(params): datasource = find_datasource_by_id(params.id) result = '' if params.cmd == 'desc': result = json.dumps(datasource, indent=2) if params.cmd == 'connection_string': result = generate_datasource_connection_string(datasource) oprint(result) return sys.exit(0)
def request_datasets(dataset_ids): query = """ query($filter: ContentListFilterInputType) { datasetsPaginate(filter: $filter) { data { id slug downloadOption { url protocol } } } } """ variables = { "filter": { "id...
The code retrieves datasets using given IDs, checks for download URLs, downloads each valid dataset, collects their directories, prints them as a comma-separated string, and returns the list of directories. It exits with an error if no datasets are found.
def pull_datasets(dataset_ids): dss = request_datasets(dataset_ids) if len(dss) == 0: eprint("FLOWNOTE-ERROR: Dataset Not Found\n") sys.exit(2) dirs = [] for ds in dss: url = ds["downloadOption"].get("url") if url: dirs.append(download(ds)) oprint(",".join(dirs)) return dirs
def request_notebook(nb_id, path): query = """ mutation($id: ID!, $uniqPath: String) { topicSnapshotCreate(id: $id, uniqPath: $uniqPath) } """ variables = { "id": nb_id, "uniqPath": path } response = request(query, variables) return response["topicSnapshotCreate"] def run_cmd(cmd, err = "Unknow...
The main task of the code is to download a Jupyter notebook from a given URL, execute it using Jupyter nbconvert, convert the output to HTML format, and optionally upload the generated HTML file to a specified destination. The function handles notebook retrieval, execution, conversion, and output management based on pr...
def run_notebook(params): url = request_notebook(params.id, params.snapshot) file_name = "{}.ipynb".format(params.id) html_file_name = "{}.html".format(params.id) run_cmd("wget '{0}' -O '{1}' && jupyter nbconvert --no-input --execute '{1}'".format(url, file_name)) if (params.output): upload_output(param...
def debug_log(image, name="Computer Vision"): if debug: cv2.imshow(name, image) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite("./logs/" + name + ".jpg", image) def perspective_transform(image): pts = np.transpose(get_shapes(image, BORDER_COLOUR_LOWER, BORDER_COLOUR_HIGHER, False...
The main task of the code is to capture and process a camera image of a board game, rotate and transform the image to isolate the board, extract piece positions, update the abstract board representation, release resources, and return the previous board state for comparison.
def update_board(self): # Capturing the image from a camera cam = cv2.VideoCapture(self.camera_index, cv2.CAP_DSHOW) retrieved, image = cam.read() if retrieved == False: raise CameraReadError("Error reading from webcam") # Rotating the image height, width, c...
def perspective_transform(image): pts = np.transpose(get_shapes(image, BORDER_COLOUR_LOWER, BORDER_COLOUR_HIGHER, False, "Border")) rect = np.zeros((4, 2), dtype="float32") a = pts.sum(axis=1) rect[0] = pts[np.argmin(a)] rect[3] = pts[np.argmax(a)] b = np.diff(pts, axis=1) rect[1] = pts[np...
The main task of the code is to test an image processing pipeline that loads an image, displays it, applies a perspective transformation, and extracts board positions and piece states. It reads an image file, visualizes the original and transformed images, and outputs the abstract board representation along with knocke...
def test_image(): # cam = cv2.VideoCapture(0) # retrieved, image = cam.read() retrieved = True if retrieved: # Showing the image before the transformation image = cv2.imread('WhiteBlue3.jpg') cv2.imshow('board.jpg', image) cv2.waitKey(0) cv2.destroyAllWindows() ...
def getInitData(url): request = requests.get(url) id_ = getId(url) isVideo_ = isVideo(url) uniqueId_ = getUniqueId(request) clientId_ = getClientId(request) gqlvars_ = getGqlVars(isVideo_, id_) query = getQuery(request) body_ = getBody(request, query) return {'Client-ID': client...
The main task of the code is to retrieve an m3u8 URL for a Twitch stream by processing an input nickname, extracting video ID and type, validating access, and generating a signed URL using tokens and signatures for stream access.
def getM3U8byInput(nickname): url = f"{ORIGIN}{nickname}" headers = getInitData(url) id, isVideo = list(reversed(["", *url.split("twitch.tv/")[-1].split("/")][-2:])) if(access:= getAccess(isVideo, id, headers)): token = access.get("value") or {} signature = access.get("signature") or {} ...
def setNickname(nickname): if(not nickname): nickname = input("Input nickname or video id. Example:" \ "\n- https://www.twitch.tv/Nickname\n- https://www.twitch.tv/videos/123456" \ "\n- Nickname\n- videos/123456\n") return nickname def setTimer(durati...
The code downloads a video stream using ffmpeg in a separate thread, managed by a timer. It fetches an M3U8 link based on a nickname, initiates the download, and monitors the process until the link expires or the specified duration elapses, ensuring graceful termination.
def download(nickname = (sys.argv[1:] or [""])[0], filename = "", duration = None): try: nickname = setNickname(nickname) timer = setTimer(duration) filename, m3u8_link = getM3U8byInput(nickname) if(m3u8_link): thread = threading.Thread(target=ffmpegstart, args=(m3u8_link...