dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def send_command(self,command): if 'PASS' not in command: print(f'< {command}') self.irc.send((command + '\r\n').encode()) def send_privmsg(self,channel,text): self.send_command(f'PRIVMSG #{channel} :{text}') def loop_for_messages(self): while True: # If you want ...
The code connects to an IRC server, authenticates using OAuth, joins specified channels, sends a greeting message to each, and starts a loop to handle incoming messages.
def connect(self): self.irc = socket.socket() self.irc.connect((self.irc_server , self.irc_port)) self.send_command(f'PASS {self.oauth_token}') self.send_command(f'NICK {self.username}') for channel in self.channels: self.send_command(f'JOIN #{channel}') s...
def mandatory_properties(self): """ MANDATORY FUNCTION.This function will compute all mandatory properties. These properties will be used for OCTP outputs and include: 1. The volume of the OCTP production run (average result of NPT run) in m^3. 2. The box size of the OC...
The function calculates self-diffusion coefficients for independent species in m²/s using mean squared displacement (MSD) data. It applies optional Yeh-Hummer (YH) corrections for system size effects, checks box size validity, and generates log-log plots of MSD vs. time. Results are stored in a DataFrame with labels in...
def self_diffusivity(self, YH_correction=False, box_size_check=False, plotting=False): """ OPTIONAL FUNCTION: The self-diffusion coefficients of the independent species are computed in m^2/s. Parameters ---------- YH_correction : Boolean, optiona...
def check_for_red_card(self): if self.cards_used >= self.deck.red_card_index: self.cards_used = 0 return True return False def placing_bets(self, window): for p in self.players: flag_to_menu = p.place_bet(window) if flag_to_menu is False: ...
The main task of the code is to manage a card game round, including checking for a reshuffled deck, handling player bets, dealing cards to players and the dealer, executing player actions, determining winners, updating scores, and resetting game states. It also includes UI updates for displaying game status, results, a...
def new_round(self, window): print("---------- NEW ROUND ----------\n") # checking for a reshuffle for the decks if self.check_for_red_card() is True: self.deck.shuffle() self.deck.place_red_card() print("deck reshuffled") draw_rotated_rectangle(...
def fetch_user( session ): check_internet() response = session.get( base_address + "/fetch_user", headers=headers ) try: response = json.loads( response.text ) except: clear_screen() print("\nError in API") input("\n\nPress Enter") return None if response['returncode']==0: return response else: ...
The function gathers user input to fetch a reporting dataset. It collects either a specified number of usernames or all users, applies an optional date filter, and calls `fetch_reporting` with the session, user list, and filter parameters to generate the report.
def fetch_reporting_caller( session ): no_of_user = input("\nNumber of User ( type ALL for all users ):") user_list = [] _filter_ = {} if no_of_user.isnumeric(): no_of_user = int(no_of_user) for i in range(no_of_user): user_list.append( input("\nEnter username:") ) elif no_of_user=="ALL": user_list = f...
def validate(self, siteswap: str) -> bool: if not any(c in siteswap for c in self.multiplex_characters): return self.vanilla_validator.validate(siteswap) if not self._valid_string_(siteswap): return False if not self.num_balls(siteswap): return False if self.collisions(siteswap): return False return True def ...
The code validates a siteswap pattern and prints its details, including validity, number of objects, and period, if valid. If invalid, it reports the error.
def print_details(self, siteswap: str) -> None: if not self.validate(siteswap): print(f"Invalid siteswap: {siteswap}") print() return print(f"Siteswap: {siteswap}") print(f"Number of objects: {self.num_balls(siteswap):0.0f}") print(f"Period: {self.period(siteswap)}") print()
def _get_vertical_animation_transition(self): """Returns the animation transition for based on whether we will vertically expand or retract.""" will_expand = not self._expanded_vertical if will_expand: if self.transition_expand_y: return self.transition_expand...
This method animates the vertical size hint (size_hint_y) of a UI component to either its minimum or maximum allowed value when vertical resizing is enabled. It cancels existing animations, validates the target y_hint value, and triggers either a standard or special-case animation to smoothly transition the size hint, ...
def _animate_height_hint(self, y_hint, *_args): """If we are allowed to resize vertically, and if the y_hint is one of the values min_y_hint or max_y_hint, then we perform the needed animation to animate to that value of y_hint. This will call self._resolve_size_hint_xy if the current si...
def underAttack(self, r, c): self.whiteToMove = not self.whiteToMove # Switching to the opponents point of view oppMoves = self.getAllMoves() self.whiteToMove = not self.whiteToMove # Switching turns back for oppMove in oppMoves: if oppMove.endRow == r and oppMove.endColo == ...
This function generates valid castling moves for the king if the current player isn't in check and has the appropriate castling rights. It checks for king-side and queen-side castling possibilities, calling respective methods to add valid moves to the list, based on the current player's turn and available castling perm...
def getCastleMoves(self, row, colo, moves): if self.underAttack(row, colo): return # You cannot castle if you are in check if (self.whiteToMove and self.currentCastlingRight.whiteKingSide) or (not self.whiteToMove and self.currentCastlingRight.blackKingSide): self.getKingSideCast...
def getAllMoves(self): moves = [] for row in range(len(self.board)): # Rows for colo in range(len(self.board[row])): # Coloumns for each row coord = self.board[row][colo] turn = coord[0] if(turn == 'w' and self.whiteToMove) or (turn == 'b' and ...
The main task of the code is to generate all valid moves by checking for checks, castling, and en passant. It iterates through potential moves, simulates each, and removes invalid ones that leave the king in check. It also determines checkmate or stalemate if no valid moves remain, then restores original game state var...
def getValidMoves(self): # Copying the current enPassant and castling rights tempEnPassantPossible = self.enpassantPossible tempCastleRights = CastleRights(self.currentCastlingRight.whiteKingSide, self.currentCastlingRight.blackKingSide, self.currentCastlingRight.whiteQueenSide, self.cur...
def color_print(str, color): red = "\033[31m" green = "\033[32m" yellow = "\033[33m" blue = "\033[34m" white = "\033[39m" if(color == "red"): __prt_clr_help(str,red) elif(color == "green"): __prt_clr_help(str,green) elif(color == "yellow"): __prt_clr_help(str,yell...
The code performs validation checks on Git, CMake, and the compiler, with optional Vulkan validation based on the `min_validation` flag. It sets `self.has_been_run` to True, executes validation methods, and updates `self.validated_all` if all checks pass. The function returns after logging validation status.
def ValidateAll(self, min_validation:bool): self.has_been_run = True if(min_validation): color_print("Starting Minimum Validation...","blue") else: color_print("Starting Standard Validation...","blue") self.ValidateGit() self.ValidateCMake() self.V...
def get_test(): global test_X global test_Y csv_reader = pd.read_csv("./test.csv", chunksize=100) Y_chunk = [] X_chunk = [] for chunk in csv_reader: for index, row in chunk.iterrows(): coordinates_match = re.match(r"\((.*),(.*)\)", row.iloc[0]) if coordinates_matc...
The main task of the code is to execute a machine learning workflow by loading test data, defining a model architecture, and generating data from a CSV file for further processing. The `main()` function orchestrates these steps, with `get_test()` handling data retrieval, `defineModel()` setting up the model structure, ...
def main(): global model get_test() defineModel() data_generator("./pixel.csv", 100)
def get_rc_for_move(self, direction): '''Get row and column differences for each direction that ship can be moved. Args: direction: direction to move fleet Returns: row_diff: units to be added to row coordinate col_diff: units to be added to column coordinate ...
This function moves a fleet of ships in the specified direction (N, S, E, W) by updating their coordinates. It checks if new positions are valid (on-board and unoccupied), reverting to original coordinates if invalid. Valid moves update the grid and track ship positions, while invalid moves preserve previous states. Th...
def move_ships(self, direction): '''Move fleet one unit in direction specified by player. Args: direction: N, S, E, W direction input by user ''' rd, cd = self.get_rc_for_move(direction) shipinfo_local = self.shipinfo.copy() if rd != 0 or cd != 0: ...
def train_one_epoch(self): ''' Train the model for 1 epochs ''' self.model.train() train_pbar = tqdm(enumerate(self.train_loader), total=(len(self.train_loader))) train_preds, train_targets = [], [] for idx, cache in train_pbar: inputs = s...
This function trains a model for a specified number of epochs, performing training and validation each epoch. It computes metrics (precision, recall, F1, AUC, MCC) for both training and validation sets, tracks the best validation F1 score, and saves the model checkpoint if a directory is provided. The function returns ...
def fit(self, epochs: int = 70, checkpoint_dir: str = None, custom_name: str = f"model.pth", track_dir: str = f'./track/', threshold: float = 0.5, ): ''' Low-effort alternative for doing the complete training and validation proc...
def output_formula(features, weights, bias): return sigmoid(np.dot(features, weights) + bias) def error_formula(y, output): return - y*np.log(output) - (1 - y) * np.log(1-output) def update_weights(x, y, weights, bias, learnrate): output = output_formula(x, weights, bias) d_error = y - output weight...
This code trains a neural network using gradient descent to classify data. It initializes weights and bias, iterates over epochs to update parameters based on computed errors, tracks training loss and accuracy, and visualizes the decision boundary, data points, and error trends over time.
def train(features, targets, epochs, learnrate, graph_lines=False): errors = [] n_records, n_features = features.shape last_loss = None weights = np.random.normal(scale=1 / n_features**.5, size=n_features) bias = 0 for e in range(epochs): del_w = np.zeros(weights.shape) for ...
def get_pmids( response): """ Function tha get the pmids from a make_response :param response: The response to get the pmcids :return: The list of pmids fetched """ pmids = [] for post in response.xpath('//channel/item'): pmids.append( post.xpath('link//text()')...
The code parses a response to extract PMIDs, then fetches abstracts and full articles from the NCBI PubTator API using these PMIDs, storing the retrieved data into a SQLite database for later use.
def parse(self, response): url = "https://www.ncbi.nlm.nih.gov/research/pubtator-api/publications/export/biocjson" database_manager = Manager(os.getcwd() + '/data/database/data.db') pmids = get_pmids(response) if pmids: get_abstract_articles(pmids, url, database_manager) ...
def post_summoner(self, summoner) : print(summoner) body = { "id" : summoner['id'], "accountid" : summoner['accountId'], "puuid" : summoner['puuid'], "name" : summoner['name'], "profileiconid" : summoner['profileIconId'], "revision...
This function processes each participant in a League of Legends match, extracting statistics, runes, and styles. It uses the Riot API to fetch summoner data, checks for existing league and champion mastery records, and either posts new or updates existing match participant records in a database, ensuring data synchroni...
def post_matchParticipants(self, match) : for participant in match['info']['participants'] : styles = [] runes = [] for style in participant['perks']['styles'] : styles.append(style['style']) for style in participant['perks']['styles'] : ...
def post_match(self, match) : body = { 'matchid' : match['metadata']['matchId'], 'gamemode' : '{mode}'.format(mode=match['info']['gameMode']), 'gameduration' : match['info']['gameDuration'], 'gamename' : match['info']['gameName'], 'gametype' : match['i...
The main task of the code is to post comprehensive match data by sequentially invoking three methods: `post_match`, `post_matchTeams`, and `post_matchParticipants`, each handling specific aspects of the match information. The method returns `True` to indicate successful execution of all data posting operations.
def post_all_match_data(self, match) : self.post_match(match) self.post_matchTeams(match) self.post_matchParticipants(match) return True
def Read_JSON(jsonFile="POI_Trentino.json"): #2892 column_names = ['ATT:Id','ATT:Name','ATT:ParkingArea','ATT:Description','ATT:Type','COM:Id','COM:Name','COM:OpeningHours','COM:Price','COM:Telephone','COM:Url','LOC:Id','LOC:Latitude','LOC:Longitude','ADD:Id','ADD:City','ADD:Commune','ADD:PostalCode','ADD:Provi...
The main task of the code is to merge multiple datasets (a JSON file and several CSV files) into a unified dataset. It reads a JSON file, modifies its schema, then iterates through a list of CSV files, processes each by adjusting their schemas, and merges them sequentially into the initial JSON dataset. The final merge...
def mergeAllDatasets(jsonDataset="POI_Trentino.json", csvList="csv.txt", csvFolder="./CSV_POI/"): #open the JSON dataset, modify its schema and store it in the dictionary dataset= Read_JSON(jsonDataset) #read the CSVs, modify their schema and store them in the dictionary csvList = cf.getListCSV(csvList)...
def generate_sample_points(points_X, points_Y): '''Generate 100 sampled points for a gesture. In this function, we should convert every gesture or template to a set of 100 points, such that we can compare the input gesture and a template. :param points_X: A list of X-axis values of a gesture. :par...
The main task of the code is to process gesture coordinates from input data, generate sample points, prune templates, calculate shape and location scores, integrate them to determine the best matching word, and return the result with processing time. It performs gesture recognition by comparing input gestures against t...
def shark2(): start_time = time.time() data = json.loads(request.get_data()) gesture_points_X = [] gesture_points_Y = [] for i in range(len(data)): gesture_points_X.append(data[i]['x']) gesture_points_Y.append(data[i]['y']) gesture_points_X = [gesture_points_X] gesture_poin...
def df_header_to_snake(df: pd.DataFrame) -> pd.DataFrame: df = df.copy() df.columns = [str_to_snake(x) for x in df.columns] return df def _delete_added_entries(added_entries: dict): import lamindb as ln for table_entries in added_entries["entries"].values(): for entry in table_entries: ...
This function inserts all rows of a DataFrame into LaminDB by mapping DataFrame columns to a SQLModel table's fields, handling column renaming, data formatting, and error rollback. It returns a dictionary containing column mappings and the added database entries, grouped by table name.
def add_from_df( df: pd.DataFrame, table: sqm.SQLModel, column_map: dict = None ) -> Dict[str, Dict]: """Quick-insert all rows of a DataFrame as entries into LaminDB.""" import lamindb as ln added_entries = {"mappings": {}, "entries": {}} # type: ignore # Rename columns df_temp = df.copy() ...
def df_header_to_snake(df: pd.DataFrame) -> pd.DataFrame: df = df.copy() df.columns = [str_to_snake(x) for x in df.columns] return df def get_sample_table(sample: str) -> sql.schema.Table: """Get a single sqlalchemy table for the sample of interest.""" tables = get_sql_tables(sample) if not tabl...
This function maps columns of an input DataFrame to corresponding LaminDB tables by converting column names to snake case, identifying foreign key relationships in a target table, and matching columns to associated tables. It returns a dictionary linking DataFrame columns to their respective SQL tables based on name ma...
def map_cols_to_tables( df: pd.DataFrame, target_table: str ) -> Dict[str, sql.schema.Table]: """Map df columns to LaminDB tables associated with columns from input table.""" mapping = {} temp_df = df_header_to_snake(df) sample_table = get_sample_table(target_table) sample_fk_tables = get_sql_fk...
def map_cols_to_tables( df: pd.DataFrame, target_table: str ) -> Dict[str, sql.schema.Table]: """Map df columns to LaminDB tables associated with columns from input table.""" mapping = {} temp_df = df_header_to_snake(df) sample_table = get_sample_table(target_table) sample_fk_tables = get_sql_fk...
The main task of the code is to process a pandas DataFrame by mapping its columns to target database tables, insert the data into relevant tables, and return mappings and added entries. It handles errors by cleaning up inserted data if exceptions occur, ensuring data integrity during the insertion process.
def parse_and_insert_df(df: pd.DataFrame, target_table: str) -> Dict[str, Dict]: added_entries = {"mappings": {}, "entries": {}} # type: ignore try: # insert columns into relevant tables mapper = map_cols_to_tables(df, target_table) added_entries = _add_columns(df, mapper) df = ...
def input_pre_handling(): """ Parse arguments from command line :return: (job_id, storage) :rtype: tuple[basestring, basestring] """ assert len(sys.argv) >= 2, 'Not enough arguments' job_id = str(sys.argv[1]) storage_mod = '' if len(sys.argv) <= 2 else str(sys.argv[2]) return job_id, storage_mod def save_env...
The main task of the code is to process a job by downloading its archive from a specified storage module, executing the job's startup script, and uploading the results. It handles input preprocessing, environment setup, storage module auto-update, archive extraction, job execution, and result uploading, with detailed e...
def main(): global storage job_id, storage = input_pre_handling() if not save_env(): log.error('Saving ENV vars failed') if not storage: out_print('no storage module specified, running legacy /run.sh for backward compatibility.') return shell_run('%s/run.sh' % os.path.dirname(__file__), [job_id]) # TODO g...
def refine_url(one_url): url_obj = urlparse(one_url) url_path = url_obj.path if len(url_path) > 0 and url_path[-1] == "/": url_path = url_path[0:-1] return url_obj.scheme + "://" + url_obj.netloc + url_path def record_url(one_url): queue.append(one_url) seen.add(one_url) def get_file_nam...
The code crawls a website, extracts text from pages, saves content to text files, manages URL queues, handles errors, and organizes data into domain-specific directories. It uses dynamic fetching, filters hyperlinks, logs errors, and ensures unique URL processing while maintaining a structured file storage system.
def crawl(url, wait_sec=0): global error_url global WAIT_SEC WAIT_SEC = wait_sec # Parse the URL and get the domain local_domain = urlparse(url).netloc url = refine_url(url) record_url(url) # Create a directory to store the text files if not os.path.exists("text/"): os.mkdi...
def set_observation_healpix(self,obs, sideHP=32768, nestedHP=True): ''' Set healpix for observations using standard parameters See original cnd.py for more details ''' obs.Healpix = hp.ang2pix(sideHP , np.radians(obs.RA) , np.radians(90.-obs.Dec), nest=nestedHP) def get_similar_o...
The function `upgraded_check_near_dups` identifies near-duplicate observations by filtering a list of previous observations (`previous_obs`) against a target observation (`target_obs`). It uses HealPix-based spatial proximity, angular separation, temporal closeness, and observatory location similarity to iteratively re...
def upgraded_check_near_dups(self,target_obs, previous_obs): ''' check for near duplicates *** THIS SHOULD PROBABLY BE IMPLEMENTED DIRECTLY IN SQL *** *** (NOT JUST AS AN IMPORTED PYTHON FUNC) *** This is rough-and-ready - Refer to the original cn...
def onMouseMove(self, event): if self.xyZkey_engine.onMove: self.xyZkey_engine.onMove(event.x, event.y) if self.xyZkey_engine.xKeyDown: if self.last_tick.x == None: return self.last_tick.__set__(event.x, event.y) if self.last_tick.hypotThreshold(self.t...
The code handles mouse events by checking the event type and delegating to specific methods: MoveEvent triggers onMouseMove, ButtonEvent with "up" triggers onMouseRelease, and "down"/"double" triggers onMousePress, enabling differentiated responses to various mouse actions.
def onMouseEvent(self, event): if type(event) == MoveEvent: return self.onMouseMove(event) elif type(event) == ButtonEvent: if event.event_type == "up": return self.onMouseRelease(event) elif event.event_type == "down" or event.event_type == "double": ...
def insertion_sort(arr, columns): """ # arr: list of sublists which consists of records from the dataset in every sublists. # columns: store the column indices from the dataframe. Finally, returns the final sorted 2D array. """ for unsorted_movie in range(1, len(arr)): index = unsorted_m...
The code reads a CSV dataset, prepares it by including the `tconst` column (index 0) and specified columns as indices, converts data into a list of sublists, and sorts it using a selected algorithm (insertion, selection, quicksort, etc.). It returns the sorting time and a list of `tconst` values from the sorted data. T...
def sorting_algorithms(file_path, columns, select): """ # file_path: a string representing the path to the CSV file # columns: a list of strings representing the columns to sort the 2D array on # select: an integer representing the sorting algorithm to be used # colum_vals: is a list of integers re...
def getfuncHeader(name, fun, extra): retval = genfuncPrototype(name, fun) line = "" if pType(fun["ReturnType"]) == "": line = line + "void " + extra + retval else: rettype = pType(fun["ReturnType"]) if name == "GetDocPointer" or name == "GetCharacterPointer": rettype = "sptr_t " line = line + rettype + "...
The code generates C++ function implementations for Scintilla's interface by iterating over feature definitions, filtering non-deprecated functions, converting parameters (e.g., QString to QByteArray), handling type-specific encodings, and constructing method stubs with SCI_ constants and appropriate return/send statem...
def printFunctionImpl(f, out): for name in f.order: v = f.features[name] if v["Category"] != "Deprecated": if v["FeatureType"] in ["fun", "set", "get"]: header = getfuncHeader(name, v, "ScintillaIFace::") + "\n" out.write(header) out.write("{\n") line = " " endline = "" # Convert ju...
def getfuncHeader(name, fun, extra): retval = genfuncPrototype(name, fun) line = "" if pType(fun["ReturnType"]) == "": line = line + "void " + extra + retval else: rettype = pType(fun["ReturnType"]) if name == "GetDocPointer" or name == "GetCharacterPointer": rettype = "sptr_t " line = line + rettype + "...
This function generates inline function implementations for non-deprecated features in a code file. It processes comments, constructs function headers, and writes C-style function bodies with SCI_ command invocations, handling parameter types, return types, and formatting. The output includes proper indentation, commen...
def printInlineFunctionImpl(f, out): for name in f.order: v = f.features[name] if v["Category"] != "Deprecated": if v["FeatureType"] in ["fun", "set", "get"]: line = "" indent = "\t\t" indent2 = "\t\t\t" if not v["Comment"] in ["", " "]: line = indent + "/**\n"; for cline...
def Contains(s,sub): return string.find(s, sub) != -1 def printFunctionDefs(f, out): for name in f.order: v = f.features[name] if v["Category"] != "Deprecated": if v["FeatureType"] in ["fun", "set", "get"]: line = "" if not v["Comment"] in ["", " "]: line = line + " /**\n" for cline in ...
The code processes input lines, copying them to output until encountering specific comment markers (e.g., "//++EventTypes"). When such markers are found, it pauses copying and prints predefined definitions (via functions like printEventDefs) to the output. Resuming copying occurs upon encountering "//--", ensuring sele...
def genMainControl(input, output, definition): copying = 1 for line in input.readlines(): if copying: output.write(line) if Contains(line, "//++EventTypes"): copying = 0 printEventDefs(definition, output) if Contains(line,"//++EventPrivates"): copying = 0 printEventPrivates(definition, output) ...
def split_sentences(text): """ Utility function to return a list of sentences. @param text The text that must be split in to sentences. """ sentence_delimiters = re.compile(u'[.!?,;:\t\\\\"\\(\\)\\\'\u2019\u2013]|\\s\\-\\s') sentences = sentence_delimiters.split(text) return sentences def ge...
This code processes input text to extract and rank keywords. It splits text into sentences, generates candidate keywords by filtering out stop words, calculates word scores, combines them into keyword candidates, and sorts these candidates by score in descending order to return the most relevant keywords.
def run(self, text): sentence_list = split_sentences(text) phrase_list = generate_candidate_keywords(sentence_list, self.__stop_words_pattern) word_scores = calculate_word_scores(phrase_list) keyword_candidates = generate_candidate_keyword_scores(phrase_list, word_scores) sor...
def drug_search(drug_name: str): '''function searches for drug in drugbank metadata and outputs drugbank id''' for row in data: for item in row: if drug_name.lower() == item.lower(): return(row[0]) def L1000link(drug_name): '''given drug name, returns link to L1000FWD pag...
This function retrieves and summarizes drug information from DrugBank or L1000FWD databases. If the drug name is not found in DrugBank, it checks L1000FWD. It returns a formatted summary with links to relevant resources, or an error message if the drug is not found in either database.
def drug_summary(drug_name): '''function takes in drug name and outputs summary; if drug name not found in drug bank data, L1000FWD data will be searched through and outputted''' if drug_search(drug_name) == None: if (str(drug_name)).lower() in pertid.keys(): return("*Drug Summary:* " + ...
def drug_enrichment(drug_list): '''drugenrichr api that takes in user inputted drugset and outputs enrichment data''' ENRICHR_URL = 'http://amp.pharm.mssm.edu/DrugEnrichr/enrich' query_string = '?userListId=%s&backgroundType=%s' user_list_id = (drugenrichr(drug_list))['userListId'] drug_set_library ...
The function generates a horizontal bar chart visualizing the top 10 drug enrichment results from a given drug set, plotting -log10(p-values) as bar heights with color-coded significance levels. It customizes axes, labels, and text formatting, inverts the y-axis for descending p-value order, and saves the graph as a PD...
def drugenrichr_graph(drug_set): '''creates bar graph from drug set data''' data = (list((drug_enrichment(drug_set)).values()))[0] data.sort(key= lambda x: x[2]) name = [item[1] for item in data][:10] pvalue = [item[2] for item in data][:10] convertedpvalues = [numpy.negative(numpy.log10(item)) ...
def drug_enrichment2(drug_list: list, library: str): '''drugenrichr api that takes in user inputted drugset and library and outputs enrichment data''' ENRICHR_URL = 'http://amp.pharm.mssm.edu/DrugEnrichr/enrich' query_string = '?userListId=%s&backgroundType=%s' user_list_id = (drugenrichr(drug_list))['u...
The main task of the code is to generate a horizontal bar graph visualizing top 10 enriched terms from a drug set against a biological library, using -log10(p-values) as bar heights, with dynamic color coding, custom labels, and saving the plot as a PDF file.
def drugenrichr_graph2(drug_set, library): '''creates bar graph from file uploaded drug set data''' data = (list((drug_enrichment2(drug_set, library)).values()))[0] data.sort(key= lambda x: x[2]) name = [item[1] for item in data][:10] pvalue = [item[2] for item in data][:10] convertedpvalues = [...
def create_druglist(text): '''takes in text and outputs formatted list of drugs that can be analyzed by drugenrichr''' if type(library(text)) == list: drugs = [drug.lower() for drug in library(text)] druglist = (drugs)[1:] if len(druglist) == 1: if ' ' in druglist[0]: ...
The function processes input text to generate a drug list, performs enrichment analysis, and sends results to a Slack channel. It uploads a generated graph file to the same channel, then deletes the file and returns a 200 response.
def some_processing2(info): drugset = create_druglist(info['text']) enrichment_analysis = drugenrichr_link(drugset) channel = info['channel_id'] graph = drugenrichr_graph(info['text']) filepath = graph time.sleep(10) slack_client.chat_postMessage( channel= channel, ...
def get_file_data(id): '''load data from user uploaded files''' path3 = id file3 = open(path3, newline= "") reader3 = csv.reader(file3) header = next(reader3) data3 = [row for row in reader3] return([item for sublist in data3 for item in sublist]) def drugenrichr_link(drug_list): '''out...
The main task of the code is to process drug data by performing enrichment analysis, generate a graph, and send the results to a Slack channel. It retrieves file data, executes analysis, constructs a visualization, uploads the graph to Slack, and cleans up temporary files before returning a success response.
def some_processing3(message): file = (message.get('files'))[0] id = file['id'] drugs = get_file_data(id) enrichment_analysis = drugenrichr_link(drugs) channel = message["channel"] library2 = drug_library_name2(message) graph = drugenrichr_graph2(drugs, library2) time.sleep(10) sla...
def set_v(self, sl, sr): self.set_l(sl) self.set_r(sr) def turn(self, angle): vr = (self.hz * self.w * angle) / 2 vl = -vr self.set_v(vl, vr) def follow_circle(self, r): vl = -((self.w * (self.v_max * 0.225) * (self.hz ** 2)) / r) + self.v_max self.set_v(vl, self....
The code controls an agent's movement to navigate towards, align with, and follow a circular path by adjusting velocity and heading based on the agent's current objective state (IDLE, GET_TO_CIRCLE, ALIGN_TO_CIRCLE, FOLLOW_CIRCLE, DEBUG). It calculates distances, tangent angles, and angular differences to transition be...
def operate(self, circpos, r): if self.objective == obs.IDLE: self.set_v(0, 0) elif self.objective == obs.GET_TO_CIRCLE: dist = distance((self.x, self.y), circpos) if dist < r - 5: x = self.hz * (r - dist) self.set_v(x, x) e...
def initialize_driver(): # Configure Selenium chrome_options = Options() chrome_options.add_argument("--headless") # Run Chrome in headless mode service = Service(driver_path) driver = webdriver.Chrome(service=service) return driver def get_themes(driver): # Load the page with Selenium ...
The main task of the code is to scrape themes and their sub-themes from a website using a web driver, process the text by removing accents, and store the structured data in a JSON file. It initializes a driver, retrieves themes and sub-themes, cleans the text, and saves the results to "../data/raw_data/theme_subthemes....
def main(): logging.basicConfig(level=logging.INFO) driver = initialize_driver() try: themes = get_themes(driver) logging.info("Themes:") logging.info(themes) theme_subthemes = {} for theme in themes: sub_themes = get_sub_themes(driver, theme) ...
def startinstance(): try: initdataretptr = POINTER(tagVARIANT) startInstance = handle.startInstance startInstance.argtypes = None startInstance.restype = initdataretptr initData = startInstance() if (initData.contents.vt == VT_ERROR): raise Exception(initD...
This function retrieves financial time-series data from a FAME database using specified parameters, processes input flags to control data format (across/within columns, heading inclusion, reversal), interacts with a C library via ctypes to fetch and structure the data, then converts the result into a 2D matrix for Pyth...
def FAMEData(expression, startdate, enddate, numrecords, frequency, across, heading, ireversed): isAcross = 0 includeHeading = 0 isReversed = 0 try: global instancestarted if instancestarted is False: startinstance() instancestarted = True if (across[0])....
def primeGenerator(self,bit_length: int) -> int: range_lower_limit = pow(2, bit_length - 1) range_upper_limit = pow(2, bit_length) - 1 while True: sampled_prime = self.randomBitsGenerator(bit_length) while sampled_prime not in range(int(range_lower_limit), int(range_uppe...
The main task of the code is to implement RSA encryption by generating a 1024-bit RSA key pair (public and private keys), converting plaintext to bytes, and encrypting the data using the public key components (e=65537, n=p*q). The encrypted ciphertext is returned as the result.
def Encryption_RSA(self,plaintext): key_size = 1024 prime_number_bit_length = key_size // 2 # print(plaintext) pt_in_bytes = bytes(plaintext, 'utf-8') # print(pt_in_bytes) p = self.primeGenerator(prime_number_bit_length) q = self.primeGenerator(prime_number_bit_le...
def _investment_demand(self, q, capital): """Non-renewable energy sector demand for investment.""" demand = ((2 / 3) * (q - 1) * (1 / self._phi))**0.5 * capital return demand def _marginal_percentage_adjustment_costs(self, capital, investment): """Non-renewable sector marginal costs of c...
The function computes the time derivative of Tobin's q (q_dot), modeling its evolution based on investment demand, adjustment costs, and the marginal productivity of capital. It combines the interest rate and depreciation-adjusted q, investment-driven adjustments, and the ratio of capital's marginal product to its pric...
def equation_motion_q(self, q, capital, capital_price, energy_price, fossil_fuel_price, interest_rate): """Differential equation describing the time evolution of Tobin's q.""" I = self._investment_demand(q, capital) q_dot = ((interest_rate + self._delta) * q + self._marginal_per...
def initUi(self): self.tree = QTreeWidget(self) self.tree.setHeaderHidden(True) def initData(self): for i, parent in enumerate(self.parents): p_obj = QTreeWidgetItem(self.tree) # connect parent to treewidget p_obj.setText(0, parent['name']) p_obj.setIcon(0, self.icon_dir) # p_obj.setExpanded(True) # s...
The code initializes a class by setting up icons for UI elements, collecting parent and child objects into lists, and calling methods to initialize the user interface, data, and layout structure.
def __init__(self): super().__init__() self.icon_dir = QIcon(QPixmap("folder.png")) self.icon_logo = QIcon(QPixmap("logo.ico")) # collect the parents self.parents = [] self.parents.append(parent0) self.parents.append(parent1) # collect the children self.children = [] self.children.append(children...
def _get_model(self): """ Creates our model with access to intermediate layers. This function will load the VGG19 model and access the intermediate layers. These layers will then be used to create a new model that will take input image and return the outputs from these intermediate laye...
This code performs neural style transfer by optimizing an image to match both the content of the input image and the style of a reference image. It uses a pre-trained model to extract features, computes style (Gram matrix) and content features, and iteratively updates the image via gradient descent with Adam optimizer....
def run_style_transfer(self, content_weight=1e3, style_weight=1e-2): model = self._get_model() for layer in model.layers: layer.trainable = False # Get the style and content feature representations (from our specified intermediat...
def highestPowerof2(n): res = 0 for ii in range(n, 0, -1): # If i is a power of 2 if ((ii & (ii - 1)) == 0): res = ii break return res def myImResize(IM, sz): szin = IM.shape...
The code aligns an ensemble of 2D data fields (e.g., weather maps) by computing pairwise displacement vectors between members using image registration. It resizes each field to a power-of-2 grid, computes deformation fields via a solver, and applies these displacements to align each member to a reference frame. The res...
def computeAlignedEnsemble(niter, lscale, vmode, nlon, nlat, nmem, meml, hmemT): # Initialize the aligned ensemble hmem_FA = np.zeros((nlon,nlat,nmem)) XX = [] # Resize images loop for imem in meml: thisHmemT = hmemT[imem,:,:] if imem...
def __get_webdata_item_from_app(self, webdata_item_num: int) -> {}: print("Webdata item num - %d" % webdata_item_num) webdata_item = {} for field_name, value in self.regexp_xpath_options.items(): field = self.__find_webdata_field(webdata_item_num, field_name) if field:...
The code scrapes items from a webpage by repeatedly loading more content, appending each item to a list, and saving them if a saver is active. It uses a loop to fetch items, checks for maximum count limits, and navigates to the next page when elements are exhausted, with delays between requests to avoid overloading the...
def __find_short_items(self, website_link: str, *args) -> []: webdata_short_items = [] webdata_item_num = 1 while True: webdata_short_item = self.__get_webdata_item_from_app(webdata_item_num) webdata_short_items.append(webdata_short_item) if self.saver: ...
def __waiting_anytype_selector(self, selector: {}, wait_time: int) -> WebElement: print("Waiting for selector or XPATH has been started") if "XPATH" in selector: print("-- Waiting for XPATH %s --" % (selector["XPATH"])) try: element = WebDriverWait(self.driver, w...
This function scrapes detailed data from web items by navigating to their detail links, extracting additional information, and appending it to a list. It checks for required "detail_link" fields, handles missing links with warnings, and optionally saves results. The process stops after reaching a specified item limit o...
def __find_detail_items(self, webdata_short_items: [], *args) -> []: webdata_detail_items = [] webdata_item_num = 1 for webdata_item in webdata_short_items: if "detail_link" in webdata_item: self.driver.get(webdata_item["detail_link"]) self.__waiting_...
def __login(self, login_data: {}): print("Login to service") login_field = self.__waiting_anytype_selector(self.xpath_options["auth"]["login_xpath"], self.time_options["wait_login_form"]) pass_field = self.__waiting_anytype_selector(self.xpath_options["auth"]["password_xpath"], self.time_option...
The main task of the code is to scrape data from a website by navigating to the provided link, handling login if required, accepting cookies, retrieving list items (either from the page or preloaded data), and extracting detailed item data from those list items, finally returning the collected detailed data as a list.
def __get_data_from_app(self, website_link: str) -> []: # Step 1 self.driver.get(website_link) # Step 2 if self.login_data: self.__login(self.login_data) # The first loading for accept cookies self.__find_webdata_field(1, "item_body") # Step 3 - Li...
def __get_data_from_app(self, website_link: str) -> []: # Step 1 self.driver.get(website_link) # Step 2 if self.login_data: self.__login(self.login_data) # The first loading for accept cookies self.__find_webdata_field(1, "item_body") # Step 3 - Li...
The main task of the code is to scrape data from multiple application links provided in the `app_links` list. It iterates through each link, initiates scraping, collects data using `__get_data_from_app`, accumulates results into `__webdata_items`, and logs progress. After processing all links, it pauses for a configure...
def run(self, app_links: []): start_time = datetime.datetime.now() for app_link in app_links: print("-- Scraping has been started from: %s --" % app_link) self.__webdata_items += self.__get_data_from_app(app_link) print("-- Scraping has been finished from: %s --" % ...
def write_so(): # Read the so file's bytes. b64_so = read_so('exec.so') # The below payload will write the .so file to the /tmp directory when executed format_payload = '<?php file_put_contents("/tmp/{EXT_FILE}", base64_decode("{b64_so}")); ?>' so_payload = format_payload.format(EXT_FILE=EXT_FILE, b64_so=b64_so.d...
The code's main task is to exploit vulnerabilities by writing a shared library to /tmp, generating a FastCGI payload to bypass PHP's disable functions, writing the payload to /tmp, leveraging LFI to include the payload for RCE, and finally reading a flag written to /tmp/flag via the exploited RCE.
def main(): # write so file to /tmp directory write_so() # Generate our RCE php fastcgi payload to bypass disable functions fcgi_payload = fcgi_gen() # write the fcgi_payload to the /tmp directory write_tmp(fcgi_payload) # exploit LFI to include the php code and gain RCE exploit_lfi(SESS_FILE) # finally re...
def pcsquares(value): ''' Offer a visual representation of a number 0.0 - 1.0. Return a string with unicode representations of open and closed boxes, with each box representing the value of 0.2 (20%), rounded down. :param value: The value to be represented (float or int). ''' valuepc = value...
The main task of the code is to generate and send a detailed analysis report to a user via a bot, summarizing run metrics, quality checks, and visual data. It processes input data to calculate thresholds, formats results with status indicators, sends text and images, and concludes with a report link and end message.
def execute_report(self, bot, update, run): # TODO see flows user = update.effective_user runname = re.sub('Auto_[\w]*?_', '', run['resultsName']) run_dir_id = run['id'] if run['analysismetrics'] is None: bot.sendMessage(chat_id=user.id, text='No analysis me...
def generate_initial_population(): result = list() i = 0 while i < NUMBER_OF_POPULATION: result.append(get_random_initial_state()) i += 1 return result def is_goal(population): for individual in population: if individual.fitness > OBJECTIVE_THRESHOLD: return True ...
The code implements a genetic algorithm (GA) to optimize a population of individuals toward a goal. It iteratively evaluates fitness, selects parents via tournament selection, generates offspring through crossover and mutation, and replaces the population with the best individuals. The process repeats until the maximum...
def ensemble(): population = generate_initial_population() stepLimit = GA_STEP_LIMITATION while stepLimit > 0 and not is_goal(population): for individual in population: individual.fitness = objective_function(individual) parents = select_parents_with_tournament_selection(populati...
def _init_potential_pools(self): """ Initializes the potential pools of all columns. A potential pool is a set of input bits that a column can connect to. """ for column in range(self.number_of_columns): potential_pool_indices = self.get_potential_pool(column) ...
The code initializes neural network components by setting up potential pools, permanence values, and connected synapses, establishing the structure for learning and memory operations in the system.
def _initialize(self): self._init_potential_pools() self._init_permanences() self._init_connected_synapses()
def iterateForVstar(n, winReward, loseReward, tieReward, games, boardSize, agentSide, gamma): l = [] W = [] validStateIndices = getValidStateIndices(agentSide) #initialize the first W for i in range(len(validStateIndices)): #W.append(random.randint(100, 500)) W.append(0) l.appe...
The code computes optimal policies for a game using value iteration. It generates a list of policies by iterating over V-star values, calculating the optimal policy (pi-star) for each, and constructing full policy vectors by padding with zeros. The function returns all derived policies, starting with an arbitrary initi...
def getPoliciesValueIteration(n, winReward, loseReward, tieReward, boardSize, agentSide, gamma): games = getGames(boardSize) #get the list of V's V_stars = iterateForVstar(n, winReward, loseReward, tieReward, games, boardSize, agentSide, gamma) policies = [] #append the arbitrary policy as the...
def isComplete(): for cell in goalPuzzle: if goalPuzzle[cell] is None: return False return True def selectEmptyCell(): # Find the next cell which has the smallest domain to track. Set minSizeDomain to sqrSize+1 to make sure all domains # are considered. minSizeDomain = sqrSize+1 ...
This code implements a backtracking algorithm to solve a constraint satisfaction problem, such as a Sudoku puzzle. It recursively assigns values to empty cells, checks constraints, and explores possible solutions. If a valid configuration is found, it returns the solved puzzle; otherwise, it backtracks by resetting val...
def backTracking(problemPuzzle): if isComplete(): return goalPuzzle else: cell = selectEmptyCell() for value in cellDomain[cell]: goalPuzzle[cell] = value if checkConstraints(cell, problemPuzzle): result = backTracking(problemPuzzle) ...
def read_input(domain_for_cell, board): input_string = sys.argv[1] index_assignment = 0 for row in LIST_ROW: for col in range(1, 10, 1): board[row+str(col)] = int(input_string[index_assignment]) domain_for_cell[row+str(col)] = [] index_assignment += 1 def generate...
The code solves a Sudoku puzzle using two methods: AC3 constraint propagation and backtracking search (BTS). It first initializes domains and the board, then applies AC3 to reduce domains. If AC3 solves the puzzle, it returns the solution with "AC3" noted. If AC3 fails, it performs BTS on a copied board and domain, ret...
def solve_sudoku(): domain_for_cell = {} board = {} read_input(domain_for_cell, board) generate_domain_for_cell(domain_for_cell, board) # Make a deep copy of board and domain_for_cell for each of the method board_bst = copy.deepcopy(board) domain_for_cell_bst = copy.deepcopy(domain_for_cell)...
def Read_Corpus(path): corpus_file = open(path, 'r') lines = corpus_file.readlines() text = "" for line in lines: striped_line = line.strip() if striped_line != '': text = text + " " + striped_line return text def substitue_tokens(sentences): sub_sentences = [] fo...
The code tokenizes a corpus by reading text from a file, splitting it into sentences, replacing URL mentions with tokens, and then tokenizing each sentence into individual words or subwords, returning a list of tokenized sentences.
def tokenize_corpus(path): corpus = Read_Corpus(path) sentences = sent_tokenize(corpus) url_metions = substitue_tokens(sentences) sentence_tokenized = [] for sentence in url_metions: tokenized_sen = tokenize_sentence(sentence) sentence_tokenized.append(tokenized_sen) return sente...
def Read_Corpus(path): corpus_file = open(path, 'r') lines = corpus_file.readlines() text = "" for line in lines: striped_line = line.strip() if striped_line != '': text = text + " " + striped_line return text def substitue_tokens(sentences): sub_sentences = [] fo...
The main task of the code is to process a text corpus by reading it from a file, splitting it into individual sentences, replacing specific tokens (e.g., URLs), and tokenizing each modified sentence into a list of words or subwords. The function returns a list of tokenized sentences for further analysis or processing.
def tokenize_corpus(path): corpus = Read_Corpus(path) sentences = sent_tokenize(corpus) url_metions = substitue_tokens(sentences) sentence_tokenized = [] for sentence in url_metions: tokenized_sen = tokenize_sentence(sentence) sentence_tokenized.append(tokenized_sen) return sente...
def file_load_to_tree(path): return ET.parse(path) def get_edit_texts(package_root, parent_map): query_sentences = [] edit_text_items = [] # Loop to find all EditText views in the current view (and their corresponding input hint) for item in package_root.findall(".//node[@class='android.widget.Edit...
This function extracts and returns UI elements (edit texts, checkboxes, buttons, and clickable views) from an XML file structure based on a specified package name, aiding in automated UI testing or interaction.
def get_attributes_to_fill(path, package_name): tree = file_load_to_tree(path) print("--------------------") print(package_name) root = tree.getroot() parent_map = {c: p for p in tree.iter() for c in p} package_root = root.find(f"./node/[@package='{package_name}']") edit_texts = get_edit_...
def print_time(process=None): print((f"[{process}] " if process else "") + f"time used: ", time.time() - t_start) def ana_client_buffer(f_name, stream_data): """ Fill in init / startup / last / cum_rebuf """ last_chunk_time = defaultdict(lambda: np.nan) for df in pd.read_csv(f_name, sep=',...
The main task of the code is to automate the downloading and analysis of time-series data (video_sent, SSIM, client_buffer) from Google Cloud Storage for 60 consecutive days starting from 2021-01-01. It processes each day's data into statistical group metrics using the stream2scheme function, saves results as NumPy fil...
def main(): root = "data" Path(root).mkdir(parents=True, exist_ok=True) setting_file = "2021-03-06T11_2021-03-07T11-logs-expt_settings" timef = r"%Y-%m-%d" one_day = datetime.timedelta(days=1) curr_date = datetime.date(2021, 1, 1) for _ in range(60): try: need_files = ["...
def save_histogram(data, bins, clip, title, path, remove_zeros=False): data = data.todense().flatten() data = data[data != 0] if remove_zeros else data hist = histogram1d(data, bins=bins, range=clip) plt.ticklabel_format(style='plain') plt.title(title) plt.ylabel("Count") plt.xlabel("Values"...
The main task of the code is to analyze and visualize single-cell RNA-seq data by generating histograms for preprocessed and raw training/test datasets, and evaluating latent variable models (normal/gamma distributions) through learning curves, ELBO tables, and PCA plots to assess data characteristics and model perform...
def main(): test_data = anndata.read_h5ad("data/SAD2022Z_Project1_GEX_test.h5ad") train_data = anndata.read_h5ad("data/SAD2022Z_Project1_GEX_train.h5ad") results_path = "eval_results" os.makedirs(results_path, exist_ok=True) data_to_labels = {("preprocessed", "training"): train_data.X, ...
def take_picture(self, hull): """ returns the value of the space the robot is currently occupying """ return hull.matrix[self.y][self.x] def program_output(list_intcode, dict_intcode, instruction_pointer, base_wrapper, input_from_camera): """ produces the output of the program_li...
The code runs a robot that uses an internal Intcode program to process camera inputs of a hull's state. It determines painting colors and movement commands from program outputs, repeatedly updating the hull's appearance and position until a termination flag is triggered. The final hull state is then printed.
def run_robot(self, hull): """ robot uses it's internal intcode program as instructions input will be provided by it's camera from pictures of the hull output from the program will drive first: color to paint and second: movement """ flag = True while flag: ...
def _generate_hex(): import secrets return secrets.token_hex(16) def _write_to_redis(key, value): return RedisWrapper.set(key, value) def _write_properties_to_redis(dict_name, data: dict): for key, value in data.items(): RedisWrapper.set_dict(dict_name, key, value) def update...
The code generates a unique hexadecimal token, stores it in Redis with the provided unique identifier, writes associated properties to Redis using the token as a key, updates the token's time-to-live (TTL), and returns the generated token.
def generate_new_token(self, unique_identifier): generated_token = self._generate_hex() self._write_to_redis(unique_identifier, generated_token) self._write_properties_to_redis(generated_token, self.properties) self.update_ttl(generated_token) return generated_token
def get_htg_identifier(self): return self._HTG_PREFIX + self.unique_identifier def _get_from_redis(key): return RedisWrapper.get(key) def update_ttl(self, token): for key in self._get_redis_keys(token): RedisWrapper.set_ttl(key) def generate_new_token(self, unique_identifier): ...
The main task of the code is to retrieve or generate a token based on an HTG identifier. It first checks Redis for an existing token; if found, it updates its TTL and returns it. If not, it generates a new token and returns it, ensuring efficient token management with Redis persistence and expiration handling.
def url(self): htg_identifier = self.get_htg_identifier() existing_token = self._get_from_redis(htg_identifier) if existing_token: self.update_ttl(existing_token) return existing_token return self.generate_new_token(htg_identifier)
def __init_finger_table(self, node_id): """Initialize finger table for a node which has just joined Arguments: node_id {Integer} -- The node whose help is being taken to join """ global M n_dash = self.network_api.get_node(node_id) # Initialize first...
The code integrates a new node into a Chord network by discovering existing nodes via multicast search (up to depth 500). If a node is found, it initializes the finger table, updates network references, and transfers keys from the successor node. If no node is found, it establishes itself as the first node, setting up ...
def join(self): """Run when a new node joins the network""" global M # Discover node through which, can enter the Chord Network # Implementation for expanding multicast search - Check till depth 500 for depth in range(500): found_node = self.network_api.hop(self.get_n...
def read_gaf_line(line): Qid, Qlen, Qs, Qe = line.split("\t")[:4] Tid, Tlen, Ts, Te = line.split("\t")[5:9] Am, Alen, Aq = line.split("\t")[9:12] d = {"Qid" : Qid, "Qlen" : int(Qlen), "Qs" : int(Qs), "Qe" : int(Qe), "Tid" : Tid, "Tlen" : int(Tlen), "Ts" : int(Ts), "Te" : int(Te), ...
The code processes GAF alignment and GFA graph files to identify and store alignments informative for structural variants (SVs) based on breakpoint overlaps. It parses command-line arguments, extracts alternative node lengths from the GFA, filters alignments with sufficient nodes, checks SV overlaps using link informat...
def main(args): parser = argparse.ArgumentParser( description="---" ) parser.add_argument( "-a", "--gaf", metavar="<align_file>", nargs=1, help="align file in gaf format", required=True ) parser.add_argument( "-g", "--gfa", metavar="<g...
def get_client() -> jack.Client: _CLIENT.activate() return _CLIENT def get_default_outputs(stereo=True) -> Dict[str, jack.Port]: outputs = get_audio_ports(input=True) if not stereo: return outputs keys = set(_get_name_without_channel(n) for n in outputs) return {k: [v for _, v in out...
This function connects an audio output port to the appropriate JACK output, handling both mono and multi-channel scenarios. It disconnects existing connections, then links the specified port to the correct output(s) based on channel mapping, ensuring proper audio routing in a JACK audio system.
def connect_audio_output(self, port: Union[jack.Port, str] ): client = get_client() port_name = port if isinstance(port, str) else port.name outputs = [v for k, v in get_default_outputs().items() if port_name in k] if len(outputs) == 0: raise ValueError("Port not found") ...
def adj_mx_from_skeleton16(cfg,num_joints = 64): num_joints = 2 * 16 edges = getadj16(cfg) return adj_mx_from_edges(num_joints, edges, sparse=False) def adj_mx_from_skeleton16_nosys(cfg,num_joints = 64): num_joints = 2 * 16 edges = getadj16_nosys(cfg) return adj_mx_from_edges(num_joints, e...
The function `gatScaleAdj` generates and returns a list of adjacency matrices by calling multiple skeleton-based functions (`adj_mx_from_skeletonX`) with varying parameters, such as different skeleton scales (16, 8, 4) and system inclusion flags (`nosys`). Its main task is to produce diverse adjacency matrices for grap...
def gatScaleAdj(cfg): return [adj_mx_from_skeleton16(cfg),adj_mx_from_skeleton16_nosys(cfg),adj_mx_from_skeleton8(cfg),adj_mx_from_skeleton8_nosys(cfg),adj_mx_from_skeleton4(cfg),adj_mx_from_skeleton4_nosys(cfg)]
def create_sequence_array(number, end): """ Takes a number and create a array where elements are integer and start from that number ends at spcific number. Example: create_sequence_array(number=1, end=4) output: [1,2,3,4] """ f = [] for n in range(end): f.append(number) number = number + 1 return f d...
The main task of the code is to generate a 4x4 "magic matrix" by creating a sequence array, splitting it into parts, and systematically reversing specific rows and columns (columns 1 and 2, then rows 1 and 2) to achieve a transformed matrix structure.
def magic_matrix_4X4(number, end, parts): f = create_sequence_array(end=end,number=number) int(number) array = split_array(f, parts) array = reverse_2d_arrays_col(array, 1) array = reverse_2d_arrays_col(array, 2) array = reverse_2d_arrays_row(array, 1) array = reverse_2d_arrays_row(array, 2) return array
def optimal_Bayes_prediction(llr, pi, Cfn, Cfp, th=None): if th is None: th = - np.log((pi * Cfn) / ((1 - pi) * Cfp)) Pred = np.zeros([llr.shape[0]]) Pred[llr > th] = 1 return Pred def compute_binary_confusion(predictions, labels): CM = np.zeros((2, 2)) CM[0, 0] = ((predictions == 0) *...
The function computes the Discriminative Cost Function (DCF) and minimum DCF for varying effective prior log-odds, evaluating classifier performance under different prior assumptions. It iterates over a range of priors, calculates optimal Bayesian predictions, confusion matrices, and corresponding risks, returning DCF ...
def Bayes_plot_components(llr, true_labels): effPriorLogOdds = np.linspace(-3, 3, 21) DCF = np.zeros([effPriorLogOdds.shape[0]]) minDCF = np.zeros([effPriorLogOdds.shape[0]]) for index, p_tilde in enumerate(effPriorLogOdds): pi_tilde = 1 / (1 + np.exp(-p_tilde)) pred = optimal_Bayes_pre...
def LBG(X, gmm, th, alpha, psi, diag, tied): new_gmm = [] for c in gmm: # Find eigenvalue corresponding to the largest eigenvalue of the cov matrix U, s, _ = np.linalg.svd(c[2]) # Compute displacement of the mean d = U[:, 0:1] * s[0] ** 0.5 * alpha new_gmm.append((c[0] / ...
The main task of the code is to classify test data using a Gaussian Mixture Model (GMM) classifier. It iteratively builds GMMs for each class via the LBG algorithm, refining component parameters with constraints on covariance matrices. The classifier computes log-likelihoods for test data, applies likelihood ratio comp...
def GMM_classifier(DTR, LTR, DTE, n_classes, num_components, diag, tied, t=1e-6, psi=0.01, alpha=0.1): S = np.zeros([n_classes, DTE.shape[1]]) all_gmm = [] llr = 0 for count in range(int(np.log2(num_components))): for c in range(n_classes): # Define the starting components of gmm ...
def processImage(self): self.downscaleImage() self.IMAGE = self.getImage() img_width = self.IMAGE.shape[0] img_height = self.IMAGE.shape[1] # print(self.IMAGE.shape) # print(img_width) # print(img_height) self.IMAGE = np.reshape(self.IMAGE, (img_width * i...
The code processes an image, computes color clusters, generates a histogram, checks if a desired color is present, prints the result, and returns the boolean outcome of the color presence check.
def driver(self): self.processImage() self.computeClusters() self.plotHistogram() print("Desired Color - {} for image - {} is present: {}".format(self.DESIRED_COLOR, self.IMAGE_STRING, self.colorPresent())) return self.colorPresent()
def _conv_layer(net, num_filters, filter_size, strides, relu=True, type=0): weights_init = _conv_init_vars(net, num_filters, filter_size) bias_init = tf.Variable(tf.zeros([num_filters], dtype=tf.float32)) strides_shape = [1] + list([strides]) * 2 + [1] net = tf.nn.bias_add(tf.nn.conv2d(net, weights_init...
This code defines a neural network for image generation or enhancement. It processes an input image through convolutional layers, residual blocks (for feature refinement), transposed convolutions (upsampling), and outputs a scaled image tensor using tanh activation. The network likely performs tasks like super-resoluti...
def net(image, type=0): conv1 = _conv_layer(image, 32, 9, 1, type) conv2 = _conv_layer(conv1, 64 ,3, 2, type) conv3 = _conv_layer(conv2, 128 ,3, 2, type) residual1 = _residual_block(conv3, 3, type=1) residual2 = _residual_block(residual1, 3, type=1) residual3 = _residual_block(residual2, 3, type...
def reset(self): padding = (0,) * 19 packetFormat = 'c' + 19 * 'B' # 1 char & 19 unsigned char resetByte = bytes('R', 'utf-8') packet = struct.pack(packetFormat, resetByte, *padding) self.serial_chars.write(packet, withResponse=False) BTL_RESET_STATUS[self.peripheral_obj...
The code initiates a Bluetooth handshake by repeatedly sending 'H' packets to a peripheral device, waiting for an ACK response. It tracks timeout counts, resets the device every 5 attempts, and re-establishes connections if disconnected. Upon receiving an ACK, it sends an 'A' response. The loop continues until the hand...
def initiate_handshake(self): timeout_count = 0 try: while not BTL_HANDSHAKE_STATUS[self.peripheral_obj_beetle.addr]: # send handshake packet to BTL message = [BTL_TYPE[self.peripheral_obj_beetle.addr] + PLAYER, 'LAPTOP->BTL H sent'] print(mess...
def reset(self): padding = (0,) * 19 packetFormat = 'c' + 19 * 'B' # 1 char & 19 unsigned char resetByte = bytes('R', 'utf-8') packet = struct.pack(packetFormat, resetByte, *padding) self.serial_chars.write(packet, withResponse=False) BTL_RESET_STATUS[self.peripheral_obj...
The main task of the code is to establish a BLE handshake with a peripheral device by repeatedly sending 'H' packets, waiting for an ACK response, and handling timeouts by resetting and reconnecting. It loops until the handshake status is confirmed, ensuring communication is established.
def initiate_handshake(self): timeout_count = 0 try: while not BTL_HANDSHAKE_STATUS[self.peripheral_obj_beetle.addr]: # send handshake packet to BTL message = [BTL_TYPE[self.peripheral_obj_beetle.addr] + PLAYER, 'LAPTOP->BTL H sent'] print(mes...
def reset(self): padding = (0,) * 19 packetFormat = 'c' + 19 * 'B' # 1 char & 19 unsigned char resetByte = bytes('R', 'utf-8') packet = struct.pack(packetFormat, resetByte, *padding) self.serial_chars.write(packet, withResponse=False) BTL_RESET_STATUS[self.peripheral_obj...
The main task of the code is to establish a Bluetooth Low Energy (BLE) handshake with a peripheral device by repeatedly sending a 'H' handshake packet, waiting for an ACK response, and handling timeouts by resetting the device and reconnecting if necessary. It formats and transmits packets using struct.pack, monitors A...
def initiate_handshake(self): timeout_count = 0 try: while not BTL_HANDSHAKE_STATUS[self.peripheral_obj_beetle.addr]: # send handshake packet to BTL message = [BTL_TYPE[self.peripheral_obj_beetle.addr] + str(PLAYER), 'LAPTOP->BTL H ...
def connect(self): BTL_HANDSHAKE_STATUS[self.peripheral_obj_beetle.addr] = False message = [BTL_TYPE[self.peripheral_obj_beetle.addr] + PLAYER, 'attempting connection...'] print(message) try: self.peripheral_obj_beetle.disconnect() self.peripheral_obj_beetle.conne...
The code handles BLE communication by waiting for notifications from a peripheral device, sending acknowledgment packets when triggered, and maintaining connection via recursive calls. It checks reset status, manages ACK flags, and reinitializes connections on errors, ensuring continuous data exchange with the peripher...
def run(self): try: while True: if BTL_RESET_STATUS[self.peripheral_obj_beetle.addr]: break if self.peripheral_obj_beetle.waitForNotifications(2.0): padding = (0,) * 19 packetFormat = 'c' + 19 * 'B' ...
def connect(self): BTL_HANDSHAKE_STATUS[self.peripheral_obj_beetle.addr] = False print(BTL_TYPE[self.peripheral_obj_beetle.addr] + PLAYER, 'attempting connection...') try: self.peripheral_obj_beetle.disconnect() self.peripheral_obj_beetle.connect(self.peripheral_obj_beetl...
The main task of the code is to handle BLE peripheral communication by waiting for notifications, sending acknowledgment packets when triggered, monitoring packet counters (good, dropped, fragmented), and reinitializing connections/handshakes on errors or reset conditions. It runs in an infinite loop until a reset flag...
def run(self): try: while True: #current_time = START if BTL_RESET_STATUS[self.peripheral_obj_beetle.addr]: break if self.peripheral_obj_beetle.waitForNotifications(2.0): if ACK_IR_SENT_flag[self.peripheral_obj...
def connect(self): BTL_HANDSHAKE_STATUS[self.peripheral_obj_beetle.addr] = False print(BTL_TYPE[self.peripheral_obj_beetle.addr] + str(PLAYER), 'attempting connection...') try: self.peripheral_obj_beetle.disconnect() self.peripheral_obj_beetle.connect(self.p...
The code continuously sends game state updates and acknowledgment signals to connected Bluetooth devices. It checks for reset status, retrieves player health, shield, and bullet data from queues, formats them into packets, and transmits them via serial communication. It handles two device types (G/V), sends specific pa...
def run(self): try: while True: if BTL_RESET_STATUS[self.peripheral_obj_beetle.addr]: break if BTL_TYPE[self.peripheral_obj_beetle.addr] == 'G' and not game_state_queue_to_gun_beetle.empty(): updated_game_state = game_state_que...
def generate_story(text, model, tokenizer, num): DEFAULT_SYSTEM_PROMPT = "Below is a summary of a children's story. Write a full story more than 1000 words. " + \ "Make sure your story contains " + num + " paragraphs, with each paragraph separated by [ENDING]." + \ ...
The code generates a story using a model based on the given prompt, processes the generated text by parsing, removing unnecessary parts, and compiling the full story. It returns both the cleaned text and the complete story structure.
def create_story(prompt, model, tokenizer, num): generated_text = generate_story(prompt, model, tokenizer, num) wrapped_text = parse_text(generated_text) wrapped_text = remove_unnecessary_text(wrapped_text) full_story = [] full_story = get_full_story(wrapped_text) return wrapped_text, full_story
def join_code_params(code, *params): built_str = code if params: # Add ~ because join doesn't put it at the start built_str = built_str + "~" + "~".join(params) return built_str def handle_msg(sock=None, to_send="", client_args=[]): # send_with_size(sock,to_send,"",True) soc = get_s...
The function handles a received zipped file by modifying the client argument to append ".gz", sending a file message with the filename, decompressing the file to the specified output, and returning an empty string. It prepares for decompression, executes it, and leaves cleanup commented out.
def handle_recived_zipped_file(fields, client_args): chunk_amount, compress_file_name = fields output_filename = client_args[0] client_args[0] = client_args[0] + ".gz" send_str = join_code_params("FILE", compress_file_name) handle_msg(to_send=send_str, client_args=client_args) # handle_file([cod...
def print_system_notification(message): data = str(message) now = str(datetime.now())[:-7] text.insert("insert", "({}) : {}\n".format(now, data), 'notification') def connect(): client_id = g_entry_client_id.get() if not client_id: print_system_notification("[err] client id = empty; please f...
The code connects to a server using a client ID, handles connection errors, sends the client ID upon successful connection, and logs status messages. It retrieves the client ID from a GUI input, attempts a socket connection, and triggers data reception after establishing a link.
def connect(self): now = str(datetime.now())[:-7] client_id = g_entry_client_id.get() if not client_id: print_system_notification("[err] client id = empty; please fill") else: try: self.s.connect((self.host, self.port)) self.client...
def print_system_notification(message): data = str(message) now = str(datetime.now())[:-7] text.insert("insert", "({}) : {}\n".format(now, data), 'notification') def unlock_car(self): if self.car_id == -1: print_system_notification("no car found car") else: if not sel...
This code processes incoming commands by splitting them into client ID and message ID, then triggers specific system notifications and actions (e.g., unlocking/locking cars, handling rent requests) based on predefined message ID patterns. It maps each ID to a corresponding task, executing methods like `unlock_car()` or...
def handle_message(self, command): client_id = command.split(' ',1)[0] message_id= command.split(' ',1)[1] if message_id== "0 2": print_system_notification("post car") elif message_id == "1 3": print_system_notification("request car") elif message_id == "0...
def _job_added(self, job_id, jobstore, added_ts, job=None): with self.write_lock: if job_id in self.jobs: return self.jobs[job_id] = { 'added_time': added_ts, 'modified_time': added_ts, 'removed_time': None, ...
This method handles job execution events by either adding a new job or updating existing event data. It creates an event dictionary with job details, merges additional parameters, appends the event to the job's history, and notifies listeners of the event. Thread safety is ensured via a write lock.
def _job_execution_event(self, job_id, jobstore, event_name, event_ts, **kwargs): with self.write_lock: if job_id not in self.jobs: self._job_added(job_id, jobstore, event_ts) event = { 'job_id': job_id, 'event_name': event_name, ...
def _repr_jobstore(self, jobstore): return str(jobstore) def _repr_executor(self, jobstore): return str(jobstore) def _repr_ts(self, ts): """ Args: ts (datetime): Returns: str: The timestamp string representation. """ if ts: re...
This method inspects a scheduler's configuration by extracting job stores, executors, and metadata, updating internal state with scheduler details like class name, timezone, and job defaults. It logs jobstore additions and new jobs using timestamps, ensuring the system tracks scheduler state and job changes for monitor...
def _inspect_scheduler(self): if hasattr(self.scheduler, '_jobstores') and isinstance(self.scheduler._jobstores, dict): self.jobstores = { alias: self._repr_jobstore(store) for alias, store in self.scheduler._jobstores.items() } if hasattr(self.scheduler, '_execu...
def wcdm(z, om, w): # For redshifts z and Omega_m om and constant w, # compute D_M(z)=r(z) in Hubble distance (c/H0) units for a flat Universe. # Can give z or w as vectors; will produce a vector output. # om must be a scalar; see owcdm() to allow a vector # This requires w<-1/3 if one is using the ...
The code tests the accuracy of cosmological distance and time calculation functions (wcdm, owcdm, etc.) by comparing their outputs with reference implementations (e.g., wcdm_romberg, owcdm_romberg). It evaluates various models (LCDM, WCDM) under different parameters (matter density, equation of state, curvature) and re...
def test(): print("Testing the base wcdm code") x = wcdm(1.0,0.3,-1) print("LCDM, om=0.3, z=1: r(z) = ", x, " Err = ",x-wcdm_romberg(1.0,0.3,-1) ) x = wcdm(1.0,0.3,-0.2) print("WCDM, om=0.3, w=-0.2, z=1: r(z) = ", x, " Err = ",x-wcdm_romberg(1.0,0.3,-0.2)) x = wcdm(1.0,0.3,-0.4) print("WCD...
def forward_propagation(self, X): self.layer_outputs["input_image"] = X h = self.cnn_layer(X) self.layer_outputs["layer_0"] = h h = self.relu_layer(h) self.layer_outputs["layer_1"] = h h = self.cnn_layer(h, layer_i=2, border_mode="valid") # backpropagated self.l...
The code performs backpropagation in a CNN to compute gradients for weight updates. It calculates cross-entropy error, propagates it backward through layers (including ReLU derivatives and max-pooling backprop), computes deltas for convolutional and fully connected layers using matrix operations and convolutions, and s...
def back_propagation(self, X, expected_person): nb_features = self.layers[0]["param_0"].shape[0] nb_channels = 3 # TODO _ not hardcode y = self.expected[expected_person] cnn_out = self.forward_propagation(X) print("ERROR: ") cross_entropy_error = self.cross_entropy_er...
def DumbClipTriangleToBox(t, V): return IntersectBounds(V, Bounds([t])) def FindPlane(V, bounds): Chat, phat, psidehat = +INFINITY, Plane(0, 0.0), 0 for k in range(3): #for each dimension in turn E = [] #eventlist for B in bounds: if B[k][0] == B[k][1]: E.app...
This function recursively constructs a KD-tree for triangles by splitting them based on bounding boxes and planes, storing nodes and triangles in provided lists. It checks if a triangle list is small enough to store directly, otherwise splits the bounding box, partitions triangles, and recursively builds left/right sub...
def RecBuild(tri, T, V, kdnodes, kdtriangles, depth): if len(T) <= LIMIT: kdnodes.append((0.0, len(kdtriangles), 0, 0, True)) kdtriangles.extend(T) kdtriangles.append(-1) return len(kdnodes) - 1, depth bounds = [] for i in T: t = tri[i] B = DumbClipTriang...
def get_schedule_name(event): return event["ResourceProperties"]["ScheduleName"] def is_schedule_ready(schedule_name): is_ready = False schedule = sm.describe_monitoring_schedule(MonitoringScheduleName=schedule_name) status = schedule["MonitoringScheduleStatus"] if status == "Scheduled": lo...
The function handles updates for a schedule. If the schedule does not exist (ResourceNotFound), it delegates to create_handler. Otherwise, it logs an error and re-raises unexpected exceptions during schedule readiness checks.
def update_handler(event, context): """ If this is an update for new schedule then call create_handler """ schedule_name = get_schedule_name(event) logger.info("Updating schedule: %s", schedule_name) try: is_schedule_ready(schedule_name) except ClientError as e: if e.response...
def test(self, epoch): timestr = time.strftime("%H:%M:%S", time.localtime()) print(timestr) total_mse_loss = 0 total_g_loss = 0 total_d_loss = 0 total_vgg_loss = 0 batch_num = 0 for batch_index, batch in enumerate(self.validDataloader): free_...
The code trains a generative model using MRI datasets, alternating between discriminator and generator updates. It loads training and validation data, iterates over epochs, processes batches, adjusts learning rates periodically, and saves the model. The discriminator is trained multiple times per batch, while the gener...
def train(self): self.dataset = MRIDataset(self.level) self.dataloader = DataLoader(self.dataset, batch_size=self.batch_size, shuffle=True) self.validDataset = MRIValidDataset(self.level) self.validDataloader = DataLoader(self.validDataset, batch_size=self.batch_size, shuffle=True) ...
def __validate_username(username: str) -> Result: if username is None or username == "": return Result(False, "Username can't be empty.") if len(username) < MIN_USERNAME_LENGTH: return Result(False, f"Username must be at least {MIN_USERNAME_LENGTH} characters long.") if len(username) > MAX_U...
The code validates a user's username, email, and password using helper functions. It collects validation results, filters out successful ones, and returns the first failure if any exist. Otherwise, it returns a default success result. This ensures all user creation fields meet required criteria before proceeding. Your ...
def validate_create_model(user: UserCreate) -> Result: results = [ __validate_username(user.username), __validate_email(user.email), __validate_password(user.password), ] invalid_results = tuple(filter(lambda r: not r.is_success, results)) return invalid_results[0] if invalid_r...
def cohere(self, flock, c): neighborhood = self.getNeighborhood(flock) cm = vector(0,0,0) for boid in neighborhood: cm.x += boid.tie.pos.x cm.y += boid.tie.pos.y cm.z += boid.tie.pos.z if len(neighborhood) > 0: cm.x = cm.x / len(neighborhoo...
This code updates an agent's movement by applying flocking behaviors: cohesion (grouping), separation (avoiding collisions), alignment (matching velocity), and fleeing from a hawk. It then handles boundary constraints and adjusts the agent's direction and position based on normalized velocity.
def move(self, hawk, flock, a, c, s, r): self.cohere(flock, c) self.separate(flock, s) self.align(flock, a) self.run(hawk, r) self.edge() self.tie.axis = self.tie.velocity.norm() self.tie.pos += self.tie.velocity.norm()
def cohere(self, flock, c): neighborhood = self.getNeighborhood(flock) cm = vector(0,0,0) for boid in neighborhood: cm.x += boid.tie.pos.x cm.y += boid.tie.pos.y cm.z += boid.tie.pos.z if len(neighborhood) > 0: cm.x = cm.x / len(neighborhoo...
The main task of the code is to update an agent's movement in a flocking simulation by applying cohesion, separation, and alignment rules to the flock, enforcing boundary constraints, and normalizing velocity to adjust position. The function combines these behaviors to navigate the environment while avoiding collisions...
def moveNoHawk(self, flock, a, c, s, r): self.cohere(flock, c) self.separate(flock, s) self.align(flock, a) self.edge() self.tie.axis = self.tie.velocity.norm() self.tie.pos += self.tie.velocity.norm()
def chase(self, flock): neighborhood = self.getNeighborhood(flock) if len(neighborhood) > 0: self.x_wing.velocity += (neighborhood[0].tie.pos - self.x_wing.pos) def eat(self, flock): neighborhood = self.getNeighborhood(flock) if len(neighborhood) > 0: for boid in ...
The code's main task is to control an entity's movement by chasing flock members, eating within the flock, maintaining boundary constraints, and updating the x_wing's position using normalized velocity. It combines social behavior (chasing/eating), environmental interaction (edge handling), and physics-based motion (ve...
def move(self, flock): self.chase(flock) self.eat(flock) self.edge() self.x_wing.axis = self.x_wing.velocity.norm() self.x_wing.pos += self.x_wing.velocity.norm() * 2
def read_input(): store_parameters = input() sliced_parameters = store_parameters.split('\t') store_dimensions = Dimension(int(sliced_parameters[1]), int(sliced_parameters[0]), 0) pillar_count = int(input().split()[0]) pallet_count = int(input().split()[0]) pillar_array = [] for _ in range(s...
The code processes input (from file or stdin), reads store/pallet data, places pallets in a store layout using a `place` function, and outputs the result. It handles input redirection, data parsing, pallet placement logic, and result rendering in a structured format.
def main(): if(len(sys.argv) > 1 and sys.argv[1] == 'FILE'): fd = open('input.txt', 'r') sys.stdin = fd store_dimensions, pillars_array, pallet_dimensions, output_array = read_input() if(len(pallet_dimensions) > 0): place(pallet_dimensions, pillars_array, output_array, store_dimens...
def generate_summary(): schema = add_chain_of_critique_to_schema(get_subschema("summary")) response = gpt4_xml(xml_schema=schema, system_prompt=generate_summary_prompt) last_idea = response.xpath(".//idea")[-1] summary = last_idea.xpath(".//summary")[0] return summary def generate_title(novel): ...
The function ensures a novel XML structure is complete by generating missing elements like timestamp, summary, title, setting, blurb, cover art, characters, and chapters. It iterates through chapters and moments, adding prose where absent, returning False if any element is incomplete and True when fully populated.
def work(novel): """ Does one step of work on the novel then returns True if the novel is complete, False otherwise. """ # check if there is no title if not novel.xpath(".//timestamp"): e = etree.Element("timestamp") e.text = str(datetime.now().isoformat()) novel.append(e...
def _intercept(self, ray: Ray) -> None | np.ndarray: """ Works out the nearest point of interception between the ray's origin and the Optical Element's surface. Returns array if this exists, None otherwise. Takes care of case where curvature = 0. :param Ray ray: Ray object to calculate ...
The function `propagate_ray` simulates the propagation of a light ray through a medium by calculating its intersection point and applying Snell's law for refraction. It returns the new position (`new_p`) and direction (`new_k`) vectors of the ray after interaction. If no intersection is found or total internal reflecti...
def propagate_ray(self, ray: Ray) -> tuple: """ Generalised propagate ray function to be properly implmented in sub-classes Raises an error if no intersection is found, or total internal reflection occurs, especially useful when debugging. This error does not break any functionality. ...
def extract_pages_urls(URL): """ Get the 5 URL's (pages) that are in the main page Input: Main URL Output: Set of URL of the different pages """ page = requests.get(URL) soup = BeautifulSoup(page.content, "html.parser") pagination = soup.find('div', class_="pagination1") pages_urls = set() ...
The main task of the code is to scrape book data from URLs by extracting book links, processing each book's text and image content, aligning their lengths by trimming discrepancies, and saving the structured data as a JSON file. It ensures text-image pairs are synchronized before storing them in a dictionary format for...
def main(input_url, output_filepath): """ Loads data from URL """ logger = logging.getLogger(__name__) logger.info('Getting Data from URL') all_book_links = set() for URL in extract_pages_urls(input_url): all_book_links = all_book_links.union(extract_book_links(URL)) logger.info(f'We h...
def updateMatrixS(self,match,missmatch): for key in self.matrixS: for key2 in self.matrixS[key]: if(key == key2): self.matrixS[key][key2] = match else: self.matrixS[key][key2] = missmatch def makeFGlobalMatrix(self): fil...
This method performs global sequence alignment using dynamic programming. It updates the scoring matrix with provided match/mismatch values, sets the gap penalty, constructs the alignment matrix, and executes traceback to determine the optimal alignment path.
def _global(self, _match=0, _missmatch=0, _gap=-2): if(_match != 0 and _missmatch != 0): self.updateMatrixS(_match,_missmatch) self.gap = _gap self.makeFGlobalMatrix() return self.globaltraceback()
def updateMatrixS(self,match,missmatch): for key in self.matrixS: for key2 in self.matrixS[key]: if(key == key2): self.matrixS[key][key2] = match else: self.matrixS[key][key2] = missmatch def makeFGlobalMatrix(self): fil...
This method performs global sequence alignment using dynamic programming. It updates a scoring matrix with given match/mismatch values, sets a gap penalty, constructs a global alignment matrix, and returns the optimal alignment via traceback. The function adjusts parameters, builds the matrix, and executes backtracking...
def _global(self, _match=0, _missmatch=0, _gap=-2): if(_match != 0 and _missmatch != 0): self.updateMatrixS(_match,_missmatch) self.gap = _gap self.makeFGlobalMatrix() return self.globaltraceback()
def updateMatrixS(self,match,missmatch): for key in self.matrixS: for key2 in self.matrixS[key]: if(key == key2): self.matrixS[key][key2] = match else: self.matrixS[key][key2] = missmatch def makeFLocalMatrix(self): max_...
This code performs local sequence alignment by updating a scoring matrix with given match/mismatch values, setting a gap penalty, constructing a local alignment matrix, and returning the optimal alignment via traceback. It handles matrix updates, gap penalties, and alignment tracing for bioinformatics applications.
def _local(self, _match=0, _missmatch=0, _gap=0): if(_match != 0 and _missmatch != 0): self.updateMatrixS(_match,_missmatch) self.gap = _gap self.makeFLocalMatrix() return self.localtraceback(_match, _missmatch, _gap)
def updateMatrixS(self,match,missmatch): for key in self.matrixS: for key2 in self.matrixS[key]: if(key == key2): self.matrixS[key][key2] = match else: self.matrixS[key][key2] = missmatch def makeFLocalMatrix(self): max_...
The main task of the code is to perform a local sequence alignment by updating the scoring matrix with given match/mismatch values, setting the gap penalty, constructing a local alignment matrix, and executing a traceback to determine the optimal alignment result, returning the outcome of this alignment process.
def _local(self, _match=0, _missmatch=0, _gap=0): if(_match != 0 and _missmatch != 0): self.updateMatrixS(_match,_missmatch) self.gap = _gap self.makeFLocalMatrix() return self.localtraceback(_match, _missmatch, _gap)