dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def cross_bounds(): v1,v2,v3 = mycar.get_car() X = v1[0] Y = v1[1] if(X<0 or X>1000 or Y<0 or Y>1000): return True else: return False def collision(): white = (255,255,255) for point in environment: try: color = screen.get_at(point) if color ==...
The code calculates a reward value for an agent navigating towards a goal. It increases reward when approaching the goal, decreases it for crossing bounds or collisions, and adds a large bonus upon reaching the goal. The function tracks progress using global variables and returns the computed reward for reinforcement l...
def get_reward(): reward = 0 global distance global col global cb global reached d = (goal[0]-mycar.x)**2+(goal[1]-mycar.y)**2 if d > distance: reward-=1 if d < distance: reward+=1 if cross_bounds(): cb = True reward-=5 if collision(): col ...
def handle_bot_response(msg): if not msg["text"].startswith(u'\u200b'): return userName = msg["from"]["first_name"] responses = ( "Mmm… you have interesting taste", f"Ooo {userName}, that’s kinda kinky", "Ah, I see that you’re a man of culture as well", f"{userName}...
This function processes incoming messages by routing them to appropriate handlers based on command prefixes. It checks if the message originated from the bot, parses query data, and executes actions like greetings, login/logout, or specific commands. Errors in parsing are logged, and unsupported queries are ignored.
def handle_normal_query(data): msg = data["message"] if msg.get("via_bot") and msg["via_bot"]["username"] == BOT_USERNAME: handle_bot_response(msg) return try: query = BotQuery.parse_event(data) except Exception as err: logger.error(f"Unsupported query: {err}") ...
def handle_inline_query(query: BotQuery): query_id = query.inline_query_id query = query.inline_query_text animeList = anilist.getAnime(query) results = [] # inline query can only return up to 20 items for idx in range(min(MAX_ITEMS, len(animeList))): anime = animeList[idx] ti...
The code processes incoming events by parsing the request data into a BotQuery object, determines the query type (inline, callback, or normal), and routes it to the appropriate handler. It logs details, handles errors, and returns a 200 OK response with the original request data in JSON format, ensuring proper event pr...
def handler(event, context): data = event["body"] logger.info(f"Received event with content: {data}; context: {context}") body = { "request": data } try: query = BotQuery.parse_event(data) except Exception as err: logger.error(f"Unsupported query: {err}") retur...
def uint_to_binstr(number, size): return bin(number)[2:][-size:].zfill(size) def bits_required(n): n = abs(n) result = 0 while n > 0: n >>= 1 result += 1 return result def run_length_encode(arr): # determine where the sequence is ending prematurely last_nonzero = -1 for i...
The code writes encoded Huffman tables and block data to a file in a specific binary format. It serializes DC/AC tables with their sizes, Huffman codes, and run-length encoded values, followed by block counts and encoded symbols. The output adheres to bit-length specifications for each data component, ensuring structur...
def write_to_file(filepath, dc_y, ac_y, dc_c, ac_c, blocks_count, tables): try: f = open(filepath, 'w') except FileNotFoundError as e: raise FileNotFoundError( "No such directory: {}".format( os.path.dirname(filepath))) from e for table_name in ['dc_y', '...
def is_castling_allowed(board, current_square): flattened_board = [] for sub_array in board: flattened_board.extend(sub_array) try: current_square = SQUARES[current_square] except KeyError: current_square = current_square = SQUARES['e1'] if flattened_board[current_square].name != "...
The function generates all legal moves for a king on a chessboard, including castling. It checks each of the 8 possible directions for valid moves, ensuring the target square is not attacked and within bounds. It handles piece color conflicts, avoids same-color collisions, and converts numerical square indices to chess...
def generate_king_moves(board, current_square): ''''' flattened_board = [] for sub_array in board: flattened_board.extend(sub_array) flattened_board[SQUARES['e8']] = King('black'); flattened_board[SQUARES['e1']] = King('white'); flattened_board[SQUARES['c4']] = Queen('black'); flat...
def Trade(self, Source, Value): if self.PayResource(Source): self.oil += Value.oil self.coal += Value.coal self.tool += Value.tool self.coin += Value.coin self.steel += Value.steel self.PrintTransaction(Source, Value, True) retu...
The main task of the code is to perform trades and advancements using a personal card's resources. It executes a specified number of trades (defaulting to the maximum) based on the card's primary source and value, then advances designated cards if resources allow, handling validation and resource limits.
def PersonalCard(self, card, **kwargs): ''' Perform the trades on a personal card :param card: Card ID :param kwargs: 'trade' or 't' being equal to a number will perform that many trades (but clamped at the limit) If not specified, do the max. ...
def getBackground(size): path = r'background.png' if not directory == None: path = os.path.join(directory, path) img = cv2.imread(path) h = img.shape[0] w = img.shape[1] dim = (int(w * size), int(h * size)) return cv2.resize(img, dim, interpolation=cv2.INTER_AREA) def RenderCard(card...
The main task of the code is to generate a horizontal image displaying all cards from a dictionary input. It scales each card, arranges them side-by-side on a background, overlays them into a composite image, and saves the result. The function handles scaling, card rendering, positioning, and image saving, returning th...
def RenderCards(Cards, scale=1.0, **kwargs): ''' Takes the dictionary containing the cards in your hand and generates an image showing all cards :param Cards: :param args: :param kwargs: :return: ''' cardCount = len(Cards) # Determine the size of the background if 'scale' in kwar...
def IsPersonalCard(self, card): return 'p' in card.value def UnplayPersonalCard(self, card, **kwargs): # Prep to undo first trade pValue = CardDeck[card]['PrimarySource'] pSource = CardDeck[card]['PrimaryValue'] self.ShowRes() for i in range(self.lastTrade1): ...
The function undoes the last played card by checking if it's a personal card, then either unplays it or reverses its action. If successful, it marks the card as inactive. It also resets advancement tracking and trade variables, returning the operation's status.
def UndoLastCardBase(self): if self.lastCard == None: print("No last card found.") if self.IsPersonalCard(self.lastCard): status = self.UnplayPersonalCard(self.lastCard) else: status = self.Card(self.lastCard, undo=True) if status: self.car...
def IsPersonalCard(self, card): return 'p' in card.value def PersonalCard(self, card, **kwargs): ''' Perform the trades on a personal card :param card: Card ID :param kwargs: 'trade' or 't' being equal to a number will perform that many trades (but clamped at the limit) ...
This method processes playing cards by validating each card's presence in the player's hand and ensuring it hasn't been played before. It marks the card as played, determines if it's a personal card, executes the corresponding action (PersonalCard or Card), and updates the last played card if successful.
def PlayCardBase(self, *args, **kwargs): for arg in args: # Make sure this card is in their hand if not arg in self.cards: print('Tried to play {} but it is not in your hand! Skipping...'.format(arg)) continue if self.cards[arg][0]: ...
def get_quarterly_storage_price( self, record: BillableProjectRecord, start_date: datetime.date, ) -> float: """Calculate a quarter's storage price for one billable project. Parameters ---------- record Record with all the storage information. ...
The main task of the code is to generate a LaTeX-formatted quarterly bill document using a Jinja2 template. It processes input data including project records, date ranges, storage costs, and power user charges, calculates subtotals and totals, and renders the structured content into a formatted bill with variables like...
def generate_quarterly_bill_tex( self, record: BillableProjectRecord, quarter_start: datetime.date, env: Environment, ) -> str: """Generate tex file of a quarterly bill. Parameters ---------- record Record with all the storage information....
def immovable_urls(): """Extremely long search, not recommended for anyone unless you can wait for many hours.""" result = set() for weapon in list(settings.weapon_list.keys()): if check_variant(weapon): continue for weapon_type in get_weapon_type(weapon): for weapon...
The function `data_creation` generates a list of URLs for weapon-related data (e.g., rolls, unrolls) based on specified search settings. It dynamically includes URLs from various sources like generic rolls, wished weapons, and specific weapon searches, ensuring no duplicates. It also estimates the wait time based on th...
def data_creation(): """Prepares the weapon list""" url_list = [] # Should never be used unless you have all the time in the world. # it searches for every godroll and unroll. if settings.non_existant_search: url_list.extend(immovable_urls()) # creates the url of generic rolls. if s...
def get_strongest_version(self): """Finds the best version of the weapon, useful to weight stats when rating rivens""" versions = self.get_ocurrences() strongest = utils.get_weapon(self.weapon_name) for version in versions: if utils.get_weapon(version)["critical_chance"] > s...
This code initializes a Riven weapon object with attributes like name, price, stats, and polarity. It calculates derived values such as riven rating, real value, and checks if the weapon is wanted. The class also determines weapon type, strongest version, and disposition, while setting flags for updates and desirabilit...
def __init__( self, weapon="", name="", initial_price=-1, buyout_price=-1, seller="", polarity="", rerolls=-1, mastery_rank=-1, riven_rank=-1, stats=[], ): self.weapon_name = weapon # name of the weapon. self.na...
def Plot1(): # Size = 20 #Over head same for every example Methods = [Solve_MMAP_Method, Solve_AP_Method, Solve_PF_Method] #, Solve_Limit_Method Method_Names = ["MMAP", "AP", "PF"] epss = 10**(np.arange(-15,1,1,dtype=float)) E1a = lambda eps: Example_1(eps = eps, Size = ...
The main task of the code is to execute multiple plotting functions sequentially, generating or updating visualizations such as Plot1, Plot2, PlotE2, PlotE4, and PlotE5. It orchestrates the creation of these plots in a predefined order, likely for data visualization or analysis purposes.
def UpdatePlot(): Plot1() Plot2() PlotE2() PlotE4() PlotE5()
def load_and_process_input_data(input_file_path: str, local_output_path: str) -> None: """ Load input data from a CSV file, process it into chunks, and write those chunks to a local directory. Parameters: - input_file_path: The file path of the input CSV. - local_output_path: The directory path whe...
The main task of the code is to orchestrate a data pipeline: loading and processing input data, uploading processed chunks to Google Cloud Storage (GCS), and parsing the most recent data. The function coordinates these steps to handle data from input to storage and analysis, ensuring seamless data flow and processing f...
def main(): """ Main function to orchestrate loading, processing, uploading, and parsing data. Returns: None """ load_and_process_input_data(config.INPUT_FILE_PATH, config.LOCAL_OUTPUT_PATH) upload_chunks_to_gcs(config.LOCAL_OUTPUT_PATH, config.BUCKET) process_most_recent_data(config.BU...
def reset_parameters(self): """ Reset all training parameters to default """ self.buffer = ReplayBuffer(self.BUFFER_SIZE) self.policy_network = DeepQNetwork() self.target_network = DeepQNetwork() self.target_network.load_state_dict(self.policy_network.state_dict(...
The code trains a neural network using a Deep Q-learning approach, either through self-play or against an optimal player, with epsilon-greedy exploration. It accumulates rewards and losses over epochs, updates the target network periodically, and includes performance testing at intervals. The training includes reproduc...
def train(self, epsilon_greedy, adversary_epsilon, self_training = False, run_test = True, seed=45): """ Perform a full training of the neural network :param epsilon_greedy: the epsilon-greedy function (depending on the epoch) for the epsilon-greedy policy in the DeepQ player :param adve...
def _advance(self) -> str: self.current += 1 return self.source[self.current - 1] def _addSimpleToken(self, token_type: TokenType): self._addToken(token_type, None) def _match(self, expected: str) -> bool: if self._isAtEnd(): return False if self.source[self.current]...
This function scans input characters to identify and tokenize symbols, operators, comments, and identifiers. It processes parentheses, braces, punctuation, arithmetic operators, and comparison operators (e.g., handling "!=" or "=="). It skips single-line and block comments starting with "/". Whitespace is ignored excep...
def _scanToken(self): c = self._advance() if c == "(": self._addSimpleToken(TokenType.LEFT_PAREN) elif c == ")": self._addSimpleToken(TokenType.RIGHT_PAREN) elif c == "{": self._addSimpleToken(TokenType.LEFT_BRACE) elif c == "}": se...
def delta_MH( self, T , burning): self.num_hold = self.delta self.like_hold = self.log_likelihood_partial_integrated( T ) ranD_lock.acquire() self.delta = self.delta + self.ranD.normal( scale = self.sigma_delta ) ranD_lock.release() if self.delta <= 0: ...
This code runs a Markov Chain Monte Carlo (MCMC) simulation for a model with parameters beta, delta, gamma, etc. It performs Metropolis-Hastings updates (delta_MH, propose_E), writes sampled values to files at specified intervals (controlled by 'thin'), and avoids writing during a 'burning' phase. File locking ensures ...
def run(self, iterations, thin, file_handles, burning): if self.T != 1.0 and self.write: print('Something horrible as happend...\n', self.T, self.write) sys.exit() beta_out, delta_out, gamma_out, K_out, A_out, E_kappa_out = file_handles for i in range(iterations): ...
def list_files(dir): # open wavs directory and list files files = os.listdir(dir) print(f"\nlooking for .wavs in {dir}...", end="\n\n") wavs = False for i in files: if '.wav' in i or '.WAV' in i: wavs = True print(i) time.sleep(0.02) print() if wav...
The main task of the code is to process WAV audio files by allowing users to select a file, apply time-stretching or audio manipulation with customizable parameters (such as factor, buffer size, offset, start/end points), and optionally save or preview the modified audio. It includes user interaction for file selection...
def main(): dir = './wavs/' # default distribution directory # open and print header header = open('readme.md', 'r') header_lines = header.readlines() for i in range(26): print(header_lines[i], end="") time.sleep(0.02) # main application loop while True: # list file...
def simulate(self, considerClumping=False): ind = np.arange(self.s) allps = np.zeros((self.s,self.N,3)) allos = np.zeros((self.s,self.N,3)) for i in ind: self.arr.formUp() allps[i] = self.arr.ps allos[i] = self.arr.os self.arr.timestep(self...
The function `getStill` generates a static plot by creating a figure and axis, updating the axes with data from `self.s-1`, and plotting multiple instances (determined by `times`) using `np.linspace` to space frames evenly. It returns the generated figure.
def getStill(self, times=10): if(self.new): self.simulate() fig, ax = plt.subplots() self.updateAxes(self.s-1,ax) frames = np.linspace(0,self.s,times,endpoint=False).astype(int) for i in frames: self.plotInstance(i, ax) return fig
def get_rule(self, txt): try: tokens = self.tokenify(txt) tree = self.treeify(tokens) if len(tree) == 0: return {} if "SENTENCE" not in tree[0]["PART"]: return {} except Exception: if self.debug: ...
The main task of the code is to add a rule to the object's rule list and trigger updates. It first converts a string input into a rule object using `get_rule`, appends the rule to `self.rules`, and then calls `update_rules` and `update_meta_rules` to synchronize internal state and metadata. This ensures new rules are i...
def add_rule(self, rule): if type(rule) is str: rule = self.get_rule(rule) self.rules.append(rule) self.update_rules() self.update_meta_rules()
def _check_events(self): # A Helper method to to reduce the size of the run_game method for event in pygame.event.get(): # event loop for monitoring all the events occurring through out the running of the program if event.type == pygame.QUIT: sys.exit() ...
The main task of the code is to manage the core game loop by continuously checking events, updating the player's ship movement, handling bullet updates, and rendering the game screen in real-time, ensuring smooth gameplay and interaction within a loop that runs indefinitely until terminated.
def run_game(self): # essential method for managing all the game program while True: self._check_events() self.ship.update_movement() self._update_bullets() self._update_screen()
def get_containing_voxel_ijk(self, x, y, z): """ Internal function to get the meshgrid indices for the center of a voxel that contains the given position. Note that pyMCDS stores meshgrids as 'cartesian' (indexing='xy' in np.meshgrid) which means that we will have ...
The function `get_concentrations_at` determines the concentrations of all chemical species at a specified 3D point (x, y, z) by identifying the containing voxel, retrieving substrate names, and extracting corresponding concentration values from 3D arrays. It returns these concentrations in an array ordered by substrate...
def get_concentrations_at(self, x, y, z): """ Return concentrations of each chemical species inside a particular voxel that contains the point described in the arguments. Parameters ---------- x : float x-position for the point of interest y :...
def get_mesh_spacing(self): """ Returns the space in between voxel centers for the mesh in terms of the mesh's spatial units. Assumes that voxel centers fall on integer values. Returns ------- dx : float Distance between voxel centers in the same units as the...
The main task of the code is to filter and return a dataframe containing only the cells located within the same voxel as the specified (x, y, z) point. It calculates the voxel containing the point, defines its spatial bounds using mesh spacing, and filters the cell dataframe to include only cells whose positions fall w...
def get_cell_df_at(self, x, y, z): """ Returns a dataframe for cells in the same voxel as the position given by x, y, and z. Parameters ---------- x : float x-position for the point of interest y : float y_position for the point of interes...
def side(self, input, name): with tf.name_scope(name) as scope: #net1, end_points1 = resnet_v2.resnet_v2_101(input, None, is_training=True, global_pool=False, output_stride=16) net1 = Darknet53(darknet53_npz_path="darknet53.conv.74.npz", trainable=True, scratch=False).build(input, tf.con...
The code initializes a model to compute a loss based on the difference between two processed inputs. It scales input tensors, processes them with a `side` method, calculates the Euclidean distance between outputs, applies a margin, and computes loss and accuracy for a matching task.
def __init__(self, input1, input2, match): #with arg_scope(resnet_v2.resnet_arg_scope()) as scope: with tf.variable_scope("", reuse=tf.AUTO_REUSE) as scope: self.x1 = tf.scalar_mul(0.003922, tf.cast(input1, dtype=tf.float32)) self.x2 = tf.scalar_mul(0.003922, tf.cast(input2, dtyp...
def draw_dirt(self): surf = pygame.Surface((5, 5)) surf.fill((220, 220, 220)) for i in range(surf.get_width()): for j in range(surf.get_width()): amount = [random.randint(-10, 10) for i in range(3)] #self.update_surrounding(surf, i, j, amount) ...
The code initializes a game/environment by creating terrain elements (dirt, sand, grass, cloud) through specific drawing methods and loads a map from a text file. It sets up the initial state of the game world by generating these components and referencing a level file for further processing.
def __init__(self): self.dirt = self.draw_dirt() self.sand = self.draw_sand() self.grass = self.draw_grass(self.dirt) self.cloud = self.draw_cloud() self.map = './levels/level2.txt'
def run_bert_model( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=None, output_hid...
The function `tally_contributions` analyzes the token-level contributions of a sentence through a BERT model's layers. It tokenizes the input, runs the model to extract hidden states, and computes relative dot products between token representations and precomputed factors (e.g., attention, normalization, feed-forward c...
def tally_contributions(sentence): inputs = tokenizer([sentence], return_tensors="pt") attested, keywords = run_bert_model(model, **inputs, output_hidden_states=True) target_total = attested.last_hidden_state.squeeze(0) attested_hidden_states = [h.squeeze(0) for h in attested.hidden_states] all_fact...
def run_bert_model( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=None, output_hid...
This code analyzes token contributions in the final layer of a BERT model by calculating relative dot products between token embeddings and model components (input, normalization, feed-forward, multi-head attention). It returns a list of token metadata with positional offsets and contribution scores for each component,...
def tally_contributions_last_layer(sentence): inputs = tokenizer([sentence], return_tensors="pt", truncation=True, return_offsets_mapping=True) offset_mapping = inputs['offset_mapping'].squeeze(0) del inputs['offset_mapping'] attested, keywords = run_bert_model(model, **inputs, output_hidden_states=True...
def run_bert_model( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=None, output_hid...
The code computes input term contributions across BERT layers by combining layer normalization parameters and input terms, then calculates relative dot products between hidden states and aggregated contributions. It processes tokenized input, extracts hidden states and normalization terms, iteratively computes layer-wi...
def tally_ipt_contrib_accross_layers(sentence): inputs = tokenizer([sentence], return_tensors="pt", truncation=True) attested, keywords = run_bert_model(model, **inputs, output_hidden_states=True) targets = [h.squeeze(0) for h in attested.hidden_states] ln_terms = extract_layer_norm_terms(keywords) ...
def run_bert_model( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=None, output_hid...
This function analyzes how each token's contribution evolves through layers of a transformer model by computing relative dot products between hidden states and factors like attention, normalization, and feed-forward components. It returns a structured list of token-specific contributions across layers, optionally savin...
def tally_contributions_coarse_mha(sentence, pickle_file=None): inputs = tokenizer([sentence], return_tensors="pt", truncation=True) attested, keywords = run_bert_model(model, **inputs, output_hidden_states=True) target_total = attested.last_hidden_state.squeeze(0) attested_hidden_states = [h.squeeze(0)...
def run_bert_model( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=None, output_hid...
The code generates predictions for all possible keyword combinations using a BERT model and classifier. It extracts factors from the BERT's last layer, sums them for each subset in the powerset, and applies the classifier to produce predictions for every combination.
def pred_lm(inputs): _, keywords = run_bert_model(model_lm.bert, **inputs) factors = get_factors_last_layer(keywords) pred_from = lambda *keys: model_lm.cls(sum(factors[k] for k in keys).unsqueeze(0)) return {keys: pred_from(*keys) for keys in powerset()}
def printParameters(cself, dest=sys.stdout): print("Calibration results ", file=dest) print("====================", file=dest) #get the covariances std_baselines, std_cameras = recoverCovariance(cself) #print cameras print("Camera-system parameters:", file=dest) for cidx, cam in enumerate...
The main task of the code is to generate a detailed calibration report containing text output, graphs, camera system visualizations, trajectory plots, and per-camera error analyses. It organizes content into paginated figures, saves them as a PDF, and optionally displays them on screen, handling outlier data visualizat...
def generateReport(cself, filename="report.pdf", showOnScreen=True, graph=None, removedOutlierCorners=None): #plotter figs = list() plotter = PlotCollection.PlotCollection("Calibration report") offset = 3010 #Output calibration results in text form. sstream = StringIO() printParame...
def GetUser(id): user_list = GetUsers() for u in user_list: if u['id'] == id: return u return None def SendMsg(msg, c): msg = json.dumps(msg) c.send(bytes(msg,FORMAT)) def SimulateGame(user,guess,conn): SortUsers(GetUsers()) number = random.randint(1,10) u_users = []...
This code handles client connections by processing login, logout, and play events. It maintains active users, logs login activities, and sends appropriate responses. Upon login, it verifies user existence, updates active users, and logs details. Logout removes users from the list. The 'play' event triggers game simulat...
def handleClient(connection, address): print(f"client with address: {address} has connected") connected = True while connected: msg = connection.recv(HEADER).decode(FORMAT) if msg: msg = json.loads(msg) if msg['EVENT'] == 'logout': connected = False ...
def month_end(year, month): return Timestamp( year=year, month=month, day=days_in_month(year, month), hour=21 ) def open_monolevel(name, year): with warnings.catch_warnings(): #this warning seems too verbose, doesn't matter warnings.simplefilter('ignore', category=xar...
The function constructs input data for machine learning models by extracting storm and non-storm events from a dataset for a given year-month. It filters storms, removes rare end-of-month events, generates synthetic non-storm coordinates, interpolates meteorological data (monolevel/pressure levels) onto these points, a...
def construct_inputs(year, month, df): try: #slice out storms during this year-month period sl = df[(df.year == year) & (df.month == month)].copy() sl.sort_values('time', inplace=True) #also remove rare events in the last 3 hours of the month t = month_end(year, month) - T...
def word2vec_trainer(corpus, word2ind, mode="CBOW", mode2="HS", mode3=None, dimension=300, learning_rate=0.05, iteration=10000): # Xavier initialization of weight matrices W_emb = torch.randn(len(word2ind), dimension) / (dimension**0.5) W_out = torch.randn(len(word2ind), dimension) / (dimension**0.5) windo...
The main task of the code is to train a Word2Vec model (using either SkipGram or CBOW) on a text corpus, with options for Hierarchical Softmax/Negative Sampling and subsampling. It processes input text, builds a vocabulary, and trains word embeddings. If the 'test' flag is enabled, it evaluates the model on a predefine...
def main(): parser = argparse.ArgumentParser(description='Word2vec') parser.add_argument('mode', metavar='mode', type=str, help='"SG" for skipgram, "CBOW" for CBOW') parser.add_argument('part', metavar='partition', type=str, help='"part" if you want to train o...
def annotate_seg(seg_all, cell_data): rdr_sum,rdr_mean,vaf_mean,vaf_estimate,n_bin = [],[],[],[],[] for _, row in seg_all.iterrows(): df = cell_data[cell_data['CHROM']==row.chrom] _seg = df[(df.START<=row.end) & (df.END>=row.start)] n_bin.append(_seg.shape[0]) rdr_sum.append(_se...
The code processes genomic segment and cell data to infer ploidy and copy number variations (CNVs). It annotates segments with cell data, filters segments, identifies allelic balanced clusters, calculates metrics like RDR/VAF variance, infers ploidy using statistical models, and merges adjacent segments based on CN sta...
def postprocess(seg_path,data_path,MAX_WGD=1): seg_all = pd.read_csv(seg_path,sep='\t') cell_data = pd.read_csv(data_path,sep='\t') rdr_sum,rdr_mean,vaf_mean,n_bin = [],[],[],[] # annotate segments seg_all = annotate_seg(seg_all, cell_data) seg_all = seg_all[seg_all.NBIN>2] # ann...
def STinit(c: np.ndarray, D: csr_matrix) -> np.ndarray: power = DCTpower(c) ST = [] B = D.tocoo() for i, j in zip(B.row, B.col): if j >= i - 1 and j <= i + 1: D[i, j] = power[j] else: D[i, j] = power[j] + 7 for i, k in enumerate(D.argmax(axis=1)): if i...
The code computes global masking thresholds by processing input arrays `c` and `D`. It initializes a structure `ST`, reduces it using `Tq` data, calculates intermediate thresholds `Ti` via masking, and finally applies `Global_Masking_Thresholds` to `Ti` and `Tq`. The task involves signal processing or audio analysis, l...
def psycho(c: np.ndarray, D: np.ndarray) -> np.ndarray: Kmax = D.shape[0] ST = STinit(c, D) Tq = np.load("./Tq.npy")[0, :] (ST, PM) = STreduction(ST, c, Tq) Ti = Masking_Thresholds(ST, PM, Kmax) return Global_Masking_Thresholds(Ti, Tq)
def frameDCT(Y: np.ndarray) -> np.ndarray: return dct(Y.reshape((-1, 1)), axis=0)[:, 0] def Dksparse(Kmax: int) -> csr_matrix: D = lil_matrix((Kmax, Kmax)) def getDeltaK(k): if k <= 2: return 1 elif k > 2 and k < 282: return 2 elif k >= 282 and k < 570: ...
The code performs a Discrete Cosine Transform (DCT) on a random matrix, generates a sparse matrix, computes masking thresholds using psychoacoustic models, applies thresholding to reduce signal components, and visualizes the results. It loads precomputed thresholds, processes them with masking functions, and plots the ...
def main(): np.random.seed(0) a = np.random.rand(36, 32) c = frameDCT(a) # 1152 (32 * 36) D = Dksparse(36 * 32 - 1) # print(DCTpower(b).dtype) ST = STinit(c, D) # print(ST) # print(MaskPower(c, ST)) Tq = np.load("./Tq.npy") Tq = Tq[0, :] (ST, PM) = STreduction(ST, c, Tq) ...
def cache_cnf(cnf_file='~/.my.cnf',db=None): '''Like read_cnf but reads the CNF file only once and caches the results''' global DSN_CACHE if DSN_CACHE is None: DSN_CACHE = read_cnf(cnf_file,db=db) return DSN_CACHE def connect(dsn=None): '''Returns a new database connection given the dsn (a d...
The function tests if modifying the cached database connection settings (DSN) affects future database connections. It updates the cached DSN to use 'scottdb', establishes a new connection, and verifies the active database. If successful, it confirms the cache change took effect; otherwise, it raises an error. The test ...
def _testing_changed_cache(cnf_file): '''Testing that changing the db in the cache changes future connections''' # checking modification of DSN. But students can't switch to scottdb, so # this is just for scott scottdsn = cache_cnf(cnf_file) # we will use scottdb from now on scottdsn['database']...
def load_tess_objects(self, objects) -> None: # retrieve all objects by TIC ID from the TIC catalog # TIC fields: https://mast.stsci.edu/api/v0/_t_i_cfields.html tic_table = Catalogs.query_criteria(catalog="Tic", ID=objects) tic_table.rename_column("ID", "Identifier") if len(tic...
(The code processes catalog associations by grouping object IDs under their respective catalog names, then loads each catalog's data into dedicated tables using specific methods. It skips unsupported catalogs and errors on unknown types, ensuring organized and efficient data handling.)
def handle(self, *_, **options) -> None: # organize by catalog for more efficient querying id_dict = defaultdict(set) for association in models.CatalogAssociation.objects.all(): id_dict[association.catalog].add(association.catalog_id) # load each type of catalog into its own...
def initialize_annotation_display(self): """ initializes the functionalities of the annotation display like the list and the buttons to browse annotations """ logging.info('Initializing annotation display') self.id_to_shape = dict() self.annotation_frame = tkinter.Frame...
(The main task of the code is to initialize a GUI application for visualizing brainwave data with annotations. It sets up logging, loads project data from a specified path, initializes graphical displays (plots and annotations), handles window events, creates interactive buttons (annotate, export, close), and configure...
def __init__(self, master, path, toolitems): logging.basicConfig(filename='event_log.log', level=logging.INFO) FIGSIZE = (8, 3) self.window_id = next(self.id_generator) self.master = master self.toolitems = toolitems self.master.protocol("WM_DELETE_WINDOW", self.master.q...
def is_alive(self): return self.alive == True def is_target_alive(self, target): return target.alive == True def damage_boost(self, target): if self.type == "Fire" and target.type == "Water": boost = 0.5 return boost elif self.type == "Water" and target.type == "F...
This code defines an 'attack' method where a character (self) deals damage to a target if both are alive. It calculates damage using a boost factor, applies it to the target's health, and checks for experience gain if the target dies.
def attack(self, target): if self.is_alive(): if self.is_target_alive(target): damage = self.damage_boost(target) * self.level * 3 print("> {} attacks {} and deals {} Damages (Boost x{})".format(self.name, target.name, damage, self.damage_boost(target))) ...
def draw_gui(self, level, player): """ Draws the game Graphical UI. Arguments: level -- an instance of the class Level player -- an instance if the class Player """ self.draw_level(level) self.draw_player(player) self.draw_text("black", "Your bag: ", (45,...
The main task of the code is to display and update game objects on the screen by rendering the GUI, handling events, updating the player's state, and maintaining a consistent frame rate using Pygame. It processes the level and player instances to visualize the game world, respond to user inputs, and ensure smooth gamep...
def display_game(self, level, player): """ Displays and updates the game objects on the screen. Arguments: level -- an instance of the class Level player -- an instance if the class Player """ self.draw_gui(level, player) self.pygame_event_get() self.upda...
def login(self): # Create user credentials handler for the program username, password = self.get_userpass() # Authenticate user if self.dbhandler.authenticate_user(username=username, password=password): return FacebookUserCredentials(username, password) return None...
This function provides a command-line interface (CLI) prompt for user interaction, offering login, signup, and exit options. It processes user commands using regex, authenticates login attempts, and navigates to the homepage upon successful login or signup. The loop continues until the user exits, ensuring interactive ...
def prompt(self): ''' This function gives the cli prompt to the user ''' print("\tWelcome to Facebook CLI") print("---Quick Help---") print("login ,for login to your account") print("signup , for create new account") print("----------------") whi...
def await_resource(resource, timeout=240): assert "/" in resource, resource start_time = get_time() while True: notice(f"Waiting for {resource} to become available") if run(f"kubectl get {resource}", output=DEVNULL, check=False, quiet=True).exit_code == 0: break if ge...
The function `run_step` executes commands specified in `step_data` for each site, handling Kubernetes context setup, command execution with path replacement, and waiting for resources, external IPs, HTTP responses, or console readiness. It skips "readme" commands and optionally checks for errors.
def run_step(work_dir, skewer_data, step_data, check=True): if "commands" not in step_data: return if "title" in step_data: notice("Running step '{}'", step_data["title"]) for site_name, commands in step_data["commands"].items(): site_data = skewer_data["sites"][site_name] ...
def check_environment(): check_program("base64") check_program("curl") check_program("kubectl") check_program("skupper") def apply_standard_steps(skewer_data): notice("Applying standard steps") for step_data in skewer_data["steps"]: if "standard" not in step_data: continue ...
The function `run_steps` executes predefined steps from `skewer_data`, skipping the "cleaning_up" step initially. It runs each step in a try block, handling exceptions by printing debug information if enabled, including Kubernetes and Skupper status checks. Finally, it ensures cleanup by executing the "cleaning_up" ste...
def run_steps(work_dir, skewer_data, debug=False): check_environment() apply_standard_steps(skewer_data) try: for step in skewer_data["steps"]: if step.get("id") == "cleaning_up": continue run_step(work_dir, skewer_data, step) if "SKEWER_DEMO" in E...
def _conv3x3_layer(self, layer_input, filter_shape, stride): """Convolutional layer Parameters: layer_input: Tensor output from previous layer filter_shape: list dimensions of filter stride: int number of strides to conv...
This code initializes a ResNet-like neural network for classification, defining placeholders for input images and labels, constructing convolutional and residual layers with configurable filters, applying batch normalization and ReLU activation, performing global average pooling, and setting up softmax output, cross-en...
def __init__(self, residual_units=3, class_num=10, learning_rate=.001): # creating placeholders inputs and output of variable size self.images = tf.placeholder(tf.float32, [None, 32, 32, 3]) self.labels = tf.placeholder(tf.float32, [None, class_num]) # starting filter configura...
def face_detector(img_path): ''' Function returns "True" if face is detected in image stored at img_path. Parameters: img_path (string): path to the image Returns: (boolean): "True" if face is detected, "False" otherwise ''' face_cascade = cv2.CascadeClassifier('ha...
The function detects if an input image contains a human face or a dog. If either is detected, it predicts the breed using `predict_breed`. If neither is detected, it returns an error message asking for a valid image.
def dog_breed_detector(img_path): ''' Function to detect dog breed for input image of human or dog. It returns an error if none. Parameters: img_path (string): input image path Returns: None ''' if face_detector(img_path) > 0: return(predict_breed(img...
def update_window3(self): company_tabs = [] for company in self.tickers: df1, df2, df3, df4, df5 = company_index_exhibit(company) company_info_layout = [] if not df1.empty: company_overview_layout = create_row_layout( df1, f"{comp...
This code manages a GUI window (window2) by handling user interactions such as opening URLs from a table, updating and launching other windows (window3, window5, window6, window7) based on button presses, and closing the window when the user exits. It processes events like table selections, sentiment analysis triggers,...
def run_window2(self): while True: event, values = self.window2.read() if event == sg.WIN_CLOSED: break if event == "-TABLE-": # First selected row row_clicked = values["-TABLE-"][0] url = self.data_overview[row...
def updateSheet(sheet): for city in sheet["Weather"][1:]: if(city[4]==1): cityName = getCityName(city[0],sheet) temp = fetchWeatherForCity(cityName) if(city[3]=="F"): city[1]=round(convertToFahrenheit(temp["temp"]),1) elif (city[3]=="C"): ...
The code defines a function `intervalScript` that schedules itself to run every 30 seconds using a timer. It retrieves data from a file, updates a sheet with this data, and prints an acknowledgment. The global timer `t` ensures the function recurs periodically.
def intervalScript(): global t t= threading.Timer(30.0, intervalScript) t.start() updateSheet(getFile(fileName)) printAck()
def _is_scope_subset(self, needle_scope, haystack_scope): needle_scope = set(needle_scope.split()) haystack_scope = set(haystack_scope.split()) return needle_scope <= haystack_scope def _is_token_expired(self, token_info): now = int(time.time()) return token_info['expires_at'] <...
This function retrieves a cached authentication token from a specified file path. It validates the token's scope and checks expiration. If valid, it returns the token; if expired, it refreshes using the refresh token. If the cache file is inaccessible or scopes don't match, it returns None.
def get_cached_token(self): ''' Gets a cached auth token ''' token_info = None if self.cache_path: try: f = open(self.cache_path) token_info_string = f.read() f.close() token_info = json.loads(token_info_string) ...
def xg_dataprep(data_json_dir, data_info_dir, output_dir, mode): #Read in data_info and json_data data_info = pd.read_csv(data_info_dir) df = process_json_data(data_json_dir, mode) #Train - test split by geneid train_test_split_proportion = 0.8 df_train, df_valid, data_info_train, data_info_va...
The main task of the code is to execute a machine learning pipeline: preprocess data using different methods (xg_old/xg_new/zac), train a sklearn model if not prefit, evaluate its performance on validation data using predicted probabilities, and return the trained model. It handles data preparation, model training, val...
def full_pipeline(data_json_dir, data_info_dir, output_dir,sklearn_model, who_mode, prefit, processed): if who_mode =="xg_old": xg_dataprep(data_json_dir, data_info_dir, output_dir, "old") elif who_mode == "xg_new": xg_dataprep(data_json_dir, data_info_dir, output_dir, "new") elif who_mode =...
def nav_column_style(): return lambda cls: f""" .{cls} {{ display: flex; flex-direction: column; padding: 12px; gap: 12px; }} @media(max-width: {get_max_width_breakpoint()}) {{ .{cls} {{ display: none; }...
The main task of the code is to generate a navigation column for a webpage, including a logo image, a header link to the homepage, a divider, and navigation links. It uses a `doc` object to create structured HTML elements with specified styles, dimensions, and content, organizing them into a cohesive sidebar layout.
def nav_column(doc): class_name = doc.style(nav_column_style()) width, height = get_logo_dimensions() img_url = get_logo_url() with doc.tag("div", {"class" : class_name}): doc.tag("img", {"src" : img_url, "width" : width, "height" : height}) with doc.tag("h1", {"class" : doc.style(header...
def print_board(self): board = self.reverse_board_order(self.board) print(board) print("\n-------") for row in board: for element in row[:-1]: print(element, end=" ") print(row[-1]) print("-------") def move(self, player): if self....
The code runs a game loop where two players take turns making moves on a board until a winner is determined. It prints the board layout, alternates moves between players, checks for a win after each move, and returns the winning player if one is found. If no winner is determined, it returns the current state.
def run(self): self.print_board() print('board reads left to right, top to bottom. Top left corner = 1, top right corner = 3, bottom left corner = 7, bottom right corner = 9, etc. You are playing against a random player.') while self.winner is None: self.move(self.p1) sel...
def read_topics(topic_files=['../../data/misinfo-resources-2021/topics/misinfo-2022-topics.xml', '../../data/misinfo-resources-2021/topics/misinfo-2021-topics.xml']) -> dict: """ Read Qrels from multiple TREC topic XML file. :param topic_files: list of topic filenames :retur...
The function processes multiple CSV files containing model responses, extracts key data (query ID, question, answer, stance), matches them against ground truth from TREC topics, and compiles results into a structured DataFrame. It cleans data, compares ChatGPT answers to ground truth, and returns a table with labels, f...
def read_results_csv(csv_files, topics=read_topics(), label="") -> pd.DataFrame: """ Process the supplied CSV files into Dataframe of results :param csv_files: list of CSV files :param topics: list of TREC topic files :return: Dataframe with one row per topic per file. """ results = [] f...
def InputValidation(inp): match inp.lower(): case '1': return True case '2': return True case '3': return True case '4': return True case 'q': return True case _: return False def ShowSellerRankin...
The main task of the code is to present a menu-driven interface allowing users to select options for viewing seller rankings, inserting sales, viewing sales history, displaying credits, or quitting. It validates input and executes corresponding functions based on user choices, ensuring valid selections through a loop.
def SelectOption(): userInput = '' print('\n- Select an option:') while True: userInput = input(' (1) Show seller ranking (2) Insert sale (3) Show Sales history (4) Show Credits (Q) Quit application\n') if InputValidation(userInput): break print('\n- Select a valid opt...
def add_2(mat): r = random.randint(0,3) c = random.randint(0,3) while mat[r][c] !=0: r = random.randint(0,3) c = random.randint(0,3) mat[r][c] = 2 return mat def display_board(mat , board): #compensating the number to be in between of a particular block in the board i...
The code implements a 2048 game where the player controls tile movements (WASD) on a 4x4 grid. It initializes the board with two '2's, processes moves, checks game states (win/loss), adds new tiles when possible, and allows replay after winning/losing. The loop continues until the player chooses to stop.
def main(): board = ['' for x in range(16)] mat = [[0 for x in range(4)] for x in range(4)] mat = add_2(mat) mat = add_2(mat) status = None name = input("HI TRAVELLER ! WHAT IS YOUR NAME ? ") wanna_play = input("HI {} , WELCOME TO 2048 GAME ! DO YOU WANNA PLAY THIS GAME ? (ENTER YES OR NO) ...
def init(): # method for designing board in the starting of the game global score , high_scores mat = [[0 for x in range(4)] for x in range(4)] mat = add_2(mat) mat = add_2(mat) score , high_score = 0,0 return mat def move_up(mat): mat = transpose(mat) mat , change = move_left(mat) mat = transpose(mat) retu...
This code implements a 2048-like tile-merging game using Pygame. It initializes a game board, handles keyboard input for tile movement, updates the score, tracks high scores, and renders the game state. The main loop processes events, updates the game matrix (mat) based on directional inputs, adds new tiles after valid...
def main(): global score , mat run = True clock = pygame.time.Clock() board = ['' for x in range(16)] mat = init() score = 0 high_score = 0 while run : clock.tick(FPS) ind = 0 for i in mat: for j in i: if j != 0 : board[ind] = str(j) else: board[ind] = "" ind += 1 for event...
def cal_fitness_rmse(population, size_population, fitness_population): fitness = [] for possibility in range(0,size_population): if fitness_population[possibility] == -1: possibility_test = [] for item in range(0,total_prototypes): possibility_test.append(int((population[possibility])[item])) seeds_...
This code implements a genetic algorithm to optimize prototype selection for a given fitness function (RMSE or alternative). It initializes a population of 600 individuals, evaluates fitness, and iteratively evolves the population through crossover, mutation, and elitism. The goal is to find the optimal set of prototyp...
def prototypes_ga(tipo_fitness): prototypes=[] #create initial population size_population = 600 population = np.zeros(shape=(size_population,total_prototypes)) for aux in range(0,size_population): individual_random = np.zeros(total_prototypes) individual_random = np.random.choice(total_points_train, total_pro...
def balance_factor(root: NodeOfAVLTree) -> int: lh = get_height(root.left) rh = get_height(root.right) return lh - rh def rotate_left(root: NodeOfAVLTree) -> NodeOfAVLTree: result = root.right temp = root.right.left root.right.left = root root.right = temp update_height(root) updat...
This function balances an AVL tree by performing rotations on the root node based on its balance factor. If the balance factor exceeds 1 (left-heavy) or is less than -1 (right-heavy), it applies left or right rotations respectively, with additional checks for double rotations when child nodes have opposite balance fact...
def apply_rotation(root: NodeOfAVLTree) -> NodeOfAVLTree: bf = balance_factor(root) if bf > 1: if balance_factor(root.left) == -1: root.left = rotate_left(root.left) return rotate_right(root) elif bf < -1: if balance_factor(root.right) == 1: root.right = ro...
def update_height(root: NodeOfAVLTree): lh = get_height(root.left) rh = get_height(root.right) root.height = max(lh, rh) + 1 def apply_rotation(root: NodeOfAVLTree) -> NodeOfAVLTree: bf = balance_factor(root) if bf > 1: if balance_factor(root.left) == -1: root.left = rotate_lef...
This function inserts a key into an AVL tree, recursively placing it in the correct position, then updates the tree's height and applies necessary rotations to maintain balance. It handles duplicate keys by notifying the user and ensures the AVL property is preserved through rotations after insertion.
def insert(root: NodeOfAVLTree, key: int) -> NodeOfAVLTree: if root is None: return NodeOfAVLTree(key) elif root.data > key: root.left = insert(root.left, key) elif root.data < key: root.right = insert(root.right, key) else: print(f"key {key} already exists in the Tree...
def update_height(root: NodeOfAVLTree): lh = get_height(root.left) rh = get_height(root.right) root.height = max(lh, rh) + 1 def apply_rotation(root: NodeOfAVLTree) -> NodeOfAVLTree: bf = balance_factor(root) if bf > 1: if balance_factor(root.left) == -1: root.left = rotate_lef...
This function deletes a node with the specified key from an AVL tree, maintaining balance through rotations and height updates. It handles cases where the node has no children, one child, or two children, using an inorder successor for the latter. After deletion, it ensures the tree's height is updated and applies nece...
def delete(root: NodeOfAVLTree, key: int) -> NodeOfAVLTree: if root is None: print(f"key {key} is not present in the Tree") elif root.data > key: root.left = delete(root.left, key) elif root.data < key: root.right = delete(root.right, key) else: if root.right is None: ...
def home(): with st.container(border = True, height = 660): # Apply the custom CSS st.markdown(custom_css, unsafe_allow_html=True) st.markdown('<h1 class="center-heading">EXERCISE MONITORING SYSTEM</h1>', unsafe_allow_html=True) print("Home") def group...
The main task of the code is to create a Streamlit sidebar menu with customizable options, icons, and styles, routing users to different functions (Home, Groups, Dashboard, etc.) based on their selection. It uses `option_menu` to define the menu structure, applies specific styling for container, icons, and navigation l...
def main_1(): with st.sidebar: selected = option_menu( menu_title="Main Menu", # required options=["Home", "Groups", "Dashboard", "Requests", "Profile", "Logout"], # required icons=["house", "people-fill", "display-fill", "chat-left-fill", "person-circle", "box-arrow-ri...
def parse(puzzle_input): """Parse input""" puzzle_input = puzzle_input.split("\n\n") puzzle_input = [p.split("\n") for p in puzzle_input] return [list(map(eval, p)) for p in puzzle_input] def part1(data): """Solve part 1""" right_order = [] for i, pair in enumerate(data, start=1): if...
The code defines a function `solve` that processes a puzzle input by parsing it into structured data, then computes two solutions using separate functions (`part1` and `part2`). It returns both solutions as a tuple. The main task is to solve a puzzle by analyzing input data through two distinct computational steps and ...
def solve(puzzle_input): """Solve the puzzle for the given input""" data = parse(puzzle_input) solution1 = part1(data) solution2 = part2(data) return solution1, solution2
def parse_data(puzzle_input): """ Parse input Resource types are indexed with integers: 0 = ore 1 = clay 2 = obsidian 3 = geode """ bps = [] for line in puzzle_input.splitlines(): bp = [] maxspend = [0] * 3 # how much resources can we spend at ea...
The main task of the code is to solve a puzzle by parsing input data and computing two parts of the solution. It processes the input using `parse_data`, then yields results from `part1` and `part2` functions, which likely represent distinct steps or sub-problems in the puzzle-solving process.
def solve(puzzle_input): """Solve the puzzle for the given input""" data = parse_data(puzzle_input) yield part1(data) yield part2(data)
def part1(data): """Solve part 1""" return run_game(data, 20, part=1) def parse(puzzle_input): """Parse input""" monkey_re = re.compile( r"Monkey (?P<idx>\d+):\n" r"\s+Starting items: (?P<items>.*?)\n" r"\s+Operation: new = (?P<op>.*?)\n\s" r"+Test: divisible by (?P<test>...
The code defines a `solve` function that processes a puzzle input by parsing it, then computes two solutions using `part1` and `part2` functions. It returns both solutions as a tuple. The main task is to split the puzzle into two distinct problems, solve each separately, and combine their results. The function is struc...
def solve(puzzle_input): """Solve the puzzle for the given input""" solution1 = part1(parse(puzzle_input)) solution2 = part2(parse(puzzle_input)) return solution1, solution2
def _make_divisible(self, v, divisor, min_value=None): if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) if new_v < 0.9 * v: new_v += divisor return new_v def _conv_block(self, inputs, filters, kernel, stri...
This code defines a MobileNetv2 architecture with a customizable width parameter (alpha). It constructs the network by stacking convolutional blocks and inverted residual blocks, progressively increasing feature depth while controlling model complexity through alpha. The function returns the built neural network model ...
def BaseMobileNet(self, inputs, alpha = 1.0): """MobileNetv2 This function defines a MobileNetv2 architectures. # Arguments input_shape: An integer or tuple/list of 3 integers, shape of input tensor. k: Integer, number of classes. alpha: Intege...
def BaseMobileNet(self, inputs, alpha = 1.0): """MobileNetv2 This function defines a MobileNetv2 architectures. # Arguments input_shape: An integer or tuple/list of 3 integers, shape of input tensor. k: Integer, number of classes. alpha: Intege...
The function `build_age_branch` constructs a neural network branch for age prediction in a face recognition model. It processes inputs through a MobileNet base, applies convolutional blocks, global average pooling, dropout, and a final 1x1 convolution to output a single age value. The branch uses adjustable width via `...
def build_age_branch(self, inputs, alpha = 1.0): """ Used to build the age branch of our face recognition network. This branch is composed of three Conv -> BN -> Pool -> Dropout blocks, followed by the Dense output layer. """ k = 1 x = self.BaseMobileNet(input...
def BaseMobileNet(self, inputs, alpha = 1.0): """MobileNetv2 This function defines a MobileNetv2 architectures. # Arguments input_shape: An integer or tuple/list of 3 integers, shape of input tensor. k: Integer, number of classes. alpha: Intege...
The code constructs a gender classification branch for a face recognition network. It converts inputs to grayscale, processes them through a MobileNet-based feature extractor, applies global average pooling, dropout regularization, and a final convolutional layer to output a softmax probability distribution over specif...
def build_gender_branch(self, inputs, num_genders=2, alpha = 1.0): """ Used to build the gender branch of our face recognition network. This branch is composed of three Conv -> BN -> Pool -> Dropout blocks, followed by the Dense output layer. """ x = Lambda(lambda c: tf....
def BaseMobileNet(self, inputs, alpha = 1.0): """MobileNetv2 This function defines a MobileNetv2 architectures. # Arguments input_shape: An integer or tuple/list of 3 integers, shape of input tensor. k: Integer, number of classes. alpha: Intege...
The code constructs a neural network branch for race classification in a face recognition model. It processes inputs through a MobileNet base, applies convolutional blocks, global average pooling, dropout, and outputs a softmax-activated dense layer with `num_races` classes, providing probability distribution over race...
def build_race_branch(self, inputs, num_races = 5, alpha = 1.0): """ Used to build the race branch of our face recognition network. This branch is composed of three Conv -> BN -> Pool -> Dropout blocks, followed by the Dense output layer. """ k = num_races x = se...
def build_age_branch(self, inputs, alpha = 1.0): """ Used to build the age branch of our face recognition network. This branch is composed of three Conv -> BN -> Pool -> Dropout blocks, followed by the Dense output layer. """ k = 1 x = self.BaseMobileNet(input...
This code constructs a multi-task deep learning model named 'face_net' that processes input data through three parallel branches for age, gender, and race prediction. It uses shared inputs and alpha parameter for branch-specific processing, combining outputs into a single model with three distinct prediction heads.
def build_multi_model(self, input_shape, alpha = 1.0): inputs = Input(shape=input_shape) age_branch = self.build_age_branch(inputs, alpha = alpha) gender_branch = self.build_gender_branch(inputs, alpha = alpha) race_branch = self.build_race_branch(inputs, alpha = alpha) model = M...
def init_openai(model=DefaultLLM): global Client, LLM openai.api_key = os.getenv("OPENAI_API_KEY") if openai.api_key==None: print(OpenAI_KEY_notset) return Client = OpenAI() LLM=model return (Client, LLM) def read_page_list(filename): with open(filename, 'r') as f: li...
This function processes web texts by embedding each split string from URLs, storing embeddings with metadata in a file. It reads text lists, splits content, generates embeddings, indexes text parts, saves results in NPZ format, and returns embeddings with metadata including model, folder, and text details.
def embedweb(webfolder=WebFolder, model=DefaultLLM): # This function embeds all the texts in the web folder # It first creates the string TextListFile that contains the list of URLs and the list of texts # It then creates the string EmbeddingFileName that will be the file to take the embeddings and the metadata...
def embedweb(webfolder=WebFolder, model=DefaultLLM): # This function embeds all the texts in the web folder # It first creates the string TextListFile that contains the list of URLs and the list of texts # It then creates the string EmbeddingFileName that will be the file to take the embeddings and the metadata...
The function updates or creates embeddings for a web folder by checking if an existing embedding file exists. If not, it generates new embeddings. If the file exists, it verifies the model consistency and compares text titles between metadata and a list file. New titles are processed by fetching text, splitting into se...
def update_embeddings(webfolder=WebFolder, model=DefaultLLM): # This function updates the embeddings for the web folder. # It checks if there is an embedding file for the web folder specified. # If not, it creates the embedding file. # If there is an embedding file, it checks the follolwing: # 1. If...
def next_day(): increment_day(1) def previous_day(): increment_day(-1) def previous_week(): increment_day(-7) def next_week(): increment_day(7) def add_event(stdscr): win = curses.newwin(1, 50, 1, 1) box = Textbox(win) rectangle(stdscr, 0, 0, 2, 52) stdscr.refresh() box.edit() ...
This function processes keyboard inputs to navigate a calendar interface, triggering actions like moving to the next/previous day, advancing to the next/previous week, or adding an event. It maps specific key presses to corresponding functions, enabling user interaction with a calendar system.
def handle_key_calendar_mode(key, stdscr): if key == config.NEXT_KEY: next_day() elif key == config.PREVIOUS_KEY: previous_day() elif key == config.UP_KEY: previous_week() elif key == config.DOWN_KEY: next_week() elif key == config.ADD_EVENT_KEY: add_event(std...
def draw_month_header(window): calendar_width = (cell_width + 1) * 7 + 1 core_string = "| " + str(current_year) + " - " + get_month_string(current_month - 1) + " |" top_string_width = len(core_string) top_string = "" for i in range(top_string_width): top_string += "-" padded_top_string ...
This function draws a calendar in a specified window for a given date (year, month, day), incorporating event dates and holidays. It updates global variables with the current date and event/holiday data, then renders the calendar by clearing the window, drawing the month header, weekdays, a delimiter, and the calendar ...
def draw_calendar(window, year, month, day, dates_with_events=[], holidays_parameter=[]): global current_year global current_month global current_day global events_dates global holidays current_year = year current_month = month current_day = day events_dates = dates_with_events ...
def cycle_mode(): global current_state if current_state.mode == Modes.CALENDAR: current_state.mode = Modes.EVENTS current_state.selected_event = 0 else: current_state.selected_event = None current_state.mode = Modes.CALENDAR def handle_key_calendar_mode(key, stdscr): if ...
This function handles key presses by either switching modes (if the key matches the cycle mode key) or delegating to mode-specific handlers (Calendar or Events mode). It returns the updated current state after processing the key input.
def handle_key_pressed(key, stdscr): # Handle switch mode key if key == config.CYCLE_MODE_KEY: cycle_mode() return current_state # Handle key for current mode if current_state.mode == Modes.CALENDAR: handle_key_calendar_mode(key, stdscr) elif current_state.mode == Modes.EVE...
def check_random_state(seed: int): """ Checks the random seed. :param seed: Seed number :return: Random seed """ if seed is None or seed is np.random: return np.random.mtrand._rand if isinstance(seed, numbers.Integral): return np.random.RandomState(seed) if isinstance(s...
The function performs t-SNE (t-distributed Stochastic Neighbor Embedding) to reduce the dimensionality of input data `X` to a 2D representation. It calculates pairwise affinities using either 'exact' or 'barnes_hut' methods, initializes 2D points with Gaussian noise, and applies gradient descent in two phases: early ex...
def TSNE(X: np.array, perplexity: int = 30, n_iter: int = 1000, learning_rate: float = 200., early_exaggeration: float= 4.0, method: str = "exact", random_state: int = None, verbose: int = 0): """ Calculates 2d representation of input data. :param X: Input data :param perplexity: Input perplex...
def init_db(): try: with open("flag.txt", "r") as f: flag = f.read().strip() except: flag = "you_need_to_connect_to_the_remote_service_to_get_the_flag" printline("Unable to open flag.txt. Using dummy flag value: {flag}".format(flag=flag)) # Use non-persistent database, s...
The main task of the code is to initialize a database, display a message about being stuck on YouTube during a reunion dinner, and then enter an infinite loop to keep the program running indefinitely.
def main(): init_db() printline("It's time for reunion dinner, but you are hooked onto YouTube videos...") loop_forever()
def initialize(): return [] def fib_fun(m = 0, nlimit = 20, floatLim = np.finfo(np.single).max): ''' Parameters ---------- m : int, optional Index of the current element. The default is 0. nlimit : TYPE, optional If int, stops the sequence at the n-th element, else- b...
The code calculates the sum of all even Fibonacci numbers using a brute-force method. It initializes a Fibonacci sequence, filters even numbers, and sums them, returning the result as a 32-bit float.
def run(): ''' Returns ------- sumFibEven : float32 (np.single) A sum of all even Fibonacci numbers meeting the criteria. Brute force approach (each number checked individually). ''' limit = True tab = initialize() tab = fib_fun(nlimit = limit) idxAndVal = is_even(...
def get_year_month(date: datetime): """Get year month for scoring data""" relative_date = date - relativedelta(months=1) year = relative_date.year month = relative_date.month return year, month def get_file_path(destination_dir: str = "", filename: str = "", logger: get_run_logger = None): ""...
The main task of the code is to process and score bike trip data for a specified date. It reads input data (CSV/Parquet), preprocesses features, applies scoring logic, outputs results to S3, and cleans temporary files. The function handles date resolution, file path management, and data format-specific reading (local/S...
def batch_score(date: datetime = None): """Main python function that runs the script""" logger = get_run_logger() run_date = '' if date is None: ctx = get_run_context() run_date = ctx.flow_run.expected_start_time else: run_date = date year, month = get_year_month(date=r...
def random_nbit_prime(n): while True: p = random_nbit_integer(n) if is_prime(p): return p def gcd(a,b,k,seed): p=b+1 while b: a, b = b, a%b if int(bin(p)[:k/4+32],2) < seed: return a else: return 2 def fast_multiply(p, qv, k, seed): e = 65537 ...
The main task of the code is to generate RSA cryptographic parameters (e, n, p, q, d) with a fixed 1024-bit size, using a predefined seed for deterministic prime generation. It validates the input 'e' value, ensures coprimality with p-1, computes the RSA modulus n = p*q, and derives the private exponent d via modular i...
def generate(self, e=65537, size=1024): if type(e) not in [int, long]: raise ValueError("Bad e") if e < 3: raise ValueError("Too small e") if size != 1024: raise ValueError("Only 1024 size is implemented at the moment") k = size seed = 47628311...
def _setup(self) -> None: pass def _send(self) -> None: tx = self._tx_var.get() self.msgs.append(tx) self._update() if tx and self._serial is not None: self._tx.put(tx) self._tx_var.set('') def _down(self) -> None: self._set_msg_index(self.msgs_i -...
This code initializes a GUI application for serial communication, setting up a Tkinter interface with port selection, baud rate configuration, data termination options, and send/receive functionality. It integrates with settings management, thread-based port monitoring, and a text-based output display, enabling users t...
def __init__(self): super().__init__() self._setup() self.style = ttk.Style() self.style.theme_use('clam') self._serial: Serial = None self.settings = Settings.open() self.protocol("WM_DELETE_WINDOW", self._save_settings) self._baud = tk.String...
def generate_keys() -> ((int, int, int), int): p = generate_large_random_prime() start = time.time() g = find_generator_faster_hopefully(p) end = time.time() # print(f"Finding {g} took {end - start}") # start = time.time() # g = find_generator(p) # end = time.time() # print(f"Findin...
The code tests the correctness of an RSA-like encryption/decryption process by generating 1000 key pairs, encrypting a message with each public key, decrypting it with the corresponding private key, and verifying the decrypted output matches the original message using assertions.
def test(): for i in range(1000): pub_key, priv_key = generate_keys() rem, quot = encode_text(message, pub_key[0]) # message, 0 < m < p-1 encoded = encrypt(rem, pub_key) decoded = decrypt(encoded, priv_key, pub_key[0]) assert decode_text(decoded, pub_key[0], quot) == messag...
def get_channels(args): page = count() while True: query = build_query(args, next(page)) chunk = fetch_page(args, query)['result']['results'] if len(chunk) == 0 or not args.group_by_channels and ( 'infohash' in chunk[0].keys() and chunk[0][ 'availability_u...
The main task of the code is to generate an M3U playlist from channel data, handling grouping, icons, and URL filtering. It yields JSON/XML outputs if specified, but defaults to constructing an M3U string by iterating channels, appending playlist entries with `make_playlist`, and yielding the result after processing gr...
def convert_json(args): counter = count(1) for channels in get_channels(args): # output raw json data if args.json: yield json.dumps(channels, ensure_ascii=False, indent=4) # output xml epg elif args.xml_epg: for group in channels: yield ma...
def conv_bn_relu_layer(input_layer, filter_shape, stride, monitored_tensor_list): ''' A helper function to conv, batch normalize and relu the input tensor sequentially :param input_layer: 4D tensor :param filter_shape: list. [filter_height, filter_width, filter_depth, filter_number] :param stride: s...
The function constructs a ResNet with `n` residual blocks per stage, processing a 4D input tensor. It applies convolutional layers (conv0), followed by blocks with increasing channels (64 → 128 → 256 → 512), using residual connections. Batch normalization and ReLU are applied at each stage. A global average pooling and...
def inference(input_tensor_batch, n=1, reuse=False): ''' The main function that defines the ResNet. total layers = 1 + 2n + 2n + 2n +1 = 6n + 2 :param input_tensor_batch: 4D tensor :param n: num_residual_blocks :param reuse: To build train graph, reuse=False. To build validation graph and share weig...
def register_param_item(self, key: str, value: Any): self.params.append((key, str(value))) def make_search_options(self): self.rh_items: List[Tuple[str, str]] = [] item = self.category_info["subcategory"] if item: self.register_rh_item("n", item.value) item = self.g...
The main task of the code is to construct a parameter string by collecting key-value pairs from various attributes like category, sorting method, search options, and keywords. It checks if each attribute exists, registers them with specific keys ("i", "s", "rh", "k"), and returns the formatted string via `get_params_st...
def make_param_string(self): # Usable self.params: List[Tuple[str, str]] = [] item = self.category_info["category"] if item: self.register_param_item("i", item.value) item = self.sorting_method if item: self.register_param_item("s", item.value) ...
def formatted(word) -> str: return word.strip().lower() def is_state(state): """ Assumes state as str, Lowers state into lowercase, Returns state if state input matches a state in list of USA states Returns None if state does not match any state in list of USA states ...
The code's main task is to verify a user's eligibility for a driver's license by collecting and validating inputs for the state of issuance, license type, and age. It prompts the user to proceed, then ensures valid entries through loops and checks, finally calling an eligibility function with the collected data.
def main(): print("\nIn order to verify your eligibility,\n\ I would need the full name of the state of issuance, the name of the license, and your age.") time.sleep(1) # initialize answer ans = '' # ensure user types in valid input while True: ans = input("\nWould you like to proceed?...
def createHeaders(self): if (Options.verbose): print(" Creating categoris from security namespaces.") categories = {} for commodity in Options.GNUCashXML.findall(".//gnc:commodity", Options.namespaces): category = commodity.find("./cmdty:space", Options.namespaces)...
The main task of the code is to generate an Asset Category CSV file by initializing report data, creating headers/rows, aggregating row totals across date ranges, and writing the structured data to a specified output file. It processes asset balance reports, organizes them with defined depth, and prepares them for CSV ...
def __init__(self, assetBalanceReport, options): if (Options.verbose): print(" Creating Asset Category CSV") self.reports = assetBalanceReport.report self.outputFile = options.OutputFile self.depth = options.Depth self.columns = self.createHeaders() ...
def AllAdj(c, A, b): """ Find neighboring cells of a given cell `c`. Parameters: c (list): Sign vector representing the cell. A (numpy array): Coefficients of the hyperplanes. b (numpy array): Constants of the hyperplanes. Returns: list: Sign vectors of neighboring cells. """ n...
The function `CellEnum` recursively enumerates all cells in a hyperplane arrangement by exploring adjacent cells. It tracks visited cells using a set to avoid cycles. For each cell, it generates adjacent cells by flipping sign vectors, checks if they are unvisited, and ensures they have the current cell as their parent...
def CellEnum(c, A, b, visited, root_point): """ Recursively enumerates all cells in the arrangement. Args: c: Sign vector representing the cell. A: Coefficient matrix of hyperplanes. b: Constant vector of hyperplanes. visited: Set to keep track of visited cells. """ if tuple(c) in v...
def fly(self): # actions when mario dosent touch the ground if self.up is True and self.down is False and self.jump is False: self.jump = True self.jumpSteps = 100 if self.down is True: self.fall() if self.jump is True: self.goingUp() def moveMar...
This method handles game updates in a timer-driven loop, executing Mario's actions (flying, movement, collecting coins), updating the score, moving enemies, checking collisions, and managing state recording/replay. It also updates the game scene for rendering.
def timerEvent(self, event): if event.timerId() == self.timer.timerId(): self.fly() self.moveMario() self.takeCoin() self.drawScore() self.moveEnemy() self.killMario() if self.film is True and self.filmSaving is False: ...
def draw_edges(self): edges = self.myGame.Graph.edges for e in edges.keys(): # find the edge nodes src = self.myGame.Graph.nodes[e[0]] dest = self.myGame.Graph.nodes[e[1]] X_src = self.my_scale(src.pos[0], x=True) Y_src = self.my_scale(src.pos...
This function handles Pygame event processing and rendering for a game interface. It quits the game on window close, toggles a button state on mouse clicks, scales and draws the background, game elements (edges, Pokadurs, Pokémon, agent), buttons, and movement grade, then updates the display.
def run(self, client: Client): global buttonRec global buttonPress for e in pygame.event.get(): if e.type == pygame.QUIT: pygame.quit() print(client.get_info()) exit(0) return False if e.type == pygame.MOUSE...
def createShadowConfig(ss_url, port=1080): config = deepcopy( mergeMultiDicts(dnsServers, inbounds, ssOut) ) config['inbounds'][0]['port'] = port server, server_port, method, password, plugin, plugin_opts, tag = parse_ss_withPlugin(ss_url) config['outbounds'][0]['settings']['plugin'] = plugin...
This function parses a given URL to generate and save configuration files for different proxy protocols (e.g., SS, Vmess, Vless, Trojan) based on the URL scheme. It creates the appropriate config using helper functions, validates inputs, handles base64 decoding for Vmess URLs, and writes the resulting JSON configuratio...
def createConfig(url, localPort, path): ParseResult = urllib.parse.urlparse(url) # <scheme>://<netloc>/<path>;<params>?<query>#<fragment> try: if ParseResult.scheme == "ss" : config = createShadowConfig(url, port=localPort) elif ParseResult.scheme == "vmess" : if isBase6...
def labelling(data, shift, threshold): labels = collect_labels(data, threshold) df = data.join(labels) df = df.sort_index() if shift: df = df.assign(y=df["Label"].shift(shift)).dropna().drop(["Label"], axis=1) df = df.rename(columns={"y": "Label"}) df.Label = df.Label.astype(int)...
The function prepares training and test datasets for a time series model by labeling data based on shift/threshold parameters, optionally smoothing labels, slicing sequences with a window size, splitting data, and one-hot encoding labels. It returns processed features, encoded labels, and corresponding dates for traini...
def create_train_test(df_train, args): test_size = args.test_size window_size = args.window_size shift = args.shift threshold = args.threshold df_train = labelling(df_train, shift, threshold) if args.smooth: range_buy_sell(df_train, args.range_tolerance) print(df_train.query("Label ...
def retract_needle(self): self.get_logger().warn("Retracting needle!") self.command_insertion_depth(-5.0) def increment_y_axis(self): self.get_logger().info(f"Incrementing y-axis for {self.y_increment} mm") # self.pub_y_cmd.publish(Float32(data=self.y_increment)) self.command_rob...
This function manages sequential insertion depth commands during a robotic insertion task. It cycles through predefined depths, logs progress, and initiates a new trial by retracting the needle and advancing the y-axis when the depth list is exhausted.
def command_next_insertion_depth(self): """ Command to the next insertion depth """ if self._current_insdepth_idx >= len(self.insertion_depths): self.retract_needle() self.get_logger().info("Beginning new insertion trial!") self.increment_y_axis() self._c...
def command_insertion_depth(self, depth): """ Command the robot to a specified insertion depth """ x_ax_pos = min(depth, self.ax_x_max) ls_ax_pos = min(-(depth - x_ax_pos), 0.0) self.get_logger().info( f"Commanding insertion depth to {depth} mm | X->{x_ax_pos} mm and LS->{l...
This function processes user input to control insertion depth or trigger actions. It checks if the input is a float to adjust depth, handles "reset" to reset insertion, "quit" to exit, empty input for next depth step, and logs warnings for invalid commands.
def handle_keyinput(self, keyinput: str): if utilities.isfloat(keyinput): self.command_insertion_depth(float(keyinput)) elif keyinput.lower() == "reset": self.reset_insertion() elif keyinput.lower() == "quit": return False elif keyin...
def deal_initial_cards(self): self.player_hand.append(self.deck.deal()) self.banker_hand.append(self.deck.deal()) self.player_hand.append(self.deck.deal()) self.banker_hand.append(self.deck.deal()) def calculate_score(hand): count = 0 for i in hand: count += rank_int(i) ...
The code simulates a card game round by dealing initial cards, calculating scores, and determining the winner. If either player or banker has a score of 8 or higher, the round ends immediately. Otherwise, it proceeds with the player's and banker's turns before finalizing the winner.
def play_round(self): self.deal_initial_cards() player_total = calculate_score(self.player_hand) banker_total = calculate_score(self.banker_hand) if player_total >= 8 or banker_total >= 8: return self.determine_winner() else: self.player_turn() ...
def get_peripheral_properties(cfg, peripheral): return __get_peripheral_properties(cfg, peripheral, exclude_properties="", exclude=False) def count_peripheral(cfg, peripheral): count = 0 props = get_peripheral_properties_exclud...
The code processes a peripheral configuration to generate a structured dictionary. It retrieves properties, counts instances, and builds a group with device details like name, label, address, size, and interrupts. It handles controllers and non-controllers differently, appending indices for non-controllers. The result ...
def get_peripheral_group(cfg, peripheral): props = [] peripheral_group = {} count = 0 peripheral = peripheral.upper() peripheral_lo = peripheral.lower() props = get_peripheral_properties(cfg, peripheral) count = count_peripheral(cfg, peripheral) peripheral_group = {peripheral: {}} ...
def get_cpu_isa(cfg, core): isa = "rv32i" #base extension system_core = "SYSTEM_RISCV_ISA_" value = get_property_value(cfg, system_core, MMU) if value == "1": # append 'm' for math RISCV instruction extension isa = "{}m".format(isa) value = get_property_value(cfg, system_core, ATOM...
This function generates CPU metadata for a system configuration by extracting ISA, cache parameters, and other properties from a given config. It constructs a dictionary (`node`) with keys like `name`, `addr`, `isa`, and cache details. If cache data is available, it includes cache settings; otherwise, it checks for MMU...
def get_cpu_metadata(cfg, idx=0): node = {} core = "core{}".format(idx) isa = get_cpu_isa(cfg, idx) icache_way = get_cache_way(cfg, idx, ICACHE) icache_size = get_cache_size(cfg, idx, ICACHE) dcache_way = get_cache_way(cfg, idx, DCACHE) dcache_size = get_cache_size(cfg, idx, DCACHE) cac...
def get_buses(): return BUSES def get_peripherals(cfg, filter_peripherals): peripherals = [] for line in cfg: for x in filter_peripherals: if x in line: peripherals.append(x) # remove duplicate from list peripherals = list(dict.fromkeys(peripherals)) return...
The code parses a configuration file to organize peripherals and buses into structured groups, then combines them into a single dictionary. It reads the input file, extracts peripheral and bus data, categorizes them using helper functions, and merges the results into a unified SOC configuration dictionary for further u...
def parse_soc_config(filename): soc_config = {} peripheral_groups = {'peripherals': {}} bus_groups = {'buses': {}} buses = get_buses() cfg = read_file(filename) peripherals = get_peripherals(cfg, PERIPHERALS) peripheral_groups = get_peripheral_groups(cfg, peripherals) bus_groups = get_...
def encode(self, Y): Y_encoded = np.zeros((len(Y), len(self.output_layer.output_values)), dtype=float) for i in range(len(Y)): y = Y[i] Y_encoded[i, self.classes.index(y)] = 1 return Y_encoded def step_gradient(self, X, ya, lr): hidden_layers = self.hidden_layers ...
The code performs gradient descent optimization by iteratively updating model parameters using the `step_gradient` method. It calculates the cost function after each iteration, comparing the encoded target values (`ya`) with the model's predictions on input data `X`, and prints the iteration number along with the curre...
def gd(self, X, Y, lr, num_itr): ya = np.array(self.encode(Y)) for i in range(num_itr): self.step_gradient(X, ya, lr) print(i, "Cost:" ,self.cost(ya, np.array(self.predict_encoded(X))))
def F_beta(predicted_data,actual_data,beta,data_possibilities): #p: precision, r: recall. Predicted data and actual data must be the same size. At the moment will not work for multi-class true_pos, true_neg, false_pos, false_neg = get_confusion_matrix_data(predicted_data,actual_data,data_possibilities) p = ...
The function `get_metric` calculates a specified evaluation metric (F-beta, Precision, Recall, Accuracy, or AUC) based on input results and test data. It conditionally executes corresponding helper functions, with AUC also generating a ROC curve plot if enabled. The computed score is returned.
def get_metric(results, test_set_dice_score, test_set_dice_score_numerical_value, beta, data_possibilities, plot, metric, k, folder_temp): # plot = 1 (plot) or = 0 (no plot) if metric == 'F-beta': score = F_beta(results, test_set_dice_score, beta, data_possibilities) if metric == 'Precision': ...