dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def CP_decom(Tensordata, Num_Rank):
"""
Tensor CP decomposition, return CP components
Tensordata: a ndarray for tensor
Num_Rank: Assumed the number of rank (knomn)
"""
decomposed = parafac(Tensordata, Num_Rank)[1]
return decomposed
def STM_pred(New_obs, beta_hat, Tx_list, Kernel_Gamma, RPMM_... | This code performs tensor prediction by first decomposing input tensors using CP decomposition. It then applies either a standard STM prediction method or an ensemble STM prediction, depending on the 'do_RP' flag, using parameters like beta, kernel gamma, and precomputed tensor lists to generate predictions for each de... | def pred(self, newX, alpha = 0):
new_list = [CP_decom(tensor, self.rank) for tensor in newX]
if not self.do_RP:
pred = [STM_pred(newTx, self.beta, self.Tx_list, self.Kernel_Gamma) for newTx in new_list]
else:
pred = STM_Ensemble_Pred(new_list, self.beta, self.Tx_list, sel... |
def CP_decom(Tensordata, Num_Rank):
"""
Tensor CP decomposition, return CP components
Tensordata: a ndarray for tensor
Num_Rank: Assumed the number of rank (knomn)
"""
decomposed = parafac(Tensordata, Num_Rank)[1]
return decomposed
def STM_fit(Tx_list, ylabel, lambda_vec, Kernel_Gamma, RPMM_... | This code fits a model (STM or ensemble STM) by decomposing input tensors, applying kernel methods with specified parameters, and updating model coefficients (beta) and training history. It uses either STM_fit for standard training or STM_Ensemble for random projection-based ensemble learning, depending on the 'do_RP' ... | def fit(self, Tx, ylabel, Kernel_Gamma, lambda_vec, beta_init = None, maxiter = 10000, eta = 0.05):
"""
Fitting STM
"""
self.Tx_list = [CP_decom(tensor, self.rank) for tensor in Tx]
self.Kernel_Gamma = Kernel_Gamma
if not self.do_RP:
# Not doing random project... |
def oneHotEncoder(x, label_size):
x_ = torch.zeros((x.shape[0], label_size))
for i in range(len(x)):
x_[i][x[i].item()] = 1
return x_
def precision_k(true_mat, score_mat, k):
p = np.zeros((k, 1))
rank_mat = np.argsort(score_mat)
backup = np.copy(score_mat)
for k in range(k):
... | The code evaluates the performance of a multi-model system (token-level LWAN model, abstract encoder, and sentence-level SAN model) on a test dataset. It computes token and sentence-level predictions, calculates losses, and measures precision@k, NDCG@k, and F1 scores. Results are logged to a file, including classificat... | def evaluate(epoch, test_loader, lwan_model, abs_encoder_model, san_model, sent_pool, results_file, output_dir,
vocab_map, token_tag_map, sentence_tag_map, criterion, abs_encoder=True):
prec_k, ndcg_k = [], []
test_loss = []
t_preds, t_true, s_preds, s_true = [], [], [], []
sent_toks = []
... |
def oneHotEncoder(x, label_size):
x_ = torch.zeros((x.shape[0], label_size))
for i in range(len(x)):
x_[i][x[i].item()] = 1
return x_
def precision_k(true_mat, score_mat, k):
p = np.zeros((k, 1))
rank_mat = np.argsort(score_mat)
backup = np.copy(score_mat)
for k in range(k):
... | The function evaluates a model's performance on a test dataset using transformer and attention models. It computes token and sentence-level predictions, calculates loss, precision, and NDCG metrics, and logs results. It processes batches, handles embeddings, applies models (LWAN, SAN), compares predictions with labels,... | def evaluate(epoch, transformer_model, abs_transformer_model, test_loader, lwan_model, san_model, sent_pool,
results_file, output_dir, vocab_map, token_tag_map, sentence_tag_map, criterion, abs_encoder=False):
prec_k, ndcg_k = [], []
test_loss = []
t_preds, t_true, s_preds, s_true = [], [], [],... |
def oneHotEncoder(x, label_size):
x_ = torch.zeros((x.shape[0], label_size))
for i in range(len(x)):
x_[i][x[i].item()] = 1
return x_
def precision_k(true_mat, score_mat, k):
p = np.zeros((k, 1))
rank_mat = np.argsort(score_mat)
backup = np.copy(score_mat)
for k in range(k):
... | The code trains a multi-model system (LWAN, ABS encoder, SAN) for token and sentence-level tasks using a dataset. It performs forward passes, computes combined losses (token + sentence), backpropagates gradients, and evaluates metrics like precision, NDCG, and F1. Results are logged per epoch, including training loss, ... | def train(lwan_model, abs_encoder_model, san_model, train_loader, test_loader, criterion, opt, outputdir, vocab_map,
token_tag_map, sentence_tag_map, sent_pool='mean', epochs=5, abs_encoder=True, GPU=True):
if GPU:
lwan_model.cuda()
abs_encoder_model.cuda()
san_model.cuda()
min... |
def oneHotEncoder(x, label_size):
x_ = torch.zeros((x.shape[0], label_size))
for i in range(len(x)):
x_[i][x[i].item()] = 1
return x_
def precision_k(true_mat, score_mat, k):
p = np.zeros((k, 1))
rank_mat = np.argsort(score_mat)
backup = np.copy(score_mat)
for k in range(k):
... | The code trains a multi-model system combining Lwan, Transformer, Abstract Transformer, and SAN models for both token and sentence-level tasks. It processes batches of data, computes token and sentence predictions, calculates combined losses, performs backpropagation, and evaluates metrics like precision and NDCG. Afte... | def train(lwan_model, transformer_model, abs_transformer_model, san_model, train_loader, test_loader, criterion, opt,
outputdir, chkptdir, vocab_map, token_tag_map, sentence_tag_map, sent_pool='mean', epochs=5, abs_encoder=False,
GPU=True):
if GPU:
lwan_model.cuda()
abs_transform... |
def maya_main_window():
"""Return the Maya main window widget"""
main_window = omui.MQtUtil.mainWindow()
return wrapInstance(long(main_window), QtWidgets.QWidget)
def create_ui(self):
self.title_lbl = QtWidgets.QLabel("Smart Save")
self.title_lbl.setStyleSheet("font: bold 20px")
self... | This code initializes a Smart Save UI window in Maya, setting its title, size constraints, and removing the context help button. It creates a SceneFile instance and prepares the UI components and their connections for the tool. | def __init__(self):
super(SmartSaveUI, self).__init__(parent=maya_main_window())
self.setWindowTitle("Smart Save")
self.setMinimumWidth(500)
self.setMaximumHeight(200)
self.setWindowFlags(self.windowFlags() ^
QtCore.Qt.WindowContextHelpButtonHint)
... |
def maya_main_window():
"""Return the Maya main window widget"""
main_window = omui.MQtUtil.mainWindow()
return wrapInstance(long(main_window), QtWidgets.QWidget)
def create_ui(self):
self.scatter_instructions = self._create_scatter_instruct()
self.density_sbox = self._create_density_sbox()
... | This code initializes a "Scatter Tool" UI window in Maya, setting its title, size constraints, and removing the context help button. It instantiates a ScatterFX object and calls methods to create the UI layout and establish signal-slot connections for interactivity. | def __init__(self):
super(ScatterToolUI, self).__init__(parent=maya_main_window())
self.setWindowTitle("Scatter Tool")
self.setMinimumWidth(500)
self.setMaximumHeight(300)
self.setWindowFlags(self.windowFlags() ^
QtCore.Qt.WindowContextHelpButtonHint)
... |
def parse_array(arr, sort, sort_arg = 1):
parsed_array = np.array([x.split() for x in arr[1:]], dtype=np.int64)
if sort:
parsed_array = parsed_array[parsed_array[:, sort_arg].argsort()]
return parsed_array
def remap_loop(arr1, arr2):
new_arr = arr1.copy()
i = 0
for s, seed in enumerate(... | The code processes input data through a series of mappings to compute minimum values for two problem parts. It parses seed ranges, applies transformation maps (e.g., seed-to-soil), and iteratively updates values. The first part finds the minimum transformed seed value, while the second part determines the minimum valid... | def p1(v):
time1 = time.perf_counter()
#lns = get_lines(v)
chunks = get_chunks(v)
ans = 0
map_arrays = []
for c, chunk in enumerate(chunks):
if c == 0:
seeds = parse_array(chunk[0].split(), False)
seed_pairs = []
for i,seed in enumerate(seeds[::2]):
... |
def cd(self, pathname=None):
'''ftp server change folder with statement'''
ori_path = self.ftp.pwd()
try:
if pathname is not None:
self.ftp.cwd(pathname)
yield
finally:
self.ftp.cwd(ori_path)
def listdir(self, pathname=None):
''... | This function recursively deletes a directory and all its contents from an FTP server. It changes to the specified directory, iterates through each entry, deletes files directly, and recursively processes subdirectories. Finally, it removes the original directory itself. | def inner_rm(dirname):
with self.cd(dirname):
for entry in self.listdir('.'):
if self.isfile(entry):
self.ftp.delete(entry)
else:
inner_rm(entry)
self.ftp.rmd(dirna... |
def cd(self, pathname=None):
'''ftp server change folder with statement'''
ori_path = self.ftp.pwd()
try:
if pathname is not None:
self.ftp.cwd(pathname)
yield
finally:
self.ftp.cwd(ori_path)
def lcd(self, pathname):
'''local pa... | The function `inner_get` recursively downloads files and directories from a remote directory to a local directory, preserving directory structure. It counts and returns the total number of directories (`dcnt`) and files (`fcnt`) processed, handling each file via `self.get` and creating local directories as needed. | def inner_get(remotedir, localdir):
'''get file / dir recursively'''
with self.cd(remotedir), self.lcd(localdir):
dcnt, fcnt = 0, 0
for name in self.listdir('.'):
if name == '.' or name == '..':
continue
... |
def exists(self, pathname):
'''check if file or folder exist'''
return self.isfile(pathname) or self.isdir(pathname)
def cd(self, pathname=None):
'''ftp server change folder with statement'''
ori_path = self.ftp.pwd()
try:
if pathname is not None:
self... | This function copies non-recursive contents from a remote directory to a local directory, preserving modification times if specified. It creates the local directory if it doesn't exist, verifies the remote directory's existence, and downloads each file individually, returning the count of transferred files. | def get_d(self, remotedir, localdir, preserve_mtime=False):
"""get the contents of remotedir and write to locadir. (non-recursive)
:param str remotedir: the remote directory to copy from (source)
:param str localdir: the local directory to copy to (target)
:param bool preserve_mtime: *D... |
def exists(self, pathname):
'''check if file or folder exist'''
return self.isfile(pathname) or self.isdir(pathname)
def lcd(self, pathname):
'''local path change folder with statement'''
ori_path = os.getcwd()
try:
if pathname is not None:
os.chdir(pa... | The function `put_d` copies files from a local directory to a remote directory, verifying both paths exist. It preserves local file modification times if specified, uploads each file individually, and returns the count of uploaded files. | def put_d(self, localpath, remotepath, preserve_mtime=False):
"""Copies a local directory's contents to a remotepath
:param str localpath: the local path to copy (source)
:param str remotepath:
the remote path to copy to (target)
:param bool preserve_mtime:
*Defa... |
def exists(self, pathname):
'''check if file or folder exist'''
return self.isfile(pathname) or self.isdir(pathname)
def lcd(self, pathname):
'''local path change folder with statement'''
ori_path = os.getcwd()
try:
if pathname is not None:
os.chdir(pa... | The main task of the code is to recursively copy files and directories from a local path to a remote path, preserving modification times if specified. It checks path existence, traverses local files with `os.walk`, uploads files via `self.put`, creates remote directories, and returns counts of copied directories and fi... | def put_r(self, localpath, remotepath, preserve_mtime=False):
"""Recursively copies a local directory's contents to a remotepath
:param str localpath: the local path to copy (source)
:param str remotepath:
the remote path to copy to (target)
:param bool preserve_mtime:
... |
def sample_uniform_sphere(N):
cds = np.random.normal(0,1,(N,3))
normalized_cds = cds/np.reshape(np.sqrt(np.sum(cds**2,axis = 1)),(N,1))
return normalized_cds
def periodic_northsouth_modulated(t,cds, T):
"""
Parameters
----------
t: float
Time index
cds: ndarray(N, 3)
Cart... | The code performs dynamic filtration on a 3D sphere's convex hull, computes persistent homology (H₀ barcodes) for evolving simplicial complexes, and optionally generates an animation visualizing the topological changes over time with color-mapped node weights and barcode diagrams. | def do_example_sphere_filtration(change_param = 5, do_animation = False):
points = sample_uniform_sphere(100)
fig = plt.figure(figsize = (5,5))
ax = Axes3D(fig)
hull = sp.ConvexHull(points)
ax = Axes3D(plt.gcf())
for simplex in hull.simplices:
ax.plot(points[simplex, 0], points[sim... |
def sample_uniform_sphere(N):
cds = np.random.normal(0,1,(N,3))
normalized_cds = cds/np.reshape(np.sqrt(np.sum(cds**2,axis = 1)),(N,1))
return normalized_cds
def periodic_northsouth_modulated(t,cds, T):
"""
Parameters
----------
t: float
Time index
cds: ndarray(N, 3)
Cart... | The code evaluates how varying parameters (tau and dimension) affect topological persistence in a dynamic network built on a spherical point cloud. It computes maximum persistence and persistence differences across parameter combinations, visualizing results in heatmaps to compare their ratios. The analysis aims to und... | def vary_parameters(change_param = 5, lamda=1, phi=linear_phi_fn):
points = sample_uniform_sphere(100)
fig = plt.figure(figsize = (5,5))
ax = Axes3D(fig)
hull = sp.ConvexHull(points)
## Setup Dynamic Network
ts = np.arange(200)
T = 60 # Period
obsfn = lambda t, p: periodic_northsouth_m... |
def parse_args():
"""Parse arguments for running test
:return: parser for args
"""
parser = argparse.ArgumentParser()
parser.add_argument("endpoint", type=str, help="endpoint name for parent stack (str)")
parser.add_argument("region", type=str, help="region deployed in (str) [default: us-e... | The main task of the code is to execute a specified test ("redcap" or "ohdsi") using command-line arguments, retrieve global parameters (USER, PASSW, BUCKET), generate test outputs, and handle exceptions. It writes results to a JSON file, prints terminal output, and exits with an error if failures occur. The code ensur... | def main(args):
args = parse_args()
# set global values here, not to be altered elsewhere
global USER
global PASSW
USER = args.user
PASSW = args.passw
global BUCKET
BUCKET = args.bucket
filename = "test_output_" + args.region + ".json"
# exceptions raised in this file will be ... |
def init():
global altimeter
global imu
global duty_span
global file
global i2c
# create sensor object, communicating via default I2C bus
i2c = board.I2C()
## SD card logger setup
# construct completed file location
completedName = os.path.join(savePath, fileName)
# create a new file
file = open(complete... | The code monitors a vehicle's flight phases (on pad, boost, glide, apogee) using IMU and altimeter data. It detects liftoff, tracks apogee altitude, manages deployment angles via servo actuation, handles sensor failures with resets, and logs status to an SD card. The system transitions between flight states based on ac... | def main():
global start_time
global imu_fail
global alti_fail
global altimeter
global imu
start_time = time.time()
try:
status = init()
except Exception as err:
SDwrite(str(err))
## altimeter initial reading and altitude setup
on_PAD_altitude = 0
on_PAD_fail = False
if not alti_Setup_fail:
try:
... |
def get_custom_actions_data(dir):
# read all json files in custom folder
list = []
with scandir(dir) as folder:
for f in folder:
if f.name.endswith(".json") and f.is_file() and f.name != "group.json":
try_save_url(f.path)
list.append(json_file_to_dict(f)... | This function generates a list of `ExtensionResultItem` objects from custom action data. It uses a specified directory to fetch actions, replaces default icons with custom ones if defined, and creates items with names, descriptions, and processed actions. The result is a list of extension items for display or execution... | def gen_list_custom_actions(dir=ACTIONS_FOLDER, actions_list=None):
if actions_list == None: actions_list=get_custom_actions_data(dir)
items = []
for ac in actions_list:
icon_path = EXTENSION_ICON_FILE
# check if icon is defined
if 'icon' in ac:
icon_path=replace_ICON_FI... |
def division_holidays():
field_days = {}
conn = create_db_conn()
if conn is not None:
query = "SELECT division,week_holiday,additionaloff FROM week_holidaymaster{} WHERE deleted=0".format(suffix)
conn.execute(query)
result = conn.fetchall()
#division - 0 means rest of the div... | The main task of the code is to retrieve division-wise holiday data, generate individual summaries based on this data, create nudges (likely reminders or notifications), and return a success status (True). The function orchestrates data processing and action generation for holiday-related tasks. | def main():
division_wise_off = division_holidays()
#print(division_wise_off)
summary = individual_summary(division_wise_off)
create_nudges()
#print(summary)
return True |
def GoldHunt():
# Create the window
win = GraphWin('GoldHunt', 480, 520, autoflush=False)
# Create and display black recatngle for
rclabel = Rectangle(Point(0, 0), Point(480, 40))
rclabel.setFill('black')
rclabel.draw(win)
# Display round label
rounds = Text(Point(60, 20), 'Round: 0')... | This code implements a game where players click on circles to find a gold circle, tracking clicks and rounds. It initializes game windows, handles user input for names, manages game rounds with circle interactions, updates scores, and saves high scores to a file. The game includes sound effects, loop controls, and exit... | def main():
# Call GoldHunt and GameControl functions and assign appropriate variables
ghwin, rounds, clicks = GoldHunt()
playername, controlwin = GameControl()
# Intialize variables for while loops and round counts
playing = True
click = None
roundn = 0
clickcount = 0
# Play backg... |
def predict(model, X_partitions, y_partitions, scaler_y, additional_data=[]):
(X_train, X_val, X_test) = X_partitions
(y_train, y_val, y_test) = y_partitions
X = np.concatenate((X_train, X_val, X_test), axis=1)
y = np.concatenate((y_train, y_val, y_test), axis=1)
y_inverse = scaler_y.inverse_trans... | The main task of the code is to generate predictions using a model and a naive baseline, evaluate their performance on train/validation/test datasets, plot results, and save evaluation metrics in JSON files. It handles both price and change output features, transforming predictions if needed, and compares model perform... | def predict_plots(model,
X_partitions,
y_partitions,
output_feature,
reference_feature,
scaler_y,
stocklist,
directory,
additional_data=[]):
(result_train, result_val, resu... |
def unroll_curve(curve, delta_t=0.1):
"""
Unrolling curve from the sphere to a series of points in the plane and the rotation requiered
to make the unrolling.
Parameters
----------
curve : S2Curve object
Base curve with respect we are going to create an unrolled version
delta_... | This function constructs a smooth curve fitting spherical points by iteratively unrolling them onto a 2D plane, fitting 2D splines with specified smoothing, and re-rolling back to the sphere. It handles reference hemispheres, weights, and convergence tolerance to refine the fit. The output provides the time series and ... | def spherical_spline(times,
knot_values,
smoothing,
precision=0.1,
ode_stepsize=0.01,
n_iter=5,
tol=0.001,
weights=None,
fix_origin=True,
... |
def download_data(self, link):
# create youtube object
try:
yt = YouTube(link)
except VideoUnavailable:
print(f'Video {link} is unavailable, skipping.')
else:
if not self.data_dict[link]:
# save video title
video_title = self.parse_title(yt.title)
try:
mkdir(join(self.dataset_path, v... | The main task of the code is to iterate through links stored in `self.data_dict`, download data for each link using `download_data()`, pause execution for 5 seconds with `time.sleep(5)`, and then print directory structures via `print_directories()` and save the dictionary state with `save_dict()`.) | def begin_downloading(self):
for i, link in enumerate(self.data_dict.keys()):
self.download_data(link)
time.sleep(5)
self.print_directories()
self.save_dict() |
def filter_training(df, true_class, labelCol, labelFunction,
nPresentPos, nAbsentPos, nPresentNeg, nAbsentNeg):
# dfCopy = df.copy()
dfCopy = df
dfCopy['labelPos'] = df[labelCol].apply(lambda x: labelFunction(x, true_class))
dfPresentPos = dfCopy[(dfCopy['labelPos']==True) &
... | The function generates filtered training and test datasets for fine-tuning, applying bias control via parameters like `bias_strength` and `train_size`. It creates both simple and advanced dataset versions, saves them if specified, and returns four datasets: two training (biased/unbiased) and two test sets, tailored for... | def get_prompt_datasets(args, true_class, unbiased_train, train_10k, test_df, label_col, unbiased = False, save = True):
if unbiased:
filteredDf = unbiased_train
else:
present_positive, absent_positive, present_negative, absent_negative = \
int(args.train_size*args.bias_strength//2),... |
def foreign_keys(model):
return [column.name for column in foreign_key_columns(model)]
def _serialize_many(self, columns, result_set, expand = None, serialize_rel = False):
"""Called internally from __call__ if list of object need to be serialized
:param columns: Resource database table col... | This method serializes SQLAlchemy result sets (single or list) into structured data, handling fields selection, exclusion, expansion of related resources, and primary key inclusion. It determines model columns, filters attributes based on parameters, and delegates serialization to _serialize_one or _serialize_many, ens... | def __call__(self, result_set, fields = None, exclude = None, expand = None, serialize_rel = True):
"""Callable for Serializer class. Can serialize list and single instance of SQLAlchemy
resutlset objects.
Example:
.. code-block:: python
serializer = resou... |
def check_installed(self, ctx: Context):
"""Check that the toolchain for nRF connect SDK is installed"""
if not is_linux():
# Windows has a toolchain archive - make sure it has been downloaded
if not self.check_windows_toolchain(ctx):
return False
# Check... | The code installs the nRF Connect SDK by checking if the package directory exists, prompting removal if needed, ensuring Windows toolchain installation on non-Linux systems, creating the directory, and using `west` commands to initialize and update the SDK to the specified version. | def install(self, ctx: Context):
"""Install nRF connect SDK"""
if self.check_installed(ctx):
print(f"{self.package_dir} already exists")
if not u_pkg_utils.question("Do you want to remove the directory and re-install?"):
raise UAbortedException
shutil.... |
def add_rooms(self):
"""
This kicks off the main stage of generation. Note that we're not
touching the world matrix yet, we're just creating a list of Room
objects.
"""
starting_room_and_axis = self.create_starting_rooms()
self.rooms_to_bud.extend(starting_room_an... | The main task of the code is to generate a world layout by placing rooms, calculating their total floor space, and ensuring it meets the required size. If the space is insufficient, it exits early. Otherwise, it carves rooms into the world grid, marks tiles for visual/structural purposes, adds walls, and places doors t... | def generate_world(self, required_floor_space: int):
"""
This function is one full generation attempt.
"""
# Place all the rooms.
self.add_rooms()
# Now we calculate initial floorspace before adding the walls
for room in self.rooms:
self.floor_space +... |
def reset(self) -> None:
"""If at first you don't succeeed..."""
self.world = [
[Tile(x, y, self.width, self.height) for x in range(self.width)]
for y in range(self.height)
]
self.floor_space = 0
self.rooms = []
def generate_world(self, required_floor_spac... | The code repeatedly generates maps until one meets the required floor space and is fully pathable, using a brute-force approach. It resets, increments attempts, and checks conditions, breaking only when valid. Parameters control max tries and floor space, with caution against high values causing excessive computation. | def try_generation(self, max_tries=-1, required_floor_space=500):
"""
Repeatedly tries the generation until it creates a fully pathable map
with the required floor space. Fun fact: this is what Diablo 1 actually
did! Who needs fancy algorithms that get things right on the first try
... |
def messageFormat(ty, data):
dic = {"type": ty,
"data": data}
return dic
def paySmall(net):
global curPlayer
#player hasn't bet and is small.
if (curPlayer.bet == -1 and curPlayer.isSmall):
msg = messageFormat("blinds", None)
small_blind = net.send(msg)["data"][0]
... | This code initializes a multiplayer game client by setting up network communication, registering a new player, and managing game state updates. It handles player input for betting/folding decisions during their turn, updates player data from the server, and redraws the game window with current information. The loop pro... | def main():
name = ""
global playerIndex
global curPlayer
global restart
run = True
#initiates network communication
n = Network()
p = n.getP()
#initiates player information.
curPlayer = Player(0, 0, name)
playerMSG = messageFormat("new_player", curPlayer)
playe... |
def open_output(self, path: Any) -> None:
output_directory = os.path.dirname(path)
file = os.path.join(output_directory, os.path.basename(path))
try:
os.mkdir(output_directory)
except OSError:
pass
self.output_file = open(file.replace(".hack", ".out"), "w"... | This code initializes a CPU simulator by loading program instructions from a file, setting up CPU registers and memory, and executing a specified number of cycles. It opens an output file, runs the simulation, then closes the output. The main task is to simulate CPU operations based on input instructions over defined c... | def __init__(self, file_path: Any, num_cycles: int) -> None:
# ROM and helpers
file: Any = open(file_path, "r")
self.lines: Any = file.readlines()
self.num_cycles: int = num_cycles
self.been: Any = [False] * NUM_REGISTERS
# CPU
self.ram: Any = [0] * NUM_REGISTERS... |
def process_file(file_contents: list) -> tuple[DataFrame, DataFrame]:
temp_for_valid = []
temp_for_invalid = []
reader = csv.DictReader(file_contents)
for line in reader:
if validate_line(line):
temp_for_valid.append(line)
else:
temp_for_invalid.append(line)
... | The code processes a file from a Google Cloud Storage (GCS) bucket by downloading its contents, splitting them into valid and invalid dataframes using `process_file`, and then uploading these dataframes to a designated processed-data bucket in GCS for further use. | def process_data(event, context):
bucket_name = event["bucket"]
client = storage.Client()
bucket = client.bucket(bucket_name)
gcs_file = bucket.get_blob(FILE_NAME)
file_contents = gcs_file.download_as_string().decode("utf-8").splitlines()
valid_df, invalid_df = process_file(file_contents)
... |
def send_encrypted_operation(self, encrypted_operation: ProtectedOperation):
# assumes we already encrypted the data
data = encrypted_operation.json()
encrypted_data = encrypt(bitset.from_number(self.sessionKey), data)
mac = GenerateHMAC(encrypted_data, self.sessionKey)
packet = ... | The code verifies an account by encrypting session key and account data, sending it for validation, checking the response's validity, and binding public-private keys if valid. | def verify_account(self, account):
p_op = ProtectedOperation.parse_obj(
{'id': ProtectedOperationIds.VERIFY, 'data': encrypt(bitset.from_number(self.sessionKey), account),
'nonce': randint(0, 2 ** 128)})
self.send_encrypted_operation(p_op)
response_p_op = self.receive_en... |
def get_wikidata_property_from_id(pid):
try:
entity_dict = ldi.get_entity_dict_from_api(pid)
except Exception as e:
traceback.print_exc()
print(e)
return None
return WikidataProperty(entity_dict)
def _check_if_in_exclude_list(property_label):
if not property_label:
... | The main task of the code is to construct structured prompts and property relationships for entities by analyzing their interconnections. It categorizes properties (mutual, subject-as-object, target-related) from related entities, generates descriptive prompts, and prepares ground truth data for training or inference. ... | def construct_entity_properties(
original_entity,
related_entity_dicts,
ent_property_label_map,
target_true
):
coupled_entities = []
for related_entity_dict in related_entity_dicts:
property_id_label_map = {}
mutual_properties = set()
subject_as_object = set()
tar... |
def get_wikidata_item_from_label(label):
try:
results = return_sparql_query_results(LABEL_TO_QID.format(label))['results']
if not results['bindings']:
return None
qid = results['bindings'][0]['item']['value']
except Exception as e:
traceback.print_exc()
print(... | This function retrieves and processes Wikidata entities related to a subject and target, identifying coupled entities with overlapping properties. It filters entities, maps property claims, calculates overlaps, ranks entities by relevance, and constructs prompts based on shared attributes between the subject, target, a... | def get_coupled_prompts_and_properties(
subject,
target_true
):
ent = get_wikidata_item_from_label(subject)
if ent is None:
# print(f'Could not find entity for {subject}')
return None
target_ent = get_wikidata_item_from_label(target_true)
if target_ent is None:
# print(f'... |
def process_label(labels: list, mask:list, onehot=True):
"""
turns a list of labels ['HEECCC', 'HHHEEEECCC'] to one hot encoded tensor
and add padding e.g torch.tensor([[1, 0, 0], [0, 0, 1], [0, 0, 0]])
"""
max_len = len(max(labels, key=len)) # determine longest sequence in list
processed = []
if onehot:... | This function validates a neural network model on a dataset by computing average loss and accuracy. It uses cross-entropy loss with padding ignored, evaluates per-sequence accuracy with masking, and returns the mean accuracy and loss across all validation batches. | def validate(model: torch.nn.Module,
val_data: DataLoader):
model.eval()
loss_fn = nn.CrossEntropyLoss(ignore_index=-1)
last_accuracy = 0
losses = []
for i, batch in enumerate(val_data):
emb, label, mask = batch
out = model(emb) # shape: [bs, max_seq_len, 3]
# string... |
def process_labels(labels: list, mask:list, onehot=False):
"""
turns a list of labels labels and adds padding
labels: example: ['HEECCC', 'HHHEEEECCC']
"""
max_len = len(max(labels, key=len)) # determine longest sequence in list
processed = []
processed = [[CLASS_MAPPING[c] for c in label] for label in la... | The main task of the code is to evaluate the performance of a language model (lm) and an inference model (inf_model) on a validation dataset. It calculates average accuracy, language model loss, and inference loss across validation batches, using a specified loss function and model type. The function returns these metr... | def validate(lm: torch.nn.Module,
inf_model: torch.nn.Module,
val_data: DataLoader,
loss_fn,
model_type):
lm.eval()
inf_model.eval()
last_accuracy = 0
total_inf_loss = 0
total_lm_loss = 0
count = 0
sum_accuracy = 0
acc_score_list = []
... |
def process_labels(labels: list, mask:list, onehot=False):
"""
turns a list of labels labels and adds padding
labels: example: ['HEECCC', 'HHHEEEECCC']
"""
max_len = len(max(labels, key=len)) # determine longest sequence in list
processed = []
processed = [[CLASS_MAPPING[c] for c in label] for label in la... | The code evaluates the performance of an inference model (`inf_model`) using embeddings from a language model (`lm`) on a test dataset. It computes accuracy and loss metrics by comparing predicted labels (from `inf_model`) against true labels, applying masks to ignore padding. The function returns the average accuracy ... | def test(lm: torch.nn.Module,
inf_model: torch.nn.Module,
test_data: DataLoader,
verbose=False):
"""
verbose argument: whether or not to show actual predictions
"""
lm.eval()
inf_model.eval()
acc_scores = []
last_accuracy = 0
total_inf_loss = 0
total_l... |
def process_labels(labels: list, mask:list, onehot=True):
"""
turns a list of labels ['HEECCC', 'HHHEEEECCC'] to one hot encoded tensor
and add padding e.g torch.tensor([[1, 0, 0], [0, 0, 1], [0, 0, 0]])
"""
max_len = len(max(labels, key=len)) # determine longest sequence in list
processed = []
if onehot... | The function evaluates a model's accuracy on a test dataset. It processes each batch, computes per-sequence accuracy using custom functions, and returns the mean and standard deviation of accuracy scores. If `verbose` is True, it prints predictions, true labels, and individual accuracy for each sequence. The model oper... | def test(model: torch.nn.Module,
test_data: DataLoader,
verbose=False):
"""
verbose argument: whether or not to show actual predictions
"""
model.eval()
acc_scores = []
for i, batch in enumerate(test_data):
ids, label, mask = batch
labels_f = process_labels(label,... |
def process_labels(labels: list, mask:list, onehot=False):
"""
turns a list of labels ['HEECCC', 'HHHEEEECCC'] labels and adds padding
"""
max_len = len(max(labels, key=len)) # determine longest sequence in list
processed = []
processed = [[CLASS_MAPPING[c] for c in label] for label in labels]
# add mask
... | The function `validate` evaluates a PyTorch model on a validation dataset, computing both the average loss and accuracy. It processes each batch, calculates the model's output, reshapes it for loss computation, and accumulates the loss. For accuracy, it processes individual sequences, compares predicted labels with tru... | def validate(model: torch.nn.Module,
val_data: DataLoader,
loss_fn):
model.eval()
last_accuracy = 0
total_loss = 0
count = 0
sum_accuracy = 0
for i, batch in enumerate(val_data):
ids, label, mask = batch
labels_f = process_labels(label, mask=mask, onehot=Fal... |
def process_labels(labels: list, mask:list, onehot=False):
"""
turns a list of labels ['HEECCC', 'HHHEEEECCC'] labels and adds padding
"""
max_len = len(max(labels, key=len)) # determine longest sequence in list
processed = []
processed = [[CLASS_MAPPING[c] for c in label] for label in labels]
# add mask
... | The function evaluates a model's performance on a test dataset by calculating sequence-level accuracy. It processes each batch, computes predictions, compares them to true labels using a custom accuracy metric, and aggregates results. If verbose, it prints per-batch details like masks, predictions, and accuracy. Finall... | def test(model: torch.nn.Module,
test_data: DataLoader,
verbose=False):
"""
verbose argument: whether or not to show actual predictions
"""
model.eval()
acc_scores = []
for i, batch in enumerate(test_data):
ids, label, mask = batch
labels_f = process_labels(label,... |
def get_dataloader(jsonl_path: str, batch_size: int, device: torch.device,
seed: int, max_emb_size: int, tokenizer=None, masking=0, max_samples=-1) -> DataLoader:
torch.manual_seed(seed)
dataset = SequenceDataset(jsonl_path=jsonl_path,
device=device,
... | The code trains a language model (LM) and an inference model (inf_model) using a combined loss function. It supports single or dual optimizers, processes batches with masking, computes LM and inf_loss, and performs gradient accumulation. Periodic validation logs accuracy, loss, and embedding comparisons. The goal is to... | def train(lm: torch.nn.Module,
inf_model: torch.nn.Module,
train_data: DataLoader,
loss_fn,
optimizer,
grad_accum,
optimizer_lm=None,
optimizer_inf=None,
mixed=False,
valstep=100,
valsize=-1,
val_path=None,
... |
def train(model: torch.nn.Module,
train_data: DataLoader,
loss_fn,
optimizer,
grad_accum):
"""
do a train on a minibatch
"""
model.train()
optimizer.zero_grad()
total_loss = 0
count = 0
# batch accumulation parameter
accum_iter = grad_accum
... | The main task of the code is to train and validate a neural network model using specified hyperparameters and optimizers. It initializes the chosen optimizer, iterates through epochs, trains the model on the training data, validates on the validation set, tracks the best validation loss and accuracy, saves the model if... | def main_training_loop(model: torch.nn.Module,
train_data: DataLoader,
val_data: DataLoader,
batch_size: int,
lr: float,
epochs: int,
grad_accum: int,
optim... |
def train(lm: torch.nn.Module,
inf_model: torch.nn.Module,
train_data: DataLoader,
loss_fn,
optimizer,
grad_accum,
optimizer_lm=None,
optimizer_inf=None,
mixed=False,
valstep=100,
valsize=-1,
val_path=None,
... | This function trains a language model (lm) and an inference model (inf_model) using specified optimizers (Adam, Adafactor, or mixed), performing gradient accumulation, validation, and model freezing. It tracks validation loss and accuracy, saving checkpoints when performance improves. Training stops if validation metri... | def main_training_loop(lm: torch.nn.Module, # Language model
inf_model: torch.nn.Module, # inferece model for downstream
train_data: DataLoader,
val_data: DataLoader,
batch_size: int,
lr: float,
... |
def launch_enemy(self):
if Block.game_active and Block.count_enemies < gameRestart.num_of_enemies:
Block.count_enemies += 1
self.speed_x = random.randint(-Enemy.speed_zone, Enemy.speed_zone)
self.speed_y = random.randint(-Enemy.speed_zone, Enemy.speed_zone)
self.s... | This code updates an object's position based on its speed, reverses direction upon hitting screen edges, launches enemies, increases speed over time, checks for player collision to trigger a restart, and draws the object. | def update(self):
self.rect.x += self.speed_x
self.rect.y += self.speed_y
if self.rect.top <= 0 or self.rect.bottom >= screen_height:
self.speed_y *= -1
if self.rect.left <= 0 or self.rect.right >= screen_width:
self.speed_x *= -1
self.launch_enemy()
... |
def getObject(request):
log.info("GetObject Called")
try:
q = Qry()
obj = q.executeQry( request )
except Exception as e:
log.error("getObject error:" + str(e) )
raise
log.info("GetObject Called ended")
return obj
def addObject(request):
log.info("AddObjec... | The code processes a request by routing it to specific database operations (get, add, update, delete) based on the 'action' parameter. It extracts service, database, action, and data from the input, logs details, and delegates to functions like getObject(), addObject(), etc. Special cases like 'createUser' and 'deleteU... | def processRequest(req):
service = req["service"] #always cheneque
database = req["database"]
action = req["action"] # get put(insert else update) remove
data = req["data"]
log.debug("processRequest service:%s database:%s action:%s data:%s", service, database, action, data )
if action == "get... |
def addDocuments(obj):
result = None
try:
transaction = db.transaction()
for collectionId in obj:
data = obj[collectionId]
if isinstance(data, list):
result = []
#this is a multiple insert
for element in data:
... | This function processes Firestore operations by routing requests based on the 'action' parameter. It handles adding, deleting, retrieving, updating documents/subcollections, array operations, and index moves by calling corresponding handler functions. It raises an exception for unrecognized actions. | def processRequest(req):
log.debug("firestore processRequest has been called")
collection = req["database"]
obj = req["data"]
action = req["action"]
if action == "add":
#validateToken( req )
return addDocuments( obj )
elif action == "addSubCollection":
return addSubColl... |
def create_keydict(self):
k = {"alphabet":[],"nalphabet":[]}
alphabet = """ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%¨&*(-)+='{,<}.>^~;/?\|§" _"""
alphabet = self.string_to_list(alphabet)
k['alphabet'] = alphabet
self.dkey = k
def random_gen(self,list_key:list,dict_type:str)-> str... | The main task of the code is to generate a dictionary mapping characters from `self.dkey['alphabet']` to unique random keys, ensuring no duplicates. It checks if the alphabet exists, creates it if missing, then iterates through each character, generating and validating random keys, and populates the dictionary with bid... | def get_dict(self) -> dict:
"""Gen the key dictionaire"""
try: # Check if alphabet exists
self.dkey['alphabet'].count()
except:
self.create_keydict()
alpha = {}
already = []
size_of = 0
for ltr in self.dkey['alphabet']:
if not ... |
def check_key(self)->bool:
"""Check if key already exists"""
if path.exists('key.key'):
if open('key.key','r+').read() in [""," ", None, self.ver]:
return False
else:
return True
else:
return False
def create_keyfile(self):
... | The code's main task is to check for the existence of an encryption key. If the key is missing or corrupted, it generates a new key, stores it in a file, and loads it into `self.rdkey`. If the key exists, it loads it directly into `self.rdkey` and confirms its presence. The process ensures a valid key is available for ... | def start(self):
if not self.check_key():
print("pyEncrypt > (create key file or key corrupted generating other.)")
self.create_keyfile()
self.rdkey = self.get_dict()
self.write_keyfile()
else:
print("pyEncrypt > Key exists!")
self.... |
def get_name_list(text):
html = parse_text(text)
given_names = html.find_all("span", itemprop="givenName")
family_names = html.find_all("span", itemprop="familyName")
names = zip(given_names, family_names)
full_names = list()
for name in names:
given_name = clean_string(name[0].string)
... | The code extracts names, addresses, and phone numbers from input text, initializes a similarity list with zeros, and combines them into structured database rows as tuples. Each row contains a name, address, phone number, and a similarity score (initially zero), preparing data for potential later processing or matching ... | def get_database_rows(text):
names = get_name_list(text)
addresses = get_address_list(text)
phone_numbers = get_phone_numbers(text)
similarities = [0] * len(names)
database_rows = zip(names, addresses, phone_numbers, similarities)
return list(database_rows) |
def validateQuery(self, incoming_order: OrderHandler):
"""validateQuery
Description
-----------
This method check if order from stream is valid.
Parameters
----------
incoming_order : OrderHandler
An order to be checked.
Raises
------... | This code processes incoming trade orders by validating, handling, and matching buy/sell orders. It maintains order books (asks/bids), updates trade statuses, and executes matches when price conditions are met. Transactions are recorded and printed if any, ensuring order flow is processed and tracked efficiently. | def __init__(self, incoming_orders: HM) -> None:
"""__init__
Description
-----------
Class for processing new trade and set new trade status.
Parameters
----------
incoming_orders : HM
Hash Map of hash maps that represents flow of trades.
"""
... |
def find_legal_moves(self, board_state, player):
# This should include a previous move
legal_moves = []
# Count unassigned cells
for k, v in board_state.items():
if v['owner'] == '':
# Create a dictionary for each key that is empty, assigning a new spot to AI
... | The main task of the code is to determine the AI's optimal move using the minimax algorithm, apply the selected move to the game board, check for a win or draw, and reset the game with appropriate outcomes like "AI won!" or "It's a draw!". The function evaluates legal moves, selects the best one via minimax, updates th... | def AI_turn(self):
moves = self.find_legal_moves(self.cells, self.AI)
score = -inf
for move in moves:
minimax = self.minimax(move, len(moves)-1, False)
if minimax >= score:
score = minimax
best_move = move
try:
for k, v ... |
def assess_win(self, board_state):
for path in self.win_paths(board_state):
if len(set(path)) == 1 and '' not in path: # path is occupied by the same 3 symbols
return True, path[0]
return False, ''
def reset(self, condition):
answer = askretrycancel(title='GAME OVER!... | This function handles a player's turn in a game by assigning their symbol to a selected cell, updating the cell's button appearance, and checking for a win. If the player wins, the game resets with a win message; otherwise, the AI takes its turn. | def player_turn(self, index):
# player makes a selection, assign player as new button owner
if self.cells[f"cell{index}"]['owner'] == '':
self.cells[f"cell{index}"]['owner'] = self.player
self.cells[f"cell{index}"]['button']['text'] = self.player.upper()
self.cells[f"... |
def insert_space(self, row, column):
Label(self, text=' ').grid(row=row, column=column)
def player_choice(self, choice):
# Highlights pressed button green, saves value to self.player, highlights the other one red
choices = ['x', 'o']
choices.remove(choice)
self.AI = choices[0... | The code creates a GUI layout for a Tic-Tac-Toe game, inserting a greeting label, buttons for player symbol selection (X/O), and spacing elements. It initializes UI components like labels, buttons, and the game board, setting up the interface for user interaction and game setup. | def create_layout(self):
i = 0
self.insert_space(i, 0)
greeting = Label(self, text=f"Hi! Let's play Tic-Tac-Toe!\nDo you want to play")
greeting.grid(row=1, column=1, columnspan=self.dimension)
self.insert_space(1, self.dimension+1)
self.choices['x'] = Button(self,
... |
def _handle_input(self):
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
quit()
elif (self.spaceship and event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE):
self.... | The main task of the code is to execute a continuous game loop that plays audio, handles user input, updates game logic, and renders visuals in an infinite cycle. The loop starts by playing the jukebox, then repeatedly processes input, updates game state, and draws the game until terminated. | def main_loop(self):
self.jukebox.play()
while True:
self._handle_input()
self._process_game_logic()
self._draw() |
def getChainInfo(self, init=False):
try:
conn = http.client.HTTPConnection(self.node_host, self.node_port)
conn.request('GET', '/info')
response = conn.getresponse()
data = response.read().decode()
info = json.loads(data)
conn.close()
... | The main task of the code is to initiate a mining process by starting a thread to periodically fetch blockchain data. It enters a loop to continuously retrieve chain information, load parameters like difficulty and block reward, gather transactions, assemble a block template, and mine it until instructed to stop. The t... | def startMiner(self):
self.stop_threads = False
self.pollT = threading.Thread(target=self.pollChainInfo)
self.pollT.start()
chain_info = self.getChainInfo(True)
while not self.stop_threads:
chain_info = self.getChainInfo()
if chain_info is None:
... |
def create_srt(transcriptions):
# Initialize an empty list to store the SRT subtitles
subtitles = []
# Loop through each transcription
for i, (start, end, text) in enumerate(transcriptions):
# Create a SRT subtitle object with the index, start time, end time and text
subtitle = srt.Subtitle(index=i+1, ... | The main task of the code is to add subtitles to a video file by generating an SRT file from the video's segments, merging it with the original video using ffmpeg, and returning the subtitled video as an in-memory object while cleaning up temporary files. | def subtitle(path):
# Save the SRT file with the same name as the original file but with .srt extension
srt_path = path.rsplit(".", 1)[0] + ".srt"
with open(srt_path, "w") as f:
f.write(create_srt(transcribe_segments(get_file_segments(path))))
# Generate new path for subtitled file with same name as origin... |
def run_mapper(data_array, col_names, interval, overlap, dbscan_eps, dbscan_min_samples, filter_function, filter_parameters=None):
"""This function is called when the form is submitted. It triggers construction of Mapper.
Each parameter of this function is defined in the configuration.
To cus... | The main task of the code is to process input data for a Mapper algorithm, applying normalization, computing topological features (ph0/ph1), and generating subgraphs for selected variables. It loads data, filters columns, runs Mapper with parameters like interval/overlap, and returns results as JSON, including subgraph... | def get_graph():
mapper_data = request.form.get('data')
mapper_data = json.loads(mapper_data)
selected_cols = mapper_data['cols']
all_cols = mapper_data['all_cols'] # all numerical cols
categorical_cols = mapper_data['categorical_cols']
data = pd.read_csv(APP_STATIC+"/uploads/processed_data.csv"... |
def _color_function(member_ids, color_function):
return np.mean(color_function[member_ids])
def _type_node():
return "circle"
def _size_node(member_ids):
return int(np.log(len(member_ids) + 1) + 1)
def _format_tooltip(
env,
member_ids,
custom_tooltips,
X,
X_names,
lens,
lens_name... | The function converts graph data into a structured JSON format for visualization, mapping nodes with attributes (color, size, tooltips) and links with source-target relationships and widths. It processes nodes and links from the input graph, applies custom functions to determine properties, and returns a JSON-ready dic... | def format_mapper_data(
graph, color_function, X, X_names, lens, lens_names, custom_tooltips, env, nbins=10
):
# import pdb; pdb.set_trace()
json_dict = {"nodes": [], "links": []}
node_id_to_num = {}
for i, (node_id, member_ids) in enumerate(graph["nodes"].items()):
node_id_to_num[node_id] =... |
def getAllKeys(self):
try:
allkeys=[]
for i in range(self.count):
allkeys.append(self.getAllKeysByRedis(self.rd[i]))
return allkeys
except:
return []
def whichRedisIsDown(self,keysList):
mink=min(keysList)
index=keysList.index(mink)
if len(set(keysList)) == 1:
r... | This code synchronizes Redis instances after a node heals by identifying keys in the union of all sets but not in the intersection. It detects the down node, retrieves data from other nodes using zrange, and merges them into the healed node's Redis via a pipeline transaction. If all nodes are up, it executes the merge,... | def mergeRedisAfterHeal(self):
try:
allKeys=self.getAllKeys()
setList=[]
keysLen=[]
for keys in allKeys:
setList.append(set(keys))
keysLen.append(len(keys))
inter=set.union(*setList).difference(set.intersection(*setList))
downIndex=self.whichRedisIsD... |
def mergeRedisAfterHeal(self):
try:
allKeys=self.getAllKeys()
setList=[]
keysLen=[]
for keys in allKeys:
setList.append(set(keys))
keysLen.append(len(keys))
inter=set.union(*setList).difference(set.intersection(*setList))
downIndex=self.whichRedisIsD... | The function retrieves the top `n` words from a Redis instance, bypassing a potentially down server. If `repair` is True, it first merges Redis data. It identifies the active Redis node, fetches the top key, and returns the highest-ranked words using `zrevrange`. | def get_top_words(self, n: int,
repair: bool = False) -> List[Tuple[str, int]]:
if repair:
self.mergeRedisAfterHeal()
words=[]
allKeys=self.getAllKeys()
setList=[]
keysLen=[]
for keys in allKeys:
setList.append(set(keys))
keysLen.append(len(keys))
down... |
def get_browsers():
"""
very very hardcoded/dirty re/split stuff, but no dependencies
"""
html = get(settings.BROWSERS_STATS_PAGE)
html = html.decode('windows-1252')
html = html.split('<table class="w3-table-all notranslate">')[1]
html = html.split('</table>')[0]
pattern = r'\.asp">(.+?... | The code loads browser data, processes their names by replacing specified values and normalizing them, creates a weighted randomization list based on percentages, validates the structure of the resulting data, and returns a dictionary containing browser versions and randomized entries for user agent generation. | def load():
browsers_dict = {}
randomize_dict = {}
try:
for item in get_browsers():
browser, percent = item
browser_key = browser
for value, replacement in settings.REPLACEMENTS.items():
browser_key = browser_key.replace(value, replacement)
... |
def rm(path):
if exist(path):
os.remove(path)
def write(path, data):
with io.open(path, encoding='utf-8', mode='wt') as fp:
dumped = json.dumps(data)
if not isinstance(dumped, text):
dumped = dumped.decode('utf-8')
fp.write(dumped)
def load():
browsers_dict = {}... | The code's main task is to delete the file/directory at the specified path and then rewrite it with the output of the `load()` function. This effectively replaces the existing content at the given path with newly loaded data. | def update(path):
rm(path)
write(path, load()) |
def exist(path):
return os.path.isfile(path)
def update(path):
rm(path)
write(path, load())
def read(path):
with io.open(path, encoding='utf-8', mode='rt') as fp:
return json.loads(fp.read()) | The function `load_cached` checks if a file at the specified path exists. If not, it updates the file. Then, it reads and returns the content of the file, ensuring data is either loaded from an existing cache or freshly updated before retrieval. | def load_cached(path):
if not exist(path):
update(path)
return read(path) |
def getWH(shape):
return np.array(shape[1::-1]).astype(float)
def normal(pts, side, mn, MN):
pts_MN_center_mn = pts * side
pts_MN = pts_MN_center_mn + mn.reshape((2, 1))
pts_prop = pts_MN / MN.reshape((2, 1))
return pts_prop
def nms(Labels, iou_threshold=0.5):
SelectedLabels = []
Labels.sort... | This code reconstructs license plate (LP) regions from neural network outputs by applying affine transformations to detected points, normalizing coordinates, performing non-max suppression (NMS) for overlapping detections, and warping the original image to extract LPs in specified sizes (one-line or two-line) based on ... | def reconstruct(I, Iresized, Yr, lp_threshold):
# 4 max-pooling layers, stride = 2
net_stride = 2 ** 4
side = ((208 + 40) / 2) / net_stride
# one line and two lines license plate size
one_line = (470, 110)
two_lines = (280, 200)
Probs = Yr[..., 0]
Affines = Yr[..., 2:]
xx, yy = n... |
def get_plate(img_path, max_dim=608, min_dim=256):
img = preprocess_image(img_path)
aspect_ratio = float(max(img.shape[:2])) / min(img.shape[:2])
new_side = int(aspect_ratio * min_dim)
final_dim = min(new_side, max_dim)
_, plate_img, plate_type, coords = detect_lp(wpod_net, img, final_dim, lp_thresh... | The code detects a license plate in an image, preprocesses it (grayscale, blur, thresholding), and uses either a Mobile-Nets model or PyTesseract OCR to recognize characters. It crops and resizes detected characters for model input or applies OCR with whitelist constraints, returning the final plate number string. | def detect_plate(input_img):
# detection
# get plate coordinate from input
try:
plate_img, plate_type, cor = get_plate(input_img)
except AssertionError:
return ""
# image preprocessing
# scales the detected license plate and converts it to 8-bit image
plate_image = cv2.conve... |
def sleeping_stage(api):
market_close_flag = True
while datetime.datetime.now().hour < 4:
time.sleep(7200) # Sleeps for 2 hours
while datetime.datetime.now().hour < 13: # set to 5 for local machine 13 for cloud
time.sleep(1200) # sleeps for 20 minutes
while market... | The code reads stock symbols from a file, fetches historical 1-minute and 1-day price data for each symbol, processes it into bars, and uses a trading API to execute automated trades. It continuously updates data every 6 hours, groups minute-level bars into daily intervals, and runs trading logic while waiting for the ... | def main():
if len(sys.argv) != 2:
print("ERROR: Wrong number of arguments!")
exit(-1)
with open(sys.argv[1]) as file:
lines = file.readlines()
lines = [line.rstrip() for line in lines]
api = tradeapi.REST(keys, keys_to_the_vip, paper_products)
high_volume_stocks = ... |
def _run_maxfilter(raw, subject, kind):
bads = _parse_bads(subject, kind)
raw.info['bads'] = bads
cal = op.join(path_maxfilter_info, 'sss_params', 'sss_cal.dat')
ctc = op.join(path_maxfilter_info, 'sss_params', 'ct_sparse.fif')
raw = mne.preprocessing.maxwell_filter(
raw, calibration=cal,
... | The code processes raw EEG data by fixing magnetometer coil types, applying MaxFilter for noise reduction, adding SSP (Signal Space Separation) for EOG/ECG artifact removal, and computing global rejection thresholds for epochs. It returns the cleaned raw data and rejection parameters for subsequent epoch rejection. | def clean_raw(raw, subject):
mne.channels.fix_mag_coil_types(raw.info)
raw = _run_maxfilter(raw, subject, 'rest')
_compute_add_ssp_exg(raw)
reject = _get_global_reject_epochs(raw)
return raw, reject |
def undeclare_hexcodes(self, css):
varname_hex_map = self.get_varname_hex_map(css)
css = self.remove_hexcode_declarations(css)
css = self.replace_varnames_with_hexcodes(css, varname_hex_map)
return css
def get_colorname_hex_map(self, css):
dict_ = {}
hex_codes = self.ge... | This function replaces hex color codes in CSS with CSS variables, generating variable declarations. It processes the input CSS to identify hex codes, maps them to named variables, substitutes the hex values with variables, and returns the updated CSS along with the variable declarations for consistent color management. | def declare_hexcodes(self, css):
if not hexutils.find_all(css):
return css
css = self.undeclare_hexcodes(css)
colorname_hex_map = self.get_colorname_hex_map(css)
set_variable_name = self.set_variable_name(colorname_hex_map)
css = hexutils.HEX_CODE_RE.sub(set_variab... |
def parse_data(args):
num = float
dtype = np.float32
data = []
with open(args.data_file, 'r') as f:
for line in f:
data.append([num(t) for t in line.split()])
dev_cutoff = int(.9*len(data))
train_xs = np.asarray(data[:dev_cutoff],dtype=dtype)
dev_xs = np.asarray(data[dev_... | The code implements an Expectation-Maximization (EM) algorithm for clustering data points. It allows initializing clusters either randomly (via `--cluster_num`) or from a file (`--clusters_file`), supports tied covariance matrices, and processes training/dev data. The model trains for specified iterations, computes log... | def main():
import argparse
import os
print('Gaussian') #Do not change, and do not print anything before this.
parser = argparse.ArgumentParser(description='Use EM to fit a set of points')
init_group = parser.add_mutually_exclusive_group(required=True)
init_group.add_argument('--cluster_num', ty... |
def parse_data(args):
num = float
dtype = np.float32
data = []
with open(args.data_file, 'r') as f:
for line in f:
data.append([num(t) for t in line.split()])
dev_cutoff = int(.9*len(data))
train_xs = np.asarray(data[:dev_cutoff],dtype=dtype)
dev_xs = np.asarray(data[dev_... | The code implements the Expectation-Maximization (EM) algorithm to fit a Gaussian Mixture Model (GMM) to a dataset. It allows initializing clusters either via a specified number or from a file, supports tied covariance matrices, and trains the model for a given number of iterations. The script computes log-likelihoods ... | def main():
import argparse
import os
print('Gaussian') #Do not change, and do not print anything before this.
parser = argparse.ArgumentParser(description='Use EM to fit a set of points.')
init_group = parser.add_mutually_exclusive_group(required=True)
init_group.add_argument('--cluster_num', t... |
def displayAlert_text_(self, message, text):
LogDebug("Displaying alert: %@ (%@)", message, text)
alert = NSAlert.alloc().init()
alert.setMessageText_(message)
alert.setInformativeText_(text)
alert.runModal()
def setSourcePlaceholder(self):
self.sourceLabel.setStringValue... | This method handles a source failure by displaying an alert with the provided message and text, disabling the source UI element via placeholder setting, changing its text color to indicate a disabled state, and stopping any ongoing busy processes to signal completion of the failure handling task. | def sourceFailed_text_(self, message, text):
self.displayAlert_text_(message, text)
self.setSourcePlaceholder()
self.sourceLabel.setTextColor_(NSColor.disabledControlTextColor())
self.setBusy_(False) |
def parse_args(self, cmd_name, args, min_required=0, max_required=float('inf')):
args = args.strip()
args = args.split(" ") if len(args)>0 else args
N = len(args)
if N<min_required or N>max_required:
if min_required == max_required:
required = min_required
else:
required = "... | This code changes the current directory in a system, parses input arguments, checks system status, and handles responses. It attempts to navigate to a specified directory, validates if the target is a file (rejecting it), and updates the directory if valid. Error handling ensures proper feedback for invalid operations. | def do_cd(self, dir):
args = self.parse_args('cd', dir, 1, 1)
if not ns_is_responding(): self.do_quit()
if args:
arg = self.parse_path(args[0])
print(HTML('Changing dir to: <green>{}</green>'.format(arg)))
result = json.loads(CONN.root.get(arg))
if result["status"]==1:
try... |
def parse_args(self, cmd_name, args, min_required=0, max_required=float('inf')):
args = args.strip()
args = args.split(" ") if len(args)>0 else args
N = len(args)
if N<min_required or N>max_required:
if min_required == max_required:
required = min_required
else:
required = "... | The code lists directory contents, handling errors and formatting outputs with HTML tags. It parses arguments, checks system status, retrieves data from a server, processes entries to distinguish files/directories, and prints formatted results. If a file is mistakenly listed, it shows an error; otherwise, it displays e... | def do_ls(self, dir="."):
args = self.parse_args('ls', dir, 0, 1)
if args is None: return
try:
arg = self.parse_path(args[0])
except IndexError:
arg = self.parse_path(args)
if not ns_is_responding(): self.do_quit()
result = json.loads(CONN.root.get(arg))
if result["status"... |
def parse_args(self, cmd_name, args, min_required=0, max_required=float('inf')):
args = args.strip()
args = args.split(" ") if len(args)>0 else args
N = len(args)
if N<min_required or N>max_required:
if min_required == max_required:
required = min_required
else:
required = "... | The main task of the code is to create a directory on a server, checking if it already exists. If the directory exists, it returns an error message; otherwise, it creates the directory and returns the result. The function parses arguments, verifies server status, retrieves data, and handles responses through JSON opera... | def do_mkdir(self, dir):
args = self.parse_args('mkdir', dir, 1, 1)
if not ns_is_responding(): self.do_quit()
if args:
arg = self.parse_path(args[0])
temp = json.loads(CONN.root.get(arg))
if (temp["status"]==1):
result = {
"status": 0,
"message": "Directory alr... |
def parse_args(self, cmd_name, args, min_required=0, max_required=float('inf')):
args = args.strip()
args = args.split(" ") if len(args)>0 else args
N = len(args)
if N<min_required or N>max_required:
if min_required == max_required:
required = min_required
else:
required = "... | The code handles file deletion operations, parsing arguments for a force flag, checking namespace status, and deleting files with optional force deletion. It updates the current directory if the deleted path was the current directory and prints the operation result. | def do_delete(self, files):
args = self.parse_args('delete', files, 1)
if args:
if args[0] == "-force":
force = True
args = args[1:]
else:
force = False
if not ns_is_responding(): self.do_quit()
for arg in args:
path = self.parse_path(arg)
... |
def parse_args(self, cmd_name, args, min_required=0, max_required=float('inf')):
args = args.strip()
args = args.split(" ") if len(args)>0 else args
N = len(args)
if N<min_required or N>max_required:
if min_required == max_required:
required = min_required
else:
required = "... | The main task of the code is to copy a file or directory from a source path to a destination path. It parses input arguments, validates system responsiveness, executes the copy operation via a connection object, processes the JSON response, and prints the result. The function ensures proper argument handling, system st... | def do_copy(self, args):
args = self.parse_args('copy', args, 2, 2)
if args:
src = self.parse_path(args[0])
dest = self.parse_path(args[1])
if not ns_is_responding(): self.do_quit()
result = json.loads(CONN.root.copy(src, dest))
self.print_response(result) |
def parse_args(self, cmd_name, args, min_required=0, max_required=float('inf')):
args = args.strip()
args = args.split(" ") if len(args)>0 else args
N = len(args)
if N<min_required or N>max_required:
if min_required == max_required:
required = min_required
else:
required = "... | The main task of the code is to handle a "move" command by parsing source and destination paths, executing a move operation via a connection, updating the current directory if the source was the current directory, and printing the operation result. It checks system responsiveness and quits if unresponsive, ensuring pro... | def do_move(self, args):
args = self.parse_args('move', args, 2, 2)
if args:
src = self.parse_path(args[0])
dest = self.parse_path(args[1])
if not ns_is_responding(): self.do_quit()
result = json.loads(CONN.root.move(src, dest))
if src == self.parse_path(self.CURRENT_DIR):
... |
def parse_args(self, cmd_name, args, min_required=0, max_required=float('inf')):
args = args.strip()
args = args.split(" ") if len(args)>0 else args
N = len(args)
if N<min_required or N>max_required:
if min_required == max_required:
required = min_required
else:
required = "... | The code uploads a local file to a distributed storage system by splitting it into blocks, replicating them across multiple servers, and updating the namenode with block mappings. It checks local/remote existence, configures replication/block size, uploads blocks to selected storage servers, and records metadata for fi... | def do_upload(self, args):
args = self.parse_args('upload', args, 2, 2)
if args:
local_path = args[0]
remote_path = self.parse_path(args[1])
if not ns_is_responding(): self.do_quit()
res = json.loads(CONN.root.get(remote_path))
result = {
"status": 1
}
... |
def parse_args(self, cmd_name, args, min_required=0, max_required=float('inf')):
args = args.strip()
args = args.split(" ") if len(args)>0 else args
N = len(args)
if N<min_required or N>max_required:
if min_required == max_required:
required = min_required
else:
required = "... | The main task of the code is to download a file from a remote server to a local directory by retrieving data blocks from storage servers, handling errors such as missing files or directories, and writing the retrieved data to a local file. It verifies the existence of both remote and local paths, fetches blocks sequent... | def do_download(self, args):
args = self.parse_args('download', args, 2, 2)
if args:
remote = self.parse_path(args[0])
local = args[1]
if not ns_is_responding(): self.do_quit()
#print(remote)
res = json.loads(CONN.root.get(remote))
result = {
"status": 1
... |
def path_list(self, path):
path = path.replace("/", " ").strip().split(" ")
return [x for x in path if len(x.strip())>0]
def exposed_mark_new_block(self, block_id, ss):
self.ss_blocks_map[ss][1].append(block_id)
self.save_ss_blocks_map()
print('New block {} at {}. Presence marked.'.format(block_id, ... | This function processes a block map to register new blocks in a remote directory structure. It extracts block identifiers from the input map, marks them as new, and updates a nested data structure at a specified path with these blocks. The changes are saved, and a confirmation message is returned. | def exposed_new_file(self, struct_path, ss_block_map):
path = self.path_list(struct_path)
data = self.struct
blocks = []
# ss_block_map is like [['ss1', 'sdjal83923s1'], ['ss2', 'sfaoir830ds2']]
for x in ss_block_map:
if x[1] not in blocks: blocks.append(x[1])
self.exposed_mark_new_... |
def exposed_get(self, path):
path = self.path_list(path)
try:
res = reduce(getitem, path, self.struct)
status = 1
message = "Resource found!"
data = {} if not bool(res) or res=="" else res
except (KeyError, TypeError):
status = 0
message = "No resource found on given pat... | The main task of the code is to copy a file from a source path to a destination path in a distributed storage system. It checks if the source exists, verifies the destination is a directory, replicates the source file's blocks to alive storage servers, constructs new block IDs, updates the destination's data structure,... | def exposed_copy(self, src, dest, part_of_moving=False):
temp = json.loads(self.exposed_get(src))
temp_dest = json.loads(self.exposed_get(dest))
if temp["status"]==0 or temp_dest["status"]==0:
if temp["status"]==0:
return self.get_return(0, "Source not found at {}".format(src))
if temp_d... |
def path_list(self, path):
path = path.replace("/", " ").strip().split(" ")
return [x for x in path if len(x.strip())>0]
def exposed_get(self, path):
path = self.path_list(path)
try:
res = reduce(getitem, path, self.struct)
status = 1
message = "Resource found!"
data = {} if not ... | The function deletes a resource at the specified path, handling directory emptiness checks, block deletions from servers, and final file system removal. It ensures proper cleanup by removing block mappings before deleting files, using force_delete to bypass emptiness checks, and conditionally executing server-side dele... | def exposed_delete(self, path, part_of_moving=False, force_delete=False):
path = path[:-1] if path[-1]=="/" else path
keys = self.path_list(path)
temp = json.loads(self.exposed_get(path))
if temp["status"]==0:
return self.get_return(0, "Resource not found at {}".format(path))
# ask ... |
def exposed_copy(self, src, dest, part_of_moving=False):
temp = json.loads(self.exposed_get(src))
temp_dest = json.loads(self.exposed_get(dest))
if temp["status"]==0 or temp_dest["status"]==0:
if temp["status"]==0:
return self.get_return(0, "Source not found at {}".format(src))
if temp_d... | The main task of the code is to move a resource from a source path to a destination path by first copying it, then deleting the original source. It handles the copy operation, checks the status, updates the message if successful, prints source/destination details, forces deletion of the original, and returns a formatte... | def exposed_move(self, src, dest):
temp_str = self.exposed_copy(src, dest, part_of_moving=True)
temp = json.loads(temp_str)
if temp["status"]==1:
temp["message"] = "Resource {} moved to {}".format(src, dest)
else:
return temp_str
print('Src:', src)
print('Dest:', dest)
self... |
def getWords(file1):
"""Builds a list of words based on name of input file."""
my_file = open(file1,"r")
data = my_file.read()
if(file1 == 'articles.txt'):
articles = data.replace('\n',' ').split(' ')
return articles
if(file1 == 'nouns.txt'):
... | The main task of the code is to generate a random verb phrase by selecting a verb from a list, appending a noun phrase, and adding a prepositional phrase, all concatenated into a coherent grammatical structure. | def verbPhrase():
"""Builds and returns a verb phrase."""
return random.choice(getWords(verbs)) + " " + nounPhrase() + " " + \
prepositionalPhrase() |
def nounPhrase():
"""Builds and returns a noun phrase."""
return random.choice(articles) + " " + random.choice(nouns)
def verbPhrase():
"""Builds and returns a verb phrase."""
if (random.random()> 0.5):
phrase = random.choice(verbs) + " " + adjective() + " " + nounPhrase()
else:
... | The main task of the code is to generate a random sentence by concatenating a noun phrase and a verb phrase, with a 50% chance of adding a conjunction and an additional verb phrase for complexity. | def sentence():
"""Builds and returns a sentence."""
completeSentence = nounPhrase() + " " + verbPhrase()
if(random.random()> 0.5):
completeSentence = completeSentence + " " + conjunction() + " " + verbPhrase()
return completeSentence |
def board_char (self, index):
"""
Returns the character of the game string at the specified index
Parameters:
index (int): Currently selected index in game string
Returns:
(str) : Character from game string
"""
return self._board[index]
d... | The function performs a flood fill algorithm to reveal adjacent cells on a board. If a selected cell has a value of zero (no neighboring Pokémon), it recursively reveals all adjacent cells until non-zero cells are encountered. Non-zero cells only reveal themselves. The function returns a list of indices representing ce... | def big_fun_search(self, index):
"""
Searching adjacent cells to see if there are any Pokemon"s present.
Find all cells which should be revealed when a cell is selected.
For cells which have a zero value (i.e. no neighbouring pokemons) all the cell"s
neighbours are revealed. If... |
def board_char (self, index):
"""
Returns the character of the game string at the specified index
Parameters:
index (int): Currently selected index in game string
Returns:
(str) : Character from game string
"""
return self._board[index]
d... | The main task of the code is to modify the game board by revealing cells based on a player's search action. It checks if the selected cell is unflagged and not containing a Pokémon, then updates the board with numbers from search results. If a Pokémon is found, it halts further processing. The board is updated by repla... | def mod_board (self, index):
"""
Oversees the modification of the game board and the actions with the board.
Runs several other functions that together compose a player's search action.
Reveals cells specified from the search functions.
Parameters:
index (int... |
def merge_tuples(tuples_list):
tuples_list.sort(key=lambda x: x[0])
newTupList = []
for i in range(len(tuples_list)):
tup = tuples_list[i]
overlap = True
if len(newTupList) == 0:
newTupList.append(tup)
else:
for j in range(len(newTupList)):
... | The code reads intervals from a file, validates the input count (1–100), parses tuples, merges overlapping intervals, sorts them by size, and executes test cases. It processes interval data, ensures correctness, and verifies functionality through merging, sorting, and testing. Your return | def main():
# open file intervals.in and read the data and create a list of tuples
infile = open("intervals.in", "r")
n = int(infile.readline().strip())
if n < 1 or n > 100:
return "invalid N: 1 <= N <= 100"
tupList = []
for i in range(n):
num = infile.readline().strip()
... |
def get_max_prime(n):
prime = 2 * n + 1
while is_prime(prime) == False:
prime += 1
return prime
def insert_word (s, hash_table):
lenWord = len(hash_table)
hashIndex = hash_word(s, lenWord)
w = hash_table[hashIndex]
if len(w) == 0:
hash_table[hashIndex] = s
... | The code reads words from a file, hashes them into a list using double hashing, identifies reducible words (those containing vowels or recursively reducible), and outputs the longest reducible words alphabetically. It calculates prime-sized hash tables, processes collisions, and filters words based on reducibility rule... | def main():
# create an empty word_list
word_list = []
# open the file words.txt
infile = open("words.txt", "r")
# read words from words.txt and append to word_list
line = infile.readline().strip()
while line != "":
word_list.append(line)
line = infile.readline().strip()
... |
def euler_angles(params, f_seq, mprime, backupNNLO = True):
"""
Computes the (l, m) euler angles alpha, beta, and gamma evaluated for the parameters in the dict params at the frequencies in f_seq.
params: parameter dictionary
f_seq: REAL8Sequence LAL object that contains a frequency array
mprime: mp... | The code computes the plus and cross polarizations of gravitational waves for given parameters and frequency sequences using specified modes. It calculates contributions from each mode, applies Euler angles and twist factors, and combines results with a polarization rotation based on the zeta angle, returning the final... | def hpc_slow(params, f_seq, backupNNLO = True, modelist = np.array([[2,1], [2,2], [3,2], [3,3], [4,4]]) ):
"""
Computes the plus and cross polarizations for the parameters in the dict params at the frequencies in f_seq.
params: parameter dictionary
f_seq: REAL8Sequence LAL object that contains a frequen... |
def euler_angles(params, f_seq, mprime, backupNNLO = True):
"""
Computes the (l, m) euler angles alpha, beta, and gamma evaluated for the parameters in the dict params at the frequencies in f_seq.
params: parameter dictionary
f_seq: REAL8Sequence LAL object that contains a frequency array
mprime: mp... | The function computes the (l, mprime) component of gravitational wave plus and cross polarizations for given parameters and frequencies. It calculates the polarization components using Euler angles, twist factors, and the polarization angle zeta, returning adjusted hplus and hcross values. The backupNNLO flag determine... | def hpc_component(params, f_seq, l, mprime, backupNNLO = True):
"""
Computes the (l, mprime) component of plus and cross polarizations for the parameters in the dict params at the frequencies in f_seq.
params: parameter dictionary
f_seq: REAL8Sequence LAL object that contains a frequency array
l: l ... |
def euler_angles(params, f_seq, mprime, backupNNLO = True):
"""
Computes the (l, m) euler angles alpha, beta, and gamma evaluated for the parameters in the dict params at the frequencies in f_seq.
params: parameter dictionary
f_seq: REAL8Sequence LAL object that contains a frequency array
mprime: mp... | The function computes the prefactor of the (l, m′) L-frame mode of gravitational wave strain in specified detectors (e.g., H1, L1, V1) for given parameters and frequencies. It calculates detector-specific response factors (F⁺, F×) using Euler angles, polarization corrections, and time delays, then combines them with st... | def compute_old_C_prefactor(params, f_seq, l, mprime, backupNNLO = True, detstrings = ['H1', 'L1', 'V1']):
"""
Computes the prefactor of the (l, mprime) L frame mode of the strain in the detectors in detstrings for the parameters in the dict params at the frequencies in f_seq.
params: parameter dictionary
... |
def euler_angles(params, f_seq, mprime, backupNNLO = True):
"""
Computes the (l, m) euler angles alpha, beta, and gamma evaluated for the parameters in the dict params at the frequencies in f_seq.
params: parameter dictionary
f_seq: REAL8Sequence LAL object that contains a frequency array
mprime: mp... | The function `compute_C_prefactor` calculates the prefactor of the (l, m′) time-dependent L-frame mode of gravitational wave strain for specified detectors. It uses parameters like sky location, polarization, and detector responses to compute polarization-rotated coefficients (Cplus, Ccross) and combines them with dete... | def compute_C_prefactor(params, f_seq, l, mprime, backupNNLO = True, detstrings = ['H1', 'L1', 'V1']):
"""
Computes the prefactor of the (l, mprime) time-dependent L frame mode of the strain in the detectors in detstrings for the parameters in the dict params at the frequencies in f_seq.
params: parameter d... |
def euler_angles(params, f_seq, mprime, backupNNLO = True):
"""
Computes the (l, m) euler angles alpha, beta, and gamma evaluated for the parameters in the dict params at the frequencies in f_seq.
params: parameter dictionary
f_seq: REAL8Sequence LAL object that contains a frequency array
mprime: mp... | The function computes prefactors for time-dependent L-frame modes of gravitational wave strain in specified detectors. It processes parameters (like source orientation, polarization, sky position), calculates Euler angles and twist factors for given modes, applies polarization rotations, and combines detector-specific ... | def compute_C_prefactors(params, f_seq, modelist = np.array([[2,1], [2,2], [3,2], [3,3], [4,4]]), backupNNLO = True, detstrings = ['H1', 'L1', 'V1']):
"""
Computes all prefactors of the time-dependent L frame modes of the strain in the detectors in detstrings for the parameters in the dict params at the frequen... |
def euler_angles(params, f_seq, mprime, backupNNLO = True):
"""
Computes the (l, m) euler angles alpha, beta, and gamma evaluated for the parameters in the dict params at the frequencies in f_seq.
params: parameter dictionary
f_seq: REAL8Sequence LAL object that contains a frequency array
mprime: mp... | The code computes the plus and cross polarizations of gravitational waves in the detector frame for given parameters and frequency sequences. It uses Euler angles and twist factors derived from orbital and detector orientations to transform mode-based waveforms (l,m) into detector coordinates. The function efficiently ... | def hpc(params, f_seq, backupNNLO = True, modelist = np.array([[2,1], [2,2], [3,2], [3,3], [4,4]]) ):
"""
Computes the plus and cross polarizations for the parameters in the dict params at the frequencies in f_seq more quickly.
params: parameter dictionary
f_seq: REAL8Sequence LAL object that contains a... |
def euler_angles(params, f_seq, mprime, backupNNLO = True):
"""
Computes the (l, m) euler angles alpha, beta, and gamma evaluated for the parameters in the dict params at the frequencies in f_seq.
params: parameter dictionary
f_seq: REAL8Sequence LAL object that contains a frequency array
mprime: mp... | This function computes the (l, mprime) components of gravitational wave polarizations (plus and cross) using parameters and frequency sequences. It calculates these via Euler angles, twist factors, and polarization adjustments, returning the final hplus and hcross values. The backupNNLO flag determines error handling f... | def hpc_component_fast(params, f_seq, l, mprime, backupNNLO = True):
"""
DOES NOT YET WORK!
Computes the (l, mprime) component of plus and cross polarizations for the parameters in the dict params at the frequencies in f_seq.
params: parameter dictionary
f_seq: REAL8Sequence LAL object that contain... |
def lal_hpc(params, f_seq):
"""
Computes the plus and cross polarizations for the parameters in the dict params at the frequencies in f_seq by calling lal for the polarizations directly.
params: parameter dictionary
f_seq: REAL8Sequence LAL object that contains a frequency array
"""
pdict = {'DL... | This function computes gravitational wave strain in specified detectors (H1, L1, V1) for given parameters at frequencies in `f_seq`. It calculates detector response coefficients, applies time delays based on source and detector locations, and combines plus/cross polarizations with phase corrections. The result is a com... | def compute_strain(params, f_seq, backupNNLO = True, modelist = np.array([[2,1], [2,2], [3,2], [3,3], [4,4]]), uselal = False, detstrings = ['H1', 'L1', 'V1']):
"""
Computes the strain in the detectors in detstrings for the parameters in the dict params at the frequencies in f_seq.
params: parameter diction... |
def get_binning_data_bisect_1(data, hhat0, hhat, C, fmin, fmax, N0, E, correlated_bin_error = True):
"""
Computes the binning data needed to do mode by mode relative binning with scheme 1
(fbin: array of frequencies of the bin edges (Hz)
Nbin: number of bins
fbin_ind: array of indices of bin edges... | The function computes binning data for relative binning, essential for likelihood calculations. It processes input data and a fiducial model, using either mode-by-mode or modeless schemes (1 or 2) to determine frequency bins. Depending on the mode, it calculates summary statistics (A0, A1, B0, B1) and bin edges, incorp... | def setup_binning(data, fiducial_model, modebymode = True, test_model = None, Etot = 0.01, correlated_bin_error = True, rmax = 2, scheme = 1):
"""
Compute the binning data for relative binning. This only needs to be done once for a particular fiducial model. The results are used in computing the likelihood with... |
def get_booking_and_charges(name_id, page):
name_list = [name_id,]
soup = BeautifulSoup(page, 'html.parser')
#print(soup.prettify())
count = 0
# because of nested tables look for tables with subtables and process both
# tables separately
all_tables = soup.find_all("table")
li... | The code processes an individual's data from a web page and merges it with existing database records. It retrieves details from the index listing, fetches additional data from the detail page, and compares it with the database. If there are updates, it updates or inserts records into the database, ensuring consistency ... | def get_person_dict(index_listing, db_cur):
#start with single listing and expand it by going to the details page
global date_string_today, date_string_file_today
if args.verbose >= 3: print(index_listing)
index_info = {}
link = index_listing[0]
index_info["link"] = link
name_id = link.split(r"/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.