dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def update_buffer(self, S_tm1, c_t, o_tm1, ident):
with tf.name_scope('update_buffer'):
# concat previous output & context
idt = tf.tanh(fc_layer(ident, self.hidden_size, self.hidden_size, "fcUb1"))
# :tf.contrib.layers.fully_connected(ident,self.hidden_size))
o_t... | This function processes a sequence in a loop by updating an attention-based buffer, computing weighted context, and generating the next output using fully connected layers. It blends input data with previous outputs during training, applies attention mechanisms to focus on relevant input positions, reshapes buffer cont... | def while_body(self, idx, o_t, sS_t, mu_t, out, attns, context, ident, x, train_flag):
o_tm1 = tf.cond(train_flag,
lambda: tf.expand_dims(x[idx]*0.5+o_t*0.5, 0),
lambda: tf.expand_dims(o_t, 0)
)
# if not self.training:
# ... |
def check_password(user_pass):
if(len(user_pass) >= 12):
check_strength(user_pass)
else:
help_message()
def store_password_decision_tree_newusers(user_pass_1):
while True:
print("How would you like to store your password? \n")
print("1- SQL Database\n")
print("2- Text fil... | The code implements a password manager with a menu-driven interface. It displays an ASCII art welcome message, then lets users choose between registering as a new user, logging in as a returning user, or exiting. New users can check or store passwords, while returning users perform similar actions but through a differe... | def main():
print(
'''
Y
.-^-.
/ \ .- ~ ~ -.
() () / _ _ `. _ _ _
\_ _/ / / \ \ . ~ _ _ ~ .
| | / / \ \ .' .~ ~-. `.
| | / / ) ) / / `.`.
\ \_ _/ / / / ... |
def random_start(self):
chrom, length = choice(list(self.get_lengths().items()))
f1, f2 = VALID_CHROM_FLANKS[chrom]
idx = randint(f1, length - f2)
strand = choice(['+', '-'])
return chrom, idx, strand, length
def scan_codon_from(
self, codon, chrom, start, strand,
... | The function `find_codon` searches for a specified codon in a genome sequence by scanning from random starting positions. It iterates up to `max_scans` times, each time scanning up to `max_iter_per_scan` positions. If found, it returns the chromosome, codon position, strand, length, and optionally the surrounding seque... | def find_codon(
self, codon: str,
max_scans: t.Optional[int] = None,
max_iter_per_scan: t.Optional[int] = None,
fetch: bool = False,
flank_size: t.Optional[int] = 100,
):
assert max_scans is None or max_scans >= 1
idx_codon = None
i... |
def _eps3(truncation_level, n_epsilons):
# NB: instantiating truncnorm is slow and calls the infamous "doccer"
tn = scipy.stats.truncnorm(-truncation_level, truncation_level)
eps = numpy.linspace(-truncation_level, truncation_level, n_epsilons + 1)
eps_bands = tn.cdf(eps[1:]) - tn.cdf(eps[:-1])
retu... | The function computes a 6D disaggregation matrix representing the conditional probability of an intensity measure type (IMT) exceeding a specified level (IML) at a given site, considering rupture scenarios categorized by magnitude, distance, coordinates, epsilon, and tectonic region type. It processes seismic sources, ... | def disaggregation(
sources, site, imt, iml, gsim_by_trt, truncation_level,
n_epsilons, mag_bin_width, dist_bin_width, coord_bin_width,
source_filter=filters.nofilter, **kwargs):
"""
Compute "Disaggregation" matrix representing conditional probability of an
intensity mesaure type ``i... |
def Generate_PlotOrder(total_codebook, sel_codebook, sort_by_region=True):
"""Function to cleanup plot_order given total codebook and selected codebook"""
chr_2_plot_indices = {}
chr_2_chr_orders = {}
_sel_Nreg = 0
for _chr in sorted(np.unique(total_codebook['chr']), key=lambda _c:sort_mouse_chr(_c)... | The function converts a structured distance dictionary into a matrix format, organizing distances between genomic regions based on chromosome order and codebook selections. It handles cis (same chromosome) and trans (different chromosome) interactions, populates a symmetric matrix with distances, and returns the matrix... | def assemble_ChrDistDict_2_Matrix(dist_dict,
total_codebook, sel_codebook=None,
use_cis=True, sort_by_region=True):
"""Assemble a dist_dict into distance matrix shape"""
if sel_codebook is None:
sel_codebook = total_codebook
# get ... |
def Generate_PlotOrder(total_codebook, sel_codebook, sort_by_region=True):
"""Function to cleanup plot_order given total codebook and selected codebook"""
chr_2_plot_indices = {}
chr_2_chr_orders = {}
_sel_Nreg = 0
for _chr in sorted(np.unique(total_codebook['chr']), key=lambda _c:sort_mouse_chr(_c)... | The function `assemble_ChrDistDict_2_Matrix_V2` converts a dictionary of chromosomal distance data (`dist_dict`) into a symmetric distance matrix. It uses a codebook to map genomic positions to indices, sorts chromosomes by region, and populates the matrix with cis (same-chromosome) or trans (cross-chromosome) distance... | def assemble_ChrDistDict_2_Matrix_V2(dist_dict,
total_codebook, sel_codebook=None,
use_cis=True, sort_by_region=True):
"""Assemble a dist_dict into distance matrix shape"""
if sel_codebook is None:
sel_codebook = total_codebook
# g... |
def read_file_bytes(fname: str) -> bytes:
opener = get_opener_for_file(fname)
with opener(fname, "rb") as reader:
return reader.read()
def remove_preview_element_from_root(root: Element) -> Element:
for elem in root.findall("./preview"):
xprint("Removing <preview>")
root.remove(elem)... | This function compresses or decompresses an XML file by modifying its internal elements. If compressing, it removes preview elements and replaces strokes; if decompressing, it replaces strokes differently. The processed XML is saved to the output file, with a header added during decompression. | def process_compress_decompress(kind: str, infile: str, outfile: str) -> None:
"""
Compress or decompress file based on the `kind`.
This is the core function of this script.
"""
input_data = read_file_bytes(infile)
root = ET.fromstring(input_data)
if kind == "compress":
remove_previ... |
def compress_dstring(dstring: str) -> str | None:
"""
We only compress SVGs produced by xournal, with a fixed pattern for dstring.
If should be of the form: M num num L num num L num num ...
"""
splits = dstring.split()
if len(splits) % 3 != 0:
return None
commands = splits[::3]
... | The main task of the code is to process a path element by compressing its 'd' attribute string, updating it if compression succeeds, and then applying scaling adjustments to the element's coordinates and stroke width. | def process_path_elem(elem: Element) -> None:
dstring = elem.get("d", "")
if not dstring:
return None
compressed = compress_dstring(dstring)
if compressed is None:
return None
elem.set("d", compressed)
set_xy_scaling_for_path_elem(elem)
scale_stroke_width(elem) |
def linecount_table():
rows = header()
rows += [
r'\begin{tabular}{ |l|l| }',
r'\hline',
r'\multicolumn{2}{|c|}{Line Counts} \\',
r'\hline',
r'Language & \# Lines \\',
r'\hline',
fr'Rust & {get_rust_lines()} \\',
fr'Written Egg & {sum(get_written_... | The code generates LaTeX files (`linecount.tex`, `detailed-linecount.tex`, `benchmarks.tex`) by writing table content from functions, then compiles each using `pdflatex` in the specified output directory. It suppresses command output and ensures PDFs are generated for all `.tex` files in the directory. The main task is... | def generate_latex(output_path):
with open(f'{output_path}/linecount.tex', "w") as f:
f.write(linecount_table())
with open(f'{output_path}/detailed-linecount.tex', "w") as f:
f.write(detailed_linecount_table())
with open(f'{output_path}/benchmarks.tex', "w") as f:
f.write(benchmarks... |
def checkPythonVersion(version):
"""Exit if the provided python version is less than the supported version."""
if version < MINIMUM_PYTHON:
sys.stderr.write("Minimum python version {} required, found {}\n".format(tupleToDotted(MINIMUM_PYTHON), tupleToDotted(version)))
sys.exit(EXIT_CODES["python... | The main task of the code is to process gcov coverage files by filtering, optionally zeroing counters, and generating a JSON report summarizing coverage data across source files using parallel gcov execution. It validates dependencies, handles file operations, and logs processing results. | def getGcovCoverage(args):
# Need at least python 3.5 because of use of recursive glob
checkPythonVersion(sys.version_info[0:2])
# Need at least gcov 9.0.0 because that's when gcov JSON and stdout streaming was introduced
checkGcovVersion(getGcovVersion(args.gcov))
# Get list of gcda files to proc... |
def parseArgs():
parser = argparse.ArgumentParser(description='A parallel gcov wrapper for fast coverage report generation')
parser.add_argument('-z', '--zerocounters', dest='zerocounters', action="store_true", help='Recursively delete all gcda files')
# Enable Branch Coverage
parser.add_argument('-b',... | The main task of the code is to process code coverage data by parsing arguments, retrieving coverage reports (either combined or from gcov), scanning source files for exclusion markers, applying diff-based filtering, validating sources, and exporting the processed coverage data to the specified output format, while man... | def main():
args = parseArgs()
# Setup logging
setupLogging(args.quiet, args.verbose)
# Get report from appropriate source
if args.combine:
fastcov_json = getCombineCoverage(args)
skip_exclusion_markers = not args.scan_exclusion_markers
else:
fastcov_json = getGcovCover... |
def _send_command(self, command) -> None:
self._digital_write(self._dc_pin, 0)
self._digital_write(self._cs_pin, 0)
self._spi_writebyte([command])
self._digital_write(self._cs_pin, 1)
def _delay_ms(self, delay) -> None:
utime.sleep(delay / 1000.0)
def _read_busy(self) -> None:
... | This code turns on a display by sending a specific command (0x12), waiting for 100 milliseconds to allow the device to process it, and then checking the device's busy status to ensure it is ready for further operations. | def turn_on_display(self) -> None:
self._send_command(0x12)
self._delay_ms(100)
self._read_busy() |
def reset(self) -> None:
for _ in range(3):
self._digital_write(self._reset_pin, 1)
self._delay_ms(20)
self._digital_write(self._reset_pin, 0)
self._delay_ms(2)
self._digital_write(self._reset_pin, 1)
self._delay_ms(20)
def _send_command(self, comm... | This code initializes a display module by configuring power settings, voltage levels, booster soft start parameters, PLL frequency, resolution, VCOM settings, and data intervals. It sends specific commands and data to set up hardware parameters for proper operation, ensuring the display functions correctly after initia... | def _init(self) -> None:
self.reset()
self._send_command(0x01) # POWER SETTING
self._send_data(0x03)
self._send_data(0x00) # VGH=20V,VGL=-20V
self._send_data(0x2b) # VDH=15V
self._send_data(0x2b) # VDL=-15V
self._send_data(0x13)
self._send_command(0x0... |
def _send_command(self, command) -> None:
self._digital_write(self._dc_pin, 0)
self._digital_write(self._cs_pin, 0)
self._spi_writebyte([command])
self._digital_write(self._cs_pin, 1)
def _send_data(self, data) -> None:
self._digital_write(self._dc_pin, 1)
self._digital_w... | This function clears the display by sending specific commands and data to initialize the screen buffer. It calculates the width in 8-pixel segments, sends 0x10 and 0x13 commands with 0xff data to fill the display area, then executes 0x12 to refresh and delays before turning the display on. The purpose is to reset the d... | def clear(self) -> None:
if self.WIDTH % 8 == 0:
wide = self.WIDTH // 8
else:
wide = self.WIDTH // 8 + 1
self._send_command(0x10)
for j in range(0, self.HEIGHT):
for i in range(0, wide):
self._send_data(0xff)
self._send_comman... |
def cos(a):
a = math.radians(a)
return round(math.cos(a), 6)
def arccos(a):
x = round(math.acos(a), 6)
x = math.degrees(x)
return x
def cal_m_triplet(S, T):
ps = get_polygon(S)
pt = get_polygon(T)
m1 = abs((ps.area + pt.area - 2*ps.intersection(pt).area)/ps.area)
T[0], T[1] = T[1], ... | The main task of the code is to calculate crystal morphology parameters, determine the minimum value from computed triplet parameters to identify the most probable crystal plane, and verify if this plane matches the one with the maximum relative surface area. It processes lattice parameters, computes geometric relation... | def cal_m_params(S, params):
idcode, a, b, c, alpha, beta, gamma = params
reader = EntryReader('csd')
crystal = reader.crystal(idcode)
try:
morphology = CrystalDescriptors.Morphology(crystal)
except:
return
if (a == 0 or b == 0 or c == 0 or alpha == 0 or beta == 0 or gamma =... |
def generate_real_samples(dataset, n_samples):
"""
Choose random instances
"""
ix = randint(0, dataset.shape[0], n_samples)
"""
Retrieve selected images
"""
X = dataset[ix]
"""
Generate 'real' class labels (1)
"""
y = ones((n_samples, 1))
return X, y
def generate_... | This function trains a GAN by alternating between updating the discriminator with real and fake samples, then training the generator via the GAN model. It processes batches of data, trains the discriminator on real samples, then on generated fakes, and updates the generator using inverted labels. Losses are printed per... | def train(g_model,
d_model,
gan_model,
dataset,
latent_dim,
n_epochs=500,
n_batch=128):
"""
Batch per epoch
"""
batch_per_epoch = int(
dataset.shape[0] / n_batch)
"""
Half batch
"""
half_batch = int(n_batch / 2)
"... |
def export_example_model():
my_model = get_model('example.fdm')
model_export(my_model, 'example.dot')
return my_model
def get_food_data_from_database():
my_model = get_model('example.fdm')
all_food = []
for menu_section in my_model.menu_sections:
for item in menu_section.items:
... | This code parses menu data from a database, categorizes food and drink items into specific types, and generates a structured table using a Jinja2 template. It organizes items like main dishes, soups, drinks, etc., applies menu styling, and outputs the rendered table to the specified folder. | def parse_table(output_folder):
abs_image_path = os.path.abspath("images/menu_logo.png")
col_names = ['Name', 'Price', 'Images']
main_dishes = []
soups = []
hot_drinks = []
appetizers = []
house_specials = []
salads = []
deserts = []
alchocols = []
carbonateds = []
juices... |
def face_detect(image):
orig_h, orig_w = image.shape[0:2]
frame = create_letterbox_image(image, 128)
input_frame = cv2.cvtColor(cv2.resize(frame, (128, 128)), cv2.COLOR_BGR2RGB)
input_tensor = np.expand_dims(input_frame.astype(np.float32), 0) / 127.5 - 1
result = model_face_detect.predict(input_tens... | This function processes an input image to detect, align, and optionally crop faces. It identifies face regions, applies preprocessing, uses a model to detect facial landmarks, aligns faces based on detected landmarks, and yields aligned faces or their coordinates. The process includes boundary checks, padding, and cond... | def face_process(image, isLoad=False, cropData=False):
orig_h, orig_w = image.shape[0:2]
final_boxes = face_detect(image)
for bx in final_boxes:
x1, y1, x2, y2 = bx[:4]
w_face = x2 - x1
h_face = y2 - y1
if x1 < 0 or y1 < 0 or x2 > orig_w or y2 > orig_h:
if not cro... |
def decode_emotion(self, path, top=7):
""" decode the given image with emotion related information
Arguments:
path: image path, a string
top: the top sentiments you want, an integer
Returns:
length: an integer
top_sorted_results: a list of emoti... | The main task of the code is to decode image data by extracting emotional analysis results, contextual metadata (title, description, keywords), and rendering findings on the image. It compiles these into a structured dictionary for return, using `decode_emotion` and `decode_context` methods, with `top` controlling resu... | def decode_image(self, path, top=7):
""" pack all decoded information into a python dictionary to return
"""
length, top_sorted_results, original_results = self.decode_emotion(path, top=top)
title, description, keywords = self.decode_context(path)
self.renderResultOnImage(origin... |
def set_sentiment_list(self, query):
self.sentiment_list = query['top_sorted_results']
def rescale_sentiment_list(self):
self.sentiment_list = [self.rescale_sentiment(sentiment) for sentiment in self.sentiment_list]
def merge_sentiment_list(self):
# squared_sentiment_list = [[(item[0], (item[1]*... | This function recommends the top 'top' quotes from a database based on a sentiment-driven scoring system. It processes the input query to generate sentiment values, rescales them, and merges results. It iterates through quotes, calculates scores, and dynamically maintains a sorted list of top-scoring lines, replacing l... | def recommend_lines(self, query, top=3):
"""
"""
self.set_sentiment_list(query)
self.rescale_sentiment_list()
self.merge_sentiment_list()
ranks = []
count = 0
total = 0
for line in self._database['quotes']:
score = self.get_rank_score... |
def raw_train(shuffle=False):
"""
Date range for train:
min: Timestamp('2014-10-19 05:24:15')
max: Timestamp('2015-02-18 06:00:44')
"""
train_dev = historical_data()
data, _ = train_test_split(
train_dev,
shuffle=shuffle,
train_size=settings.train_size,
... | The main task of the code is to sequentially execute three functions—`raw_train()`, `raw_dev()`, and `raw_test()`—likely for processing training, validation, and testing datasets in a machine learning or data analysis workflow. The `main()` function orchestrates these steps, ensuring each dataset is handled in order. | def main():
raw_train()
raw_dev()
raw_test() |
def train():
return preprocess(load.raw_train(), "train")
def dev():
return preprocess(load.raw_dev(), "dev")
def test():
return preprocess(load.raw_test(), "test") | The main task of the code is to execute three phases—training, validation, and testing—of a machine learning model. The `main()` function sequentially calls `train()` to build the model, `dev()` to evaluate its performance on a validation set, and `test()` to assess its generalization on unseen data, ensuring the model... | def main():
train()
dev()
test() |
def get_batch(source, i, bptt, seq_len=None):
seq_len = min(seq_len if seq_len else bptt, len(source) - 1 - i)
data = source[i:i+seq_len]
target = source[i+1:i+1+seq_len].view(-1)
return data, target
def repackage_hidden(h):
"""Wraps hidden states in new Tensors,
to detach them from their histor... | The code trains a neural network model (likely a language model) using sequence data, tracking training and validation/test losses/perplexity (ppl) across epochs. It employs dynamic sequence lengths (bptt), dropout, and regularization (alpha/beta). Each epoch includes training with backpropagation, evaluation on valida... | def train(args, model, criterion, optimizer, train_data, val_data, test_data, eval_batch_size, test_batch_size):
results = {
'train_losses': [],
'train_ppl': [],
'val_losses': [],
'val_ppl': [],
'test_losses': [],
'test_ppl': [],
'epoch_elasped_times': []
... |
def arg_parser():
parser = argparse.ArgumentParser(description='PyTorch NLP Distributed Training')
parser.add_argument('--dataroot', type=str, default='.',
help='location of the data corpus')
parser.add_argument('--dataset', type=str, default='PennTreebank',
h... | The code trains a language model (RNN) on a dataset, using specified optimization methods (e.g., SGD, Adam), with options for reproducibility, GPU acceleration, and result logging. It loads or generates data, initializes the model and loss function, configures the optimizer, trains the model, and saves training results... | def main():
args = arg_parser()
args.tied = True
torch.cuda.set_device(args.gpu_id)
print(f"| Requested GPU {args.gpu_id} "
f'| Assigned GPU {torch.cuda.current_device()} |')
# Set the random seed manually for reproducibility.
if args.reproducible:
torch.manual_seed(args.seed... |
def updateDirection(self):
angle = 0#this will later be calculated from newDirectionData
if (len(self.rayData) != 0):
mappedRayData = self.rayData.copy()
for i in range(len(self.rayData)):
mappedRayData[i] /= 400
self.nn.nextInputs(mappedRay... | The code updates an agent's position based on direction and speed, using a neural network to determine movement. It checks for collisions, reverts position if collided, and calculates a fitness score. Ray data is gathered for environment interaction, ensuring the agent navigates without crossing boundaries. | def update(self):
lastPosition = self.position
self.updateDirection() #Rotate body data and determine how much to turn using neural network
self.position = Point(self.position.x + self.direction.x * self.speed, self.position.y + self.direction.y * self.speed) #move in the relative forward direc... |
def start_state(self):
return (self.n - 1) * (None,)
def possible_tags(self, word):
tags = self.word_lexicon[word]
if tags:
return tags
else:
return self.unknown_word_tags
def log_tag_probability(self, tag, tag_history):
logs = []
for lambda_coeff,... | The main task of the code is to train a probabilistic model on unlabeled text using the Forward-Backward algorithm. It iteratively computes forward and backward probabilities (alphas/betas) for each word and tag combination, accumulates expected counts for transition and output probabilities, and updates model paramete... | def train_unlabeled(self, words):
words = list(words)
T = len(words)
known_words = frozenset(words)
# Debug output
print("\nStarting Forward-Backward algorithm, unsupervised learning on unlabeled data (%s tokens)" % len(words), file=sys.stderr)
print("The algorit... |
def start_state(self):
return (self.n - 1) * (None,)
def possible_tags(self, word):
tags = self.word_lexicon[word]
if tags:
return tags
else:
return self.unknown_word_tags
def log_tag_probability(self, tag, tag_history):
logs = []
for lambda_coeff,... | The main task of the code is to decode a sequence of words into their most probable part-of-speech tags using the Viterbi algorithm. It computes log probabilities for tag transitions and word-tag emissions, prunes intermediate states to limit complexity, and backtracks from the highest-probability path to reconstruct t... | def decode(self, data):
words = list(data)
# Viterbi algorithm
stage = { self.start_state() : ViterbiTrelisNode(log_gamma=0) }
for word in words:
new_stage = defaultdict(ViterbiTrelisNode)
for tag in self.possible_tags(word):
for previous_state, p... |
def tag_cross_entropy(self, held_out_data):
sum = 0
count = 0
tags = [tag for word,tag in held_out_data]
for tag, tag_history in zip(tags, self.history_generator(tags)):
sum += self.log_tag_probability(tag, tag_history)
count += 1
return -sum / count
def n... | The code performs the Expectation-Maximization (EM) algorithm to smooth interpolation weights (lambdas) for a language model. It iteratively updates lambdas using held-out data by calculating log probabilities, accumulating evidence for each lambda, normalizing, and checking for convergence (stopping when lambda change... | def train_lambdas(self, held_out_data):
held_out_data = list(held_out_data)
tags = [tag for word,tag in held_out_data]
# Debug output
print("\nStarting Smoothing EM Algorithm", file=sys.stderr)
print("Actual Lambdas:", ' '.join(map(lambda x: "%.3f" % x, self.lambdas)), ... |
def soft_e_policy(S,w,env,e):
sample = np.random.uniform()
Q_values = np.zeros(env.action_space.n)
for i in range(env.action_space.n):
Q_values[i] = Q(S,i,w,env)
if(sample > e):
action = np.argwhere(Q_values == np.amax(Q_values))
action = action.flatten()
a = np.random.... | The code implements the **SARSA (on-policy) reinforcement learning algorithm** using linear function approximation for the MountainCar-v0 environment. It updates the weight vector `w` iteratively by approximating the Q-function with a linear combination of features, applying the SARSA update rule:
`w ← w + α [R + γQ(... | def Sarsa_on_policy():
total_g = 0
alpha = 0.1
gamma = 0.1
e = 0.1
env = gym.make('MountainCar-v0')
w = np.zeros(21)
for episode in range(1000):
G = 0
if(episode%100 == 0):
print(G)
print(episode)
S = env.reset()
action = soft_e_policy... |
def ultrasonic():
global distance1, distance2, distance3, distance4, heading
# print("DISTANCE1=",distance1,"DISTANCE2=", distance2)
if distance1 < b_threshold or distance2 < b_threshold:
backward()
time.sleep(1)
if distance1 < distance2:
print("ULTRASONIC OVERRIDE: BA... | The code subscribes to multiple ultrasonic, IMU, and GPS topics to monitor sensor data. It processes readings in callbacks, checks if the robot's distance to a goal (dist) is under 1.0 meters, and triggers a stop if reached. The loop continuously sleeps, updates sensor data, calculates heading differences, and displays... | def listener():
rospy.Subscriber("/ultrasonic/front/left", Range, callback1)
rospy.Subscriber("/ultrasonic/front/right", Range, callback2)
rospy.Subscriber("/ultrasonic/back/left", Range, callback3)
rospy.Subscriber("/ultrasonic/back/right", Range, callback4)
rospy.Subscriber("/imu", Imu, callback... |
def _setup_parameters_(self):
self.u = 1 + self.pu # Expected value in the up state
self.d = 1 - self.pd # Expected value in the down state
self.qu = (math.exp((self.r - self.div) * self.dt) - self.d) / (self.u - self.d)
self.qd = 1 - self.qu
def _initialize_stock_price_tree_(self):
... | The code calculates the initial payoff of a financial instrument using a binomial tree model. It initializes parameters, constructs a stock price tree, traverses the tree to compute payoffs, and returns the first payoff value at the root node. | def price(self):
self._setup_parameters_()
self._initialize_stock_price_tree_()
payoffs = self.__begin_tree_traversal__()
return payoffs[0] |
def is_train_test_file_exists(self):
try:
logging.info("Checking if training and test file is available")
is_train_file_exists = False
is_test_file_exists = False
train_file_path = self.data_ingestion_artifact.train_file_path
test_file_path = self.dat... | The main task of the code is to validate data by checking the existence of train/test files, verifying dataset schema, and detecting data drift. If successful, it generates and returns a `DataValidationArtifact` with validation status, file paths, and success message. Exceptions trigger a `HousingException` with error ... | def initiate_data_validation(self) -> DataValidationArtifact:
try:
self.is_train_test_file_exists()
self.validate_dataset_schema()
self.is_data_drift_exists()
data_validation_artifact = DataValidationArtifact(
schema_file_path = self.data_validati... |
def parse_arguments():
"""Parse and return the command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--data_path', help="Directory for data, e.g. './data/lmd_matched'.", required=True)
parser.add_argument('--midi_dir', help="Name of data folder containing MIDI files, e.g. 'l... | The function filters and returns songs longer than a specified minimum duration with a 4/4 time signature by parsing arguments, loading MIDI files, checking duration and time signature, and collecting qualifying songs while ignoring errors. | def get_long_songs():
"""Get songs longer than min length that are in 4/4 time."""
args = parse_arguments()
long_songs = []
for song in fliter_genres():
try:
midi_data = pretty_midi.PrettyMIDI(midi_path(song))
if midi_data.get_end_time() >= int(args.min_length):
... |
def parse_arguments():
"""Parse and return the command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--data_path', help="Directory for data, e.g. './data/lmd_matched'.", required=True)
parser.add_argument('--midi_dir', help="Name of data folder containing MIDI files, e.g. 'l... | The main task of the code is to convert selected MIDI files into either MIDI or pianoroll (NPZ) format based on the `use_muspy` argument. If `use_muspy` is True, it writes MIDI files using `pretty_midi`; otherwise, it converts MIDI files to pianoroll data and saves them as NPZ files using `pypianoroll`. The code handle... | def main():
"""Main function: Converts selected MIDI files to pianoroll."""
args = parse_arguments()
songs = get_long_songs()
if args.use_muspy:
final_path = os.path.join(args.data_path, 'results', 'midi_files')
if not os.path.exists(final_path):
os.mkdir(final_path)
for song ... |
def downsample(mesh, target_cells=10000):
'''
downsample the mesh to a certain amount of cells
to be noticed, the result may not be in the exact number as your input
if you input 10,000, it could downsample to 9,999
'''
mesh_ds = mesh.clone()
mesh_ds = mesh_ds.decimate(target_cel... | The code performs inference on a 3D mesh by loading/downsampling the mesh, running prediction with a model, optionally restoring high-resolution details, and visualizing the result. It measures and prints time taken for each step: loading, inference, and high-resolution restoration. | def test_inf(mesh_path, cfg, model, with_refine=True, with_new_features=False, with_high_res=True):
print('start inf')
time0 = time.time()
mesh = vedo.Mesh(mesh_path)
mesh_ds = downsample(mesh) if mesh.ncells > 10001 else mesh
time1 = time.time()
print(f'loading and downsample time: {time1 - tim... |
def push_to_lex(query):
lex = boto3.client('lex-runtime')
response = lex.post_text(
botName='GetArtPieces',
botAlias='prod',
userId="root",
inputText=query
)
print("lex-response", response)
labels = []
if 'slots' not in response:
... | This code processes a search query by sending it to Lex for label extraction, searching Elasticsearch for image paths based on labels, fetching product details from DynamoDB, and returning structured JSON results or a 404 error if no matches are found. | def lambda_handler(event, context):
q = event['queryStringParameters']['q']
print(q)
img_paths = []
outputArray= []
labels = push_to_lex(q)
print("labels", labels)
if len(labels) != 0:
for label in labels:
if (label is not None) and label != '':
response =... |
def authentication(username, password):
with psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST) as conn:
with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
cur.execute("SELECT user_password FROM registeredvoter WHERE voter_id = %s;", [uuid.UUID(userna... | The code's main task is to securely register a vote by authenticating a voter, generating a cryptographic key, blinding it with RSA, signing it via an online verifier, verifying the signature, and registering the vote on Ethereum using the signed key and ballot details. | def start():
user_id = input("Please enter your voter_id : ")
passwd = getpass.getpass("Enter your password : ")
ballot_id = int(input("Enter your ballot id : "))
authentication(user_id, passwd)
key = int(secrets.token_hex(16), 16)
public_ballot_key = serialization.load_pem_public_key(readPublic... |
def build_map(b_map, max=None):
batch_size, b_len = b_map.size()
if max is None:
max=b_map.max() + 1
if torch.cuda.is_available():
b_map_ = torch.cuda.FloatTensor(batch_size, b_len, max).fill_(0)
else:
b_map_ = torch.zeros(batch_size, b_len, max)
b_map_.scatter_(2, b_map.unsq... | The code processes input data for training or inference in a neural network model. It constructs a 'source_map' from item sequences and routes processing to either 'do_train' (for training) or 'do_infer' (for inference) based on the 'method' parameter, enabling task-specific data handling and model execution. | def forward(self, data, method='mle_train'):
data['source_map'] = build_map(data['item_seq'], max=self.item_vocab_size)
if method == 'train':
return self.do_train(data)
elif method == 'infer':
return self.do_infer(data) |
def recursive_file_search(directory: str, list_filter=None) -> list:
"""
Finds all files in a directory and its subdirectories.
If list_filter is defined, pass it to filter which is called
on the list before returning
"""
sub_dirs = [path.abspath(directory), ]
all_files = []
... | The function processes data from a directory containing experiment results by grouping files, identifying baseline files, calculating average baselines, predicting workload runtimes, and generating histograms and system monitor graphs. It filters directories with valid results/baselines, computes predictions, and outpu... | def process_data(directory: str, no_titles: bool = False) -> None:
"""
Gather all files in a directory and its subdirectories and process these
result files. It is advisable to call this function per directory that
contains data from multiple machines/experiments. For example, a directory
that conta... |
def update_height(node):
if node is None:
return 0
node.height = 1 + max(height(node.left), height(node.right))
return node.height
def balance_factor(node):
if node is None:
return 0
return height(node.left) - height(node.right)
def right_rotate(x):
y = x.left
T2 = y.right
... | This function inserts a key into an AVL tree while maintaining balance through rotations. It recursively inserts the key into the appropriate subtree, updates node heights, calculates balance factors, and applies left/right rotations to resolve imbalance in four cases (LL, RR, LR, RL). The function ensures the AVL prop... | def insert_avl(root, key):
if root is None:
return TreeNode(key)
if key < root.key:
root.left = insert_avl(root.left, key)
else:
root.right = insert_avl(root.right, key)
update_height(root)
balance = balance_factor(root)
# Left-Left case
if balance > 1 and key < r... |
def find_min(node):
current = node
while current.left is not None:
current = current.left
return current.key
def update_height(node):
if node is None:
return 0
node.height = 1 + max(height(node.left), height(node.right))
return node.height
def balance_factor(node):
if node is... | This function deletes a node with the specified key from an AVL tree while maintaining its balance. It recursively finds the node, handles cases with 0 or 1 child, replaces with the inorder successor when both children exist, updates tree heights, and applies rotations (left/right) to restore balance based on the node'... | def delete_avl(root, key):
if root is None:
return root
if key < root.key:
root.left = delete_avl(root.left, key)
elif key > root.key:
root.right = delete_avl(root.right, key)
else:
if root.left is None:
return root.right
elif root.right is None:
... |
def extract_feature_for_each_image(ImageData):
imageDescriptor = []
length = len(ImageData)
for i in range(length):
img = ImageData[i]
image8bit = cv.normalize(img, None, 0, 255, cv.NORM_MINMAX).astype('uint8')
k,descriptor = sift.detectAndCompute(image8bit,None)
if descriptor is None: imageDescri... | The code creates a visual dictionary using k-means clustering on image features. It extracts descriptors from training and testing images, initializes centroids, iterates k-means 20 times, and generates histograms for training/test sets based on the learned centroids, saving them for further use in tasks like image ret... | def CreateVisualDictionary(k):
print("Extracting Testing Images Data...")
test_image_descriptor = extract_feature_for_each_image(test_images)
print("Extracting Training Images Data")
train_image_descriptor = extract_feature_for_each_image(train_images)
trainDescriptors = extractFeatures(train_image_descripto... |
def _get_paths(self, dataset_raw_path):
if not dataset_raw_path:
return []
if not os.path.isdir(dataset_raw_path):
paths = [dataset_raw_path]
else:
paths = [os.path.join(dp, f) for dp, dn, filenames in os.walk(dataset_raw_path) for f in filenames]
retu... | The code processes multiple input files by performing inference on each line using a specified deployment model, writes results to an output file, and logs progress. It checks deployment status, reads JSON prompts, executes inference, and stores generated text with metadata. The function handles error tracking and peri... | def inference_dir(self, args, input_dir, output_file_path, deployment_id, max_tokens, print_interval=20):
file_complete_paths = self._get_paths(input_dir)
logger.info(f"file_complete_paths: {file_complete_paths}")
logger.info(f"prepare to write all inference results into {output_file_path}")
... |
def get_best_feature(train_data, label_name, label,method):
feature_only = train_data.columns.drop([label_name,"weight","prediction"])
#print(feature_only)
max_info_gain = -1
best_feature = None
for i in feature_only:
feature_gain = get_info_gain(train_data,label_name,label, i, method)
... | The function `get_tree` recursively constructs a decision tree by selecting the best feature to split the data at each node. It uses `get_best_feature` to determine the optimal feature based on the specified method (e.g., Gini or entropy). The data is partitioned using `get_sub_tree`, and the tree structure is updated ... | def get_tree(train_data, label_name, label, pre_feature, node, max_depth, method):
if train_data.shape[0] > 0 and max_depth > 0:
best_feature = get_best_feature(train_data, label_name, label, method)
#print("get tree best feature" + best_feature + "\t" + str(max_depth))
train_data, tree_dict... |
def get_best_feature(train_data, label_name, label,method):
feature_only = train_data.columns.drop(label_name)
#print(feature_only)
max_info_gain = -1
best_feature = None
for i in feature_only:
feature_gain = get_info_gain(train_data,label_name,label, i, method)
if max_info_gain < fe... | This function recursively constructs a decision tree by selecting the optimal feature to split the training data, building the tree structure as a nested dictionary. It uses a specified method to determine the best feature, partitions the data, and recursively builds subtrees for each split until the maximum depth is r... | def get_tree(train_data, label_name, label, pre_feature, node, max_depth, method):
if train_data.shape[0] > 0 and max_depth > 0:
best_feature = get_best_feature(train_data, label_name, label, method)
#print("get tree best feature" + best_feature + "\t" + str(max_depth))
train_data, tree_dict... |
def get_id3_tree(train_data, label_name, label,max_depth, method):
tree_dict = {}
get_tree(train_data, label_name, label, None, tree_dict, max_depth, method)
return tree_dict
def get_error_rate(tree, test_data, label_name):
wrong_count = 0
correct_count = 0
error = 0
predictions = []
for... | This code implements the AdaBoost algorithm using decision stumps for classification. It iteratively trains weak learners (decision trees) on weighted training data, adjusts weights based on error rates, and combines predictions via weighted sums. It tracks training/test errors at each iteration, updates model weights ... | def adaboost(train_data, test_data, label_list):
errors_of_stump = []
errors_of_stump_test = []
adaboost_errors = []
adaboost_errors_test = []
adaboost_sum = np.zeros(len(train_data))
adaboost_sum_test = np.zeros(len(test_data))
weights = [1/len(train_data)] * len(train_data)
train_erro... |
def _create_init_dirs(self):
for directory in [self.output_dir, self.raw_dir, self.masked_dir,
self.ordered_dir,self.warped_dir,
self.temp_vrt_dir, self.full_vrt_dir,
self.tile_tif_dir, self.mosaic_dir, self.chips_dir
... | This code manages a pipeline for processing satellite tiles, allowing users to specify start and end steps (download, process, chip, upload). It validates inputs, executes selected pipeline stages in order, and handles data processing, tiling, and cloud storage uploads, ensuring proper directory setup and error checkin... | def run(self, tiles=None, start_step='download', end_step='upload'):
'''
Steps:
1. Download
2. Process
3. Chip
4. Upload
'''
step_dict = {
'download': 1,
'process': 2,
'chip': 3,
'upload': 4
}
... |
def state_space_info(self):
return self.player_num + 1
def action_space_info(self):
return self.total_bean_num + 1
def reset(self):
"""
reset game
Returns:
state, 0, done, state
"""
self._reset()
def get_state(self):
"""
:return curren... | The code simulates an environment where an agent takes random actions, observes states, and tracks rewards until termination. It initializes state/action dimensions, resets the environment, and iterates through steps, logging the agent's index, state, action, reward, next state, and bean counts. Upon completion, it out... | def run(self):
done = False
state_dim, action_dim = self.state_space_info(), self.action_space_info()
print(f"state size: {state_dim}, action size: {action_dim}.")
print('-----------')
print(self.reset())
print('-----------')
while not done:
state = s... |
def embed_edges(self, edges, label):
embedded_edges = []
embedded_labels = []
for n1, n2 in edges:
embedded_edges.append(self.hadamard[str(n1), str(n2)])
embedded_labels.append(label)
return embedded_edges, embedded_labels
def negative_embeds(self):
normal... | The code performs link prediction by generating positive and negative edge embeddings, combining them for model training, and detecting anomalous edges. It first embeds training edges, creates negative samples, trains on combined data, then identifies outliers. | def linkpredict(self):
if self.verbose:
print('Beginning Link Prediction')
self.pos_edge_embeddings, self.pos_edge_label = self.embed_edges(self.TrainGraph.edges(), 1)
self.negative_embeds()
self.fitpredict(self.combine(self.pos_edge_embeddings, self.neg_edge_embeddings),
... |
def execdb(self,arg):
print(f'Executing:{arg}')
while not self.dbstatus:
time.sleep(0.2)
else:
self.dbstatus = False
try:
mycon = mysql.connector.connect(host='localhost',database='spyonic',user='root',password='root')
mycurs = ... | This code handles admin and client registration/login via a server socket. It accepts connections, verifies credentials, generates unique IDs, updates databases, and spawns threads for ongoing communication. Admins get device count tracking, while clients link to admins. Errors like duplicate emails or incorrect passwo... | def accepter(self):
while self.status:
try:
cli , addr = self.server.accept()
cli.send('namex'.encode())
data = pickle.loads(cli.recv(2048))
if data['type'] == 'admin':
x = ['idk']
if data['user']... |
def _post_upload(self, **kwargs) -> Any:
for name, data in kwargs["files"].items():
path = self.dir / name
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, mode="wb") as f:
f.write(data)
return self._response(
content={"mes... | This function routes API requests to specific handlers based on HTTP method and path. It directs POST requests to /upload or /delete, GET requests to /list, /info, or /key, and raises an error for unmatched endpoints, ensuring proper request processing and error responses. | def _call_api(self, method: str, path: str, **kwargs) -> Any:
if method == "POST" and path == "/upload":
return self._post_upload(**kwargs)
elif method == "POST" and path == "/delete":
return self._post_delete(**kwargs)
elif method == "GET" and path == "/list":
... |
def fetch_file_list(self, path_on_server: Optional[str] = None) -> Any:
"""
Fetch the file list of your Neocities site.
Parameters
----------
path_on_server : str or None, optional
If provided, the API will return a list of files for this path.
Returns
... | This function deletes all files from a Neocities site, excluding 'index.html', which is replaced with an empty template. It waits for a specified duration before initiating deletions, fetches the file list, filters out 'index.html', and deletes remaining files. The operation is irreversible, with a warning to back up f... | def delete_all(self, waiting_seconds: int = 10) -> Any:
"""
Delete all files on your Neocities site.
Notes
-----
Since index.html cannot be deleted, replace it with an empty template file.
Parameters
----------
waiting_seconds : int, optional
... |
def convert2github_api(url):
"""
Convert original GitHub path into GitHub API to get data
Args:
url (str): GitHub url.
e.g., https://github.com/jcwchen/MLabHack2020/tree/master/data/onnx/mnist
Returns:
str: GitHub API url.
e.g., https://api.github.com/repos/jcwchen/MLab... | The function parses a GitHub URL to validate a model's ONNX file and associated module, retrieves repository metadata (star count, owner), and returns a status dictionary. It downloads files from the URL, checks for required files, validates the ONNX model, and verifies the module's class name. The result includes vali... | def parse_github_url(url, module_fname, class_name):
"""
parse files, validate the target model and get metadata from the GitHub url
Args:
url (str): GitHub url.
e.g., https://github.com/jcwchen/MLabHack2020/tree/master/data/onnx/mnist
Returns:
dict: {validation status: int, sta... |
def is_valid_path(board, path, words):
if not validate_path(path):
return None
word = extract_word(board, path)
if word in words:
return word
return None
def _board_cells():
cell_lst = []
for row in range(BOARD_SIZE):
for col in range(BOARD_SIZE):
cell_lst.app... | This function recursively finds all valid paths of length n on a board using a dictionary of words, backtracking through possible moves while pruning the word dictionary at each step to only include feasible options. It returns a list of all valid paths that match dictionary words, ensuring each path is of exact length... | def find_all_paths(n, path: List, words_dict, board):
if len(path) == n and is_valid_path(board, path, words_dict):
return [path[:]]
if not words_dict:
return []
result = []
if len(path) == 0:
for coord in _board_cells():
path.append(coord)
result.extend(
... |
def is_valid_path(board, path, words):
if not validate_path(path):
return None
word = extract_word(board, path)
if word in words:
return word
return None
def _board_cells():
cell_lst = []
for row in range(BOARD_SIZE):
for col in range(BOARD_SIZE):
cell_lst.app... | The function `find_all_words` recursively explores all possible paths of length `n` on a board to identify valid words from `words_dict`. It starts with empty paths by iterating over all board cells and then extends paths by moving to adjacent cells. The recursion depth adjusts based on the number of letters in each ce... | def find_all_words(n, path: List, board, words_dict, result):
if n == 0:
if is_valid_path(board, path, words_dict):
result.append(path[:])
return
if len(path) == 0:
for coord in _board_cells():
path.append(coord)
if len(board[coord[0]][coord[1]]) == 1:... |
def login():
"""this method handles login capabilities for the user
the method first checks whether there are any users , the allows login or redirects to registration or
to smart password locker
"""
if User.users:
uname = input("please enter your username : " )
masterk = input("please enter your ma... | The main task of the code is to present users with options to login, register, or exit the application. It continuously prompts for input until a valid choice (1, 2, or 3) is made, executing corresponding functions (login(), register()) or exiting the app with a 3-second delay. Invalid inputs trigger error messages, en... | def landing_section():
"""this is the first function (after main) to be executed, it allows the user to specify either to
login, register or leave the app"""
selecting = True;
while selecting:
"""this loop continues to execute until a login or register function returns a true value"""
inp = int(input("1: login,... |
def screen(x):
"""this is for wrapping some texts together for a good view"""
print("#"*50)
print(""*2)
print(x)
print(""*2)
print("#"*50)
def landing_section():
"""this is the first function (after main) to be executed, it allows the user to specify either to
login, register or leave the app"""
selecting = Tr... | The main task of the code is to implement a password locker application that authenticates users via a landing section, then allows logged-in users to create, view, delete, or search accounts through a menu-driven interface. The loop enables repeated interactions until logout, ensuring secure access to account manageme... | def main():
"""
this is the first function to be executed,
the landing section is called here, and if the return value is true, then the password locker options are unlocked..
"""
screen("hello and welcome to password locker")
decided = landing_section()#this means that if landing page returned a true value
if... |
def spike_plot(lfp, neural_spiking, band, save_path=None):
spike_lfp_phases = _get_spike_lfp_phases(lfp, neural_spiking, band)
# Create a polar histogram to visualize the spike phase distribution.
# The `bins` parameter controls the number of bins in the polar plot.
plt.figure(figsize=(8, 8))
n, bi... | This function analyzes neural spiking activity relative to local field potential (LFP) signals in a specified brain area. It loads neural data, extracts LFP and spiking signals, then generates multiple visualizations showing spike-LFP phase relationships for alpha and theta oscillations. Plots are saved in brain-area-s... | def phase_spiking(fname="steinmetz_2016-12-14_Cori.nc", brain_area="MOs"):
data = _load_data(fname)
lfp = _load_lfp(data, brain_area)
neural_spiking = _load_spiking(data, brain_area)
save_path = join(cfg.PLOT_PATH, brain_area)
spike_plot(lfp, neural_spiking, "alpha", save_path=save_path)
spike... |
def houghTrans(imageG,image_org):
edges = cv2.Canny(imageG,50,150,apertureSize = 3)
linesP = cv2.HoughLinesP(edges, 1, np.pi / 180, 50, None, 50, 10)
l = linesP[1][0]
return l
def inRange(r, item, items):
retVal = []
for obj in items:
... | The code detects white objects in an image, tracks their positions over time, identifies associated numbers, and accumulates a total sum when these objects cross a detected line. It uses thresholding, dilation, Hough transform for line detection, and object tracking with history logging to recognize and sum numbers fro... | def findObject(image):
global total
global i
global listaBr
global stap
global line
boundaries = [([230, 230, 230], [255, 255, 255]) ]
img_org = image.copy()
gray = cv2.cvtColor(img_org, cv2.COLOR_BGR2GRAY)
(lower, upper) = boundaries[0]
lower = np.array(lower... |
def getCmdArg():
'''
Function: This function get the user second input comand line argument. It check whether the input
number of command line arguments are correct, whether the file names input order are correct.
Argument: None
Return: a tsv file path, and a json path
'''
try:
numC... | The code processes a training JSON dataset to compute TF-IDF vectors, checks for existing output files, and writes results to a TSV file with user confirmation to prevent overwrites. It loads data, validates format, calculates document frequencies, computes IDF weights, and generates term vectors for storage. | def main():
knnTsvPath, trainJsonPath = getCmdArg()
isFileExists = check_tsv_file_in_path(knnTsvPath)
if isFileExists:
while True:
choice =input(f"Are you sure you want to overwrite {knnTsvPath}? (y/n): ")
if choice.lower() == "y":
break
elif choice.lower() =='n':
return
... |
def getCmdArg():
'''
Function: This function get the user second input comand line argument. It check whether the input
number of command line arguments are correct, whether the file names input order are correct.
Argument: None
Return: a tsv file path, and a json path
'''
try:
... | The main task of the code is to evaluate a document classification model using Rocchio's algorithm. It processes input files, classifies documents, calculates precision, recall, and F1 scores for each class, then aggregates results into macro-averaged (average per-class F1) and micro-averaged (global TP/FN/FP) metrics,... | def main():
rocchioTSVPath, testJsonPath = getCmdArg()
data = getData(testJsonPath)
checkFormat(data)
C, D, dic = getCandD(data)
results = classify_documents(testJsonPath, rocchioTSVPath)
F1List = []
TPtotal = 0
FPtotal = 0
FNtotal = 0
for c in C:
TP, FP, FN, TN, precisi... |
def getCmdArg():
'''
Function: This function get the user second input comand line argument. It check whether the input
number of command line arguments are correct, whether the file names input order are correct.
Argument: None
Return: a tsv file path, and a json path
'''
try:
numC... | The main task of the code is to train a Multinomial Naive Bayes classifier using JSON data, check for existing TSV file conflicts, prompt user confirmation for overwriting, and save computed probabilities and priors to a TSV file. It retrieves input paths, validates data format, calculates model parameters, and outputs... | def main():
nbcTSVPath, trainJsonPath = getCmdArg()
isFileExists = check_tsv_file_in_path(nbcTSVPath)
if isFileExists:
while True:
choice =input(f"Are you sure you want to overwrite {nbcTSVPath}? (y/n): ")
if choice.lower() == "y":
break
elif choice.lower() =='n':
return
... |
def getCmdArg():
'''
Function: This function get the user second input comand line argument. It check whether the input
number of command line arguments are correct, whether the file names input order are correct.
Argument: None
Return: a tsv file path, and a json path
'''
try:
numC... | The code evaluates a classification model's performance using F1 scores. It processes input data and NBC TSV files, calculates precision, recall, and F1 for each class, then computes macro-averaged (class-wise average) and micro-averaged (global TP/FP/FN) F1 scores, outputting detailed metrics. | def main():
nbcTSVPath, testJsonPath = getCmdArg()
data = getData(testJsonPath)
checkFormat(data)
C, D, dic = getCandD(data)
results = getAllNBs(nbcTSVPath, D, C)
F1List = []
TPtotal = 0
FPtotal = 0
FNtotal = 0
for c in C:
TP, FP, FN, TN, precision, recall, F1 = calcSign... |
def create_random_walks(self):
type0_is_done = False
type1_is_done = False
while not type0_is_done:
[type0_is_done, self.type0_trajectory] = self._attempt_random_walk(0)
while not type1_is_done:
[type1_is_done , self.type1_trajectory] = sel... | This code generates images from random walk trajectories on a canvas, creating two types of trajectory patterns (Type 0 and Type 1). It converts these trajectories into matrices, renders them as grayscale images, and optionally displays them side-by-side if `show_graph` is True. The function also prepares these images ... | def make_image(self , show_graph = True,canvas_size = (9,9)):
#The choice of canvas size will change the size of the next layer made, but does not affect already made layers.
self.canvas_size = canvas_size
self.rad_x = np.floor(canvas_size[0]/2)
self.rad_y = ... |
def create_random_walks(self):
type0_is_done = False
type1_is_done = False
while not type0_is_done:
[type0_is_done, self.type0_trajectory] = self._attempt_random_walk(0)
while not type1_is_done:
[type1_is_done , self.type1_trajectory] = sel... | The code generates a synthetic image by creating random walks on a grid defined by `canvas_size`, converting the trajectory into a matrix, and rendering it as an image without saving to a file. It randomly selects between two trajectory types and returns the resulting image. | def make_data_layer(self,canvas_size = (9,9)):
#Makes a data image that does not create a new file in image_dict
self.canvas_size = canvas_size
self.rad_x = np.floor(canvas_size[0]/2)
self.rad_y = np.floor(canvas_size[1]/2)
self.create_random_walks()
... |
def objective(w):
"""w0:angle, x1:ny, x2: thrust"""
#desired_pos = [x+2000*math.cos(w[0]), y+2000*math.sin(w[0])]
npos = [x+0.85*vx, y+0.85*vy] #desired_pos
fpos = [
npos[0] + 0.85*(vx + w[1]*math.cos(w[0])), #npos, podorientation[i] / #desired_pos
... | The code implements a genetic algorithm to minimize an objective function by evolving a population of bitstring solutions over generations. It initializes a population, evaluates fitness, selects parents, applies crossover and mutation, and iteratively updates the best solution found. The algorithm uses a previous best... | def genetic_algorithm(objective, bounds, n_bits, n_iter, n_pop, r_cross, r_mut, pbest):
# initial population of random bitstring
if pbest is None:
pop = [randint(0, 2, n_bits*len(bounds)) for _ in range(n_pop)]
# keep track of best solution
best, best_eval = pop[0], objective(decode... |
def __parse_value(self, value, error_msg=None, map_to_higher_reg=False):
old_value = value
if map_to_higher_reg:
register_mapping = {"al": "rax", "eax": "rax", "edi": "rdi", "esi": "rsi",
"edx": "rdx", "ecx": "rcx", "r8d": "r8", "r9d": "r9"}
value... | This function processes a move instruction by determining the bit size of the value (8, 16, 32, or 64 bits) based on input type and register context. It handles memory addressing (e.g., with parentheses or underscores) and updates either memory locations or register values accordingly, applying specific adjustments lik... | def __execute_move_instruction(self, value, register):
bits = 64
if (
type(value) == str
and not value.isdigit()
and value != "r8"
and (value.endswith("8") or value == "al")
):
value = value[:-1] if value != "al" else value
... |
def __parse_value(self, value, error_msg=None, map_to_higher_reg=False):
old_value = value
if map_to_higher_reg:
register_mapping = {"al": "rax", "eax": "rax", "edi": "rdi", "esi": "rsi",
"edx": "rdx", "ecx": "rcx", "r8d": "r8", "r9d": "r9"}
value... | This function performs arithmetic operations (add, sub, imul, idiv) on CPU registers, handling memory addresses, string literals, and value type conversions. It validates register states, maps 32-bit to 64-bit registers, resolves memory references, executes operations, and updates register values with proper formatting... | def __execute_arithmetic_operation(self, value, register, operator):
if self.__registers[register].value == None and self.__registers[register].num_bytes != 32:
error_utils.error(
msg=f"Register {register} does not have any value, set a value to perform arithmetic operation"
... |
def calculate_offset(lines_list):
offset = 0
for line in lines_list:
offset += len(line) + 1
return offset
def lst_flatten(lst):
l = []
for i in lst:
if isinstance(i, list):
l += lst_flatten(i)
else:
l += [i]
return l
def content(self, content):... | This function writes content to a file at a specified path. It determines the file mode as 'w+' (create/new) or 'r+' (existing), sets a newline prefix if in 'r+' mode, seeks to either the start (if reset=True) or a calculated offset, then writes the provided content (flattened from self.content()) to the file. | def txt_writer(self, reset = False, *args, **kwargs):
mode = 'w+' if not self.path.exists() else 'r+'
prefix = '\n' if mode == 'r+' else ''
with open(self.path, mode) as info_file:
cursor = 0 if reset else calculate_offset(info_file.readlines())
info_file.seek(cursor)
... |
def do_all(self, arg):
"""Prints all model instance"""
if arg == "":
models = [
str(model) for id, model in storage.all().items()
]
else:
if not self.__model_exists(arg):
print("** class doesn't exist **")
retur... | This method processes commands by splitting input into model and action parts, routing them to corresponding functions like do_all, do_count, do_show, do_destroy, or do_update based on the action suffix, handling string parameters and formatting arguments appropriately. | def default(self, line):
"""Handles default commands"""
args = line.split('.', 1)
if len(args) == 2:
if args[1] == "all()":
model = args[0]
return self.do_all(model)
if args[1] == "count()":
model = args[0]
... |
def _extract_embeddings(self, documents):
embeddings = self.embedding_model.embed_documents(documents)
return embeddings
def _reduce_dimensionality(self, embeddings):
self.umap.fit(embeddings)
reduced_embeddings = self.umap.transform(embeddings)
return np.nan_... | The main task of the code is to process input documents by generating embeddings (if not provided), reducing dimensionality via UMAP (if enabled), clustering embeddings to assign topics, and returning the predicted topics as a list. It integrates embedding extraction, dimensionality reduction, clustering, and topic ass... | def fit_transform(self, documents, embeddings=None):
documents = pd.DataFrame({"Document": documents,
"ID": range(len(documents)),
"Topic": None})
if embeddings is None:
self.embedding_model = select_backend(self.e... |
def globalVars():
global RANDOM_SEED_VALUE
RANDOM_SEED_VALUE = 5
global POPULATION_SIZE
POPULATION_SIZE = 50
global MUTATION_RATE
MUTATION_RATE = .1
global GENERATIONS
GENERATIONS = 100
global globalBestRule
globalBestRule = (0.0, 'e250|e053&e119', True)
global rnd
... | The code implements a genetic algorithm to evolve optimal trading rules for stock market data. It initializes a population of rules, evaluates their fitness, and iteratively mutates and selects the best-performing rules across generations. The algorithm adjusts mutation rates if convergence stalls, aiming to identify t... | def stockRunner():
globalVars()
global globalBestRule
stockData = sr.readAllFileStocks()
population = genereatePopulation(POPULATION_SIZE)
population = calcFitness(stockData, population)
for i in range(GENERATIONS):
population = generateIntermediatePopulation(population, POPULATION_SIZ... |
def choose_how_begin(self):
self.how_begin = randint(0, 1) # 0 is PLAYER, 1 is PC
self.turn_of = self.how_begin
if self.how_begin:
print(start_pc.format(computer=self.computer))
else:
print(start_player.format(player=self.player))
def clear_game(self):
se... | The main task of the code is to initialize and execute a game, determining the winner (computer or player) based on the `start()` method's return value. It configures game settings via `options`, clears the game state, displays the board, and outputs the result ("Tie" or the winner's name) along with a separator line. | def do_start(self, **options):
self.computer = options.get('computer', 'PC')
self.player = options.get('player', 'PLAYER')
self.choose_how_begin()
self.clear_game()
exist_a_winner = self.start()
self.show_board()
if exist_a_winner is None:
print("Tie")... |
def bet_statement(self):
return "Currently have $" + str(self.bet)
def get_bet(self):
try:
bet_amount = int(input("Enter amount to be bet: \n"))
if bet_amount > self.bet:
print("Betting more than you have.")
return self.get_bet()
elif b... | This code simulates a Blackjack game round by initializing a deck, handling betting, dealing cards to player and dealer, executing player and dealer turns, determining the winner, and resetting the game state. It manages game flow, including shuffling, drawing, betting, turn logic, and result declaration. | def game(self):
deck = Deck()
game_over = False
deck.shuffle()
self.bet_statement()
bet = self.get_bet()
self.player_cards.append(deck.draw())
self.dealer_cards.append(deck.draw())
do_dealer_turn = self.player_turn(deck)
if do_dealer_turn:
... |
def featureLen(self):
"""Returns the length of feature vectors given by feature()"""
return 3;
def getNumFrames(self):
"""Convenience providing access to the AudioFile frame count"""
return self.audioFile.numFrames();
def memberNotes(self, frame):
"""
Returns a list of no... | The function `memberFeatures` generates a NumPy array containing feature vectors from all member notes across frames. It first checks a cache (`memberCache`); if not empty, it returns the cached result. Otherwise, it iterates through each frame, extracts feature vectors for member notes using `feature(i,j)`, and concat... | def memberFeatures(self):
"""
Returns an array of all feature vectors which correspond to member notes.
"""
if not self.memberCache is None:
return self.memberCache;
members = np.empty([0,self.featureLen()]);
for i in range(self.getNumFrames()):
i... |
def featureLen(self):
"""Returns the length of feature vectors given by feature()"""
return 3;
def getNumFrames(self):
"""Convenience providing access to the AudioFile frame count"""
return self.audioFile.numFrames();
def nonMemberNotes(self, frame):
"""
Returns a list of... | This function retrieves and aggregates feature vectors from non-member notes across all frames into a single array, utilizing a cache to avoid redundant computation. It checks if cached results exist, otherwise iterates through each frame, collects features from non-member notes, and concatenates them into a NumPy arra... | def nonMemberFeatures(self):
"""
Returns an array of all feature vectors which do not correspond to
member notes.
"""
if not self.nonMemberCache is None:
return self.nonMemberCache;
nonmem = np.empty([0,self.featureLen()]);
for i in range(self.getNum... |
def get_tayangan_type(tayangan_id):
is_film = query("SELECT id_tayangan FROM FILM WHERE id_tayangan = %s", [str(tayangan_id)])
if is_film:
return 'film'
is_series = query("SELECT id_tayangan FROM SERIES WHERE id_tayangan = %s", [str(tayangan_id)])
if is_series:
return 'series'
re... | The main task of the code is to retrieve detailed information about a media item (film or series) based on its ID. It first determines the item's type using `get_tayangan_type`, then routes the request to either `detail_film` or `detail_series` functions. If the type is unrecognized, it returns a 404 error response ind... | def detail_tayangan(request, id):
id = str(id)
tayangan_type = get_tayangan_type(id)
if tayangan_type == 'film':
return detail_film(request, id)
elif tayangan_type == 'series':
return detail_series(request, id)
else:
return HttpResponse("Tayangan not found", status=404... |
def connect_PLC(self):
'''
Perform initial connection
'''
status_connected = False
try:
socket.inet_aton(self.plc_ip)
self.verify_configuration()
self.plc_client.connect(self.plc_ip, rack=0, slot=1, tcpport=102)
except RuntimeError:
... | The main task of the code is to continuously read PLC data from a specified memory area, process it into a structured dataframe by extracting values based on predefined data types, and periodically send the resulting dataframe to a shared queue. The loop handles connection errors by attempting reconnection, manages que... | def run(self):
'''
Read plc data until the connection is interrupted,
dataframe with values filled sent to queue is the result
'''
broker_condition_stop = not self.connect_PLC()
while not broker_condition_stop and not self.broker_stop_event.is_set():
... |
def xml_from_raw(raw_result: str) -> etree.Element:
"""Turn plain text content from HTTP request into XML tree."""
xml_data = bytes(raw_result, "utf-8")
try:
return etree.fromstring(xml_data)
except Exception as E:
logging.error(f"Error while parsing XML data:\n {E}")
return etre... | The function `parse_payload` converts raw XML data into InfluxDB time-series points by parsing the XML, grouping data by time intervals, and structuring it into payloads. It logs progress, processes the input into XML, extracts points, organizes them temporally, and generates a list of InfluxDB-compatible dictionaries ... | def parse_payload(raw_data: str) -> List[Dict[str, Any]]:
"""Take raw XML data and parse it into InfluxDB points."""
logging.debug("Building InfluxDB payload...")
raw_xml = xml_from_raw(raw_data)
points = points_from_xml(raw_xml)
groups = group_by_time(points)
return list(payload_from_group(t, g... |
def clean_class_member_key(key):
return key.replace(" ", "_")
def generate_rel_class_name(rel_type):
# Relationship type best practices are like FRIENDS_WITH
# We want to convert that to FriendsWithRel
return string.capwords(rel_type.replace("_", " ")).replace(" ", "") + "Rel"
def build_prop_string(uniq... | This function generates code definitions for relationship types in a graph database, constructing class members for relationships with their target labels, types, cardinality (if inferred), and associated property models. It handles constraints, indexes, and dynamically creates structured relationship classes for undef... | def build_rel_type_definition(
label, outgoing_relationships, defined_rel_types, infer_cardinality: bool = True
):
class_definition_append = ""
rel_type_definitions = ""
for rel in outgoing_relationships:
rel_type = rel[0]
rel_name = rel_type.lower()
target_label = rel[1]
... |
def get_node_labels():
query = "CALL db.labels()"
result, _ = db.cypher_query(query)
return [record[0] for record in result]
def clean_class_member_key(key):
return key.replace(" ", "_")
def build_prop_string(unique_properties, indexed_properties, prop, prop_type):
is_unique = prop in unique_propert... | This code generates Python class definitions modeling a Neo4j database schema, connecting via Bolt URL to inspect node labels, properties, constraints, and relationships. It creates StructuredNode classes with attributes and relationships, managing imports like StructuredNode/RelationshipTo, and outputs the complete co... | def inspect_database(
bolt_url,
get_relationship_properties: bool = True,
infer_relationship_cardinality: bool = True,
):
# Connect to the database
print(f"Connecting to {bolt_url}")
db.set_connection(bolt_url)
node_labels = get_node_labels()
defined_rel_types = []
class_definitions... |
def get_Nb(AES_type):
if AES_type == 128 or AES_type == 192 or AES_type == 256:
return 4
else:
return None
def get_Nr(AES_type):
if AES_type == 128:
return 10
elif AES_type == 192:
return 12
elif AES_type == 256:
return 14
else:
return None
def for... | This code implements an AES encryption algorithm by performing rounds of substitution, shifting, mixing columns, and adding round keys. It initializes the state matrix, expands the key, and iterates through specified rounds (Nr) based on the cipher type. Each round applies SubBytes, ShiftRows, MixColumns (except the fi... | def cipher(input, key, type):
Nb = get_Nb(type)
Nr = get_Nr(type)
print("round[ 0 ].input\t", format_input(input))
print("round[ 0 ].k_sch\t", format_input(key))
state = input.reshape(4, 4).T
# print("state:\n", state)
# print("key:\n", key)
w = key_expansion(key, type)
# print("w:\... |
def get_Nb(AES_type):
if AES_type == 128 or AES_type == 192 or AES_type == 256:
return 4
else:
return None
def get_Nr(AES_type):
if AES_type == 128:
return 10
elif AES_type == 192:
return 12
elif AES_type == 256:
return 14
else:
return None
def for... | This function decrypts data using the inverse AES algorithm. It applies inverse transformations (shift rows, substitution bytes, mix columns) in reverse order of encryption rounds, using key expansion and round keys. The process starts with reshaping input, expands the key, and iteratively applies inverse operations, e... | def inv_cipher(input, key, type):
Nb = get_Nb(type)
Nr = get_Nr(type)
print("round[ 0 ].iinput\t", format_input(input))
print("round[ 0 ].ik_sch\t", format_input(key))
# print("input:\n", input)
state = input.reshape(4, 4).T
# print("state:\n", state)
# print("key:\n", key)
w = key_... |
def parse_input_string(input_string):
return np.array([int(input_string[i:i + 2], base=16) for i in range(0, len(input_string), 2)])
def cipher(input, key, type):
Nb = get_Nb(type)
Nr = get_Nr(type)
print("round[ 0 ].input\t", format_input(input))
print("round[ 0 ].k_sch\t", format_input(key))
... | The code's main task is to encrypt a user-provided message using AES encryption. It prompts the user to select an AES key size (128, 192, or 256 bits), input a key, and enter the plaintext message. The inputs are parsed, encrypted via a cipher function, and the output is formatted for display. | def encrypt():
print("Let's do encryption:\n")
aes_type = None
while aes_type != 128 and aes_type != 192 and aes_type != 256:
aes_type = int(input("Input AES type (128, 192, or 256): "))
key_input = input("Input the key: ")
plain_text = input("Input the message: ")
parsed_plain_text =... |
def parse_input_string(input_string):
return np.array([int(input_string[i:i + 2], base=16) for i in range(0, len(input_string), 2)])
def inv_cipher(input, key, type):
Nb = get_Nb(type)
Nr = get_Nr(type)
print("round[ 0 ].iinput\t", format_input(input))
print("round[ 0 ].ik_sch\t", format_input(key)... | The code performs AES decryption by prompting the user for the AES key size (128/192/256), encryption key, and ciphertext. It parses inputs, applies the inverse AES cipher, and formats the decrypted output. | def decrypt():
print("Let's do decryption:\n")
aes_type = None
while aes_type != 128 and aes_type != 192 and aes_type != 256:
aes_type = int(input("Input AES type (128, 192, or 256): "))
key_input = input("Input the key: ")
encrypted_text = input("Input the message: ")
parsed_encrypte... |
def init(cds_address):
encrypted_shares_json = call_keyring(cds_address, "StartInit", 2)
encrypted_mk_shares = json.loads(encrypted_shares_json)
result = None
shares = {}
for encrypted_mk_share in encrypted_mk_shares:
shareholder_id = encrypted_mk_share['id']
encrypted_share = enc... | The code processes command-line arguments to determine an action (init, unlock, or state) for a cryptographic system, using an address from either an environment variable or a provided argument. It handles help requests, validates inputs, and delegates tasks to corresponding functions based on the specified action. | def main(argv):
address = os.environ["CDS"]
help_promt = "usage: keyring.py {init | unlock | state}" \
" [-h | --help | -a <woorl address>| --address <woorl address>]"
try:
opts, args = getopt.getopt(argv, "ha:", ["help", "address="])
except getopt.GetoptError:
six.prin... |
def vertMatch(self, piece):
twos, threes, fours = 0, 0, 0
for xCor in range(self.width): # for each column
yCor = 0
matches = 0
while yCor < self.height: # count contiguous matching pieces
if self.content[yCor][xCor] == piece:
matc... | The code checks if a player has won by verifying if there's at least one occurrence of four consecutive pieces in a row (vertically, horizontally, or diagonally). It aggregates counts from three directional checks and returns `True` if any four-in-a-row exists, otherwise `False` | def isWon(self, piece):
vMatchCount = self.vertMatch(piece)
hMatchCount = self.horiMatch(piece)
dMatchCount = self.diagMatch(piece)
fours = vMatchCount[2] + hMatchCount[2] + dMatchCount[2]
if fours > 0: # if there's at least 1 four in a row
return True
return... |
def vertMatch(self, piece):
twos, threes, fours = 0, 0, 0
for xCor in range(self.width): # for each column
yCor = 0
matches = 0
while yCor < self.height: # count contiguous matching pieces
if self.content[yCor][xCor] == piece:
matc... | The code calculates a heuristic score by aggregating counts of two and three consecutive matches in vertical, horizontal, and diagonal directions. It sums these counts and returns a weighted score: 3 points per two-match and 10 points per three-match, combining them to evaluate board states likely to lead to a win in g... | def heuristic(self):
vMatchCount = self.vertMatch(-1)
hMatchCount = self.horiMatch(-1)
dMatchCount = self.diagMatch(-1)
twos = vMatchCount[0] + hMatchCount[0] + dMatchCount[0]
threes = vMatchCount[1] + hMatchCount[1] + dMatchCount[1]
score = (twos*3) + (threes*10)
... |
def test(x, y): # ye square kocholo dor player, age mouse to oon click shod okeye
global Player1
if ((x <= (Player1.x + 50)) and (x >= (Player1.x - 50))) and ((y <= (Player1.y + 50)) and (y >= (Player1.y - 50))):
return True
return False
def speed_dots(x, y, px, py):
global Player1, Balls, mous... | The code handles mouse events to track position changes, manage click states, and calculate movement speed between two points. It captures initial and final mouse coordinates during a click-and-drag action, uses these to animate or compute velocity via `speed_dots()` and `speed()`, and resets states for subsequent inte... | def mouse(): # in ham braye mouse e
global Event, mouse_click, mouse_ready, xmouse1, ymouse1, xmouse2, ymouse2
try:
if Event.type == P.MOUSEBUTTONDOWN and mouse_click: # mouse_click ye sharte ke age test()=True dobare nmizare in shart ok she
xa, ya = P.mouse.get_pos()
if test(x... |
def get_information(character_name) -> None | tuple:
"""
Return information from the character's data file
:param character_name: name of character
:return: None if character doesn't exist | profession and social status if they do exist
"""
with open("Text Summaries/character_objects.json", "r")... | The function processes a query by searching a Pinecone index, generates a contextually appropriate response based on the receiver's social class/profession, manages conversation history, and optionally saves interactions. It returns the generated answer along with prompt and reply token counts, updating the index with ... | def run_query_and_generate_answer(
query: str,
receiver: str,
context: list[str],
index_name: str = "chatnpc-index",
save: bool = True,
) -> str | tuple[str, int, int]:
"""
Runs a query on a Pinecone index and generates an answer based on the response context.
:param query: The query to ... |
def create_spacial_affinity_kernel(spatial_sigma: float, size: int = 15):
kernel = np.zeros((size, size))
for i in range(size):
for j in range(size):
kernel[i, j] = np.exp(-0.5 * (distance.euclidean((i, j), (size // 2, size // 2)) ** 2) / (spatial_sigma ** 2))
return kernel
def correct_... | This function enhances image exposure by correcting underexposure using a spatial affinity kernel and gamma/lambda parameters. If 'dual' is True, it also corrects overexposure by inverting the image, then fuses under/over-corrected versions using blending coefficients. The result is clipped to 8-bit unsigned integers f... | def enhance_image_exposure(im: np.ndarray, gamma: float, lambda_: float, dual: bool = True, sigma: int = 3,
bc: float = 1, bs: float = 1, be: float = 1, eps: float = 1e-3):
# create spacial affinity kernel
kernel = create_spacial_affinity_kernel(sigma)
# correct underexposudness
... |
def Extract_Level_String(self, examples_codes,df):
for example_code in examples_codes:
Temporal = pd.DataFrame(columns=["Structures","token"] + ["{}".format(i) for i in range(13)])
with open(r"Super_Mario_Brothers_Maps/Processed/mario-{}.txt".format(example_code)) as infile:
... | The main task of the code is to generate feasible sequences (pre_Level) using a grammar-based model (G) by iterating through epochs and batches. It ensures sequences meet feasibility criteria (Jumping_Fiasible_Word) and processes them via the Quest method. The function validates sequences against knowledge constraints,... | def Generate_Mapping(self,example_code, Knowledge, df, Level_Len, module=None, batch_size=1, epochs=256, seed=None,Game_Mode = 0):
if not(module):
module = Level_Len
level_sec = self.Extract_Level_String([example_code[0]],df=df) #+" "+ Extract_Level_String([example_code[1]])
#Displa... |
def def_fields():
fields = {"metadata": {}, "game_data": {}}
return fields
def read_lines_from_zst_file(file):
print(os.path.exists(file))
print(os.path.getsize(file))
with (
zstd.open(file, mode="rb", dctx=DCTX) as zfh,
io.TextIOWrapper(zfh) as iofh,
):
for line in iofh:... | The function parses metadata and game data from a zst file line-by-line, extracting details like event, site, time control, ratings, and game results. It handles debug logging, identifies game types (bullet, rapid, classical), processes game outcomes, and yields structured data. Special cases include in-progress games ... | def parse_game_metadata(debug, debug_idx, fil):
fields = def_fields()
counter = 1
line_num = 0
print("before read from zst")
for line in read_lines_from_zst_file(file):
print(line)
line_num += 1
if debug and (counter == debug_idx):
print(
f"extra d... |
def set_tables():
meta_dict = {
"game_id": "bigint",
"rated": "boolean",
"bullet": "boolean",
"blitz": "boolean",
"rapid": "boolean",
"classical": "boolean",
"correspond": "boolean",
"event": "text",
"white_won": "boolean",
"draw": "boo... | The main task of the code is to process game metadata, insert it into a database, log progress every 500 entries, and time the operation. It initializes data structures, sets up logging, iterates through parsed game data, and terminates when reaching a specified game ID limit, while handling debug modes and database co... | def main():
print(
"""=================================================================
=================================================================
=================================================================
================================================================... |
def _get_genotype_data(self, chr, pos, ref, alt, data_type):
chr_var = chr if chr != 23 else 'X'
if data_type == 'imputed':
tabix_iter = self.tabix_files_imputed[threading.get_ident()][chr-1].fetch('chr'+str(chr_var), pos-1, pos)
samples = list(self.samples_imput['row_id'])
... | This function processes variant data by parsing input variants, applying filters, retrieving genotype and annotation information, and returning structured results including timing metrics and metadata. It converts filters to boolean values, fetches genotype data, handles chip data type specifics, counts genotypes, and ... | def get_variants(self, variants, filters, data_type):
start_time = timeit.default_timer()
filters = {k:(True if v=="true" else v) for k,v in filters.items()}
filters = {k:(False if v=="false" else v) for k,v in filters.items()}
if 'gpThres' in filters:
filters['gpThres'] = fl... |
def _get_genotype_data(self, chr, pos, ref, alt, data_type):
chr_var = chr if chr != 23 else 'X'
if data_type == 'imputed':
tabix_iter = self.tabix_files_imputed[threading.get_ident()][chr-1].fetch('chr'+str(chr_var), pos-1, pos)
samples = list(self.samples_imput['row_id'])
... | The code processes variant data by parsing input variants, retrieving genotype information, applying filters, and generating a TSV file. It constructs filenames based on data type and filters, transforms data (e.g., encoding sex, sorting), and returns the file as a downloadable attachment. Key steps include variant par... | def write_variants(self, variants, filters, data_type):
vars_data = []
for variant in variants.split(','):
chr, pos, ref, alt = utils.parse_variant(variant)
var_data = self._get_genotype_data(chr, pos, ref, alt, data_type)
if var_data is not None:
var... |
def _check_host(self, host: Player) -> bool:
return self.players_handler.get_player_data(host).rights == PlayerRights.host
def _round_timer(self) -> None:
async def update_state(round: int):
sleep(self.play_time)
if not (self.state == GameState.ingame and round == self.round):
... | This method initiates a new game round by validating the host, incrementing the round count, setting the game state to 'ingame', starting a timer, positioning players, calculating the round's end time, and returning a lobby update response. | def start(self, host: Player) -> Response | None:
if not self._check_host(host):
return
self.round += 1
self.state = GameState.ingame
self._round_timer()
self.set_starting_position()
self.rounds[-1].end_time = int(time.time()
... |
def crop_query(df, log_id=0, unpublish=False):
""" function reduces df to documentType = "article" and crops it at "id" """
if not unpublish:
return df.query('documentType == "article" & id > {0} & eventType != "unpublish"'.format(log_id))
else:
return df.query('documen... | The method identifies and removes articles marked as "unpublished" by checking their log entries. It retrieves document IDs from the log, locates corresponding files in a database, and deletes matching entries from CSV files. It skips articles with a final "publish" event, logs actions, and resolves a "republish" bug b... | def _remove_deleted(self):
"""method removes articles if an unpublished event exists in log"""
deleted_articles = sorted(set(self.crop_query(pd.read_csv(self.log_file), unpublish=True)["documentId"]))
logging.info("There are {0} unpublished articles".format(len(deleted_articles)))
d = ... |
def update_log_file(self, path=None):
""" log_file update by appending an existing csv log file from Livingdocs server.
--------
:param: path to log_file.
:returns: the last publication event documented at path. """
if not path:
path = self.log_file
loggin... | This method updates a server's database by synchronizing new and existing documents from log files. It processes documents after a specified event ID, appends new entries, revises outdated ones, handles connection errors, and removes unpublished content. The update ensures the database reflects the latest state by comp... | def update_server(self, update_eventid=None):
""" a method to update the server from a given event id."""
if update_eventid:
after = update_eventid
else:
after = self.update_log_file()
logging.info("updating database, starting at event id = {0}".format(after))... |
def none_perm_module_state(self, ssh_client: any, ssh_password: str) -> str:
""" Determines the module's NON PERMANENT state. """
command = f"sudo -S sysctl -n {self.params['attribute']}"
stdout, _ = execute_command(
self.logger, True, ssh_client, command, ssh_password)
retu... | This code checks if a system parameter on a remote host matches a desired value (temporary or permanent). If not, it attempts to apply the value via an executor. It logs discrepancies and returns status codes: "ok" if already correct, "changed" if updated, or "ko" if the update failed. | def process(self, ssh_client, ssh_password, ssh_host):
if not self.params['permanent']:
none_perm_value = self.none_perm_module_state(
ssh_client, ssh_password)
if self.params['value'] != none_perm_value:
self.logger.debug(
f"{self.para... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.