dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_show(url:str,overwrite=False,name=None):
"""
url: link to the show
overwrite: overwrite show file
name: if show is already downloaded, pass name to use local data only
Uses url to download data into a dict with name and int numered seasons with k-v:episode number-link.
Data is saved for ... | The function `download_season` downloads episodes of a specified season from a show, either by fetching show data from a URL or using a provided dictionary. It creates a directory for the show, uses a progress bar to track downloads, checks for existing episode files, and downloads missing episodes iteratively until co... | def download_season(url,nr,show=None):
"""
Either gets show's data from url or show dict.
url: show's url
nr: number of the season
show: show's dict (optional)
"""
if show==None: show = get_show(url)
try:
os.mkdir(show['name'])
except:
pass
with tqdm.tqdm(
... |
def get_rays_for_spin_mass(spin, mass, count):
rcam = 1.e8
thetacam = 90.
geot = geotrace.geotrace(bhspin=spin, mbh_msun=6.2e9, rmax_geo=100./mass)
geot.set_camera_location(tcam=0., rcam=rcam, thetacam=thetacam)
geot.set_camera_properties(DX=80./mass, Dsource_cm=16.9e6*3.085678e18)
xs = []
... | This function generates and caches visualizations of ray data for black hole simulations. It loads or computes ray trajectories based on spin, mass fraction, and count parameters, then plots them with styled backgrounds, a black hole representation, and dynamic labels. If enabled, it saves the plot as a PNG, reusing ca... | def plot_frame(index, spin, massfrac, count, doplot=True):
cachename = "cache/frame_{0:05d}.h5".format(index)
loaded = False
try:
if os.path.exists(cachename):
hfp = h5py.File(cachename, 'r')
if hfp['spin'][()] == spin and hfp['massfrac'][()] == massfrac and hfp['count'][()... |
def load_gcov(fname):
metric_type = get_metric_name(fname)
if metric_type in ["mmks", "fmks"]:
return gcov_fmks(fname)
elif metric_type == "eks":
return gcov_eks(fname)
raise NotImplementedError
return None
def gcov2gcon(gcov, is2d=None):
""" convert gcov to gcon. makes some assumptions about gco... | The function `load_iharm_all` loads data from a specified dump file by first retrieving `gcov` using `load_gcov`, converting it to `gcon` via `gcov2gcon`, and then passing these along with the original `harm_dump_name` to `load_iharm`. It returns the result of `load_iharm`, alongside the raw `gcov` and derived `gcon` d... | def load_iharm_all(harm_dump_name):
""" Loads gcov, gcon for you. """
gcov = load_gcov(harm_dump_name)
gcon = gcov2gcon(gcov)
return load_iharm(harm_dump_name, gcov, gcon), gcov, gcon |
def r8vec_sftf_test ( ):
#*****************************************************************************80
#
## r8vec_sftf_test() tests r8vec_sftf().
#
# Licensing:
#
# This code is distributed under the MIT license.
#
# Modified:
#
# 03 September 2021
#
# Author:
#
# John Burkardt
#
import numpy as np
... | The `colored_noise_test()` function tests the `colored_noise()` function by generating and analyzing colored noise with varying parameters. It runs multiple test cases, adjusting the `alpha` parameter (0.0 to 2.0 in 0.25 increments) to simulate different noise spectra. The tests include generating noise paths for speci... | def colored_noise_test ( ):
#*****************************************************************************80
#
## colored_noise_test() tests colored_noise().
#
# Licensing:
#
# This code is distributed under the MIT license.
#
# Modified:
#
# 03 September 2021
#
# Author:
#
# John Burkardt
#
import plat... |
def cdelay2_test ( ):
#*****************************************************************************80
#
## cdelay2_test() tests cdelay2().
#
# Licensing:
#
# This code is distributed under the MIT license.
#
# Modified:
#
# 19 August 2017
#
# Author:
#
# John Burkardt
#
print ( '' )
print ( 'cdelay2_t... | The `pink_noise_test()` function is a test suite designed to validate the `pink_noise()` function and related utilities. It prints the Python version, executes multiple sub-tests (e.g., `cdelay2_test`, `corr_test`, `cross_corr_test`), and confirms normal execution. The purpose is to ensure correct functionality of nois... | def pink_noise_test ( ):
#*****************************************************************************80
#
## pink_noise_test() tests pink_noise().
#
# Licensing:
#
# This code is distributed under the MIT license.
#
# Modified:
#
# 19 August 2017
#
# Author:
#
# John Burkardt
#
import platform
print... |
def calculate_edit_distance(labels, predicted):
index = random.randrange(labels.size(dim=0))
return textdistance.levenshtein.distance(labels[index, :].tolist(), predicted[index, :].tolist()) * labels.size(
dim=0) / labels.size(dim=1)
def split_and_prepare(tokenizer, dataset):
# Sort by sequence leng... | The code trains a BART model for tree bracketing using a custom tokenizer, loads and splits training data, initializes optimizer and loss function, trains the model, evaluates on test data, and saves the model. It also uses Weights & Biases for tracking and calculates edit distance during testing. | def main():
# Testing
l = torch.tensor([[3, 2, 3], [1, 2, 3]])
i = torch.tensor([[1, 3, 3], [1, 2, 3]])
print(calculate_edit_distance(l, i))
# Load Training Data and Tokenizer
training_set_name = "Grammar1_7143222753796263824.json" if not args.set_name else args.set_name
tokenizer = Bracket... |
def search_NN(sentences,length_thre=2):
all = []
for sent in nltk.sent_tokenize(sentences):
pos = nltk.pos_tag(nltk.word_tokenize(sent))
prev = -2
phrase = ""
for element in range(len(pos)):
if "NN" in pos[element][1]:
#print(pos[element],element,prev)
#print(phrase)
if... | The main task of the code is to process a document by extracting and normalizing phrases, performing Google searches for each unique phrase, and collecting relevance scores and content from search results to create a vectorized representation of the document's semantic relationships with external information. | def doc_to_vec(doc):
result = {}
s = set()
for phrase in search_NN(doc):
if phrase not in s:
phrase = " ".join([i for i in [''.join(filter(check_char , word)) for word in phrase.split(" ")] if i!=" " and i!=""])
if len(phrase.split())<2:
continue
phrase = [lemmatizer.lemmatize(i,j[0]... |
def duplicate(self):
return self.dupe in ("CN", "CN-UVFA", "CN-ACTIVE")
def get_training_data(self, batch):
"""Given a batch of transitions, this method reconstructs the states,
generates a batch of weights and computes the model and target predictions for both each s_i and s_{i+1}
Argu... | The main task of the code is to update the policy's Q-values using sampled experiences from a buffer, incorporating rewards, discount factors, and next-state Q-values. It processes batches, masks irrelevant actions, and trains a model to minimize the loss between predicted and target Q-values, while updating experience... | def policy_update(self):
"""Update the policy (Q-values)
Returns:
float -- The update's loss
"""
np.random.seed(self.steps)
ids, batch, _ = self.buffer.sample(self.sample_size)
if self.direct_update:
# Add recent experiences to the priority upda... |
def update_all_priorities(self):
"""Updates all priorities of the replay buffer
"""
data = self.buffer.get_data(True)
chunk_size = 100
for i in range(0, len(data[0]), chunk_size):
chunk_data = np.array(data[1][i:i + chunk_size])
chunk_ids = data[0][i:i + ... | The function performs policy and target network updates based on step thresholds. It checks if steps exceed a buffer size threshold, then triggers policy updates at intervals and target updates at separate intervals. On the first update, it computes priorities for all experiences. Returns the policy update loss. | def perform_updates(self, steps):
"""Perform the necessary updates for the current number of steps,
The policy and the feature extraction (either implicitly or
explicitly depending on the architecture) are updated
Arguments:
steps {int} -- Number of steps
R... |
def set_weights(self, weights):
"""Set current weight vector
Arguments:
weights {np.array} -- Weight vector of size N
"""
self.weights = np.array(weights)
self.weight_history.append(self.weights)
def pick_action(self, state, weights=None):
"""Given a state a... | The code trains a reinforcement learning agent in a given environment using multiple weight vectors. It employs epsilon-greedy exploration, updates neural networks via experience replay, and dynamically switches between weight configurations at specified intervals. The agent logs training progress, adjusts exploration ... | def train(self, environment, log_file, learning_steps, weights,
per_weight_steps, total_steps):
"""Train agent on a series of weights for the given environment
Arguments:
environment {Object} -- Environment, should have reset() and step(action, frame_skip) functions
... |
def set_weights(self, weights):
"""Set current weight vector
Arguments:
weights {np.array} -- Weight vector of size N
"""
self.weights = np.array(weights)
self.weight_history.append(self.weights)
def build_models(self):
"""Builds the networks then synchroniz... | This code initializes a reinforcement learning agent with configurable parameters for multi-network, multi-head, or single-head algorithms. It sets up exploration rates, discount factors, memory buffers, neural network architectures, and training hyperparameters like learning rate and update intervals. The agent suppor... | def __init__(self,
actions,
objective_cnt,
memory_size=100000,
sample_size=64,
weights=None,
start_discount=0.98,
discount=0.98,
end_discount=0.98,
start_e=1.,
... |
def _plot_sequence(paths, name, sequence_file, **kwargs):
print('------------- plotting sequence data ------------')
seq_data = extract_sequence_data(paths, sequence_file=sequence_file, **kwargs)
if not seq_data:
rprint('No sequence data found', file=sys.stderr)
else:
plot_sequence(seq_d... | This function generates plots for given data paths, handling sequence, histogram, progression, and loop plots based on provided parameters. It checks for required parameter pairs, extracts histogram data, and triggers sub-functions to create default histograms, progression plots, or loop visualizations, ensuring valid ... | def plot(paths, name=None, default_plots=True, percentiles=None,
histogram_file=None, round_ms_digits=3, historgram_bar_width=0.005,
sequence_file=None,
progression_mapping_function=None, progression_x_label=None,
loop_file=None, loop_order=None,
**kwargs):
if seque... |
def Explosion(self, x, y) -> None:
"""
function that clear the current tile and add 1 pawn to the neighbours (explode)
"""
neigbours = self.GetNeighbours(x,y) # get the neighbours of the tile
for tile in neigbours: # for every neighbour
try: # try to add a pawn
... | The main task of the code is for the computer player to select a random playable tile, attempt to place a pawn, trigger an explosion if the tile is full, update game state, switch players, and save progress. It identifies playable tiles owned by the current player or unowned, randomly chooses one, adds pawns, handles o... | def ComputerPlay(self) -> None:
"""
get every move possible in a list and then take a random one
"""
playable_tiles = [] # list of playable tiles
for i in self.tiles:
for tile in i:
if tile.owner == self.COLORS[self.player] or tile.owner == None:
... |
def Explosion(self, x, y) -> None:
"""
function that clear the current tile and add 1 pawn to the neighbours (explode)
"""
neigbours = self.GetNeighbours(x,y) # get the neighbours of the tile
for tile in neigbours: # for every neighbour
try: # try to add a pawn
... | The ClickListener function handles tile clicks by triggering explosions if a tile is full, updating game state, changing players, saving progress, and initiating computer moves when enabled. | def ClickListener(self, x,y) -> None:
"""
Function called when a tile is clicked
manage the calls to the following functions :
- the explosion
- the change of player
- the saving of the game state
- the computer play
"""
tile = self... |
def sendSingleGcmMessage(self, message, token):
gcm_reg_ids=[token]
sendMulticastGcmMessage(self, gcm_reg_ids, message)
def convertToGcmMessage(self, message):
gcmmessage = {}
gcmmessage["data"] = {}
if 'android_collapse_key' in message["request"]:
gcmmessage["collapse_key"] = message["... | The code handles push notifications by sending messages to devices registered under specific tags via GCM (Android) or APNS (iOS) based on the platform specified in the request. It retrieves tokens from the database, sends the message using platform-specific methods, and returns "OK" upon completion. | def post(self):
msg = json.loads(self.request.get("message"))
if 1 in msg["request"]["platforms"]:
tagid = self.request.get("tagid")
q = GcmTag.query(GcmTag.tag == tagid)
for tag in q.iter():
sendSingleGcmMessage(self, convertToGcmMessage(... |
def convertToGcmMessage(self, message):
gcmmessage = {}
gcmmessage["data"] = {}
if 'android_collapse_key' in message["request"]:
gcmmessage["collapse_key"] = message["request"]["android_collapse_key"]
if 'data' in message["request"]:
gcmmessage["data"] = message["request"]["dat... | This code sends push notifications via GCM (Android) and APNS (iOS) based on platform identifiers in the request. It batches GCM tokens by country, splits them into chunks for task queue processing, and sends APNS messages individually using tag-based queries. It returns "OK" upon completion. | def post(self):
msg = json.loads(self.request.get("message"))
country = self.request.get("country")
if 1 in msg["request"]["platforms"]:
appconfig = AppConfig.get_or_insert("config")
gcmmessage = convertToGcmMessage(self,msg)
gcm_reg_ids = []
... |
def sendSingleGcmMessage(self, message, token):
gcm_reg_ids=[token]
sendMulticastGcmMessage(self, gcm_reg_ids, message)
def convertToGcmMessage(self, message):
gcmmessage = {}
gcmmessage["data"] = {}
if 'android_collapse_key' in message["request"]:
gcmmessage["collapse_key"] = message["... | This code handles a POST request to send a message to a specific device token. It retrieves platform, message, and token from the request, then sends the message via GCM (Android) or APNS (iOS) based on the platform value. The message is converted using platform-specific functions before delivery. The response is "OK" ... | def post(self):
platform = self.request.get("platform")
message = self.request.get("message")
token = self.request.get("token")
#Send a single message to a device token
if platform == "1": #Android
sendSingleGcmMessage(self,convertToGcmMessage(self,json.loads... |
def get_labelset(kwarg_question):
output_label_user = CustomUser.objects.get(username="admin")
queryset = QuestionLabel.objects.filter(questionId=kwarg_question)
diff_query = queryset.filter(labelName='Difficulty')
type_query = queryset.filter(labelName='Question Type')
precent_query = queryset.filt... | The main task of the code is to find and return the three most similar questions to a given question. It calculates similarity by comparing labels and topics of the base question with others, computes distances, sorts results by proximity, and filters the top 3 matches using their slugs. | def get_queryset(self):
kwarg_question = self.kwargs.get("question")
base_labels = get_labelset(kwarg_question)
base_topics = get_topicset(kwarg_question)
questions = Question.objects.exclude(questionId=kwarg_question)\
.only("questionId", "slug")
distan... |
def MyfileEncryptMAC(filepath):
HMACkey = genRandom(ENC_key_bytes)
ENCkey = genRandom(HMAC_key_bytes)
f = open(filepath,"rb")
message = f.read()
message = b64encode(message)
f.close()
#encrypting the message using the encryption method Myencypt and the generated key
cText, iv, tag = MyencyptMAC(message,EN... | The main task of the code is to encrypt a file using AES-GCM, decrypt the encrypted data, and verify its integrity via HMAC. It processes a JPEG file, generating ciphertext, IV, and authentication tags, then reconstructs the file at a specified path while validating cryptographic integrity through HMAC verification. | def main():
#Testing :
cText,iv,tag, ENCkey,HMACkey,ext = MyfileEncryptMAC("C:\\Reports\\ToEncrypt\\encrypt031719.jpg")
filePath = MyfileDecrypt(cText,iv,ENCkey,ext)
jasonFileHMAC(cText,iv,tag, ENCkey,HMACkey,ext)
print(filePath) |
def get_all_lists(self, replyk):
sp = self.get_list(replyk[0])
cp = self.get_list(replyk[1])
pp = self.get_list(replyk[2])
ds = self.get_list(replyk[3])
return sp, cp, pp, ds
def count_unique(self, replyk):
sp, cp, pp, ds = self.get_all_lists(replyk)
self.check_ne... | This code validates a domino game state by checking if all 14 unique pieces are correctly distributed among stock, computer, player, and domino snake. It verifies counts (stock=14, total=28), proper domino snake continuity, and status accuracy. If any condition fails, it returns an error; otherwise, confirms correctnes... | def check(self, reply: list, attach: Any) -> CheckResult:
replyk = reply.strip().split('\n')
if len(replyk) != 5:
return CheckResult.wrong("Something's wrong")
stock_pieces, computer_pieces, player_pieces, domino_snake = self.get_all_lists(replyk)
if not self.count_unique(rep... |
def remove_dups(d):
new_d = []
for x in d:
if x not in new_d:
new_d.append(x)
return new_d
def update_list_of_dicts(list_data, name, hits, opps):
found = False
# update the dictionary if it already exists
if len(list_data) > 0:
for d in list_data:
if d['na... | The code processes hit data by filtering and deduplicating records related to 'juliet' and 'FALSE' entries, aggregates hits and opportunities into groups, and writes formatted analytics to an Excel sheet. It calculates metrics like hit percentages, organizes data by function names, applies conditional formatting, merge... | def group_hit_data(suite_dat, hit_data):
list_of_dicts = []
suite_data.suite_hit_data_complete = hit_data
good_data = []
# dedupe data
for hit_dat in suite_data.suite_hit_data_complete:
# only juliet/false have 'good...' opportunities
if hit_dat[1] == 'juliet' and hit_dat[2] == 'FA... |
def calculate_test_case_score(test_case_obj):
valid_hits = []
for valid_hit_data in test_case_obj.hit_data:
valid_hits.append(valid_hit_data[2])
score = len(set(valid_hits))
test_case_obj.score = score
if test_case_obj.tc_type == 'juliet' and test_case_obj.true_false == 'FALSE':
se... | The function `collect_hit_data` processes test case data from XML projects to compile structured hit statistics. It calculates scores, percent hits, and constructs formatted data rows with metadata (CWE ID, test type, etc.) for output. It specifically aggregates results for "juliet" false cases, computes project-level ... | def collect_hit_data(suite_dat):
# file name, line number, and enclosing function
hit_data = []
# collect all valid hit data to be displayed
for xml_project in suite_dat.xml_projects:
test_case_objects = xml_project.test_cases
print('collecting hit data for project-----', xml_project.ne... |
def resetStore():
global tilesStore
tilesStore={}
global coordsCnt
coordsCnt=0
def processFile(filename,addDebugInfo):
print("processFile "+filename)
f = h5py.File(filename)
#dumpAll("", f,3306)
#return
#list(f.keys())
#['METADATA', 'ancillary_data', 'ds_geosegments', '... | The code processes HDF5 files (granules) by managing a database (storePath) of already processed files. It checks if files exist, skips processed ones unless forced, processes new files, updates the database with metadata, and logs processing details (e.g., records, tiles) to a text file. The main task is to handle, tr... | def main(storePath,options,granules):
addDebugInfo="d" in options
force="f" in options
srcs={}
# open or create src.txt (the list of already processed h5 files)
if (not os.path.exists(storePath)):
print("new tiles db will be created: "+storePath)
os.mkdir(storePath)
open(storePath+"/sr... |
def image_plotter():
row, col = 4, 4
noise = npy.random.normal(0, 1, (row * col, latent_dims))
generated_image = gen_net.predict(noise)
generated_image = 0.5 * generated_image + 0.5
fig, axs = plt.subplots(row, col)
count = 0
for i in range(row):
for j in range(col):
axs... | This function trains a Generative Adversarial Network (GAN) by alternating between training the discriminator on real and fake data, and the generator via the GAN model. It iterates over epochs, processes data in batches, evaluates models periodically, and generates visualizations of synthetic images produced by the ge... | def training(gen_net, dis_net, GAN, dataset, latent_dims, num_epochs=200, num_batch=128):
batch_per_epoch = int(dataset.shape[0] / num_batch)
min_batch = int(num_batch / 2)
display_interval = 20
for epoch in range(num_epochs):
if epoch % display_interval == 0:
image_plotter()
... |
def fill_density(volume: ti.types.ndarray()):
res = volume.shape[0]
for i, j, k in density:
density[i, j, k] = volume[i, res - j - 1, k]
def create_target_images():
for view in range(n_views):
ray_march(target_images, math.pi / n_views * view - math.pi / 2.0,
view)
... | The main task of the code is to perform 3D volume rendering using ray marching and optimize the rendering result through gradient descent iterations. It downloads a 3D model, loads it into a volume grid, generates target images, and iteratively refines the rendering by computing loss, applying gradients, and saving out... | def main():
parser = argparse.ArgumentParser()
parser.add_argument('--iters', type=int, default=100)
options = parser.parse_args()
if not os.path.exists('bunny_128.bin'):
url = 'https://github.com/yuanming-hu/taichi_assets/releases/download/llvm8/bunny_128.bin'
print(':: Downloading {}'... |
def init(target_img: ti.types.ndarray()):
for i, j in ti.ndrange(n_grid, n_grid):
target[i, j] = target_img[i, j]
smoke[0, i, j] = (i // 16 + j // 16) % 2
def forward(output=None):
for t in range(1, steps):
advect(v, v_updated, -1, t)
compute_div(t)
for k in range(num_it... | This code optimizes a velocity field to generate an image matching a target image via gradient descent. It uses Taichi's automatic differentiation to iteratively adjust the velocity field, computes forward passes, visualizes intermediate results, and applies gradients to minimize the loss between generated and target i... | def main():
parser = argparse.ArgumentParser()
parser.add_argument('--iters', type=int, default=240)
options = parser.parse_args()
target_img = cv2.resize(cv2.imread('taichi.png'),
(n_grid, n_grid))[:, :, 0] / 255.0
init(target_img)
for opt in range(options.iters):
... |
def initialize():
for i in range(n_grid):
for j in range(n_grid):
p[0, i, j] = initial[i, j]
def fdtd(t: ti.i32):
for i in range(n_grid): # Parallelized over GPU threads
for j in range(n_grid):
laplacian_p = laplacian(t - 2, i, j)
laplacian_q = laplacian(t - ... | The code performs a finite-difference time-domain (FD-TD) simulation, visualizing results in real-time via OpenCV. It generates frames at intervals, displaying and optionally saving them as PNGs to a specified output directory. The simulation runs for `steps * steps_mul` iterations, with `steps_mul` adjusting based on ... | def forward(output=None):
steps_mul = 1
interval = vis_interval
if output:
os.makedirs(output, exist_ok=True)
steps_mul = 2
interval = output_vis_interval
initialize()
for t in range(2, steps * steps_mul):
fdtd(t)
if (t + 1) % interval == 0:
img = ... |
def initialize():
for i, j in initial:
p[0, i, j] = initial[i, j]
def fdtd(t: ti.i32):
for i, j in height_gradient:
laplacian_p = laplacian(t - 2, i, j)
laplacian_q = laplacian(t - 1, i, j)
p[t, i,
j] = 2 * p[t - 1, i,
j] + (c * c * dt * dt + c * al... | The main task of the code is to simulate a physical process (via `fdtd`) over multiple time steps, compute refractive effects, and render/visualize results. It saves high-resolution images of the simulation output at specified intervals to a directory if provided, while also displaying them in real-time. The function h... | def forward(output=None):
interval = vis_interval
if output:
os.makedirs(output, exist_ok=True)
interval = output_vis_interval
initialize()
for t in range(2, steps):
fdtd(t)
if (t + 1) % interval == 0 and output is not None:
compute_height_gradient(t)
... |
def allocate_fields():
ti.root.dense(ti.i, max_steps).dense(ti.jk, n_grid).place(p)
ti.root.dense(ti.i, max_steps).dense(ti.jk, n_grid).place(p.grad)
ti.root.dense(ti.ij, n_grid).place(target)
ti.root.dense(ti.ij, n_grid).place(target.grad)
ti.root.dense(ti.ij, n_grid).place(initial)
ti.root.den... | This code performs iterative optimization to generate an image matching a target by adjusting parameters through gradient descent. It initializes a target image, sets up fields, and runs a loop for a specified number of iterations. In each iteration, it computes the loss using a forward pass, applies gradients to minim... | def main():
parser = argparse.ArgumentParser()
parser.add_argument('--iters', type=int, default=200)
options = parser.parse_args()
# initialization
target_img = cv2.imread('taichi.png')[:, :, 0] / 255.0
target_img -= target_img.mean()
target_img = cv2.resize(target_img, (n_grid, n_grid))
... |
def create_exception_col(r_df, copy_r_df):
specific_values = ["unknown", "ongoing", "Ongoing", "Unknown", "UNK", "Detection of IgA antibody to Early Ag", "Detection of IgA antibody to Early Ag and Capsid Ag", "Detection of IgA antibody to Capsid Ag"]
index = []
value = []
column = []
for i in list... | The code processes CSV files by adding unique IDs, handling exceptions, splitting records, combining data, removing unnecessary entries, formatting dates, converting values, and saving cleaned data as new CSVs. | def run_task(files):
for csv in files:
# read csv
r_df = pd.read_csv(csv)
copy_r_df = r_df.copy()
# create unique ID for each row
r_df.insert(2, 'row_num', np.arange(len(r_df)), True)
# Problem 6: Create exception column for specific values
r_df = create_e... |
def augmentHK(image,k):
w1 = image.reshape(image.shape[0], image.shape[1])
# k = random.randrange(1, 7)
global w2
if k == 1:
w2 = iaa.Sometimes(1, iaa.Affine(
scale={"x": (0.8, 1.2), "y": (0.8, 1.2)},
translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)},
rotate=(-180, 1... | The main task of the code is to train a neural network model using a combination of classification and survival analysis loss functions on image data. It loads and preprocesses training/validation datasets, applies data augmentation, constructs a TensorFlow graph with placeholders and a custom model, optimizes the mode... | def train(self):
n_epochs = 20000
checkpointdir = self.param['model_save_path']
####################################################################################
if not os.path.exists(checkpointdir):
checkpoints_dir = checkpointdir
os.makedirs(checkpoints_dir)
... |
def hosts_from_cidrs_ips(scope):
hosts = []
for cidr in scope.get('cidr', []):
hosts.extend( [ {'host':str(ip), 'scope': scope['name']} for ip in ipaddress.IPv4Network(cidr)] )
#ips
hosts.extend( [ {'host':ip, 'scope': scope['name']} for ip in scope.get('ips', []) ] )
return hosts
def ... | This code performs subdomain reconnaissance and domain analysis by collecting existing subdomains, filtering them against defined scopes, and conducting active/passive scans on new/modified domains. It processes recon results, filters anomalies, checks DNS records, updates domain scopes, and triggers workflows for port... | def main():
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt='%Y-%m-%d %H:%M',
handlers=[
logging.StreamHandler(),
logging.FileHandler(glob.tmp_dir + '/subs.log', 'w')
]
)
old_scopes_subs = uni... |
def subdomain_isgood(d:str, parent:str):
plen = len(parent) + 1
if not d.endswith('.' + parent) and d != parent:
return False
if len(d) - plen > config['domain_filter']['max_len']:
return False
if len(d[:-plen].split('.')) > config['domain_filter']['max_sub']:
return False
re... | The main task of the code is to generate and validate new subdomains using a wordlist, determine their parent domains, and return a list of dictionaries containing each subdomain's host and its identified parent domain. It filters existing subdomains, creates randomized new subdomains, checks their validity, and maps e... | def domain_purespray(domains, old_subs, alts_max, wordlist, timeout=120) -> List[Dict]:
"""
spray puredns check of random subs an set scope to them,
return list of Dict {'host', 'parent_host','scope'??}
"""
chsubs = list()
for d in domains:
domain_subs = list(filter(lambda x: subdomain_... |
def next_plat(self):
y = self.char.y
self.distanceplatform = 0
for platform in self.platforms:
if (y > platform.rect.y) and (self.collision == True):
self.aux_x = platform.rect.x
self.aux_y = platform.rect.y
self.distanceplatform = self... | The main task of the code is to process a single game step in a platformer environment, handling user input, updating character movement based on the given action, calculating rewards for successful platform transitions or errors, checking game-over conditions, and returning the reward, game status, and score. It simul... | def play_step(self,action,games):
self.next_plat()
self.frame_iteration += 1
game_over = False
x = self.char.x
y = self.char.y
#1collect user input
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
... |
def Read_ADC(Ch):
ADC_Value = ADC.ADS1263_GetAll()
try:
control = ADC_Value[1]
except:
print('Error with reading ADC. The program will be terminated')
GPIO_OFF()
write_pot(0x00)
OpAmp_ES('OFF')
exit()
Voltage = 0.0
try:
if(ADC_Value[Ch]>>31 ==... | The function HV_up adjusts the potentiometer value (i) based on the capacitor's high voltage (HV_actual) and a threshold condition. If HV_actual ≤ 4.0 V and i ≤ 0x101, it increments i, sets the potentiometer, waits for capacitor charging (tau), and reads updated values. It returns the final potentiometer value (NS_stop... | def HV_up(Previous_NS, tau):
hex_Previous_NS = int(hex(Previous_NS), 16)
i = hex_Previous_NS
HV_actual = Read_ADC(7) # actual HV across the capacitor
if i <= 0x101 and HV_actual <= 4.0:
i = i + 0x01
write_pot(i)
OpAmp = Read_ADC(8) * 6.0 # output of Op Amp (Vcc = 15 V)
... |
def write_pot(input):
msb = input >> 8
lsb = input & 0xFF
spi.xfer([msb, lsb])
def Read_ADC(Ch):
ADC_Value = ADC.ADS1263_GetAll()
try:
control = ADC_Value[1]
except:
print('Error with reading ADC. The program will be terminated')
GPIO_OFF()
write_pot(0x00)
... | This function adjusts a potentiometer based on the input Previous_NS, measures operational amplifier output and high-voltage (HV) levels using ADC readings, waits for capacitor discharge, and returns the adjusted potentiometer value, OpAmp voltage, and actual HV output. It also prints these values for monitoring. | def HV_down(Previous_NS, tau):
hex_Previous_NS = int(hex(Previous_NS), 16)
i = hex_Previous_NS
if 0x00 < i:
i = i - 0x01
write_pot(i)
OpAmp = Read_ADC(8) * 6.0
time.sleep(tau) # waiting for the capacitor discharge
HV_actual = Read_ADC(7)
else:
OpAmp... |
def txt_to_csv(filename_in, filename_out):
"""
Formats .txt file of DDG Data to .csv file.
Parameters:
filename_in (type: string): filename of txt file with DDG data (must
end in .txt).
filename_out (type: string): filename of the new csv file (must end in
.csv).
... | This code provides a menu-driven tool for processing and visualizing ddg (Delta Delta G) data. It allows users to convert .txt files to .csv, plot ddg data, plot average ddg values, compare two ddg samples, or generate significant figures files. Each choice triggers specific functions for data conversion, analysis, and... | def main():
choice = int(input('what do you want to do?\n0) close\n1) convert .txt of ddg data to .csv\n2) plot ddg data from .csv\n3) plot average ddg data from .csv\n4) plot difference between 2 ddg samples with same residues and mutations\n5) create file with significant figures for each residue\nChoose by input... |
def resample(d):
d_resample = d.resample(str(Sample_rate)+'T').mean()
return d_resample
def get_historical_weather_api(data):
first_day_minus_one_str = (data.index[0] - timedelta(days = 1)).strftime("%Y-%m-%d")
# need to add one day, overlapping have to be cut off later => useless because data is not ... | The main task of the code is to generate a feature-rich dataset by computing statistical features (averages, rolling means), time-related attributes, and merging with weather data. It also handles data resampling, gap checking, and incorporates irrigation-related metrics to enhance the input data for analysis or modeli... | def create_features(data):
# Create average cols
data['grouped_soil'] = data[DeviceAndSensorIdsMoisture].mean(axis=1)
data['grouped_soil_temp'] = data[DeviceAndSensorIdsTemp].mean(axis=1)
# Create rolling mean: introduces NaN again -> later just cut off
data['rolling_mean_grouped_soil'] = data[... |
def get_timezone(latitude_str, longitude_str):
# Convert to floats
latitude = float(latitude_str)
longitude = float(longitude_str)
geolocator = Nominatim(user_agent="timezone_finder")
location = geolocator.reverse((latitude, longitude), language="en")
# Extract timezone using timezonefinde... | The main task of the code is to preprocess sensor data by loading it from a CSV or API, aligning timestamps to the user's timezone, merging multiple sensors' data into a unified DataFrame, filling gaps, generating features, and converting data types for analysis or modeling. | def prepare_data():
global Timezone
# Load data from local wazigate api -> each sensor individually
data_moisture = []
data_temp = []
# start date is in UTC, but user expects it in his timezone
start_date = Current_config['Start_date']
lat = Current_config["Gps_info"]["lattitude"]
long... |
def raw_size(self, width, height):
header_size = 2 * 16 # height and width as 16 bit values
pixels_size = 3 * 8 * width * height # 3 channels, 8 bits per channel
return (header_size + pixels_size) / 8
def count_symbols(self, image):
pixels = image.getdata()
values = chain.from_... | This code compresses an image using a custom encoding method. It reads the input image, calculates its raw size, builds a symbol frequency tree, generates Huffman codes, encodes the image data with these codes, and writes the compressed output to a file. The process includes writing headers, the tree structure, and enc... | def compress_image(self, in_file_name, out_file_name):
print('Compressing "%s" => "%s"' % (in_file_name, out_file_name))
image = Image.open(in_file_name)
size_raw = self.raw_size(image.height, image.width)
print('RAW image size: %d bytes' % size_raw)
counts = self.count_symbols... |
def decode_header(self):
height = BitUtils.from_binary_list(self.bit_stream.read_bits(16))
width = BitUtils.from_binary_list(self.bit_stream.read_bits(16))
return height, width
def decode_tree(self):
flag = self.bit_stream.read_bits(1)[0]
if flag == 1: # Leaf, read and return sy... | The code decompresses an image from the input file into the output file by reading a bit stream, decoding the image header to obtain dimensions, reconstructing the encoding tree, and then decoding pixel data using the tree. The decompressed image is saved to the specified output file. | def decompress_image(self, in_file_name, out_file_name):
print('Decompressing "%s" => "%s"' % (in_file_name, out_file_name))
self.bit_stream = InBitStream(in_file_name)
height, width = self.decode_header()
self.bit_stream.flush() # make sure the next chunk is byte-aligned
trim... |
def scan_network():
local_ip = get_local_ip()
network_range = (local_ip[:10 - len(local_ip)]) + "1/24"
gateway_ip = (local_ip[:10 - len(local_ip)]) + "1"
request = scapy.ARP()
request.pdst = network_range
broadcast = scapy.Ether()
broadcast.dst = 'ff:ff:ff:ff:ff:ff'
request_broadcast =... | The code defines a menu-driven tool named "FloodLAN" for scanning local network devices and performing DoS attacks. It clears the terminal, displays a stylized banner, and presents options to scan devices, launch attacks (after scanning), view help, or exit. The tool checks if a network scan has been completed before a... | def main():
os.system("clear")
custom_fig = Figlet(font='big')
banner = custom_fig.renderText('FloodLAN')
print("\033[1;33m{}\033[0m".format(banner))
print("\033[1;31mFloodLAN - Local Area Network Scanner & DoS Tool\033[0m\n")
while True:
print("\033[1;34mMain Menu:\033[0m")
pr... |
def init_parser(self, filepath, logger):
self.parser = self.gpw_parser
self.parser.mainfile = filepath
if self.parser.mainfile_obj is None:
self.parser = self.gpw2_parser
self.parser.mainfile = filepath
self.parser.logger = logger
def get_mode(self):
mode ... | This code parses GPAW calculation data, extracting run parameters, basis sets (plane waves, real-space grid, or numeric AOs), and sampling methods (NVE ensemble for geometry optimization). It populates an archive with structured metadata, handling mode-specific configurations for different computational approaches (pw/... | def parse(self, filepath, archive, logger):
self.filepath = filepath
self.archive = archive
self.logger = logging.getLogger(__name__) if logger is None else logger
self.init_parser(filepath, logger)
sec_run = self.archive.m_create(Run)
sec_run.program_name = 'GPAW'
... |
def do_one_step(self, task, iseval=False, curr_rel='', istest=False):
loss, p_score, n_score = 0, 0, 0
support = task[0]
support_left = [self.ent2id[few[0]] for batch in support for few in batch]
support_right = [self.ent2id[few[2]] for batch in support for few in batch]
if iseva... | This code trains a machine learning model by iterating through epochs, performing forward passes on batches, logging training loss, saving checkpoints at intervals, and validating periodically. It implements early stopping based on validation metrics, updating the best model when performance improves. If validation met... | def train(self):
# initialization
best_epoch = 0
best_value = 0
bad_counts = 0
# training by epoch
for e in range(self.epoch):
# sample one batch from data_loader
train_task, curr_rel = self.train_data_loader.next_batch()
loss, _, _ = ... |
def train_cv_split(x_array, y_array, cv_pct):
'''
Inputs - Dataset in the form of np array, percentage of dataset you would like to select as cross validation set \n
There are two "dataset" arguments, data and data2. This is in case you have separate arrays for x and y. They will be sampled with the same in... | This function generates learning curves by varying cross-validation (CV) sizes, training a neural network multiple times for each CV size, and plotting average training/test errors. It iterates over a range of CV proportions, splits data, trains/test neural networks, collects errors, and visualizes how model performanc... | def graph_learning_curve(self, layer_n_list, n_samples = 5, n_iterations = 50, cv_size_min = 0.1, cv_size_max = 0.5, timeit = False):
'''
Does not require any prior neural net training or validation, or train/test split
'''
if timeit == True:
start = timer()
cv_sizes... |
def checkpoint(self):
##first take the masterKey from the file
try:
inFile = open('mast','r')
except IOError:
self.quitwin()
tkMessageBox.showinfo('sorry','The master key file is not available.\
We are unable to proceed. Go to siddharthkannan.webs.com and... | The main task of the code is to delete a specific account record from a file after user confirmation. It reads the input file line by line, checks for matches with a record, prompts the user to confirm deletion, and either skips writing the line to a temporary output file or keeps it. If a deletion occurs, it rearrange... | def callback():
self.checkpoint()
self.reinitialise()
inFile = open(fileName,'r')
out = open('temp','w')
flag = False ##flag will be set to true if the user has deleted an account
for i in inFile:
rem = i
... |
def checkpoint(self):
##first take the masterKey from the file
try:
inFile = open('mast','r')
except IOError:
self.quitwin()
tkMessageBox.showinfo('sorry','The master key file is not available.\
We are unable to proceed. Go to siddharthkannan.webs.com and... | The main task of the code is to confirm user intent to delete all records via a dialog box. If confirmed, it resets all data; otherwise, it reinitializes the UI frame and buttons. The function manages UI updates and data deletion based on user input. | def confirmDelete(self):
'''function that will confirm the delete all records option from the user'''
self.checkpoint()
self.frame.destroy()
self.initFrame()
if tkMessageBox.askyesno('Confirmation','Are you sure you want to delete all the records?'):
self.resetAl... |
def __search_for_player(self):
name = input("name: ")
try:
p = [p for p in self.__players if p["name"] == name][0] # player
print(self.__formatted_player(p))
except:
pass
def __teams(self):
teams = sorted(list(set([p["team"] for p in self.__players]))... | This code processes user commands by routing them to specific methods: searching players, displaying teams/countries, listing players in a team or from a country, and finding top performers by points or goals. | def __process(self, command: str):
if command == "1":
self.__search_for_player()
elif command == "2":
self.__teams()
elif command == "3":
self.__countries()
elif command == "4":
self.__players_in_team()
elif command == "5":
... |
def create_mat(mat):
mat=mat[:,1:]
return mat
def normalize(mat,weight):
column_squared_sum=np.zeros(mat.shape[1])
for j in range(mat.shape[1]):
for i in range(mat.shape[0]):
column_squared_sum[j]+=mat[i][j]*mat[i][j]
column_squared_sum[j]=np.sqrt(column_squared_sum[j])
... | This code processes a CSV file by validating inputs, normalizing data with specified weights, calculating performance scores based on impact directions, ranking results, and saving the output with scores and ranks to a new CSV file. | def main():
try:
filename=sys.argv[1]
except:
print('please provide 4 arguements as filename weight impacts outputFileName')
sys.exit(1)
print(filename)
try:
weight_input = sys.argv[2]
except:
print('please provide 3 more arguement')
sys.exit(1)
p... |
def import_data(self):
xsilFile = XSILFile("actin.xsil")
def firstElementOrNone(enumerable):
for element in enumerable:
return element
return None
self.t = firstElementOrNone(_["array"] for _ in xsilFile.xsilObjects[0].independentVariables if _["name"] == "t")
self.x = firstElement... | The code initializes a visualization class by importing data, configuring parameters, generating a colormap, and preparing data for plotting. It sets up a figure and axis, plots initial and final data points, and optionally generates a video or snapshots if enabled. The main task is to prepare and visualize data, with ... | def __init__(self, video=False, snapshots=False):
self.import_data()
self.video = video
self.snapshots = snapshots
self.set_params()
self.gen_colormap()
self.prepare_xy()
self.fig, self.ax = self.set_up_fig()
self.plot_first_last()
if self.video or self.snapshots:
... |
def reset(self):
self.curr = self.root
self._clearContents (self.root)
def validate(self, curBox, nextBox):
dest = nextBox.ocr
if curBox.ocr in self.curr.children:
temp = self.curr.children[curBox.ocr]
else:
temp = self.curr
print('current node has children',temp.children)
whi... | The function processes a list of boxes by sorting them, then validating and inserting each subsequent box into the pages if valid. It iterates through the sorted boxes, checking adjacency with the current box using `validate()`. Valid boxes are inserted via `_insert()` and become the new current box; invalid ones are s... | def processAnswerScript (self, pages, boxes):
boxes.sort()
self.reset()
# 1 a
# | | |
curBox = boxes[0]
for i in range (len(boxes)-1):
if(self.validate(curBox, boxes[i+1])):
print('inserting ',boxes[i+1],'after',curBox)
print(self._insert (curBox, pages, boxes[i+1]))
... |
def check(clauses, assignment):
global VERBOSE
if VERBOSE:
print('Checking assignment {}'.format(assignment))
print('score of assignment is {}'.format(score(clauses, assignment)))
for clause in clauses:
if not check_clause(clause, assignment):
return clause
print('Ch... | The code implements a **tabu search-based hill climbing algorithm** to find a satisfying assignment for logical clauses. It iteratively explores neighboring states by flipping variable values, selects the state with the lowest cost (score), and avoids revisiting recent assignments via a tabu list. The process continues... | def hill_climb(depth, assignment, previous_assignment):
# If the output is True or we reach the depth, return the current assignment
if check(clauses, assignment) == True or depth == 50:
return assignment
# Evaluate all possible next steps until we find the best cost... |
def generate_solvable_problem(num_variables):
global VERBOSE
k = 3 # 3-SAT
random.seed()
# < 4.2 easy; >4.2 usually unsolvable. 4.2 challenging to determine.
clauses_per_variable = 4.2
num_clauses = round(clauses_per_variable*num_variables)
# this assignment will solve the problem
... | The code solves a SAT problem using specified algorithms (e.g., backtrack, random_walk, hw7_submission) by either loading a problem from a file or generating a new one. It enforces a timeout, runs each algorithm, checks the solution's validity, and reports results including time taken and correctness. | def solve_SAT(file, save, timeout, num_variables, algorithms, verbose):
global VERBOSE
VERBOSE = verbose
if file != None:
with open(file, "r") as f:
[num_variables, timeout, clauses] = json.load(f)
print('Problem with {} variables and timeout {} seconds loaded'.format(
... |
def compose_mail(self, username, mail):
msg = f"""
From: {self.get_sender(mail)}
"""
TO = self.get_to(mail)
CC = self.get_cc(mail)
BCC = self.get_bcc(mail)
if BCC and username in BCC:
msg += f"To: <{username}>"
elif CC:
msg += "Cc: "
... | The main task of the code is to save an email message to a specific folder based on filtering criteria, generate a unique filename, and update a CSV file tracking email status (e.g., unread, attachments). It writes the email content to a text file, checks for attachments, and appends metadata to 'mail_status.csv' if th... | def save_mail(self, username, mail, filter_info, mail_No):
saved_mail = self.compose_mail(username, mail)
filter_folder = self.filter_mail(mail, filter_info)
mail_name = f"{mail_No}_{username}.txt"
csv_lines, csv_rows = Read_dtb().get_mailbox_status()
csv_lines = csv_lines[1:]
... |
def triadsList(a1, a2, trlist):
"""
List the rows corresponding to specified triads
:param a1, a2: Arrays with antenna IDs for first and second antenna
:returns: Tuple of (list of (tuple containing rows with data in the triad)),
(list of tuples contianing antenna IDs in the triad),
... | The function computes closure phases for antenna triads from visibility data in an HDF5 file, combining flags from antenna, waterfall, and data sources. It processes specified or all triads, calculates phases using complex visibilities, and returns phases, triad IDs, flags, and Julian Day in a dictionary. | def closurePh(f, time, trlist=None, antf=None, wff=None):
"""The closure phase on a triad of antennas
:param f: h5py data file
:param time: time slot to read
:param trlist: Explicit triads to compute the closure; if given
only these triads will be returned
:param antf: h5py antenna flags fil... |
def triadsList(a1, a2, trlist):
"""
List the rows corresponding to specified triads
:param a1, a2: Arrays with antenna IDs for first and second antenna
:returns: Tuple of (list of (tuple containing rows with data in the triad)),
(list of tuples contianing antenna IDs in the triad),
... | The code computes the bispectrum for specified or all antenna triads in a given time slot from an HDF5 data file. It processes visibility data, applies antenna and waterfall flags to filter invalid data, and returns the bispectrum phases, triad identifiers, flags, and Julian Day timestamps. The function supports custom... | def bispec(f, time, trlist=None, antf=None, wff=None):
"""The bispectrum on a triad of antennas
:param f: h5py data file
:param time: time slot to read
:param trlist: Explicit triads to compute the closure; if given
only these triads will be returned
:param antf: h5py antenna flags file
... |
def check_hash(path, digest, hashobj):
"""
Compare given digest and calculated one.
This returns True if the two digests match.
Otherwise this returns False.
path: Path to the input file
digest: Expected hex digest string
hashobj: hashlib object (e.g. hashlib.md5())
"""
with open(p... | (The function downloads and activates the native 64-bit d3dcompiler_47.dll for Wine, ensuring it is present by checking its MD5 hash. If missing, it downloads the DLL from a specified GitHub repository, copies it to the Wine system32 directory, and configures a registry override to prioritize the native DLL for specifi... | def activate_native_d3dcompiler_47(prefix, wine):
"""
Download/activate native 64-bit version of d3dcompiler_47.
wine: A list used to run Wine executable
"""
# check whether DLL is already downloaded
need_download = True
try:
if check_hash(File.d3dcompiler_47, File.d3dcompiler_47_md... |
def get_extension(id) -> dict:
extensions = _get_instance()["extensions"]
if id in extensions:
return copy.deepcopy(extensions[id])
return None
def create_extension(
id: str,
name: str,
publisher: str,
last_updated: str,
version: Optional[str] = None,
sha256: Optional[str] = ... | The main task of the code is to update a database with new or modified extensions. It checks each new extension against existing records, creating new entries or updating existing ones based on differences in timestamps. The function logs the number of new and updated extensions, ensuring the database reflects the late... | def update_extensions(new_extensions: list[dict]):
new_extensions_count = 0
updated_extensions_count = 0
with console.status("[bold yellow]Updating database..."):
for new_e in new_extensions:
old_e = get_extension(new_e["id"])
if old_e is None or old_e["last_updated"] != new_... |
def is_url_submission(submission: Submission) -> bool:
return len(str(submission.selftext).strip()) == 0 and \
not (is_image_submission(submission) or is_video_submission(submission)) \
and submission.url.startswith("http")
def get_image_from_submission(submission: Submission) -> list:
if is_ima... | The code converts a Reddit submission into a structured `PostResource` dictionary, mapping attributes like title, content (using selftext or URL), author, images, likes, comments, URL, date, and video. It handles content type differentiation, defaults to "Unknown" for missing authors, and converts timestamps to datetim... | def create_post_resource(submission):
return PostResource(
title=submission.title,
content=submission.selftext if not is_url_submission(submission) else submission.url,
author=submission.author.name if submission.author else "Unknown",
# If there are no images in preview, return an e... |
def initial_request(self) -> None:
"""
Gather necesary data like cookies, authorization, etc.
As far as I know, the only meaningful information gathered from this is an anti-bot cookie.
"""
resp = self.session.get(self.complaint_url)
form_action = resp.text.split("<form ... | The main task of the code is to perform a sequence of operations: initialize a request, handle a CAPTCHA, and submit a form. If any step fails, it recursively retries the entire process without explicit error handling or limits, risking infinite recursion on persistent failures. | def run(self) -> None:
try:
self.initial_request()
self.captcha = self.handle_captcha()
response = self.submit_form()
except:
# recurse into oblivion lmao
self.run() |
def initialize(self, data, k_opt=None, cluster=True):
# assumption: data has been checked and is of the form journey_id, init_state, i_state, j_state, count
if self.stochastic is True:
data = to_stochastic(data[data['count'] > 0.0].copy())
# initial segmentation (based on clustering... | The code performs Expectation-Maximization (EM) clustering on journey data to segment journeys into clusters. It initializes clusters using KMeans (if $k_{opt}$ is unspecified) or random assignments, then iteratively refines cluster parameters via EM steps until convergence (based on log-likelihood improvement threshol... | def em(self, data, k_opt=None, cluster=True, verbose=True):
"""
assumption: data has been checked
# k_opt: nbr of segments. If None it is computed
EM computation
:param data: data frame with journey_id, init_state, i_state, j_state, count with journey level checks for absorption ... |
def init_amtx_k(self, init_data):
amtx = self.init_amtx_k_(init_data)
if len(self.to_drop) > 0:
amtx = self.init_amtx_k_(init_data)
# all together
self.amtx = pd.concat([amtx, self.bmtx], axis=0).reset_index(drop=True) # segment transition matrix
self.amtx = self.... | This code initializes a Discrete-Time Markov Chain (DTMC) model for a specific segment, configuring transient and absorbing states. It sets up an absorbing matrix (identity matrix for self-transitions), initializes transition matrices, probability distributions, and state data structures using provided initial data. Pa... | def __init__(self, n_states, n_abs, segment, init_data, weighted, stochastic):
"""
Assumptions:
- states: 0,..., n_states - n_abs - 1 are transient
- states: n_state - n_abs, ..., n_states - 1 are absorbing
:param n_states: total number of states
:param n_abs: number of a... |
def __get_size_of_model(self):
torch.save(self.model.state_dict(), "./temp.p")
s = os.path.getsize("./temp.p")/1e6
os.remove('./temp.p')
return s
def prune_model(self):
self.model.cpu()
for module in self.model.modules():
if isinstance(module, nn.Conv2d):
plan =... | The main task of the code is to iteratively prune a neural network model while training it with decreasing learning rates, aiming to reduce the model's size (in MB) below a specified threshold (border_size). It evaluates accuracy after each pruning cycle, saves the pruned model, and adjusts parameters to maintain perfo... | def run_main_cycle(self, border_size = 2.5, start_lr = 0.005):
lr = start_lr
i = 1
self.__print_accuracy()
size = self.__get_size_of_model()
print('Size of the model(MB):', size)
while(size >= border_size): #MB
print("=======Cycle %d======="%(i)); i+=1
print(... |
def create_node(el, dist, left=None, right=None):
node = {}
node['id'] = el
node['dist'] = dist
node['size'] = 1
if not left is None and not right is None:
node['left'] = left
node['right'] = right
return node
def number_to_str(num):
res = chr(ord('a') + int(num) % 26)
while num // 26 != 0:
num = (num // ... | The code implements the UPGMA (Unweighted Pair Group Method with Arithmetic Mean) algorithm for hierarchical clustering. It initializes clusters from input data, iteratively merges the two closest clusters by calculating their minimum distance, updates the cluster structure, and repeats until a single cluster remains. ... | def UPGMA(inp):
# Create clusters
clusters = [create_node(number_to_str(i), 0) for i in range(len(inp))]
current = inp
# While there is more than one cluster
while len(current) >= 2:
c_min, c_ind = get_shortest_dist(current)
current, clusters = merge(current, clusters, c_ind, c_min)
return clusters[0] |
def compute_percent_returns(df: pd.DataFrame) -> pd.DataFrame:
"""
:param df: Dataframe to be augmented, should follow CANDLE_LABELS
:return: Augmented dataframe with conventional returns based on closing prices
"""
# TODO: Implement parsing for returns based on different prices (open, high, low, et... | The function retrieves cryptocurrency price data for two products over a specified date range, computes their log and percent returns, then merges the results into a single DataFrame with time-aligned returns, distinguishing columns using product-specific suffixes. | def get_crypto_pair_with_returns(prod1: str, prod2: str,
start: datetime.date, end: datetime.date = None,
granularity: str = None) -> pd.DataFrame:
df1 = compute_percent_returns(compute_log_returns(get_candles(prod1, start, end, granularity)))
df... |
def set_granularity(granularity: str = None) -> str:
# See global declarations above for explanation of GRANULARITY_LABELS
g = granularity
if granularity not in GRANULARITY_LABELS.keys():
g = "3600"
else:
g = GRANULARITY_LABELS[granularity]
return g
def get_crypto_pair_with_returns(p... | The main task of the code is to plot the moving correlation between log returns of two cryptocurrencies (prod1 and prod2) over a specified time period, including a mean correlation line. It fetches cryptocurrency price data, computes rolling correlations, and visualizes them with date-formatted axes, addressing data cl... | def plot_crypto_pair_correlation(prod1: str, prod2: str,
start: datetime.date, end: datetime.date = None,
granularity: str = None, window: str = None):
granularity = set_granularity(granularity)
dfm = get_crypto_pair_with_returns(prod1, prod2, st... |
def get_candles(prod: str, start: datetime.date, end: datetime.date = None, granularity: str = None) -> pd.DataFrame:
# Granularity must be one of the following: ["1m", "5m", "15m", "1h", "6h", "24h"]
# From API: The maximum number of data points for a single request is 300 candles. If your selection of
# ... | The main task of the code is to fetch cryptocurrency candlestick data, compute log returns, and visualize returns and correlation between BTC-USD and ETH-USD pairs for a specific date. It retrieves hourly data for BTC-USD, calculates its log returns, and generates plots comparing returns and correlations of BTC-USD and... | def main():
df = get_candles("BTC-USD", datetime.date(2021, 6, 1), granularity="1h")
print(compute_log_returns(df))
plot_crypto_pair_returns("BTC-USD", "ETH-USD", datetime.date(2021, 6, 1))
plot_crypto_pair_correlation("BTC-USD", "ETH-USD", datetime.date(2021, 6, 1)) |
def prepare(simCtx, lines, port_id, involved_dexes):
simCtx = deepcopy(simCtx)
bootstrap_line = lines[0].strip()
approved_tokens = bootstrap_line.split(',')[1:]
bootstrap_block = int(bootstrap_line.split(',')[0]) - 1
fork_url = 'http://localhost:{}'.format(FIRST_PORT+port_id)
hard_reset(fork_u... | The code simulates blockchain transactions to calculate Maximum Extractable Value (MEV) by executing transaction sequences, mining blocks, and evaluating token balances. It handles different settlement mechanisms (CEX, DEX) and logs optimal transaction samples if specified. The function returns the computed MEV, consid... | def simulate(simCtx, lines, port_id, involved_dexes, best=False, logfile=None, settlement='max'):
simCtx = deepcopy(simCtx)
# Note that nonces need to sync up with the snapshot!
fork_url = 'http://localhost:{}'.format(FIRST_PORT+port_id)
w3 = Web3(Web3.HTTPProvider(fork_url))
bootstrap_line =... |
def move_bt(cl,name,color):
(rx,ry,_,_)=cell_pos(cl)
font = pygame.font.Font('freesansbold.ttf', 20)
text = font.render(name, True, color, (0,0,0))
screen.blit(text, (rx+10,ry+10))
def entangle_cells():
global i,pturn,target,control,ct,tg,qt,entangle
if ct and tg:
player=pturn.pop()... | This function handles mouse interactions for a quantum computing game, toggling between classical, quantum, and entanglement modes. It updates game states, validates moves, displays error messages, and renders UI elements like buttons and grid lines based on user input and current game conditions. | def dsbutton(move,cl,name,cell_ol):
global clicked_side,classical,quantum,entangle,ct,tg,qt,game_moves,guidelines
if move.collidepoint(pygame.mouse.get_pos()):
if pygame.mouse.get_pressed()[0] == 1:
clicked_side=True
elif pygame.mouse.get_pressed()[0] == 0 and clicked_side == True:
... |
def pausemenu(self, width, height, state):
done = False
# Set the width and height of the screen [width, height]
size = (width, height)
CORALBLUE = (0, 255, 180, 0.8)
GRAPEFRUIT = (224, 112, 124)
self.screen = pygame.display.set_mode(size, pygame.RESIZABLE)
pygam... | The code runs a game loop handling input, audio, rendering, and game state updates. It initializes sound effects, processes events (quit, key presses), checks for level completion, updates player movement, manages walking audio, handles mouse interactions, and maintains a 60 FPS frame rate while saving game progress. | def run(self):
done = False
pygame.mouse.set_pos(self.width / 2, self.height / 2)
pygame.mixer.set_num_channels(7)
pygame.mixer.Channel(0).play(pygame.mixer.Sound("Audio/background.mp3"), -1)
pygame.mixer.Channel(1).play(pygame.mixer.Sound("Audio/soundtrack.mp3"), -1)
p... |
def set_decode_buf(self, buf):
self.decode_buf = buf
def decode_header(self):
try:
t = struct.unpack('!BBBBLLLL', self.decode_buf[:20])
self.decode_buf = self.decode_buf[20:]
ret = {
'version': t[0],
'pdu_type':t[1],
'pd... | The code decodes AgentX PDUs by parsing headers and associated data based on the PDU type. It handles RESPONSE PDUs by extracting sysUpTime, error codes, and variable bindings; GET/GETNEXT PDUs by decoding search ranges; TESTSET PDUs by parsing variable bindings. Unsupported PDU types trigger error logs, while COMMITSE... | def decode(self, buf):
self.set_decode_buf(buf)
logger.debug('Decode AgentX PDU:')
for i in hexdump(self.decode_buf, sep='-'):
logger.debug(i)
ret = self.decode_header()
if ret['pdu_type'] == pyagentx3.AGENTX_RESPONSE_PDU:
# Decode Response Header
... |
def print_struct(fields, key, value):
print("/// {}\nstruct {} {{\ndeclare_struct".format(value['description']['plaintext'], key))
for field in fields:
cur_field = fields[field]
field_type = cur_field['types'][0]
field_required = cur_field['required']
field_is_pointer = (str(fiel... | The code generates C++ struct definitions from a JSON schema, handling dependencies and exclusions. It reads input JSON, processes types, and writes C++ code to the output file, ensuring all fields are processed before printing structs. Special handling is applied for specific keys like "InputMessageContent" and depend... | def generate_types(input,output):
original_stdout = sys.stdout
input_file = open(input, 'r')
output_file = open(output,'w')
sys.stdout = output_file
print(input_file.read())
types = open("public/types.json", "r")
exclude_keys = {"InputFile": "using InputFile = File;",
"I... |
def get_article(description_soup):
articles_text = str(description_soup)
for sibling in list(description_soup.next_siblings):
if sibling.name in ["h3", "h4"]:
break
else:
articles_text += str(sibling)
articles_soup = BeautifulSoup(articles_text, "lxml")
article = ... | This function parses HTML content from a bot API documentation URL, populates a schema with categorized data (articles, methods, types), and optionally updates version numbers or processes changelogs. It extracts structured information, handles nested elements, and organizes content into the schema's dictionaries based... | def generate_bot_api_data(schema, dwn_url=BOT_API_URL, update_version=False, changelog=False):
r = requests.get(dwn_url)
soup = BeautifulSoup(r.text, features="lxml")
if update_version:
schema["version"] = soup.find_all("strong")[2].text.lstrip("Bot API ")
sections = soup.find_all(["h3", "h4"])
... |
def read_file(self, file_path):
# Try to open the file
try:
with open(self.file_path, 'r') as f:
try:
data = f.read()
return data
except Exception as e:
self.read_error = LASFileCriticalError(
... | The code initializes an object by reading a file's content, extracting its version, splitting it into sections, validating these sections, and setting error attributes. It handles file input, data parsing, structure validation, and error tracking during initialization. | def __init__(self, file_path=None):
if file_path is not None:
self.file_path = file_path
self.sections = []
self.curve_names = None
# Try to open and read the file into a string
data = self.read_file(self.file_path)
if data is not None:
... |
def checkReset(reset):
global byte_to_send
if not resetButton.is_pressed or (reset == True):
byte_to_send = drive.stop
reset = True
print('Resetting...')
return reset
def initialCalibration(home):
global playerBlue
global fieldRight
global reset
global start
... | The main task of the code is to control a robot's movement and calibration using sensor data and coordinate tracking. It initializes threads for communication, calibrates the robot's angle via forward motion and gyro data, navigates based on player and ball positions, returns to a home position if out of bounds or unab... | def main():
while 1:
global anglecurrent
global fieldRight
global reset
global byte_to_send
''' Thread initialization '''
SerialThread()
RadioThread()
while (not reset):
''' This code is included every time reset button may be needed '''... |
def generate_adv(self, data, model, mult_val = 0.1):
gradient = self.get_gradient(data, model)
#print("############# GRADIENT :", gradient.sum())
sign_vec = self.get_sign_vec(data.shape[0])
sign_vec = mult_val * sign_vec
gen_adv = data + sign_vec[:,None, None, None] * np.sign... | The code trains a model (bb_model) to generate adversarial examples against a target_model. It iteratively updates the training data with adversarial samples, retraining bb_model each epoch. If check_acc is True, it evaluates the target_model's test accuracy before and after each epoch, showing the accuracy drop caused... | def train_adv(self, bb_data, bb_labels, bb_model, target_model, test_data=None, test_labels=None, check_acc=False):
if check_acc:
if type(test_data) == None or type(test_labels) == None:
raise ValueError("To Check for Test Accuracy Provide test ... |
def playerAction(self, event):
if event == '-action-':
self.player.block = False
if self.player.armed == False:
self.window['-action-'].Update("Attack")
self.window['-playerevent-'].Update("♻️ You reloaded!")
self.player.armed = True
... | This code handles player vs. enemy combat logic in a game, updating the UI with outcome messages based on blocking and attacking actions. It checks both players' block status and armed state to determine results like hits, blocks, or reloads, displaying corresponding text and triggering damage or reload functions when ... | def contest(self, event):
self.playerAction(event)
if self.enemy.block == True and self.player.block == True: #both players block
self.window['-outcome-'].Update("🛡🛡 Both of you blocked!")
elif self.enemy.block == True and self.player.block == False: #enemy blocks, player does not
... |
def clearsInstructions(self,objList):
for obj in objList:
self.bottomCanvas.delete(obj)
self.instrObj = []
def snakeCollision(self):
if self.snakeObj.getDirection() == SnakeConst.RIGHT:
return (self.snakeObj.getPosX()+self.SNAKE_CELL_W <= -1) or (self.snakeObj.getPosX()+s... | This method handles the Snake game loop by processing directional inputs to move the snake, updating its position on the canvas, checking for collisions with walls or itself, playing sound effects for movement, collisions, and eating food, and restarting the loop with a delay based on the snake's speed. If a collision ... | def play(self):
if self.playing:
if self.commands[SnakeConst.UP]:
self.snakeObj.move(SnakeConst.UP,self)
self.moving = True
elif self.commands[SnakeConst.DOWN]:
self.snakeObj.move(SnakeConst.DOWN,self)
self.moving = True
... |
def renderScoreValue(self,points):
self.bottomCanvas.delete(self.scoreObj)
if len(points) == 1:
self.scoreObj = self.bottomCanvas.create_text(self.SCORE_MARGIN_HORIZONTAL*11,self.SCORE_MARGIN_VERTICAL/2,font=self.FONT_TEXT,text=points)
elif len(points) == 2:
self... | This function resets the game state when the Enter key is pressed. It resets the score to zero, clears the snake and instructions, reinitializes game components, sets the snake's direction to right, and restarts the game loop by calling self.play() | def playAgain(self,event):
if event.keysym == "Return":
self.points = 0
self.renderScoreValue(str(self.points))
self.clearsInstructions(self.instrObj)
self.clearsSnake()
self.resetAllCommands()
self.renderSnake()
self.snakeObj.s... |
def speech_to_text():
model = whisper.load_model(MODEL)
modify_model(model)
print('Speech to text...')
results = model.transcribe(input_file)
print('... done!\n')
return results
def word_level_timestamps(parsed_speech_to_text):
print('Getting word-level timestamps...')
word_segments = stabilize_timestam... | The main task of the code is to edit a video by retaining only the segments containing specific spoken commands, identified through speech-to-text processing. It extracts word-level timestamps, filters intervals corresponding to commands, trims the video to those intervals, removes dead air, and exports the edited vide... | def main():
sts = speech_to_text()
word_ts = word_level_timestamps(sts)
commands = find_commands(word_ts)
print(f'Commands: {commands}')
keep_intervals = intervals_to_keep(commands)
print(f'Keeping intervals: {keep_intervals}')
vid = VideoFileClip(input_file)
# Edit with speech-to-text.
keep_clips =... |
def it_Fit(img1, img2, pag_size = page_r, dist = distance, mask = kernel):
flag = True
best_img = []
img_dilation = cv2.dilate(img1, mask, iterations=1)
img_dilation = figureBinary(img_dilation, threshold)
contours, hierarchy = cv2.findContours(img_dilation, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
areas = []... | The function attempts to fit the input image `img1` with images from `list_path` using two methods (`it_Fit` and `best_match`). If a match is found, `img1` is updated, and the corresponding path is removed. Unmatched paths are stored in `back_up`. The function returns the updated image, unmatched paths, and a flag indi... | def it_Fit2(img1, list_path, pag_size, dist):
kernel2 = np.ones((5,5), np.uint8)
back_up = []
flag = False
for id in range(len(list_path)):
best_img, flag1 = it_Fit(img1, call_Image(list_path[id]), pag_size, dist, kernel2)
if flag1 == False:
best_img, flag1 = best_match(img1, call_Image(list_pa... |
def call_Image(path):
img = cv2.imread(path) # Read image
img = figureBinary(img, threshold) # Binarize image
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 3D to 1D
return img
def it_Fit(img1, img2, pag_size = page_r, dist = distance, mask = kernel):
flag = True
bes... | This function identifies the best matching image from a list of paths by comparing each image's fit and density. It iterates through paths, evaluates image compatibility using `it_Fit` and `best_match`, and selects the image with the highest density or best fit, updating the best image and corresponding path accordingl... | def best_match_Image(img, path, pag_size = page_r, dist = distance):
img2 = call_Image(path[0])
best_img, flag = it_Fit(img, img2, pag_size, dist)
best_path = path[0]
if len(best_img) > 0: # If there was a fit with image 2
b_img, f2 = best_match(img, img2, pag_size)
if f2 == True:
if (flag ... |
def it_Fit(img1, img2, pag_size = page_r, dist = distance, mask = kernel):
flag = True
best_img = []
img_dilation = cv2.dilate(img1, mask, iterations=1)
img_dilation = figureBinary(img_dilation, threshold)
contours, hierarchy = cv2.findContours(img_dilation, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
areas = []... | The function identifies the best-fitting image from a list by comparing each image with the first one using 'it_Fit' and 'best_match' methods. It prioritizes images with higher density and updates the best match iteratively. The task involves selecting the optimal image combination based on fit quality and density, ret... | def couple_outPath(list_img, pag_size, dist):
img1 = list_img[0]
img2 = list_img[1]
best_img, flag = it_Fit(img1, img2, pag_size, dist)
pos = 1
if len(best_img) > 0: # If there was a fit with the image
b_img, f2 = best_match(img1, img2, pag_size)
if f2 == True:
if (flag == False) or (densi_imag... |
def call_Image(path):
img = cv2.imread(path) # Read image
img = figureBinary(img, threshold) # Binarize image
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 3D to 1D
return img
def best_match_Image(img, path, pag_size = page_r, dist = distance):
img2 = call_Image(p... | This function identifies the optimal image and corresponding path by iteratively comparing image densities. It starts with the first image in the path, then evaluates subsequent images, updating the best match (new_img) and path (new_path) whenever a higher-density image is found. The process excludes suboptimal elemen... | def start_couple(path, pag_size = page_r, dist = distance):
img1 = call_Image(path[0])
new_path = [x for x in path if x != path[0]]
new_img, drop_path, f = best_match_Image(img1, new_path, pag_size, dist)
for i in range(len(path)-1):
img = call_Image(path[i+1])
aux_path = [x for x in path if x != path[... |
def call_Image(path):
img = cv2.imread(path) # Read image
img = figureBinary(img, threshold) # Binarize image
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 3D to 1D
return img
def best_match_Image(img, path, pag_size = page_r, dist = distance):
img2 = call_Image(p... | The main task of the code is to process a list of image paths by iteratively matching and arranging images into A4-sized pages. It starts with the first image, finds the best match from remaining images, and appends them to pages. When no more matches are found, it finalizes the pages, ensuring all images are included.... | def first_start(PATH, pag_size = page_r, dist = distance):
start_time = datetime.now()
list_ofPages = []
flag = True
new_img = call_Image(PATH[0])
new_path = [x for x in PATH if x != PATH[0]]
while True:
aux_img, drop_path, flag = best_match_Image(new_img, new_path, pag_size, dist)
if flag == True:... |
def call_Image(path):
img = cv2.imread(path) # Read image
img = figureBinary(img, threshold) # Binarize image
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 3D to 1D
return img
def best_match_Image(img, path, pag_size = page_r, dist = distance):
img2 = call_Image(p... | This code arranges images from a list of paths into A4-sized pages by randomly selecting a starting image, iteratively finding the best visual match for the next image, and compiling them into a list of pages. It handles edge cases like single remaining images and ensures all images are placed on pages, returning the f... | def random_first(PATH, pag_size = page_r, dist = distance):
start_time = datetime.now()
list_ofPages = []
flag = True
drop_path = random.choice(PATH)
new_img = call_Image(drop_path)
new_path = [x for x in PATH if x != drop_path]
while True:
aux_img, drop_path, flag = best_match_Image(new_img, new_pat... |
def menuBusquedaID(endpoint):
repetir = 1
while (repetir == 1):
busqueda = input("\nIngrese el n°ID ")
resultadoBusqueda = search(endpoint+busqueda)
if len(resultadoBusqueda) == 1:
print(len(resultadoBusqueda))
opcion = input(
"ID no encontrado o ... | The main task of the code is to present a menu for selecting a Star Wars API endpoint (films, people, planets, etc.) and a search method (by ID or name/model). It validates user input, retrieves data using the chosen endpoint and search type, and displays results. The loop ensures valid selection, then executes the app... | def mainMenu():
repetir = 1
options = {
1: 'films/',
2: 'people/',
3: 'planets/',
4: 'species/',
5: 'starships/',
6: 'vehicles/'
}
while (repetir == 1):
selection = int(input(
"Bienvenido, Seleccione una opcion de busqueda \n1-films 2-... |
def alpha(distance_differ, k):
chord = 0.5
d = distance_differ[k]
angle = 2 * 180 / math.pi * math.atan(chord/2/d)
return int(angle) + 1
def control(maps2,distance_differ,mod,k):
angle= range(181,360) + range(0,181)
point= 0
z = len(distance_differ) -1
bandiera = True
free_space =0
while(bandiera):
s... | The code determines a directional angle (beta) by iterating through angular ranges, adjusting parameters (mod, k) based on distance differences and map data, and using conditional checks to refine the direction. It interacts with external functions (alpha, control, medium) to compute the final direction and related val... | def direction (maps, distance_differ, maps2):
global global_distance, global_mod
angle = range(270,360) + range(0,91)
mod = 0
k = 0
point = 0
beta = 0
clock = True
while(clock):
selection = []
p_start = len(angle)/2 + mod
point = alpha(distance_differ,k)
for i in range(point):
p = p_start - point/2 +... |
def start(msg, x, y):
angle = range(x,360) + range(0,y)
# Map matrix with values in meters
maps = {}
maps_copy = {}
for i in angle:
if round(float(msg.ranges[i]),2) == 0:
value = float(5)
else:
value = round(float(msg.ranges[i]),2)
maps[i] = value
map_distances = sorted(maps.values(), reverse = Tru... | The code processes LiDAR data to control a robot's movement using SLAM (Simultaneous Localization and Mapping). It calculates linear/angular velocities for navigation, updates odometry, and constructs a map matrix. When `cnt == 2`, it halts the robot, saves the map, and visualizes it with obstacles (red/green dots) and... | def LiDAR(msg):
global time, global_distance, global_mod, computation, odometryx,odometryy, odometryw, odometryz, x, y, w, z, a ,b, map_matrix, init
if cnt == 1:
time +=1
print ('*'*5 + 'Time' + '*'*5)
print (time)
if time == 1:
a = x
b = y
maps, max_map, distance_differ ... |
def init_instruments(self):
"""
Instruments initialization function
:param:
:return:
"""
# Creates the dictionary of instruments
self.instruments = {}
# Creates the required number of granulars
for i in range(self.list_instruments[0]):
... | The code initializes a sound module by setting up audio components, sample directories, MIDI parameters (MIDDLE, STD), and initializes instruments, thresholds, and conductors for generating and controlling sound. It prepares the system for real-time audio processing, recording, and musical composition using predefined ... | def __init__(self, list_instruments, samples_dir_melody, samples_dir_voices,samples_dir_aggressive,samples_dir_beat, list_blocks, MIDDLE, STD, record=False, normalized=False):
"""
Sound module initialization function
:param samples_dir_melody: Directory containing melodic sound samples
... |
def add_topic(self, topic_label):
"""Adds a topics
:param topic_label: str
:return: bool
"""
exists = False
for topic in self.topics:
if topic.label == topic_label:
exists = True
topic_res = topic_label
break
... | This code trains a model by associating example sentences with specified topics. It validates input types, processes examples by cleaning text, and maps each word in cleaned examples to the given topics. Finally, it sorts the data for efficient retrieval. | def train(self, topics=None, examples=None):
"""Give examples of sentences related to a topic_label
:param topics: str
:param examples: list
"""
if not isinstance(topics, str) and not isinstance(topics, list):
raise ValueError('topics must be str or list of str')
... |
def create_spin_wheel_response(request):
return {
'vote_msg': "Spin the wheel!",
'authenticated': request.user.is_authenticated
}
def get_bandname(request):
try:
return Bandname.objects.get(bandname=request.POST['bandname'])
except Bandname.DoesNotExist:
return None
def g... | The function processes a voting request by validating input data, checking for existing votes, and returning appropriate responses. It verifies the presence and validity of 'bandname' in POST data, retrieves user and IP information, checks if the user has already voted, and either saves the vote or returns predefined r... | def build_judgement_json(request, judgement):
print(request.POST)
if 'bandname' not in request.POST:
return create_spin_wheel_response(request)
if request.POST['bandname'] == '':
return create_spin_wheel_response(request)
bandname = get_bandname(request)
print(bandname)
if not ... |
def get_soup(session, formatted_url):
# after alter session get data and get text
response = session.get(formatted_url)
# get de text
html_text = response.text
# Prepare the soup
soup = BeautifulSoup(html_text, "html.parser")
# retur soup
return soup
def get_full_seo_data(soup):
... | The main task of the code is to scrape SEO data from a given URL using a session, with an optional parameter to display a help message instead. It initializes a session, fetches the URL, and processes the data via `get_soup` and `get_full_seo_data` functions if the choice is 1, otherwise showing help. Error handling is... | def browse_and_scrape(formatted_url, choice=1):
# nodes
nodes_arr = ['c1pro01','c1pro02','c1pro03','c1pro04','c2pro01','c2pro02','c2pro03','c2pro04']
try:
# get session
session = requests.Session()
# first get to cookie
response = session.get(formatted_url)
... |
def init(engine,num_applicants=-1, history_size=-1, acc=None, delete=True):
"""
Initialize the database with a specified number of applicants and random actions.
Parameters:
- engine (sqlalchemy.engine.base.Engine): The SQLAlchemy engine for database connection.
- num_applicants (int): Number of ap... | The function `timed_test` measures the average execution time of deleting a database column (e.g., "residence_city") for multiple applicants across several iterations. It initializes a database, populates test data with randomized history records, and executes deletion operations while timing each iteration. Parameters... | def timed_test(num_app, num_hist, num_iter, vacuum, engine, num_del=1, seed=-1):
"""
Measures the average execution time of a single column deletion operation in the database.
Parameters:
- num_app (int): Number of applicants to use in test.
- num_hist (float): Number of history records relative to... |
def init(engine,num_applicants=-1, history_size=-1, acc=None, delete=True):
"""
Initialize the database with a specified number of applicants and random actions.
Parameters:
- engine (sqlalchemy.engine.base.Engine): The SQLAlchemy engine for database connection.
- num_applicants (int): Number of ap... | The function evaluates the performance of batch deletion operations by measuring average time taken for varying numbers of deletions (test_sizes), comparing sequential vs non-sequential processing. It initializes/test data, runs multiple iterations, records timings, and plots results to analyze scalability and efficien... | def batch_evaluate(total_app, hist_size, num_deletes, is_sequential, engine, num_steps = 4, num_iter=5, init_db=False):
step_size = num_deletes // num_steps
test_sizes = range(step_size, num_deletes + 1, step_size)
avg_times = []
if init_db:
# test set up
if seed > 0:
ra... |
def generate_voronoi_tessellation(self, seed_values: list) -> object:
"""
Generates the voronoi tessellation from the seed values provided
:param seed_values: [x, y] list of positions to use as seeds for the voronoi tessellation
:type seed_values: list
:return: Voronoi tessellat... | The main task of the code is to generate a Voronoi tessellation-based lattice structure by creating a grid of seeds with controlled noise (standard deviation) and spatial spacing (step). It returns the lattice's vertices, edges, and cells as separate dictionaries, enabling further analysis or visualization of the tesse... | def create_example_lattice(self, voronoi_seeds_std: float = 0.15, voronoi_seeds_step: int = 20) -> tuple[dict, dict, dict]:
"""
Create a lattice with the initial Voronoi tessellation
:param voronoi_seeds_std: Noise taken from a normal of mean zero and this value as standard deviation
:t... |
def AddPersonInfo(self):
self.streak = 0
person = self.people[random.randint(0, len(self.people) - 1)]
self.unlockedPeople.append(person)
self.people.remove(person)
printG("New Person!")
printStat("Name", person.name)
printStat("Age", person.data.age)
pr... | This code defines a game loop for a trivia game with difficulty settings. It initializes game parameters, selects random questions and people, checks answers, updates score/streak, and manages lives. Difficulty affects multipliers and display colors. The game continues until lives reach zero, then triggers the GameOver... | def Game(self):
if self.data.GetDifficultyName() == "easy":
self.difficulty_multiplier = 0.8
colour = Fore.LIGHTGREEN_EX
elif self.data.GetDifficultyName() == "normal":
self.difficulty_multiplier = 1
colour = Fore.LIGHTYELLOW_EX
elif self.data.GetD... |
def train_loop_distillation_overlap(self):
self.setup_cuda_primitives()
model = self.model
n_iter_per_epoch = self.n_iter_per_epoch
iterator = iter(self.train_loader)
self.epoch = 0
next_images, next_target = next(iterator)
next_images = next_images.cuda(non_bl... | The main task of the code is to train a neural network model with options for label smoothing, distillation, and distributed training. It initializes loss functions, manages training loops (plain, distillation variants), performs validation, and saves model weights. The code handles distributed data synchronization, ac... | def train(self):
model = self.model
self.time_start = time.time()
if self.options.label_smoothing:
self.criterion = LabelSmoothing(self.options.label_smoothing).cuda()
else:
self.criterion = torch.nn.CrossEntropyLoss().cuda()
self.loss_stats = util.Stats()... |
def setup_distributed(self):
if self.distribute_initialized:
return
self.distribute_initialized = True
dist.init_process_group(backend='nccl', init_method='env://')
self.rank = dist.get_rank()
self.size = dist.get_world_size()
self.gpu = self.options.local_ra... | The code's main task is to initialize a distributed training environment, set up the model, dataset, and optimizer, create an output directory, perform a dummy communication step, and execute the training process, followed by a synchronization barrier to ensure all processes reach this point. | def run(self):
self.setup_distributed()
self.setup_model()
self.setup_dataset()
self.setup_optimizer()
try:
if self.options.out is not None:
os.makedirs(self.options.out)
except OSError:
pass
self.dummy_communication()
... |
def set_env_ref(env_ref: EnvRef)->str:
'''Create a string environment reference for use in Conda commands.
The environment command segment has one of two forms:
- If env_ref is the name of an environment:
- *'--name <Environment Name>'*.
- If env_ref is the path to an environment:
... | The function saves Conda environment specifications, a YAML file, and a JSON history file to a specified directory. It generates these files using `conda list`, `conda env export`, and `conda env export --from-history` commands, with default filenames based on the environment name. The task involves exporting environme... | def save_env_specs(env_ref: EnvRef, save_folder: Path,
spec_file: FileNameOption = True,
yml_file: FileNameOption = True,
history_json: FileNameOption = True):
'''Store *spec*, *.yml* and *.json* history files for the environment.
Default spec file names... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.