dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def build_model(self):
self.model_input = self.left
self.left_pyramid = Loss.scale_pyramid(self.left, 4)
self.right_pyramid = Loss.scale_pyramid(self.right, 4)
self.build_residual_vae()
def build_outputs(self):
'''
Compute the output of the neural network i.e. the left ... | The code initializes a model by constructing its architecture (`build_model`), defining output layers/predictions (`build_outputs`), and setting up loss functions (`build_losses`). These steps prepare the model for training and evaluation by establishing its structure, outputs, and optimization criteria. | def __init__(self):
self.build_model()
self.build_outputs()
self.build_losses() |
def build_courses_map(path):
courses_map = dict()
data = pd.read_excel(path)
for (index, row) in data.iterrows():
courses_map[row['Asignatura']] = int(index)
return courses_map
def build_pensum(courses_map, path):
N = len(courses_map)
graph = [[] for i in range(N)]
edge = [0 for i in... | The code computes the minimum number of semesters required to complete a study plan, given a maximum number of courses per semester. It constructs a graph representing course prerequisites, builds a priority queue for topological sorting, and calculates the optimal schedule. The result is the smallest number of semeste... | def compute_min_semesters(max_courses, pensum):
courses_map = build_courses_map('./db/' + pensum[1] + '.xlsx')
N = len(courses_map)
(graph, edges) = build_pensum(courses_map, './db/' + pensum[0]
+ '.xlsx')
(priority_queue, visited) = build_priority_queue(graph, edges, N... |
def get_time_to_impact(self, x0, ignore_drag=False):
"""
Returns time to impact related variables as tuple:
- t seconds
- N steps at current framerate
- x position of ball
- z position of ball
"""
drag = self.drag
if ignore_drag:
drag = False
x... | This function precomputes trajectory parameters for a nonlinear system by simulating its motion from an initial state x0. It iteratively updates the system's state using a step function until a stopping condition (x_[3] > 0) is met, calculating the total time (t_n), steps (i), and final position (x_n, z_n) of the traje... | def precompute_trajectory(self, x0):
# get linear duration
t_n, N, x_n, z_n = self.get_time_to_impact(x0)
fr = FRAMERATE
if not self.is_nonlinear():
# nothing to do
return t_n, N, x_n, z_n
dims_ball = [2, 5, 8] # FIXME copied
# we need to pre-simulate
x_ = x0.reshape((-1,))
... |
def test_fitness(self, minion):
fitness = 0
building_blocks = build_blocks(minion)
# Grade how many building blocks for the goal the minion has.
for char in goal:
if char in minion and building_blocks[char] == self.goal_blocks[char]:
fitness += building_block... | This code executes a genetic algorithm (GA) to evolve a population of programs, tracking fitness improvements across generations. It breeds new programs, applies mutations, selects elites, and logs results to a file, terminating when fitness meets a goal, generation limit, or time constraint. The GA iteratively refines... | def now_go_do_that_voodoo_that_you_do_so_well(self):
"""
Main function, runs the whole GA.
:return: returns nothing.
"""
with open("theAncientScrolls.txt", 'w') as scribe:
# Record the first 5 programs to analyze later
scribe.write("Record of the SortingLo... |
def spawn_new_minion(self):
"""
Generates a single "program" - a list of MAL instruction strings separated by newlines.
:return:
"""
minion_length = 30 # Variable to adjust how many lines each program starts with.
new_minion = []
for _ in range(minion_length - 1... | This code initializes a genetic algorithm (GA) by setting parameters like maximum generations, population size, mutation chance, and tournament size. It creates an initial population of candidate solutions ("minions"), calculates their fitness, and prepares structures for the next generation. Elite clones are retained,... | def __init__(self, max_generations, population_size, mutation_chance, tournament_size):
"""
:param max_generations: The maximum number of generations that the GA will run.
:param population_size: The number of minions (candidate sorting programs) per generation.
:param mutation_chance: T... |
def build_blocks(string):
"""
Returns a dictionary with the characters in the string and the counts of each as the vals.
:param string:
:return:
"""
dictionary = {}
for char in string:
if char in dictionary:
dictionary[char] += 1
else:
dictionary[char... | This code initializes a genetic algorithm (GA) with parameters for max generations, population size, mutation chance, and tournament selection. It sets up population structures, tracks fitness values, elite members, and prepares GA components like tournament selection and mutation. The goal is to evolve candidate solut... | def __init__(self, max_time, max_generations, population_size, mutation_chance, tournament_size):
"""
:param max_generations: The maximum number of generations that the GA will run.
:param population_size: The number of minions (candidate sorting programs) per generation.
:param mutation... |
def image_to_head(self, is_training, reuse=False):
with tf.variable_scope(self.scope, self.scope, reuse=reuse):
net = slim.repeat(self.image, 2, slim.conv2d, 64, [3, 3],
trainable=is_training, scope='conv1')
net = slim.max_pool2d(net, [2, 2], padding='SAME', scope='pool1')
net = slim.repeat(net, 2, slim... | This function constructs a detection network by processing input images through convolutional layers, extracting subject and object regions via pooling, classifying these regions using shared weights, and storing classification probabilities and predictions along with intermediate layers for further processing or analy... | def build_dete_network(self, is_training=True):
net_conv = self.image_to_head(is_training)
sub_pool5 = self.crop_pool_layer(net_conv, self.sbox, "sub_pool5")
ob_pool5 = self.crop_pool_layer(net_conv, self.obox, "ob_pool5")
sub_fc7 = self.head_to_tail(sub_pool5, is_training, reuse = False)
ob_fc7 = self.head_t... |
def build_dete_network(self, is_training=True):
net_conv = self.image_to_head(is_training)
sub_pool5, sub_fc = self.crop_pool_layer(net_conv, self.sbox, "sub_pool5")
ob_pool5, ob_fc = self.crop_pool_layer(net_conv, self.obox, "ob_pool5")
self.layers['sub_pool5'] = sub_pool5
self.layers['ob_pool5'] = ob_pool5... | This function initializes a computational graph for a multi-task model combining detection, GAN, and relation networks. It defines input placeholders for images, bounding boxes, and labels, then constructs detector, GAN, and relation networks. The graph integrates these components for tasks like object detection, image... | def create_graph(self, N_each_batch, index_sp, index_cls, num_classes, num_predicates, keep_prob_gan = None):
self.image = tf.placeholder(tf.float32, shape=[1, None, None, 3])
self.sbox = tf.placeholder(tf.float32, shape=[N_each_batch, 4])
self.obox = tf.placeholder(tf.float32, shape=[N_each_batch, 4])
self.sub... |
def build_dete_network(self, is_training=True):
net_conv = self.image_to_head(is_training)
sub_pool5 = self.crop_pool_layer(net_conv, self.sbox, "sub_pool5")
ob_pool5 = self.crop_pool_layer(net_conv, self.obox, "ob_pool5")
sub_fc7 = self.head_to_tail(sub_pool5, is_training, reuse = False)
ob_fc7 = self.head_t... | This code defines a method to create a computational graph for a neural network model. It initializes TensorFlow placeholders for input data (images, bounding boxes, labels) and configures parameters. The method builds detection networks for objects and relationships, then adds loss functions for training. Key tasks in... | def create_graph(self, N_each_batch, index_sp, index_cls, num_classes, num_predicates):
self.image = tf.placeholder(tf.float32, shape=[1, None, None, 3])
self.sbox = tf.placeholder(tf.float32, shape=[N_each_batch, 4])
self.obox = tf.placeholder(tf.float32, shape=[N_each_batch, 4])
self.sub_sp_info = tf.placehol... |
def printBoard(board):
for i in range(3):
print('[',board[i][0],']','[',board[i][1],']','[',board[i][2],']')
def checkDraw(board):
possibleWin=False
for i in range(3):
# checking rows and columns to see if each of them has both an X and an O on them, therefore making it impossible to win on ... | The code implements a tic-tac-toe game loop where a player competes against an AI. It initializes the board, lets the player choose to go first or second, alternates turns between the player and AI, validates moves, executes the AI's optimal move using bestMove(), and checks for win/draw conditions. The game ends when ... | def game_loop(board):
# we set the board as the starting board and set the starting player as the player
board=STARTING_BOARD
playerTurn=True
# we ask the player if he wants to go first or second, and change who starts accordingly
decision=input("Welcome to tic-tac-toe. Input Y if you want to start... |
def display_pp(self, prefix, pp):
"""(Used for debugging)"""
self.m_log.debug(f"{prefix}{pp.m_name} {pp.m_type}")
def try_recommit(self, load_to_recommit, plan_tp):
"""Try ammending the solution for the given plan tuple by recommitting the given load to lower merit plants"""
initial_cost... | The function `rebalance` recursively optimizes a power plant load plan by addressing underloaded plants. It calculates costs for recommitting or repartitioning load, selects the cheaper option, adjusts the plan, and recursively rebalances until all demand is covered without exceeding capacity. Key steps include: checki... | def rebalance(self, plan_tp):
"""
Recursively improving a solution by bifurcating on the cost for resolving the load currently assigned to the
last underloaded power plant in the latest solution iteration
"""
uncovered_load = plan_tp[1]
prev_pp = plan_tp[2]
if pr... |
def parse_tokens():
global room, booth_count, booths, targetCoord, queue, horizon, og_room
for tokens in tokenList:
if tokens[0] == "room" and tokens[1].isdigit() and tokens[2].isdigit():
room = [[0 for x in range(int(tokens[1]))] for y in range(int(tokens[2]))]
elif tokens[0] == "... | The code reads input tokens from a file, processes them, and simulates a state exploration to determine the minimum number of moves required to reach a target. It uses a queue to traverse rooms, updates booth coordinates, checks for target hits, and outputs the result if within a step limit. | def main():
global booths, room, targetHit, states, booths, step, booths_back
# steps_to_target = 0
# Read from the file line by line
r = open(sys.argv[1], "r")
for line in r:
line = line.replace("(", ",")
line = line.replace(")", ",")
line = line.replace(" ", '')
li... |
def peek(self):
if self.next_token == None:
self.next_token = self.lexer.next()
return self.next_token
def parse_sql(self):
tokens = []
while True:
(next_token, next_value) = self.peek()
if next_token == query_lexer.Token.EOF:
self.adva... | This method processes the next token from a lexer, determining the appropriate action: returning EOF if the token is an end-of-file marker, parsing SQL or directives based on specific token types, skipping whitespace/comments, or raising an exception for unexpected tokens. | def next(self):
while True:
(next_token, next_value) = self.peek()
if next_token == query_lexer.Token.EOF:
return (Action.EOF, '')
elif next_token == query_lexer.Token.STRING \
or next_token == query_lexer.Token.TOKEN:
return s... |
def advance(self):
if self.current_position == len(self.source):
return None
else:
self.current_position += 1
return self.source[self.current_position-1]
def looking_at_eof(self):
return self.current_position == len(self.source)
def looking_at_newline(self):
if self.looking_at_eof():
... | This function parses a string by reading characters until the closing delimiter, skipping escape sequences, and returning a STRING token if the delimiter is found; otherwise, it raises an unterminated string error. | def parse_string(self):
self.at_beginning_of_line = False
start = self.current_position
delimiter = self.advance()
while not self.looking_at_eof() and not self.looking_at_newline() and not self.looking_at(delimiter):
if self.looking_at('\\'):
self.advance()
self.advance()
if sel... |
def looking_at_eof(self):
return self.current_position == len(self.source)
def looking_at_newline(self):
if self.looking_at_eof():
return False
next = self.peek()
return next == '\n'
def advance(self):
if self.current_position == len(self.source):
return None
else:
self.current... | This function parses a comment token from the current position until the end of the line. It records the starting position, advances through characters until encountering a newline or EOF, then returns a COMMENT token with the captured text spanned from the initial position to the current one. | def parse_comment_to_eol(self):
start = self.current_position
while not self.looking_at_eof() and not self.looking_at_newline():
self.advance()
return self.token(Token.COMMENT, start) |
def looking_at_eof(self):
return self.current_position == len(self.source)
def looking_at_newline(self):
if self.looking_at_eof():
return False
next = self.peek()
return next == '\n'
def advance(self):
if self.current_position == len(self.source):
return None
else:
self.current... | This function parses a directive by advancing through the input until a newline or EOF is encountered, then returns a token of type DIRECTIVE with the start position. | def parse_directive(self):
start = self.current_position
while not self.looking_at_eof() and not self.looking_at_newline():
self.advance()
return self.token(Token.DIRECTIVE, start) |
def looking_at_eof(self):
return self.current_position == len(self.source)
def looking_at_whitespace(self):
if self.looking_at_eof():
return False
next = self.peek()
return next.isspace()
def advance(self):
if self.current_position == len(self.source):
return None
else:
self.cu... | The main task of the code is to identify and consume consecutive whitespace characters starting from the current position in the input. It records the starting position, advances through the whitespace, and returns a token of type `Token.WHITE_SPACE` spanning the consumed whitespace. This is typically used in lexers to... | def parse_white_space(self):
start = self.current_position
while not self.looking_at_eof() and self.looking_at_whitespace():
self.advance()
return self.token(Token.WHITE_SPACE, start) |
def advance(self):
if self.current_position == len(self.source):
return None
else:
self.current_position += 1
return self.source[self.current_position-1]
def looking_at_eof(self):
return self.current_position == len(self.source)
def looking_at_multi_line_string(self):
return self.looki... | This function parses a multi-line string by advancing through input characters until the end of the string is detected. It creates a STRING token from the start position if a multi-line string is found, otherwise raises an 'unterminated string' exception. It skips initial characters, checks for EOF or string terminatio... | def parse_multi_line_string(self):
self.at_beginning_of_line = False
start = self.current_position
self.advance()
self.advance()
self.advance()
while not self.looking_at_eof() and not self.looking_at_multi_line_string():
self.advance()
if self.looking_at_multi_line_string():
... |
def looking_at_eof(self):
return self.current_position == len(self.source)
def looking_at_whitespace(self):
if self.looking_at_eof():
return False
next = self.peek()
return next.isspace()
def looking_at_multi_line_string(self):
return self.looking_at('"""')
def looking_at_string_delimiter(self... | This function checks if the current position is not at the end of file, whitespace, multi-line string, string delimiter, semicolon, comment, or newline, indicating a valid token position. | def looking_at_token(self):
return \
not self.looking_at_eof() \
and not self.looking_at_whitespace() \
and not self.looking_at_multi_line_string() \
and not self.looking_at_string_delimiter() \
and not self.looking_at_semi() \
and not self.looking_at_comment_to_e... |
def advance(self):
if self.current_position == len(self.source):
return None
else:
self.current_position += 1
return self.source[self.current_position-1]
def looking_at_token(self):
return \
not self.looking_at_eof() \
and not self.looking_at_whitespace() \
and not... | This function parses a token by advancing the current position through the input until the token ends, then returns the token with its start position. It initializes line tracking, advances past the token, and constructs a token object with the start index and TOKEN type. | def parse_token(self):
self.at_beginning_of_line = False
start = self.current_position
self.advance()
while self.looking_at_token():
self.advance()
return self.token(Token.TOKEN, start) |
def _get_last_updated(self, service=None):
key = self._get_tw_key(service)
return models.KV.get(key)
def _get_tweets(self, min_date):
filters = {}
if min_date:
filters['since_id'] = min_date.value
return self.twitter.user_timeline(**filters)
def _parse_tweet(self, me... | The code retrieves and processes new tweets created after the last check, updates the tracking timestamp with the latest tweet ID, and returns whether any new tweets were found. | def run(self):
last_check = self._get_last_updated()
# get tweets where > last_updated
tweets = self._get_tweets(last_check)
for tweet in tweets:
self._parse_tweet(tweet.text,
tweet.created_at,
tweet.id,
... |
def computeBarlatDerivs(sig, L1, L2, a):
# sig is the deviatoric cauchy stress and is symmetric
# so sqrt(3/2 sig:sig) = sqrt(3/2 tr(sig * sig))
# svm = np.sqrt(1.5 * np.trace(sig.dot(sig)))
svm = effectiveTerm(sig)
if (svm < np.finfo(np.float64).eps):
return (np.zeros(6), np.zeros((6,6)... | The function computes the residual and Jacobian matrix for a plasticity model using the Barlat yield criterion with isotropic hardening. It combines elastic stiffness (modified by plasticity) and flow terms, essential for nonlinear finite element analysis. | def computeRJ_Barlat(x, sig_tr, eps0, muNew, bulkMod, dt, L1, L2, aparam):
J = np.zeros((7,7))
r = np.zeros(7)
'''
// x = [stress, d\lambda]
// where dev_stress is the 6x1 form of the deviatoric stress
// where d\lambda is used in deps = d\lambda * df / dsig
// f = phi(sig) - sig_y(eps)
... |
def ItenMat():
Iten = np.zeros((3,3,3,3))
for i in range(3):
for j in range(3):
if i == j:
delij = 1.
else:
delij = 0.
for k in range(3):
if i == k:
delik = 1.
else:
... | The function calculates an error metric for optimizing material yield parameters by comparing computed yield function values to target values (vMs) and residual stress ratios (rzxs), using a Barlat-type yield criterion. It initializes stress tensors from input parameters, computes derivatives and yield functions for ea... | def barlat_optimize(x0, stressVoigt, vMs, rzxs, aparam, r_include, wsig=10.0, wr=1.0):
error = 0.0
L1 = np.zeros((6,6))
L2 = np.zeros((6,6))
L1[0,1] = -x0[0]
L1[0,2] = -x0[1]
L1[1,0] = -x0[2]
L1[1,2] = -x0[3]
L1[2,0] = -x0[4]
L1[2,1] = -x0[5]
L1[3,3] = x0[6]
L1[4,4] = x0[7]
... |
def matNotation(voigt):
return np.asarray([[voigt[0], voigt[5], voigt[4]],
[voigt[5], voigt[1], voigt[3]],
[voigt[4], voigt[3], voigt[2]]])
def effectiveTerm(mat):
term1 = mat[0, 0] - mat[1, 1]
term2 = mat[1, 1] - mat[2, 2]
term3 = mat[2, 2] - mat[0, 0]
... | The code processes simulation data for different loading directions and temperatures, optimizing material model parameters using a Barlat model to fit experimental stress and deformation data. It calculates yield stress, plastic work, and von Mises values, then performs nonlinear optimization to determine model paramet... | def postprocessing(frve_name, fdiro, ftime, tempk, shear_loads):
#%%
# Start parsing data
# First we probably should have some way to share the loading direction names
# between the job_cli.py file and this one but until then we'll just have the
# list of names copied in the two.
# Test names a... |
def build_cddf() :
y_norm, bins = np.histogram(data['N_HI_DLA'], bins=50, density=True)
z = bins[:-1] + (bins[1]/2-bins[0]/2)
c = np.polyfit(z, np.log(y_norm),3)
pol = np.poly1d(c)
fit = np.exp(pol(z))
norma = integrate.trapz(fit, z)
fit = fit/norma
return z, fit
def build_mean_density(N... | The code computes the Voigt profile's Fourier transform for varying column densities, scales it by mean density, integrates over column density, normalizes, and saves results. It uses cosmological parameters, builds a cumulative distribution function, performs FFTs, and stores the output in a text file for analysis. | def save_function():
fidcosmo = constants.cosmo(Om=0.3)
lamb = np.arange(2000, 8000, 1)
dN, cddf = build_cddf()
r_density_mean = build_mean_density(dN, fidcosmo) # mpc-1 n-1
for i in range(dN.size):
profile_lambda = profile_voigt_lambda(lamb, zdla, dN[i])
r, profile_r = profile_lambd... |
def gather_metadata(not_in_db):
#search for a track and extract metadata from results
if len(not_in_db) > 0:
metadata = {}
for track in not_in_db:
try:
track_data = search_and_extract(track) #using the input track name as the query to search spotify
metadata[track_data[0]] = track_data[1:]
except In... | The code processes audio metadata and features to generate a user dataframe. It gathers and validates metadata, extracts Spotify and Librosa audio features, combines them with database data, remaps genres, and returns the enriched user dataframe for analysis or storage. | def not_in_database_pipeline(to_get,in_db):
metadata = gather_metadata(to_get)
metadata = check_metadata(metadata)
not_null, spotify_features = get_spotify_features(metadata)
librosa_features = [librosa_pipeline(n) for n in not_null.keys()]
user_df = combine_all_features(metadata,librosa_features,spotify_featur... |
def process_label(labels: list, mask: list, onehot=True):
"""
turns a list of labels ['HEECCC', 'HHHEEEECCC'] to one hot encoded tensor
and add padding e.g torch.tensor([[1, 0, 0], [0, 0, 1], [0, 0, 0]])
"""
max_len = len(max(labels, key=len)) # determine longest sequence in list
processed = [... | The code validates a neural network model on a dataset, computing average loss and accuracy. It processes each batch, applies masking, truncates sequences, calculates cross-entropy loss (ignoring -1 labels), and evaluates per-sequence accuracy using masked true labels. It returns the mean accuracy, mean loss, and accur... | def validate(model: torch.nn.Module,
val_data: DataLoader):
model.eval()
loss_fn = nn.CrossEntropyLoss(ignore_index=-1)
last_accuracy = 0
losses = []
acc_scores = []
for i, batch in enumerate(val_data):
emb, label, mask = batch
emb = emb.to(device)
out = mod... |
def process_labels(labels: list, mask: list, onehot=False):
"""
turns a list of labels ['HEECCC', 'HHHEEEECCC'] labels and adds padding
"""
max_len = len(max(labels, key=len)) # determine longest sequence in list
processed = []
processed = [[CLASS_MAPPING[c] for c in label] for label in labels]... | The function `validate` evaluates a PyTorch model on a validation dataset. It computes the average loss using a provided loss function and calculates per-sample accuracy by comparing model predictions against true labels, applying masking to ignore padding. The function returns the mean accuracy, mean loss, and standar... | def validate(model: torch.nn.Module,
val_data: DataLoader,
loss_fn):
model.eval()
last_accuracy = 0
total_loss = 0
count = 0
sum_accuracy = 0
acc_list = []
for i, batch in enumerate(val_data):
ids, label, mask = batch
labels_f = process_labels(labe... |
def process_labels(labels: list, mask: list, onehot=False):
"""
turns a list of labels ['HEECCC', 'HHHEEEECCC'] labels and adds padding
"""
max_len = len(max(labels, key=len)) # determine longest sequence in list
processed = []
processed = [[CLASS_MAPPING[c] for c in label] for label in labels]... | The function `test` evaluates a model's performance on a test dataset. It processes each batch, computes predictions, and calculates accuracy scores per sequence using `q3_acc`, aggregating results in `acc_scores`. If `verbose` is True, it prints predictions, true labels, and accuracy for each batch. Finally, it return... | def test(model: torch.nn.Module,
test_data: DataLoader,
verbose=False):
"""
verbose argument: whether or not to show actual predictions
"""
model.eval()
acc_scores = []
for i, batch in enumerate(test_data):
ids, label, mask = batch
labels_f = process_labels(lab... |
def train(model: torch.nn.Module,
train_data: DataLoader,
loss_fn,
optimizer,
grad_accum):
"""
do a train on a minibatch
"""
model.train()
optimizer.zero_grad()
total_loss = 0
count = 0
# batch accumulation parameter
accum_iter = grad_accum
... | This function trains a neural network model using specified optimizers, tracks training/validation loss and accuracy, implements early stopping based on validation loss, saves the best model checkpoint, and freezes the T5 language model after a designated epoch. It supports multiple optimizers (Adam, Adafactor, Adagrad... | def main_training_loop(model: torch.nn.Module,
train_data: DataLoader,
val_data: DataLoader,
batch_size: int,
lr: float,
epochs: int,
grad_accum: int,
optimize... |
def apply_peft(model, mode="all", lora_dropout=0.05):
## applying PEFT
print(model)
for param in model.parameters():
param.requires_grad = False # freeze the model - train adapters later
if param.ndim == 1:
# cast the small parameters (e.g. layernorm) to fp32 for stability
... | The main task of the code is to train and evaluate an ESM2PSSP model for a specific task, using different ESM checkpoint sizes (8M, 35M, etc.). It loads training and validation data, applies PEFT if enabled, trains the model with specified hyperparameters, and evaluates its performance on test datasets (CASP12 and new_... | def main():
# Choose model
if model_type == "esm-cnn":
if args.plm_checkpoint == "8M":
model_path = "facebook/esm2_t6_8M_UR50D"
in_dim = 320
elif args.plm_checkpoint == "35M":
model_path = "facebook/esm2_t12_35M_UR50D"
in_dim = 480
elif arg... |
def write_to_file(string_data, file_path="logfile.txt"):
with open(file_path, 'a+') as file:
file.writelines(string_data)
def check_value(cell_address, worksheet, log=True):
if log:
write_to_file(f" \n {worksheet[cell_address].value} \n ")
return worksheet[cell_address].value
def check_speci... | This function evaluates an Excel file by comparing student answers against provided answer keys. It loads the workbook, checks for required worksheets and student details (name, roll number), and generates result data by validating answers in specified cells. The output includes evaluation results and student informati... | def evaluate_excel_file(file_path, column_name, row_number, number_of_question, values_answer_key, formula_answer_key,
worksheet_name='Answers', student_name_cell='B1', student_roll_no_cell='B2'):
write_to_file(f"{'~' * 80} \n\n \n ")
if file_path:
file_name = file_path.split('/... |
def _check_convergence(self):
self.lowerbound_global = self.flb_current
self._lowerbound_hist.append(self.lowerbound_global)
self._upperbound_hist.append(self.yopt_global)
self._sampling_hist.append(self.builder.simulator.sample_number)
if self.search_instance == 1:
s... | This code implements the DDSBB algorithm to optimize a given problem by selecting an appropriate builder (BoxConstrained, BlackBox, or GreyBox) based on the problem's constraint type. It initializes optimization parameters, checks convergence, manages resources, and executes the search process. The main task is to iter... | def optimize(self, problem):
"""
Optimize the problem with DDSBB algorithm
Input
-----
problem: DDSBBModel
"""
self._lowerbound_hist = []
self._upperbound_hist = []
self._xopt_hist = []
self._sampling_hist = []
sel... |
def update_stop_criteria(self, new_stop):
"""
update stop criteria
Input
-----
new_stop: dict
dictionary constaining new stopping criteria
"""
for i in new_stop.keys():
setattr(self, i, new_stop[i])
self.stop ... | The code resumes a search process by updating time tracking, incrementing the search instance, setting a stop message, applying new stop criteria, and deciding to either continue or grow the search based on the completion indicator. It adjusts the total time elapsed to reflect the resumed operation. | def resume(self, new_stop_option):
self.time_elapsed = self.time_total
self.time_start = time.time()
self.search_instance += 1
print('Resume search with new resources')
self.stop_message = 'In search process ' + str(self.search_instance)
self.update_stop_criteria(new_sto... |
def find_devices():
"""Find SMART devices.
Yields:
(Device) Single device found by smartctl.
"""
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--device", dest="type")
devices = smart_ctl("--scan-open")
devices += smart_ctl("--scan-open", "-d", "sat")
for device... | The main task of the code is to collect SMART metrics from disk devices. It checks device activity status, SMART availability, and generates metrics like device activity, SMART capabilities, health assessments, and ATA-specific data. It skips unnecessary metrics collection for inactive disks or when SMART is disabled, ... | def collect_disks_smart_metrics(wakeup_disks):
now = int(datetime.datetime.utcnow().timestamp())
for device in find_devices():
yield Metric("smartctl_run", device.base_labels, now)
is_active = device_is_active(device)
yield Metric("device_active", device.base_labels, is_active)
... |
def smart_ctl_version():
return smart_ctl("-V").split("\n")[0].split()[1]
def metric_format_meta(metric, prefix=""):
key = metric_key(metric, prefix)
return [
"# HELP {key} SMART metric {metric.name}".format(key=key, metric=metric),
"# TYPE {key} gauge".format(key=key),
]
def metric_for... | The code gathers SMART disk metrics, formats them with "smartmon_" prefixes, and returns a list of metrics. It includes both meta and standard formatted metrics, grouping by disk names and ensuring unique meta entries per disk. | def get_metrics(wakeup_disks=True):
ret = []
version_metric = Metric("smartctl_version", {"version": smart_ctl_version()}, True)
ret += metric_format_meta(version_metric, "smartmon_")
ret += metric_format(version_metric, "smartmon_")
metrics = list(collect_disks_smart_metrics(wakeup_disks))
met... |
def smart_ctl_version():
return smart_ctl("-V").split("\n")[0].split()[1]
def metric_print_meta(metric, prefix=""):
for line in metric_format_meta(metric, prefix):
print(line)
def metric_print(metric, prefix=""):
for line in metric_format(metric, prefix):
print(line)
def collect_disks_smart_... | The code parses command-line arguments to control disk wake-up, collects SMART disk metrics, sorts them by name, and prints each metric's metadata and value with a prefix, ensuring grouped output for each disk type. | def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-s", "--wakeup-disks", dest="wakeup_disks", action="store_true"
)
args = parser.parse_args(sys.argv[1:])
version_metric = Metric("smartctl_version", {"version": smart_ctl_version()}, True)
metric_print_meta(version_met... |
def select_attack(character):
"""
Select a weapon from the available weapons.
:param character: a string to present to the user, asking for their input
:precondition: character must be a valid dictionary representation of the game character
:postcondition: checks the user entered a valid choice, an... | The function `fight` simulates a combat encounter between a character and an enemy. It alternates turns where both parties may attack based on accuracy, reducing HP accordingly. The loop continues until the enemy's HP drops to zero (character victory), the enemy flees, or the character chooses to flee. The function ret... | def fight(character: dict, foe: dict) -> bool:
"""
Runs the fight between the character and foe
:param character: a dictionary representing the characters stats
:param foe: a dictionary representing the foes stats
:precondition: character must be a valid dictionary created using the make_character ... |
def quick_sleep(timer: float = 1.0):
"""
pauses the program for a period of time
:param timer: length of time to sleep the program for
:postcondition: sleep the function for the input amount of time
"""
time.sleep(timer)
def fight(character: dict, foe: dict) -> bool:
"""
Runs the fight ... | The function `start_fight` initiates combat between a player character and a foe based on user input. It checks if the foe is a boss, triggering a direct fight and returning the defeat status. For non-boss foes, it prompts the player to fight or flee, executing the fight function or the flee function accordingly. The t... | def start_fight(character: dict, foe: dict):
"""
Starts the fight if the player has chosen to fight the foe.
:param character: a dictionary representing the characters stats
:param foe: a dictionary representing the foes stats
:precondition: character must be a valid dictionary created using the ma... |
def fetch_user_videos(self):
number = re.findall(r'share/user/(\d+)', self.url)
if not len(number): return
dytk = get_dytk(self.url)
if not dytk: return
user_id = number[0]
videos = self._fetch_user_media(user_id, dytk, self.url)
sys.stdout.write(str(videos).repla... | The `fetch` method determines the URL type using regex and routes to either `fetch_user_videos` for user profiles or `fetch_challenge_videos` for challenge pages; if neither matches, it calls `usage()`. Its primary task is to dispatch video-fetching logic based on URL patterns. | def fetch(self):
if re.search('share/user', self.url):
self.fetch_user_videos()
elif re.search('share/challenge', self.url):
self.fetch_challenge_videos()
else:
usage() |
def start_scan(self):
self.stop_button.config(relief=tk.RAISED, state=tk.NORMAL)
self.start_button.config(relief=tk.SUNKEN, state=tk.DISABLED)
self.reset_button.config( state=tk.DISABLED)
self.update_saved_vals_button.config(state=tk.DISABLED)
self.machine_state_refresh_button.co... | Your returnThe code creates a GUI with Tkinter, organizing widgets into left and right frames. The left frame includes dropdowns for file selection, parameter displays, buttons for actions (start/stop/reset/exit), and a checkbox. The right frame hosts two matplotlib plots for data visualization. The layout partitions f... | def createWidgets(self):
# create all of the main containers
left_frame = tk.Frame(self.master)#, width=240, height=height)
right_frame = tk.Frame(self.master, bg='gray2')#, width=width, height=height)
left_frame.grid(row=0, column=0)
right_frame.grid(row=0, column=1)
#p... |
def load_saved_data(self):
try:
with open(self.temp_file, 'r') as f:
self.saved_data.update(json.load(f))
except:
pass
def get_phantomjs(self):
here = os.path.dirname(os.path.abspath(__file__))
auto_install_path = None
for file in os.listd... | The main task of the code is to initialize a connection process by loading saved data, retrieving PhantomJS (a headless browser), extracting domain information, fetching user details, and collecting URLs, likely preparing for web scraping or automation tasks. | def connect(self):
self.load_saved_data()
self.get_phantomjs()
self.get_domain()
self.get_user()
self.get_urls() |
def determine_candidate_splits(training_set: list[tuple[float, float, bool]]) -> list[tuple[int, float]]:
res : list[tuple[int, float]] = []
# min0 = min(x[0] for x in training_set)
# min1 = min(x[1] for x in training_set)
# doubleState = False
# cmp_index = 0
# def cmp(lhs, rhs):
# i... | The function constructs a decision tree node (InternalNode or LeafNode) by recursively splitting the training data. It identifies candidate splits, selects the best split, partitions the data, and recursively builds subtrees for each partition. If no split is found, it returns a LeafNode with the majority label. | def make_subtree(training_set: list[tuple[float, float, bool]]) -> InternalNode | LeafNode:
split_set = determine_candidate_splits(training_set)
best_split = find_best_split(training_set, split_set)
if best_split is None:
return LeafNode(determine_label(training_set))
else:
(dim, thres) ... |
def coordinates(self):
"""
Generate coordinates.
"""
menu_type: str = self.button_image_data['type']
if menu_type == 'gameplay_ui':
self.gameplay_reading_coordinates()
return
if menu_type == 'gameplay_dialogues_choice':
self.gameplay_... | The code scales a button's sprite and text to fit the background context, adjusts its size and coordinates, and applies a semi-transparent mask when the button is pressed, ensuring proper rendering and interaction states. | def scale(self):
"""
Scale button surface, with background context.
"""
# Arg parse:
background_surface: Surface = self.background.get_data()[0]
# Devnull button_surface for new render:
self.button_surface = Surface((0, 0), SRCALPHA)
# Button size scale:... |
def get_clean_sent(df,stopwords=False):
sents=df[['Questions']]
cleaned_sent=[]
for index,row in df.iterrows():
cleaned=clean_sent(row['Questions'],stopwords)
cleaned=cleaned.lower()
cleaned_sent.append(" ".join([wnl.lemmatize(i) for i in cleaned.split()]))
return cleaned_sent
def clean_sent(sent,st... | The main task of the code is to retrieve an answer to a given question by first cleaning and vectorizing text data using a bag-of-words model, then leveraging either a GloVe embedding-based method or a retrieval function to find the most relevant response from a preprocessed dataset. The function checks if GloVe provid... | def resp1(ques,param):
cleaned_sent=get_clean_sent(df,stopwords=True)
sentences=cleaned_sent
sent_words=[[wrd for wrd in document.split()]for document in sentences]
dictionary=corpora.Dictionary(sent_words)
bow_corpus=[dictionary.doc2bow(text) for text in sent_words]
ques=clean_sent(ques,stopwor... |
def loadMaterials(self):
loadStairsMaterial(self.stage)
loadSeatMaterial(self.stage)
loadConcreteMaterial(self.stage)
loadAshPlankMaterial(self.stage)
loadWhitePlasticMaterial(self.stage)
loadWallMaterial(self.stage)
loadGrassMaterial(self.stage)
loadCeili... | The main task of the code is to construct a structure by sequentially loading materials and building its components, including stands, court, ceiling, and outdoor elements, each assigned to specific directories or locations indicated by their path parameters. | def build(self):
self.loadMaterials()
self.buildStands("/stands")
self.buildCourt("/court")
self.buildCeiling("/ceiling")
self.buildOutside("/outdoor") |
def host2subnet(ip,mask):
#Given a host in octect and mask in octect format, returns subnet in octect and mask lenght
maskbin=octect2bin(mask)
ipbin=octect2bin(ip)
len=countMaskBit(maskbin)
subnet=''
i=0
while i<32:
if i<len:
subnet=subnet+ipbin[i]
else:
... | The code extracts connected routing information from network device configurations (ASA, Juniper, F5, Cisco_IOS) by parsing interface IP addresses, masks, and statuses. It identifies active interfaces, processes IP/mask pairs, converts them to subnets, and adds routes via the `add_route` function with administrative di... | def extract_route_connected(device,config,type,routedomain):
administrative_distance=0
fh=open(config)
print('Reading connected routes from: '+type+' '+device+'\n')
if type=='ASA':
#Code for ASA follows
#How an engineer does it, it looks at the configuration, looking for interface commands, then... |
def bitlenmask2obtectmask(mask):
#i.e /24 ----> 255.255.255.0
mask1=masklen2maskbin(mask)
mask2=binIP2octect(mask1)
return mask2
def host2subnet(ip,mask):
#Given a host in octect and mask in octect format, returns subnet in octect and mask lenght
maskbin=octect2bin(mask)
ipbin=octect2bin(ip)... | The main task of the code is to insert interface configuration data into a SQLite database. It processes input parameters like interface name, device, IP address, and mask, converts them into database-compatible formats (e.g., subnet ID, device ID), and stores them in the "Interfaces" table. This function centralizes n... | def add_interface(name,device,ip_address,ip_mask,nameif,zone):
#Receives and string like: (GigabitEthernet0/7 572118 10.159.0.1 25 nameif )
mask=bitlenmask2obtectmask(ip_mask)
subnet=host2subnet(ip_address,mask)
subnet_id=get_subnet_id(subnet[0])
device_id=get_device_id(device)
conn = sqlite3.... |
def host2subnet(ip,mask):
#Given a host in octect and mask in octect format, returns subnet in octect and mask lenght
maskbin=octect2bin(mask)
ipbin=octect2bin(ip)
len=countMaskBit(maskbin)
subnet=''
i=0
while i<32:
if i<len:
subnet=subnet+ipbin[i]
else:
... | The main task of the code is to parse network device configurations (ASA, Juniper, F5, Cisco IOS) to extract connected routes, calculate subnets, and add them to a routing table using `add_route()`. It identifies interface IP addresses/masks, handles device-specific syntax, and ensures only active interfaces contribute... | def extract_route_connected(device,config,device_type,routedomain):
administrative_distance=0
fh=open(config)
print('Reading connected routes from: '+device_type+' '+device+'\n')
if device_type=='ASA':
#Code for ASA follows
#How an engineer does it, it looks at the configuration, looking for int... |
def bitlenmask2obtectmask(mask):
#i.e /24 ----> 255.255.255.0
mask1=masklen2maskbin(mask)
mask2=binIP2octect(mask1)
return mask2
def host2subnet(ip,mask):
#Given a host in octect and mask in octect format, returns subnet in octect and mask lenght
maskbin=octect2bin(mask)
ipbin=octect2bin(ip)... | This function inserts interface configuration data into an SQLite database, converting input parameters into database-friendly formats by retrieving device and subnet IDs, then storing the interface details in the 'Interfaces' table with associated identifiers and network information. | def add_interface(name,device,ip_address,ip_mask,nameif,zone):
#Receives and string like: (GigabitEthernet0/7 572118 10.159.0.1 25 nameif )
mask=bitlenmask2obtectmask(ip_mask)
subnet=host2subnet(ip_address,mask)
subnet_id=get_subnet_id(subnet[0])
device_id=get_device_id(device)
conn = sqlite3.... |
def octectmask2bitlenmask(mask):
#i.e 255.255.255.0 ----> /24
mask1=octect2bin(mask)
return str(countMaskBit(mask1))
def add_interface(name,device,ip_address,ip_mask,nameif,zone):
#Receives and string like: (GigabitEthernet0/7 572118 10.159.0.1 25 nameif )
mask=bitlenmask2obtectmask(ip_mask)
... | This function extracts and processes network interface configurations from a device's configuration file, handling ASA, Juniper, F5, and Cisco_IOS devices. It identifies interfaces, IP addresses, masks, zones, and names, processes subnet details, and calls `add_interface` to store or apply the extracted data. The code ... | def extract_interface(device,config,type,routedomain):
#administrative_distance=0
fh=open(config)
print('Reading interfaces from: '+type+' '+device+'\n')
if type=='ASA':
#Code for ASA follows
#How an engineer does it, it looks at the configuration, looking for interface commands, if it finds it
... |
def octectmask2bitlenmask(mask):
#i.e 255.255.255.0 ----> /24
mask1=octect2bin(mask)
return str(countMaskBit(mask1))
def add_interface(name,device,ip_address,ip_mask,nameif,zone):
#Receives and string like: (GigabitEthernet0/7 572118 10.159.0.1 25 nameif )
mask=bitlenmask2obtectmask(ip_mask)
... | This function extracts network interface details from device configurations, including IP addresses, masks, and zones, by parsing configuration files specific to device types (ASA, Juniper, F5, Cisco_IOS). It identifies active interfaces, handles secondary IP addresses, and maps interfaces to security zones where appli... | def extract_interface(device,config,device_type,routedomain):
#administrative_distance=0
fh=open(config)
print('Reading interfaces from: '+device_type+' '+device+'\n')
if device_type=='ASA':
#Code for ASA follows
#How an engineer does it, it looks at the configuration, looking for interface comm... |
def clean_dfs(path1, path2):
cols = ['description', 'id', 'verified', 'username', 'name', 'label']
df1, df2 = pd.read_csv(path1, usecols=cols), pd.read_csv(path2, usecols=cols, nrows = 4189)
df = pd.concat([df1, df2])
df.drop_duplicates(inplace=True, subset = ['id'])
df['description'] = df['descript... | The main task of the code is to process and evaluate text classification models using different embeddings (TF-IDF and Doc2Vec). It cleans input dataframes, splits them into training/test sets, tunes hyperparameters for each embedding method, evaluates model performance on both training and test data, and returns inter... | def main():
df, intercoder_rel = clean_dfs(path1, path2)
X_train, X_test, y_train, y_test = get_tts(df)
embeddings = ["tfidf", "doc2vec"]
best_hyperparams = {embedding: {} for embedding in embeddings}
model_evals = {}
for embedding in embeddings:
best_hyperparams[embedding] = tune_hyperp... |
def read_corpora(root, files): #takes input of: root directory (str), files (dict)
corpus_dict = {}
corpus_dict['aut'], corpus_dict['par'], corpus_dict['ac'], corpus_dict['asag'] = csv(root + files['aut']), \
csv(root + files['... | The main task of the code is to process text corpora and baseline tweets by training models, updating training data, and computing pairwise cosine similarity between updated vectors, returning a similarity matrix for analysis. | def main():
corpus_dic, baseline_tweets = read_corpora(root, files)
print(1)
params = make_params()
print(2)
model_dic = train_baselines(params, baseline_tweets)
print(3)
updates = update_training(corpus_dic, model_dic)
print(4)
cos_sim_df = cosine_similarity_df(updates)
prin... |
def get_stacked_weights_and_biases(tasks_and_constraints):
input2h_weight_bar = []
rnn_input2h_bias_bar = []
rnn_h2h_weight_bar = []
rnn_h2h_bias_bar = []
fc_weight_bar = []
fc_bias_bar = []
for el in tasks_and_constraints:
path = get_path_from_task_and_constraint(el)
param... | The code constructs a GW-RNN (Global Workspace RNN) network by integrating pretrained weights and biases with newly created global workspace parameters. It initializes layers, masks, and random weights for the GW-RNN architecture, then assembles the model using these components. The function returns a GW_RNNNet instanc... | def build_GWNET_from_pretrained(
tasks_and_constraints, env, device, pretrained_hidden_size=32, gw_hidden_size=16
):
p = len(tasks_and_constraints) + 1
c_type = tasks_and_constraints[0][1]
# import pretrained weights and biases
(
input2h_weight_bar,
rnn_input2h_bias,
rnn_h2... |
def delete_missing_replies(existing_replies: list, post_structure: Dict) -> Dict:
for key, value in list(post_structure.items()):
if str(key) + ".json" not in existing_replies:
del post_structure[key]
if isinstance(value, Dict):
delete_missing_replies(existing_replies, value)... | The function `calc_tree_dic` processes a social media thread (Twitter/Reddit) to construct a hierarchical tree structure. It maps each post to its parent, updates word frequency indices, and handles nested replies. Key steps include parsing source/reply posts, preprocessing text, estimating word frequencies, managing I... | def calc_tree_dic(tree_dic: Dict, thread: Dict, twitter: bool, word_index: int,
archive: Dict, sorted_words: list) -> (Dict, int):
parent_idx_connections = {} # Dict to translate Twitter/Reddit ID to thread post ID.
maxL = 0 # Maximum post length of each thread => reset to 0 for each new thread.... |
def compute_tree(self, x_word, x_index, num_parent, tree):
self.recursive_unit = self.create_recursive_unit()
def ini_unit(x):
return theano.shared(self.init_vector([self.hidden_dim]))
init_node_h, _ = theano.scan(
fn=ini_unit,
sequences=[ x_word ])
... | This code defines a neural network model for processing tree-structured data, initializing parameters for word embeddings, hidden layers, and classification. It constructs Theano functions for training (with gradient descent), evaluating tree states, and making predictions. The model computes hierarchical states via `c... | def __init__(self, word_dim, hidden_dim=5, Nclass=3,
degree=2, momentum=0.9,
trainable_embeddings=True,
labels_on_nonroot_nodes=False,
irregular_tree=True):
assert word_dim > 1 and hidden_dim > 1
self.word_dim = word_dim... |
def confirm_reset_data(
result_manager: ResultManager
):
"""
Confirms whether the user wishes to reset data, and if so...does (then exits)!
Parameters
----------
result_manager
An instance of a ResultManager object for managing data reads/writes and
integrity
"""
pr... | The main task of the code is to execute a questionnaire via CLI, managing result integrity by loading previous data, validating it, and resetting if corrupted. It processes each question, collects user inputs, calculates the score, displays results compared to prior data, and saves the outcome using the ResultManager. ... | def run_questionnaire(
questionnaire: Questionnaire,
result_manager: ResultManager
):
"""
Runs a questionnaire
Implements simple logic for running a cli implementation of a questionnaire.
First, an attempt is made to load in previous results, during which the
validity of the previou... |
def initEdgeList(self):
self.edgeList = [] # create heap to store edges
heapify(self.edgeList)
self.nodesWithRepeat = []
for i in self.edges:
heappush(self.edgeList, i)
self.nodesWithRepeat.append(i[1])
self.nodesWithRepeat.append(i[2])
de... | The code implements Kruskal's algorithm to construct a Minimum Spanning Tree (MST). It initializes an edge list (min-heap) and a disjoint-set data structure. The algorithm repeatedly extracts the smallest edge, checks if it connects disjoint components, and adds it to the MST if it doesn't form a cycle. This continues ... | def kruskals(self):
self.initEdgeList() # initialize min-heap
self.initDisJointSet() # initialize union-find disjoint data structure
while self.edgeCount < self.V - 1 and self.edgeList:
edge = heappop(self.edgeList) # delete edge with lowest cost from heap
... |
def instantiate_actors(self, actor_definitions):
self.print_if_verbose()
if len(actor_definitions) > 0:
self.print_if_verbose(self.instance_row.format('Instance', 'Class', 'Attributes'))
self.print_if_verbose(self.instance_row.format('-' * 15, '-' * 31, '-' * 61))
for act... | The main task of the code is to initialize test setup by instantiating actors, resetting a test report structure (tracking errors, test counts, and statuses), executing "BeforeAll" steps if defined, and preparing error handling for subsequent test execution. It prepares the environment for running test scenarios with s... | def setup_testing(self):
self.instantiate_actors(self.global_actor_definitions)
self.test_report.clear()
self.test_report['BA'] = [] # before all errors
self.test_report['TC'] = 0 # test count
self.test_report['CT'] = (None, []) # current test with e... |
def setup_testing(self):
self.instantiate_actors(self.global_actor_definitions)
self.test_report.clear()
self.test_report['BA'] = [] # before all errors
self.test_report['TC'] = 0 # test count
self.test_report['CT'] = (None, []) # current test with e... | This method executes a specified test case by setting up the testing environment, instantiating actors, processing before steps, executing test steps, handling after steps, and updating the test report. It manages test lifecycle phases, including setup/teardown when 'single' is True, and ensures proper cleanup of actor... | def run_test(self, test_name, single=True):
if single:
self.setup_testing()
# get test name
print(TText.INFO + 'Running Test "' + test_name + '"' + TText.ENDC)
test, local_actor_definitions = self.tests[test_name]
self.set_current_test(test_name)
# set local... |
def setup_testing(self):
self.instantiate_actors(self.global_actor_definitions)
self.test_report.clear()
self.test_report['BA'] = [] # before all errors
self.test_report['TC'] = 0 # test count
self.test_report['CT'] = (None, []) # current test with e... | The main task of the code is to execute all tests in a testing framework. It initializes the testing environment via `setup_testing()`, iterates through each test in `self.tests`, runs them using `run_test()` with `single=False` (likely executing all tests sequentially), and finally cleans up the environment with `tear... | def run_all(self):
self.setup_testing()
for test in self.tests.keys():
self.run_test(test, single=False)
self.teardown_testing() |
def stem_net(inputs, out_filters=N_FILTERS_STEM_NET, n_bottleneck_layers=N_BOTTLENECK_LAYERS_IN_STEM):
"""
input_shape: (x1, x2, x3)
output_shape: (x1//2, x2//2, N_FILTERS_STEM_NET * 4)
"""
# why reduce the size here and then upsample eventually? Why not to keep the original size by using
# stri... | The code defines a segmentation model using HRNet architecture, processing input images to generate three outputs: segmentation probabilities (for pixel-wise classification), position coordinates, and VIN classification probabilities. It constructs a multi-branch neural network with split-growth-fusion stages, ultimate... | def seg_hrnet(image_shape=(128, 1024, 3), n_class=20):
"""
:param image_shape:
:param n_class:
:return:
the output is a dictionary
segment: shape is (H * W * n_class)
vin: shape is (17 * 36)
"""
name_segment_prob = "segment_prob"
inputs = tf.keras.layers.Input(shape=image_shape... |
def stem_net(inputs, out_filters=N_FILTERS_STEM_NET, n_bottleneck_layers=N_BOTTLENECK_LAYERS_IN_STEM):
"""
input_shape: (x1, x2, x3)
output_shape: (x1//2, x2//2, N_FILTERS_STEM_NET * 4)
"""
# why reduce the size here and then upsample eventually? Why not to keep the original size by using
# stri... | The code defines a `seg_hrnet` function to build a segmentation model using a high-resolution network (HRNet) architecture. It processes input images through a stem network, followed by three stages of split, grow, and fuse operations to refine features. The model fuses multi-scale features and outputs a segmentation p... | def seg_hrnet(image_shape=(128, 1024, 3), n_class=20):
"""
:param image_shape:
:param n_class:
:return:
the output is a dictionary
segment: shape is (H * W * n_class)
vin: shape is (17 * 36)
"""
name_segment_prob = "segment_prob"
inputs = tf.keras.layers.Input(shape=image_shape... |
def get_jwt_token_sub(event):
"""Gets the subject from the verfied jwt token -> user_id"""
try:
return event["requestContext"]["authorizer"]["jwt"]["claims"]["sub"]
except KeyError:
print("Error: AWS Event contains no subject in jwt token")
return
def init_s3(user_context_dir):
#... | The main task of the code is to handle API requests for an AWS Lambda function by routing requests based on the URL path. It authenticates users via a JWT token, initializes S3 storage with user-specific directories, and processes file operations (upload, list, retrieve, delete) accordingly. If the request path doesn't... | def main_handler(event, context):
"""main_handler handles the internal routing and function calls of the backend based on AWS Events"""
print("Lambda function ARN:", context.invoked_function_arn)
print(event)
# Prepare Execution and extract Event/Context -> We set the current user fold to the authenti... |
def calc_dist(self, angle1, angle2):
angle1 = np.radians(angle1)
angle2 = np.radians(angle2)
index1 = self.range_index(angle1)
index2 = self.range_index(angle2)
sector_ranges = self.laser.ranges[index1:index2]
return np.mean(sector_ranges)
def wall_direction(self, hypote... | This function controls a robot to follow a wall by adjusting its angular and linear velocity based on proportional error terms from desired distance and angle. It calculates distance and angle errors relative to a target wall position, applies gains to compute the angular velocity, and clamps values to safety limits be... | def follow_wall(self):
w_max = 1
v_max = 1
w = 0
v = 0.1
d2right = self.calc_dist(88, 91)
alpha = self.wall_direction(70, 90)
DrightAng = 0 #desired right angle
DrightDist = 0.30 #desired right distance
... |
def detect_obstacle_ahead(self) -> bool:
if self.laser_scan is not None:
for distance in self.laser_scan:
if distance < self.OBSTACLE_DISTANCE_THRESHOLD:
self.goal_direction_at_obstacle = self.goal_direction
rospy.loginfo("Obstacle detected" + ... | The code's main task is to navigate a robot toward a goal while avoiding obstacles. It continuously checks for obstacles ahead, circumnavigates them if detected, moves toward the goal if unobstructed, and halts upon reaching the goal within a threshold distance, logging success and returning True. The loop runs until R... | def run(self):
# Main loop
while not rospy.is_shutdown():
if self.detect_obstacle_ahead():
self.circumnavigate_obstacle()
elif self.goal_distance < self.GOAL_REACHED_THRESHOLD:
self.set_robot_speed(Twist())
rospy.loginfo("Goal reach... |
def set_robot_velocity(self, cmd_vel):
self.pubRviz.publish(cmd_vel)
self.pubGazebo.publish(cmd_vel)
def follow_wall(self):
w_max = 1
v_max = 1
w = 0
v = 0.1
d2right = self.calc_dist(88, 91)
alpha = self.wall_direction(70, 90)
DrightAng = 0 ... | The code implements a robot navigation system that continuously monitors its state (RUNNING, BUG, REACHED), calculates its position and orientation, navigates toward a goal using odometry, avoids obstacles via laser sensors, switches to wall-following in BUG mode when obstacles are detected, and transitions back to goa... | def run(self):
while (True):
rospy.loginfo('State: {}'.format(self.state))
self.rate.sleep()
#calculate robot position
x, y, _ = self.odom.pose.pose.position.x, self.odom.pose.pose.position.y, self.odom.pose.pose.position.z
_, _, yaw = euler_from_quat... |
def parse_arguments():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='Saves or loads a snapshot of the current Konsole sessions.'
)
group = parser.add_mutually_exclusive_group(required=True)
parser.add_argument(
'-f', '--fil... | The main task of the code is to handle command-line arguments for saving or loading konsole snapshots. It enables verbose logging if specified, logs parsed arguments, and executes either `save_snapshot_to_config` or `launch_konsoles` based on `args.save` or `args.load`, respectively, using a global `VERBOSE` flag for d... | def main():
args = parse_arguments()
if args.verbose:
global VERBOSE
VERBOSE = True
DEBUG('Arguments', args)
# Main logic.
if args.save:
save_snapshot_to_config(get_konsoles_snapshot(), args.file)
elif args.load:
launch_konsoles(load_snapshot(args.file)) |
def get_closest_enemy_in_radius(self, enemies):
closest_enemy_distance = self.radius
closest_enemy_in_radius = None
closest_aligned_enemy_distance = self.radius
closest_aligned_enemy = None
for enemy in enemies:
enemy_dist = self.calc_curr_distance_to_target(enemy)
relative_angle = sel... | This code manages a shooter's firing logic by tracking fire rate cooldown, selecting valid targets within range, calculating aiming vectors, and spawning projectiles when conditions are met. It updates target tracking, enforces firing rate limits, and spawns bullets at calculated positions when the target is within a a... | def update_firing(self, dt, enemies, projectiles):
# time gap between shots
if self.fire_rate_acc < self.fire_rate:
self.fire_rate_acc += dt
else:
self.can_fire = True
if self.current_target is None or self.current_target.should_die or \
self.distance_to_target > self.radius or ... |
def update_firing(self, dt, enemies, projectiles):
# time gap between shots
if self.fire_rate_acc < self.fire_rate:
self.fire_rate_acc += dt
else:
self.can_fire = True
if self.current_target is None or self.current_target.should_die or \
self.distance_to_target > self.radius or ... | This code updates a turret's state: if placed, it calculates facing angle, rotates its image, and manages firing logic; if not placed, it validates mouse position for placement and moves with the mouse. | def update(self, mouse_pos, dt, enemies, projectiles, all_turrets, map_rect):
if self.placed:
# show attack radius when hovered over
# if self.rect.collidepoint(mouse_pos):
# self.draw_radius = True
# else:
# self.draw_radius = False
self.update_firing(dt, enemies, projectil... |
def getStateUpdateJacobian(self, dt):
'''
state transition:
distSF_in = distDF_in + velocity*dt
lateral = lateral
velocity = velocity
adjust = adjust
Funny enough, the Jacobian is not related to the state
'''
Jacobian = ... | This code implements a Kalman filter update step. It adjusts the observation data, computes Jacobian matrices, predicts the state and covariance, calculates the Kalman gain using innovation and innovation covariance, corrects the state estimate, updates the covariance matrix, and returns the new state, covariance, and ... | def update(self, observation, dt, observationCovariance=None ):
if observationCovariance is not None:
self.obs_noise_cov = observationCovariance
'''
observation = [distSF_mylap, velocity, x , y, v].T
dt: time since last update
'''
# adjust the data dypt of... |
def getStateUpdateJacobian(self, dt):
'''
state transition:
distSF_in = distDF_in + velocity*dt
lateral = lateral
velocity = velocity
adjust = adjust
Funny enough, the Jacobian is not related to the state
'''
Jacobian = ... | This function implements an Extended Kalman Filter (EKF) update step for a dynamic system, using a custom observation model. It predicts the state and covariance, computes the Kalman gain, and corrects the state estimate based on the observation. Special handling includes clamping lateral position and adjustment factor... | def update_mylap_only(self, observation, dt, observationCovariance=None ):
'''
observation = [distSF_mylap, velocity].T
dt: time since last update
'''
# distSF_in = self.state[0] + self.state[2]*dt
lateral = self.state[1]
# velocity = self.state[2]
adju... |
def set_chosen_words(self, words_list):
"""
Sets the current words_been chosen
:param words_list: list of string of words been chosen
"""
string = "\n".join(words_list)
self.chosen_words.set(str(string))
def set_score(self, val):
"""
Sets the current game ... | This function handles the check button press by validating the current word. If valid and not previously chosen, it updates the score, adds the word to the list, and refreshes the UI. Invalid words or duplicates trigger error messages. Finally, it resets the word, letters, and coordinates for the next attempt. | def check_button_event(self):
"""
handle when check button is pressed,
if word is valid, add to list, and update word
if not, print message to screen
reset letters and buttons
"""
if self.game.check_word(self.game.word):
if self.game.word not in self.g... |
def print_buttons(self):
"""
print letters button on screen and save them in self.buttons_coordinates list
"""
for i in range(16):
button = tk.Button(self.root, bg="blue", text=self.game.board.coordinate_to_letter(self.NUM_TO_COOR.get(i)),
font=... | The `graphics` method creates and displays a game's graphical interface using Tkinter. It sets up a frame, adds buttons, a score label, stopwatch, chosen letters display, correct words list, a word-checking feature, and an end-game button to the screen. | def graphics(self):
"""
makes the graphics of game and add it to screen
"""
frame = tk.Frame()
frame.pack(side=tk.RIGHT, fill=tk.BOTH)
# making buttons on screen
self.print_buttons()
# score label
self.score_event(frame)
# stopwatch
... |
def dataSampling(x):
chosen=[]
l = len(x)
chosen.append(x[0])
for i in range(1,15):
chosen.append(x[int(l/15*i)])
return chosen
def circle(sp) :
n=len(sp)
A = np.zeros((n, 3))
b = np.zeros((n))
for i in range(n):
pt = sp[i]
A[i, :] = [2.*pt[0], 2.*pt[1], 1]
... | The code reads a binary image, identifies black pixels, and fits a circle/ellipse (or uses normal equations) via least squares. It visualizes the fitted shape on the image, saves the result, re-checks the points, and prints a separator line. | def main(file, mode="circle") :
# read image and get circle points
#im1 = img.imread('case1.png')
im1 = img.imread(file)
[h, w,c] = np.array(im1).shape
points = [];
for i in range(h):
for j in range(w):
if (all(im1[i,j,:])==0):
points.append([i, j])
# sa... |
def get_account(index = 0):
if(network.show_active()=="development"):
return accounts[index]
else:
return accounts.add(config["wallets"]["from_key"])
def get_contract(contract_name):
contract_type = contract_to_mock[contract_name]
if(network.show_active()=="development"):
deploy_... | The function deploys a DappToken and TokenFarm contract, transfers DappToken supply to the farm, configures allowed tokens with price feeds, and optionally updates the front end. It initializes a DeFi system where the TokenFarm manages token staking using price oracles. | def deploy_token_farm_and_dapp_token(update=False):
account = get_account(0)
dappToken = DappToken.deploy(({"from":account}))
tokenFarm = TokenFarm.deploy(dappToken.address,{"from":account})
print(dappToken.totalSupply())
tx = dappToken.transfer(tokenFarm.address, dappToken.totalSupply() - BALANCE, ... |
def copy_directories(self):
train_dirlist = self.get_dir_list('train')
test_dirlist = self.get_dir_list('test')
test_path = self.get_dir_path('test')
for class_name in train_dirlist:
if not class_name in test_dirlist:
dir_name = os.path.join(test_path, class_n... | This function moves a random subset of data from the training directory to the test directory for each class, based on a specified rate. It calculates the number of samples to move, selects them randomly, and transfers them using shutil.move, ensuring a stratified split of data into training and testing sets. | def move_to_test(self):
self.copy_directories()
train_path = self.get_dir_path('train')
test_path = self.get_dir_path('test')
class_list = self.get_dir_list('train')
for class_name in class_list:
class_path = os.path.join(train_path, class_name)
data_list ... |
def procsetdir(d:str):
rpos = psplit(d)
dhash = gethash(rpos[0])
de = cfg.dirent(dhash,rpos[0])
cfg.dlist.append(de)
def procsetfile(f:Path):
fi = finfo(f)
#log.debug("Processing file %s", fi)
fe = cfg.filent(fi.dhash, fi.ihash, fi.name)
ie = cfg.imgent(fi.ihash, fi.tmb)
cfg.flist.ap... | The code recursively traverses a directory structure, processing each directory and its contents. It calls `procsetdir` for directories and `procsetfile` for files, ensuring hierarchical traversal and individual file/directory handling. | def file_walker(walk):
procsetdir(walk)
for item in walk.iterdir():
if item.is_dir():
file_walker(item)
else:
procsetfile(item) |
def __parseFile(self) -> None:
self.raw_target_dependency = []
self.compilation_commands = {}
# open and read Makefile
with open(self.filename, "r") as f:
raw_lines = f.read().split("\n")
raw_lines = format_lines(raw_lines)
# iterate over lines
... | The code initializes an object with a filename, parses the file's content, generates a graph representation, and creates dependency relationships. The main tasks are parsing the input file, constructing a graph structure, and identifying dependencies between components. These steps likely support analyzing or visualizi... | def __init__(self, filename: str) -> None:
self.filename = filename
self.__parseFile()
self.__generateGraph()
self.__generateDependencies() |
def print_help() -> int:
print("USAGE")
print("\t./205IQ u s [IQ1] [IQ2]")
print("")
print("DESCRIPTION")
print("\tu\tmean")
print("\ts\tstandard deviation")
print("\tIQ1\tminimum IQ")
print("\tIQ2\tmaximum IQ")
return 0
def simple_result(mean: int, standard_deviation: int) -> int:
... | The code processes command-line arguments to execute different tasks. It checks the number of arguments (`argc`) and their values. If `-h` is provided, it prints help. For 3 arguments, it runs `simple_result`; for 4, `inferior_result`; for 5, `interval_result`. Invalid inputs or argument counts trigger error handling, ... | def main(argc: int, argv: list) -> int:
try:
if argc == 2:
if argv[1] == "-h":
return print_help()
raise RuntimeError()
elif argc == 3:
return simple_result(int(argv[1]), int(argv[2]))
elif argc == 4:
return inferior_result(int(... |
def _strip_url_scheme_and_subdomain(self, url: str):
return (
self.url_scheme_subdomain_re.sub("", url).rstrip("/").replace("/", "\u2044")
)
def _get_comparison_state(self, url: str, domain_path: str):
comparison_state = ""
if os.path.exists(self._get_comparison_state_file_p... | The code compares the states of web pages from provided URLs. It strips URL schemes and subdomains, checks each page's current and latest states, and adds URLs to a set if their states differ. The driver is then closed. | def compare_sources(self, urls: list[str]):
for url in urls:
domain_and_path = self._strip_url_scheme_and_subdomain(url)
comparison_state = self._get_comparison_state(url, domain_and_path)
latest_state = self._get_latest_state(url, domain_and_path)
if latest_sta... |
def load_model(args):
model = LlamaForCausalLM.from_pretrained(
args.model_path,
load_in_8bit=args.use_8bit,
torch_dtype=torch.float16,
device_map="auto",
)
if args.use_8bit is True:
model = prepare_model_for_int8_training(model)
if args.lora_path is not None:
... | This code evaluates a model's performance on a test dataset by generating predictions, comparing them to true labels, and calculating exact match (EM) and F1 scores. It loads a model and tokenizer, processes test data in batches, uses beam search for generation, decodes outputs, and computes evaluation metrics to asses... | def test(args):
tokenizer, model = load_model(args)
test_dataset = load_test_data(args, tokenizer)
test_loader = DataLoader(test_dataset, batch_size=args.batch_size, collate_fn=collate_fn)
print(len(test_loader))
all_labels, all_preds = [], []
for input_ids, labels in tqdm(test_loader):
... |
def game_status(mouse_pos, cards_sprites, clicked_cards, game_start):
global lvl_complete, game_over, pause, get_pass, arts, sound_played
button, card = None, None
if game_start:
game_start = enlarge_all_cards(cards_sprites)
elif get_pass:
button = check_mouse_collision(mouse_pos, btn=Tr... | The code defines a game loop for a memory card game, handling user interactions (mouse clicks, keyboard input), card flipping animations, password input validation, and scene transitions. It manages game states like level completion, game over, and updates the display. The function returns a tuple (lvl, scene) when a s... | def Game(WIN, level):
global lvl_complete, game_over, get_pass, arts, text_input, currentLvl, first_card, second_card
# default values
clicked_cards, currentLvl, game_start = [], level, True
cards_sprites = Levels[currentLvl].cards_sprites_init()
# game loop
while True:
clock.tick(60)
... |
def preprocess_text(txt):
txt=txt.lower()
txt=txt.translate(translator)
txt=txt.replace('\n',' ')
txt=replace(txt)
stop_words = set(stopwords.words('english'))
tokens=[x for x in word_tokenize(txt) if x not in stop_words]
t=""
for i in tokens:
t+=ls.lemmatize(i)+" ... | The code processes input text to determine if it's a goodbye command, preprocesses it, and uses a saved model to classify the input. If classified as 'LABEL_1', it searches a database for similar text matches and returns the first found. Otherwise, it generates a response using a transformer model. The function handles... | def chat(input_text):
if input_text:
if input_text.lower() == 'bye':
return 'Goodbye'
input_text = input_text.lower()
# input_text = spellcheck(input_text)
input_text = preprocess_text(input_text)
label = saved_model(input_text)[0]['... |
def adaptive_random_prioritization(test_case_event_sequence,
distance_option,
process_module_testcase_emb_file,
all_name_without_log_list, logger):
logger.info("Prioritize based on vector")
testcase_vec = re... | This function selects and executes a test case prioritization strategy based on the 'prioritization' input. It applies adaptive random prioritization (ARP), event coverage prioritization (for 'total'/'additional'), or ideal prioritization, validating inputs like log representation compatibility. It returns prioritized ... | def get_prioritize_result(prioritization, test_case_event_sequence, distance_option,
process_module_testcase_emb_file, all_name_without_log_list,
test_case_2_mutant_id_set, result_mutant_id_matrix,
process_module_prioritize_results_file, logs... |
def _bcp(self, is_backtrack=False):
"""Boolean constraint propagation with 2 watched literals per clause."""
i = len(self.ai.assigned) - 1
if is_backtrack:
i += 1
self._handle_backtrack()
if not self.ai.assigned: # first time to run bcp
i = 0
... | The main task of the code is to implement the core CDCL algorithm for solving SAT problems. It performs binary constraint propagation (BCP), assigns variables via heuristics, detects conflicts, learns clauses, backtracks, and manages restarts. The loop continues until all variables are assigned (returning a solution) o... | def _calculate(self):
"""The main calculation part for CDCL algorithm."""
conflict_ante = self._bcp()
if conflict_ante: return None # indicate UNSAT
need_restart = self._after_bcp(conflict_ante)
if need_restart: return 'restart'
while len(self.ai.assigned) < self.num_var... |
def find_boss(self):
boss_location = gui.locateCenterOnScreen(img_dir + "BossLabel.png", confidence=0.7)
if boss_location:
return gui.Point(boss_location.x, boss_location.y + 60)
return None
def is_valid_click_location(self, x, y):
# Bottom Battle utils menu
if x > 47... | The main task of the code is to handle combat logic during a healing state by detecting and attacking bosses or aggressive enemies, executing fight sequences, using abilities, repairing after battles, and adjusting ship position to avoid hidden threats while maintaining game state tracking. | def fight_in_heal_state(self):
batteled = False
if self.GameController.shooting_boss:
boss_location = self.find_boss()
if boss_location:
batteled = True
self.GameController.is_fighting = True
self.GameController.shooting_boss = Tru... |
def find_boss(self):
boss_location = gui.locateCenterOnScreen(img_dir + "BossLabel.png", confidence=0.7)
if boss_location:
return gui.Point(boss_location.x, boss_location.y + 60)
return None
def is_valid_click_location(self, x, y):
# Bottom Battle utils menu
if x > 47... | This function handles combat by detecting and engaging nearby enemies. It prioritizes fighting a boss by attacking with specific key presses, using abilities, and executing boss-specific actions. If no boss is found, it fights aggressive enemies in a loop and passive enemies once. It manages game state flags (e.g., is_... | def fight_nearby(self):
batteled = False
# Fight boss
enemy_location = self.find_boss()
if enemy_location:
batteled = True
self.GameController.is_fighting = True
self.GameController.shooting_boss = True
self.last_time_boss_spotted = time.t... |
def find_boss(self):
boss_location = gui.locateCenterOnScreen(img_dir + "BossLabel.png", confidence=0.7)
if boss_location:
return gui.Point(boss_location.x, boss_location.y + 60)
return None
def is_valid_click_location(self, x, y):
# Bottom Battle utils menu
if x > 47... | The main task of the code is to automate fighting enemies in a game by locating bosses, aggressive enemies, and passive enemies, performing targeted attacks (e.g., shooting rockets, using abilities), managing game state flags (e.g., is_fighting, is_looting), and executing battle sequences. It prioritizes boss engagemen... | def fight_far(self):
batteled = False
# Fight boss
enemy_location = self.find_boss()
if enemy_location:
batteled = True
self.GameController.is_fighting = True
self.GameController.shooting_boss = True
if self.is_valid_click_location(enemy_l... |
def fight_in_heal_state(self):
batteled = False
if self.GameController.shooting_boss:
boss_location = self.find_boss()
if boss_location:
batteled = True
self.GameController.is_fighting = True
self.GameController.shooting_boss = Tru... | The battle function handles combat logic by prioritizing healing when needed, attacking nearby enemies first, and engaging distant enemies if no nearby targets are present. It ensures the character doesn't attack while refilling and manages movement during healing. | def battle(self):
if self.GameController.is_refilling:
return
# If low health, only kill aggr necessary and just stand still if not looting
if self.GameController.need_healing:
self.fight_in_heal_state()
return
self.preventively_moved_while_healing ... |
def groupby_values(hand):
'''Groups the cards in the hand by their values, and returns a new list
that contains only the cards that have duplicates in the hand. as well
as Aces. This will lower the computational time for the other functions'''
grouped = groupby(sorted(hand), lambda x: x[0])
new_hand... | The function determines if a player can play a valid phase based on their current phase status and hand. It checks each phase (1-7) using specific rules: grouping cards by value (phases 1,4), runs (phase 5), or custom checks (phases 2-3,6-7). If a valid play is possible, it returns the corresponding card list; otherwis... | def possible_phase(player_id, phase_status, hand):
'''Returns a possible phase play as a list of cards.
If phase play is not possible, return False.'''
curr_phase = phase_status[player_id] + 1
# if curr_phase is phase 1, check whether the phase is playable
if curr_phase == PHASE_ONE:
ne... |
def pickup_play(player_id, table, turn_history, phase_status, hand, discard):
'''At the start of the turn, determines whether it's better to draw a card
from the deck, or to draw a card from the discard pile, based on the
current hand, the table etc.
Returns a 2 tuple corresponding to the play types ... | The code determines a valid play for a player in the game Phazed. It prioritizes: (1) executing a pickup play if starting a turn or after another player's turn, (2) initiating a new phase if none has been played yet, (3) adding a card to an existing table phase if possible, and (4) discarding a card as a last resort. T... | def phazed_play(player_id, table, turn_history, phase_status, hand, discard):
'''Returns a play based on the situation of the table, and the plays
that have been done so far. The play is a 2 tuple describing the single
play.
Gives error if the returned play is not valid
'''
table_phase = table[p... |
def normalize_config(
config: Config[T],
file: bool = False,
cmdline: bool = False,
defaults: bool = True,
persistent: bool = True,
) -> Config[Values]:
"""
Creates an `OptionValues` dictionary with setting definitions taken from `self.definitions`
and values taken from `raw_options` and... | The function `get_namespace` converts a normalized configuration into a `Namespace` object by mapping settings to attributes, ensuring unique internal names. It includes defaults and persistent keys based on parameters, raises errors on duplicates, and returns a `Config` object with the `Namespace` and definitions. | def get_namespace(config: Config[T], defaults: bool = True, persistent: bool = True) -> Config[Namespace]:
"""
Returns an Namespace object with options in the form "{group_name}_{setting_name}"
`options` should already be normalized.
Throws an exception if the internal_name is duplicated
Args:
... |
def get_namespace(config: Config[T], defaults: bool = True, persistent: bool = True) -> Config[Namespace]:
"""
Returns an Namespace object with options in the form "{group_name}_{setting_name}"
`options` should already be normalized.
Throws an exception if the internal_name is duplicated
Args:
... | The function parses command-line arguments using `argparse`, creating an argument parser from provided definitions. It uses an optional `config` to set default values, parses input `args`, and returns a normalized `Config` object containing parsed values, combining command-line and configuration inputs. | def parse_cmdline(
definitions: Definitions,
description: str,
epilog: str,
args: list[str] | None = None,
config: ns[T] = None,
) -> Config[Values]:
"""
Creates an `argparse.ArgumentParser` from cmdline settings in `self.definitions`.
`args` and `namespace` are passed to `argparse.Argum... |
def parse_file(definitions: Definitions, filename: pathlib.Path) -> tuple[Config[Values], bool]:
"""
Helper function to read options from a json dictionary from a file
Args:
filename: A pathlib.Path object to read a json dictionary from
"""
options: Values = {}
success = True
if file... | The main task of the code is to parse configuration settings from a file and command-line arguments, merge them into a normalized configuration object, and return the combined configuration along with a success flag indicating whether the file parsing was successful. It integrates file-based and command-line options, e... | def parse_config(
definitions: Definitions,
description: str,
epilog: str,
config_path: pathlib.Path,
args: list[str] | None = None,
) -> tuple[Config[Values], bool]:
file_options, success = parse_file(definitions, config_path)
cmdline_options = parse_cmdline(
definitions, descriptio... |
def EvalError(x_hat,x_true,test):
mse=tf.reduce_mean(tf.square(x_hat-x_true),axis=0)
xnorm2=tf.reduce_mean(tf.square( x_true),axis=0)
mse_thisiter=mse
nmse_thisiter=mse/xnorm2
psnr_thisiter=10.*tf.log(1./mse)/tf.log(10.)
if test:
x_hat_reshaped = tf.reshape(x_hat, [-1, 256, 256, 1])
... | The function `LDAMP` implements an iterative algorithm combining a deep denoising neural network (DnCNN) with forward and adjoint operators to solve inverse problems (e.g., image reconstruction). It initializes estimates, iteratively updates them using the DnCNN to denoise intermediate results, and adjusts the solution... | def LDAMP(y,A_handle,At_handle,A_val,theta,x_true,tie,training=False,LayerbyLayer=True, test=False):
z = y
xhat = tf.zeros([n, BATCH_SIZE], dtype=tf.float32)
MSE_history=[]
NMSE_history=[]
PSNR_history=[]
SSIM_history = []
(MSE_thisiter, NMSE_thisiter, PSNR_thisiter, SSIM_thisiter)=EvalError... |
def make_example_patients(db):
event_num = 15
event_perc = 0.3
db.run_query("MERGE (p:Patient {id: 1234, name:\"star\"})")
db.run_query("MERGE (p:Patient {id: 1235, name: \"chain\"})")
db.run_query("MERGE (p:Patient {id: 1236, name:\"skiplist\"})")
events = create_events(event_num, event_perc)
... | The main task of the code is to benchmark and compare query performance in a Neo4j database under varying conditions. It initializes the database, creates constraints/indexes, generates test data, and evaluates execution times for different query strategies (star, chain, skiplist) with and without indexes. The code als... | def main():
uri, username, password = org.read_config('config.ini')
db = con.Neo4jConnection(uri, username, password)
org.create_constrains(db)
org.create_indexes(db)
make_example_patients(db)
percentages = [0.001, 0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
events_small = list... |
def set_player_points(self, points: int) -> None:
self._player_points = points
self.player_points_changed.emit(points)
def set_casino_points(self, points: int) -> None:
self._casino_points = points
self.casino_points_changed.emit(points)
def set_player_cards(self, player_cards: List[Card... | The main task of the code is to initialize a new game round by resetting player and casino points, clearing their card hands, setting an empty message, and toggling the player's turn state. It prepares the game for a fresh round by calling `_init_new_hand()` and activating the player's turn. | def start(self):
self.set_player_points(0)
self.set_casino_points(0)
self.set_player_cards([])
self.set_casino_cards([])
self.set_message('')
self.set_player_turn(False)
self._init_new_hand()
self.set_player_turn(True) |
def set_player_turn(self, player_turn) -> bool:
self._player_turn = player_turn
self.player_turn_changed.emit(player_turn)
def _add_card_for_player(self) -> None:
self._player_cards.append(self._curr_deck.pop())
self.player_cards_changed.emit()
self.player_values_changed.emit(str... | The method handles a player's "hit" action in a game, adding a card to their hand. It checks if the player's minimum card value exceeds the bust threshold; if so, it triggers a casino win and resets the hand. The player's turn state is toggled off during processing and then restored. | def hit(self):
self.set_player_turn(False)
self._add_card_for_player()
if min(cards_values(self._player_cards)) > BUSTS:
self._casino_win()
self._init_new_hand()
self.set_player_turn(True) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.