dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def load_pragmatic_scen(union=True, counts=False):
'''
helper function to load pragmatic experiment data
:param union: only include top rater confidence scenarios for both listener and speaker
:param counts: return as counts
:return: (codename listener scenarios, adjective listener scenarios, mturk ... | The function `run_rsa_analysis_pragmatic` performs pragmatic RSA (Rational Speech Act) analysis on model features to evaluate communication accuracy in scenarios involving listeners and speakers. It loads scenario data, iterates over model features and alpha values (0.1, 1.0, 5.0), computes listener and speaker alignme... | def run_rsa_analysis_pragmatic(model_feature_list, model_feature_names, csv_keys, word_list):
'''
run pragmatic top match rsa analysis and save results in ../results/temp/
:param model_feature_list: list of (adj_noun_feats, comp_func)
:param model_feature_names: names of input features
:return: None... |
def run_rsa_analysis_pragmatic(model_feature_list, model_feature_names, csv_keys, word_list):
'''
run pragmatic top match rsa analysis and save results in ../results/temp/
:param model_feature_list: list of (adj_noun_feats, comp_func)
:param model_feature_names: names of input features
:return: None... | The main task of the code is to perform linguistic analysis on codenames data using multiple semantic feature models (e.g., bigram, conceptnet, word2vec). It processes input data, loads precomputed features, and executes RSA analysis, correlation calculations, or statistical evaluations based on flags (run_rsa, run_cor... | def main(run_rsa=False, run_corr=False, gen_stats=False, experiment_num=3):
codenames_file = 'noun_adjectives.pickle'
file_path = '../output/'
csv_keys = ['SIM TYPE', 'L_Literal top 1', 'ERR', 'L_Pragmatic top 1', 'ERR', 'L_Literal top 3', 'ERR',
'L_Pragmatic top 3', 'ERR', 'LS_Literal top ... |
def FindSpeed(self):
self.xVel = math.sin(self.Direction)*self.speed
self.yVel = math.cos(self.Direction)*self.speed
def BounceRight(self):
if self.speed < self.speedmax:
self.speed+=1
## print('Ball speed : ', self.speed)
AngleDiff = math.pi/2 - self.Direction
... | The code updates a ball's position and movement in a game, handling collisions with the pad, adjusting direction and speed based on collision points, resetting the ball if it goes out of bounds, and rendering it on the screen. It tracks position history, manages spawn/reset logic, and applies turbulence effects to dire... | def Update(self, Display, clock, Pad, Blocks, parts):
## print(datetime.datetime.now().second)
self.poslist.append([self.rect.x, self.rect.y])
if len(self.poslist) > 2:
self.poslist.pop(0)
## print(self, '\n', Display, '\n', clock, '\n', Pad, '\n', Blocks)
self.SpawnTim... |
def show(self):
for row in self.board:
print(row)
def get_potential_rows(self, queen):
rows = []
for row in range(self.size):
if self.is_correct(row, queen) and self.board[row][queen] != -1:
rows.append(row)
return rows
def place_queen(self, coordi... | This code solves the N-Queens problem using backtracking with forward checking. It places queens column by column, checking for valid rows and ensuring future queens have available positions. If a valid configuration is found, it displays the solution and returns True; otherwise, it backtracks. | def solve_NQueen_FC(self, queen):
# queen represents the queen number or the column (ex: queen = 2 => it is the third queen to be placed
# or in other words, the column that is being researched is the column 2,
# as we already placed a queen per column on the previous ones)
# if the cu... |
def show(self):
for row in self.board:
print(row)
def get_potential_rows(self, queen):
rows = []
for row in range(self.size):
if self.is_correct(row, queen) and self.board[row][queen] != -1:
rows.append(row)
return rows
def place_queen(self, coordi... | This function solves the N-Queens problem using backtracking with MRV heuristic. It places queens column-by-column, selecting rows with the fewest conflicts (MRV), performs forward checking to ensure future placements are possible, and backtracks if domain exhaustion occurs. The goal is to find a valid board configurat... | def solve_NQueen_MRV(self, queen):
# queen represents the queen number or the column (ex: queen = 2 => it is the third queen to be placed
# or in other words, the column that is being researched is the column 2,
# as we already placed a queen per column on the previous ones)
# if the c... |
def d_perpendicular(l1, l2):
"""
Calculate the perpendicular distance between two lines.
"""
# Find the shorter line and assign that as l_shorter
l_shorter = l_longer = None
l1_len, l2_len = d_euclidean(l1[0], l1[-1]), d_euclidean(l2[0], l2[-1])
if l1_len < l2_len:
l_shorter = l1... | The code calculates the total trajectory distance between two line segments by combining three weighted components: perpendicular, parallel, and angular distances. It uses specified weights for each component and returns their sum, with the angular distance optionally considering directionality. | def distance(l1, l2, directional=True, w_perpendicular=1, w_parallel=1, w_angular=1):
"""
Get the total trajectory distance using all three distance formulas.
"""
perpendicular_distance = d_perpendicular(l1, l2)
parallel_distance = d_parallel(l1, l2)
angular_distance = d_angular(l1, l2, dir... |
def partition(trajectory, directional=True, progress_bar=False, w_perpendicular=1, w_angular=1):
"""
Partition a trajectory into segments.
"""
# Ensure that the trajectory is a numpy array of shape (n, 2)
if not isinstance(trajectory, np.ndarray):
raise TypeError("Trajectory must be a n... | The function `traclus` clusters trajectories by partitioning them into segments, computing a distance matrix based on directional and weighted metrics, and applying a clustering algorithm (e.g., OPTICS) to group segments into clusters. It returns partitions, segments, distance matrix, cluster assignments, and represent... | def traclus(trajectories, max_eps=None, min_samples=10, directional=True, use_segments=True, clustering_algorithm=OPTICS, mdl_weights=[1,1,1], d_weights=[1,1,1], progress_bar=False):
"""
Trajectory Clustering Algorithm
"""
# Ensure that the trajectories are a list of numpy arrays of shape (n, 2)
... |
def wrap_angle(angle):
"""
Wrap angle to [-pi, pi)
:param angle: Angle to be wrapped
:return: wrapped angle
"""
angle += pi
while angle < 0:
angle += 2*pi
return fmod(angle, 2*pi) - pi
def get_pose(self):
try:
tf_stamped = s... | This test function verifies a robot's localization accuracy by comparing its final pose (position and orientation) against predefined target values within specified tolerances. It initializes a ROS node, waits for time synchronization, triggers global localization if needed, tracks the robot's pose over time, and asser... | def test_basic_localization(self):
global_localization = int(sys.argv[1])
self.target_x = float(sys.argv[2])
self.target_y = float(sys.argv[3])
self.target_a = self.wrap_angle(float(sys.argv[4]))
tolerance_d = float(sys.argv[5])
tolerance_a = float(sys.argv[6])
ta... |
def load_param_prep():
par = np.genfromtxt("cnf_prep.csv",delimiter=',')
params=[]
params.append(np.int16(par[0])) # Porcentaje de training
params.append(np.int16(par[1])) # Longitud del segmento
params.append(np.int16(par[2])) # Cantidad de clases a cargar
params.append(np.int16(par[3])... | The main task of the code is to preprocess data by loading parameters, segmenting class data from CSV files, splitting into training/test sets, concatenating across classes, shuffling, and saving processed datasets for machine learning. It handles data preparation steps like segmentation, stratified splitting, and data... | def main():
#CARGAR PARAMETROS PREP#
params = load_param_prep()
#########################
#OBTENER DIRECTORIOS#####
carpeta_data = params[3]
dir_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), f"Data{carpeta_data}")
count = 0
arreglo_clase_segmentadas = []
arreglo_lab... |
def preprocess_sequence_data(self, examples):
"""Preprocess sequence data for the model.
Args:
examples: A list of vectorized input/output sequences.
Returns:
A new list of vectorized input/output pairs appropriate for the model.
"""
examples_with_mask = ... | The main task of the code is to train a sequence model on labeled data, using learning rate decay over epochs, evaluate performance on training and development sets (including token-level and entity-level metrics), log results to files if configured, and save the model with the best development set F1 score. The functi... | def fit(self, sess, saver, train_examples_raw, dev_examples_raw):
best_score = 0.
train_examples = self.preprocess_sequence_data(train_examples_raw)
dev_examples = self.preprocess_sequence_data(dev_examples_raw)
learning_rate_decay = 1.
for epoch in range(self.config.n_epochs):... |
def dirichlet_energy(self, snl, x):
x=x/x.norm()
if self.dtype == torch.cfloat:
x_herm = torch.complex(
x.real.transpose(0,1),
-x.imag.transpose(0,1)
)
else:
x_herm = x.transpose(0, 1)
energy = .5 * torch.trace(x_herm @ torch.sparse.mm(snl, x))
... | The code processes input data through an encoder-decoder architecture with GCN/Euler steps, computing Dirichlet energy at each layer. It applies dropout, normalization, and layer-specific parameters, returning transformed features and energy values for each layer. | def forward(self, data):
x=data.x.to(self.dtype)
U, S, Vh = data.U.to(self.dtype), data.S, data.Vh.to(self.dtype)
snl=data.snl.to(self.dtype)
energy = torch.zeros(self.num_layers+1, dtype=self.dtype)
x = self.dropout[0](x)
x = self.encoder(x)
energy[... |
def get_resolution(data: xr.Dataset) -> Resolution:
"""
Returns the resolution of the data in degrees.
"""
dx = abs(data["x"][1] - data["x"][0]).item()
dy = abs(data["y"][1] - data["y"][0]).item()
print(dx, dy)
return Resolution(dx, dy)
def regrid(
data: xr.Dataset, resolution: float | R... | The code's main task is to regrid a spatially indexed pandas DataFrame to a new resolution using specified aggregation methods. It converts the DataFrame to Xarray, adjusts spatial coordinates, calculates resolution scaling, applies aggregation (e.g., averaging), and returns the regridded data as a DataFrame. Key steps... | def regridding_interface(
dataframe, geo_columns, time_column, scale_multi, aggregation_functions
):
# Construct renaming mapping for regridding:
renaming_map = {geo_columns[1]: "x", geo_columns[0]: "y"}
# Pandas dataframe to Xarray
dataframe = dataframe.rename(columns=renaming_map)
print(dataf... |
def elapsedTimeMs(since=datetime_start):
return datetime.now()-since
def getIntersectCube(cube,other):
# if (not other.overlaps(cube)) and (not cube.overlaps(other)):
# return None
x1 = min(cube.point1.x, other.point1.x)
y1 = min(cube.point1.y, other.point1.y)
z1 = min(cube.point1.z, other.p... | The function calculates the total non-overlapping volume of all 'ON' cubes in a list by subtracting the combined volume of intersecting subsequent cubes from each ON cube's total volume, summing these adjusted values. It tracks progress every 50th cube. | def determineTotalOn(cubes):
# 0:00:00.364503 returned 175980 intersection volumes for 420 cubes
totalOn=0
n,d=0,50
for i in range(len(cubes)):
cube = cubes[i]
relevantVol=0
if cube.typ==ON:
n+=1
if n%d==0:
print(f"{elapsedTimeMs()} assessi... |
def containedByAny(cube, cubes):
for other in cubes:
if other.containsCube(cube):
return True
return False
def findOverlapping(cube, remaining):
overlappers=[]
for other in remaining:
if other.overlaps(cube) or cube.overlaps(other): # need to check both ways in case of fully ... | The code analyzes a list of cubes to identify redundancies, overlapping relationships, and statistics. It categorizes cubes as redundant (completely overlapped), tracks ON cubes with no subsequent overlaps, and distinguishes ON cubes with overlappers (including OFF types). It calculates total ON cube volumes, prints de... | def analyseCubes(cubes):
cube_map={}
for cube in cubes:
cube_map[cube.id]=cube
onWithOverlappers={}
lastON=set()
redundant=[]
for i in range(len(cubes)-1):
cube = cubes[i]
remaining = cubes[i+1:]
if containedByAny(cube, remaining):
redundant.append(cub... |
def define_attention_input(self, target_im):
model, preprocess = clip.load(self.saliency_clip_model, device=self.device, jit=False)
model.eval().to(self.device)
data_transforms = transforms.Compose([
preprocess.transforms[-1],
])
self.image_input_attn_... | The code initializes a Painter class for generating strokes/path-based images, setting parameters like stroke count, segmentation, image size, and attention mechanisms. It configures optimization flags, control points, saliency models, and CLIP-related settings for guided image generation, preparing attributes for stro... | def __init__(self, args,
num_strokes=4,
num_segments=4,
imsize=224,
device=None,
target_im=None,
mask=None):
super(Painter, self).__init__()
self.args = args
self.num_paths = num_strokes
self... |
def createIdentifierReference(self,name):
assert re.match("^[\\@A-Z][\\@A-Z0-9]*$",name.upper()) is not None # check legal variable name
assert len(name) > 1 # check not fast variable
tokens = self.tokeniser.tokenise(name) # tokenise it
addr = self.allocateHighMemory(len(tokens)*2) #... | This function creates a variable by allocating low memory for its metadata and optionally high memory for data. It validates the variable name, generates a hash address, initializes memory with the provided value, and updates internal data structures like the variables dictionary and hash table to track the variable's ... | def createVariable(self,name,initValue,memoryAllocated = 0):
self.memoryVariableCreated = True # can't add more code
name = name.lower()
assert name != "" and name not in self.variables # check ok / not exists
nameAddr = self.createIdentifierReference(name) # create tokenised version in hi... |
def _labels(self):
"""
Generate a list of labels for all sources.
"""
labels = np.unique(self.segm_cut)
return labels[labels!=0]
def _mask_all_but_target(self):
"""
Generate a mask for all sources except the targeted ones.
"""
mask_all_but_target =... | The code initializes labels and two mask attributes (`mask_all_but_target` and `mask_all`) within a class's `__post_init__` method. `self.labels` is generated via `_labels()`, while `mask_all_but_target` is created using `_mask_all_but_target()`. Finally, `mask_all` is derived by applying `_mask_all()` to `mask_all_but... | def __post_init__(self):
self.labels = self._labels()
self.mask_all_but_target = self._mask_all_but_target()
self.mask_all = self._mask_all(self.mask_all_but_target) |
def _complete_job_item(self):
"""Start a new job and call the update view to create a completed job item"""
started_job = self._start_job()
job_item = self.job_items[0]
request = self._make_request(
url_name="update_started_job",
kwargs={"pk": started_job.pk},
... | This test verifies that the 'update_started_job' view correctly deletes a completed job item. It creates a completed item and a started job, then sends a POST request to the update view with the completed item's ID and 'complete' set to False. The test ensures that after processing the request, no CompletedJobItem reco... | def test_update_job_delete_item(self):
"""Test the update view to delete a completed job item"""
completed_item, started_job = self._complete_job_item()
request = self._make_request(
url_name="update_started_job",
kwargs={"pk": started_job.pk},
data={"job_item... |
def splitsing(maxSplitsing):
global aantalSplitsingGehad
print("split")
keuze = "l"
if maxSplitsing > aantalSplitsingGehad:
if keuze == "r":
for step in range(150):
rijRecht()
for step in range(200):
#print("bezigheid")
draaiRechts()
if keuze == "s":
rijRecht(... | The function `detectWeg()` determines a robot's navigation path by checking GPIO sensor inputs (pins 8, 10, 12). It triggers actions like straight driving (`rijRecht()`), left/right turns (`bochtLinks()`, `bochtRechts()`), or splitting (`splitsing()`) based on sensor states. It uses `dubbelCheck()` for validation and p... | def detectWeg():
#print("aan het detecteren")
#Rechdoor and GPIO.input(10) == 0
if GPIO.input(8) == 0 and GPIO.input(12) == 0:
print("splitsing")
splitsing(maxSplitsing)
elif GPIO.input(8) == 1 and GPIO.input(12) == 1:
rijRecht()
elif GPIO.input(8) == 1 and GPIO.input(10) == 1 and GPIO.input(12) =... |
def get_shingles(movies_dataset):
movies = pd.read_csv(movies_dataset, encoding='utf-8')
movies_tokenized = tokenize(movies)
vocab_set = set(i for s in movies_tokenized['tokens'].tolist() for i in s)
vocab = {i: x for x, i in enumerate(sorted(list(vocab_set)))}
db = defaultdict(int)
shingles =... | The main task of the code is to implement a collaborative filtering system using Locality-Sensitive Hashing (LSH) and min-hashing to predict movie ratings. It processes movie and user rating data, constructs shingle-based hash signatures, builds LSH buckets for similarity detection, and applies these to predict test ra... | def main():
movies_filename, rating_train_filename, ratings_test_filename, output_filename = sys.argv[1:]
threshold, band_hash_size, bands, rows = 0, 2 ** 16, 20, 3
size = bands * rows
shingles, db = get_shingles(movies_filename)
hash_coefficients = get_hash_coefficients(size)
min_hash = min_... |
def get_baskets(file):
baskets = defaultdict(list)
with open(file, mode='rt') as in_file:
header = True
for line in in_file:
if header:
header = False
continue
tokens = process_line(line.strip())
if tokens:
user_... | The main task of the code is to execute the Apriori algorithm on transaction basket data to identify frequent item sets and generate association rules, then output the results in JSON format. It processes input transaction data, calculates item set support, computes rule probabilities, filters frequent item sets using ... | def main():
input_filename, output_filename, I, S = sys.argv[1:]
I, S = float(I), int(S)
baskets = get_baskets(input_filename)
item_sets_dict = get_item_sets(baskets, support=S)
probabilities = get_probabilities(item_sets_dict, len(baskets))
freq_item_sets = apriori(baskets, item_sets_dict, ... |
def print_VN_summary(self, VNs):
#
for vn_id, vn_info in VNs.items():
print("VN fqname: " + str(vn_info["name"]) + " .... uuid(" + str(vn_id) + ")")
def getAutoCompleteVNs(self, completeval, VNs):
matchingVNs = []
for vn_id, vn_info in VNs.items():
vn_name_string ... | This code handles user input to search for Virtual Networks (VNs) with three cases: printing all VN summaries if input is empty, auto-completing partial VN names, or retrieving detailed info for a fully specified VN. It uses readline for tab completion and delegates processing to helper methods like `print_VN_summary`,... | def print_VNs(self):
VNManager = VNResManager()
#VMRestManager = VMRestManager()
VNs = VNManager.VNs
VNhelper = HelperClass(VNs)
readline.set_completer_delims("\n")
readline.parse_and_bind("tab: complete")
readline.set_completer(VNhelper.complete)
... |
def get_annotated_documents_for_template_type(
all_docs: Dict[str, Any],
template_type: str,
multi_same_type_template_only: bool = True,
) -> Dict[str, Any]:
filtered = {}
for k, v in all_docs.items():
target_templates = [t for t in v if t["incident_type"].lower() == template_type]
i... | The function visualizes annotated documents from a dataset, allowing interactive or batch viewing. It filters documents by template type or inclusion of irrelevant ones, then displays document text and associated templates. In interactive mode, users navigate through documents via commands, while batch mode prints all ... | def view_annotations(
split: str,
viewing_mode: str,
keep_irrelevant: bool = False,
template_type: Optional[str] = None,
multi_same_type_template_only: bool = False,
) -> None:
with open(os.path.join(DATA_DIR, split, f"{split}_keys.json")) as f:
keys = json.load(f)
if template_ty... |
def clean_docid(value):
return re.sub(r"\s*\(.*$", "", value)
def parse_location(location_expr: str):
out = []
seen = set()
for loc1 in location_expr.split(" / "):
loc1 = loc1.strip()
for loc2 in loc1.split(":"):
loc2 = loc2.strip()
if loc2[0] == "(" and loc2[-1] ... | The function `parse_values` processes key-value pairs by filtering and parsing specific slots. It cleans document IDs for "message_id" and "incident_type", handles numeric, wildcard, and optional formats for "message_template", parses "incident_location", validates values against allowed sets, and corrects missing quot... | def parse_values(keyvals):
"""
Takes key,value pairs as input, where the values are unparsed.
Filter down to the slots we want, and parse their values as well.
"""
for key, value in keyvals:
if key == "message_id":
yield key, clean_docid(value)
continue
if key... |
def __scapegoat(self, leaf, ancestor_trail):
""" Return scapegoat node, its parent, and
the direction of the scapegoat relative to its parent,
given the leaf node from which a scapegoat should be found
and a list of tuples containing ancestors from the root to the leaf
... | This code inserts a new node into a tree, updating size counters. If the tree is empty, it creates a root node. Otherwise, it traverses the tree to find the insertion point, tracks the path, and inserts the node. If the new node's depth exceeds a threshold based on tree size and balancing factor (α), it identifies a "s... | def insert(self, key):
""" Insert new node with given key.
"""
# update tree counters
self.size += 1
self.max_size = max(self.size, self.max_size)
# insert as root if tree is empty
if self.root is None:
self.root = Node(key)
return None
... |
def search(self, key, return_parent=False):
""" Return highest node with given key---
optionally return parent of node
and direction of node relative to parent, too.
"""
# start at root
node = self.root
parent = None
direction = ''
# traver... | This code deletes a node with a specified key from a binary tree, handling cases for leaf nodes, nodes with one child, and nodes with two children. It replaces nodes with two children using the largest key in the left subtree, updates tree size, and rebalances the tree if necessary by reconstructing a balanced subtree ... | def delete(self, key):
""" Delete highest node with given key.
"""
# search for node
node, parent, direction = self.search(key, return_parent=True)
# do nothing if not found
if node is None:
return None
# else delete it
# leaf:
... |
def find_cmd_srt_paths(videos_dir: Path) -> List[Path]:
srt_path_list = list(videos_dir.glob(f"**/*[!{PREPROCESS_FLAG}].srt"))
return srt_path_list
def read_srt(srt_path: Path) -> List[pysrt.SubRipItem]:
preprocessed_srt_path = make_preprocessed_srt(srt_path)
line_list = list(pysrt.open(preprocessed_srt... | The code converts CMD-formatted SRT subtitles to TVC format by processing each subtitle line, validating it, and saving the structured JSON data as a JSONL file. It reads SRT files from a directory, transforms valid lines into TVCSubtitle objects, exports them to JSON, and aggregates results into a single JSONL file fo... | def convert_subtitles(option: Optioner) -> None:
srt_path_list = find_cmd_srt_paths(option.videos_dir)
# Convert CMD to TVC
tvc_json_list = []
for srt_path in tqdm(srt_path_list):
video_id = srt_path.stem.split(".")[0]
srt_line_list = read_srt(srt_path)
tvc_line_list: List[TVC... |
def generate_coarse_grainings(N_a):
g_bas = []
num_regions = N_a.shape[0]
while num_regions > 1:
g_ba = generate_coarse_graining(N_a)
g_bas.append(g_ba)
N_a = np.zeros((int(num_regions / 4),))
num_regions = N_a.shape[0]
return g_bas
def as_grid(N_a):
# print... | The code generates a model representing regions with interaction matrices and population distributions. It initializes a region matrix (M_a) and population vector (N_a), then constructs a grid to define spatial neighbor relationships. Spread rates between regions are set, while self-spread rates are applied diagonally.... | def generate_world(num_regions=16, spread_rate=0.2, self_spread_rate=2.0, large_case_count=False):
M_a = np.eye(num_regions)
N_a = np.zeros((num_regions,))
N_a[int(num_regions / 2) + 2] = 1.0
if large_case_count:
for i in range(num_regions):
N_a[i] = np.random.normal(loc=10.0, scale... |
def getGender():
choose = roll(2)
if choose < 2:
gender = 'Male'
else:
gender = 'Female'
return gender
def nameChoice(gender):
if roll(2) == 2:
name = pickName(gender)
else:
name = makeName()
return name
def getAppearance():
appList = ['Wears distinctive j... | The main task of the code is to generate an NPC character by combining attributes like name, gender, appearance, and mannerism using helper functions. It formats these details into a structured string, prints them with separators, and returns the NPC data for further use. | def NPCGen():
gender = getGender()
name = nameChoice(gender)
appearance = getAppearance()
mannerism = getMannerism()
NPC = 'Name: ' + name + '\n\n' + 'Sex: ' + gender + '\n\n' + 'Appearance: ' + appearance + '\n\n' + 'Mannerism: ' + mannerism
print('-------------------------------------------')... |
def getGender():
choose = roll(10)
if choose < 7:
gender = 'Male'
else:
gender = 'Female'
return gender
def nameChoice(gender):
if roll(2) == 2:
name = pickName(gender)
else:
name = makeName()
return name
def getRace():
race = ''
choose = roll(22)
... | The main task of the code is to generate a fictional NPC character by combining attributes like gender, name, race, appearance, and mannerism. It formats these details into a structured string, prints them with separators, and returns the complete NPC description for use in other parts of a program, such as a game or n... | def NPCGen():
gender = getGender()
name = nameChoice(gender)
race = getRace()
appearance = getAppearance()
mannerism = getMannerism()
NPC = 'Name: ' + name + '\n\n' + 'Sex: ' + gender + '\n\n' + 'Race: ' + race + '\n\n' + 'Appearance: ' + appearance + '\n\n' + 'Mannerism: ' + mannerism
prin... |
def _dtb(self):
dtbdebug = False
dtbdebug and logger.debug("_dtb: Disabling all Timers and Button activities")
# Disable Timers and Buttons
dtbdebug and logger.debug("_dtb: cancel standby")
self.standby_timer.cancel()
t = int(self.config['TIMES']['standby'])
self.standby_timer = Timer(... | The main task of the code is to capture a photo using a camera via gphoto2, manage lighting and countdown displays, handle errors (e.g., camera, storage, focus, battery), and save the photo to storage/backups while providing visual feedback. It retries on focus errors up to three times and transitions to maintenance mo... | def _take_photo(self, delay = None, rnd=0):
logger.debug("_take_photo")
self._dtb() # disable Timer and Buttons
# tried to take a photo 3 times - something is wrong, going to error mode
if (rnd == 3):
logger.warn("Encountered multiple errors, stopping at 3 retries")
self.error(file="fbi... |
def _dtb(self):
dtbdebug = False
dtbdebug and logger.debug("_dtb: Disabling all Timers and Button activities")
# Disable Timers and Buttons
dtbdebug and logger.debug("_dtb: cancel standby")
self.standby_timer.cancel()
t = int(self.config['TIMES']['standby'])
self.standby_timer = Timer(... | The main task of the code is to initialize the "active" state of a system by disabling timers/buttons, checking battery levels, activating lights, displaying an FBI main screen, configuring button-triggered photo-taking functions, and initiating a standby timer to transition to standby mode after a set duration if no s... | def active(self):
logger.debug("active")
self._dtb() # disable Timer and Buttons
self._set_state("active")
# looks for battery level, will display warning, and go to maintenance if camera not found
self._get_battery_level()
# Turn on Lights
if not self.config['LIGHTS']['flash_light... |
def extract_coupling_boundary_coordinates(self):
"""Extracts the coordinates of vertices that lay on the boundary. 3D
case currently handled as 2D.
:return: x and y cooridinates.
"""
vertices, _ = self.extract_coupling_boundary_vertices()
vertices_x = vertices[0, :]
... | The function `advance` manages simulation advancement using preCICE for coupling, updating the solution `u_n` via call-by-reference. It writes boundary data, communicates with the preCICE interface, reads updated data, adjusts boundary conditions, and handles checkpointing. If a checkpoint is required, it restores `u_n... | def advance(self, write_function, u_np1, u_n, t, dt, n):
"""Calls preCICE advance function using precice and manages checkpointing.
The solution u_n is updated by this function via call-by-reference. The corresponding values for t and n are returned.
This means:
* either, the checkpoint... |
def set_coupling_mesh(self, mesh, subdomain):
"""Sets the coupling mesh. Called by initalize() function at the
beginning of the simulation.
"""
self._coupling_subdomain = subdomain
self._mesh_fenics = mesh
self._coupling_mesh_vertices, self._n_vertices = self.extract_coup... | (The main task of the code is to initialize a FEniCS adapter for coupling simulations, setting up mesh, fields, and the PRECICE interface. It configures data exchange mechanisms, checks for required actions like writing initial data or reading fields, handles iteration checkpoints, and prepares the coupled boundary int... | def initialize(self, coupling_subdomain, mesh, read_field, write_field,
u_n, dimension=2, t=0, n=0, coupling_marker=0):
"""Initializes remaining attributes. Called once, from the solver.
:param read_field: function applied on the read field
:param write_field: function appli... |
def threat_instrumentation(config, scenarios):
ret = scenarios
channel_fsms = {}
keys = ["Adversary UE-to-Others", "Adversary ePDG-to-Others", "Adversary DNS-to-Others"]
lst = []
for key in keys:
if key in config:
lst.append(config[key])
for c in lst:
fs... | The main task of the code is to process initial FSMs, generate protocol stacks and scenarios under constraints, apply threat instrumentation, and output SMV models. It loads FSMs, prepares entity/context constraints, creates model variants, generates scenarios, compiles variables/FSMs, and writes SMV files with defines... | def main_combined(config=None, ofprefix=None, ofdir=None):
logging.debug("Entity Types: {}".format(config["Entity Types"]))
logging.debug("Initial FSMs Directory: {}".format(config["Initial FSMs Directory"]))
entity_types = config["Entity Types"]
context_types = config["Context Types"]
initial_fs... |
def command_line_args():
global parser
parser = argparse.ArgumentParser(description="""DOT to SMV translator.""")
parser.add_argument("-c", "--conf", metavar="<configuration file>", help="Configuration file", type=str, default="vowifi.conf")
parser.add_argument('-l', "--log", metavar="<log level (DEBUG... | The main task of the code is to process command-line arguments, validate the existence of a configuration file, create an output directory if needed, parse the configuration, configure logging, and execute the `main_combined` function with the parsed configuration and specified output parameters. | def main():
args = command_line_args()
if not os.path.exists(args.conf):
logging.error("Configuration file: {} does not exist".format(args.conf))
parser.print_help()
sys.exit(1)
if not os.path.exists(args.directory):
os.mkdir(args.directory)
conf = parse_config(args... |
def pushpos(): push((g[X], g[Y]))
def loc(x=None,y=None):
if x is None and y is None:
return (g[X], g[Y])
elif x is not None and y is not None:
g[X], g[Y] = x,y
else:
raise ValueError()
def write(s, flags="f"):
"""
flags:
"o" -- "Stay at original position" -- cursor not... | This function writes a string `s` at specified coordinates `(x, y)` while temporarily saving and restoring the cursor position to maintain context. | def paste(x,y, s):
pushpos()
loc(x,y)
write(s, "o")
poppos() |
def pushpos(): push((g[X], g[Y]))
def pushclip(): push((g[CLIPX], g[CLIPY], g[CLIPX1], g[CLIPY1]))
def clip(x=None, y=None, x1=None, y1=None):
if x is None and y is None and x1 is None and y1 is None:
return (g[CLIPX], g[CLIPY], g[CLIPX1], g[CLIPY1])
elif x is not None and y is not None and x1 is not No... | This function writes the given text into specific regions of a template defined by coordinates and labels. It iterates through parsed template data, clips and fills matching regions with spaces, then positions and writes the text at the specified location. The operations use a stack to manage clipping and positioning c... | def template_write(label, text):
pushpos()
pushclip()
for (x,x1,y,y1, cur_lbl, kind) in g[PARSED_TEMPLATE]:
if kind in {".", "_"} and label == cur_lbl:
clip(x,y,x1,y1)
fill(x,y,x1,y1, " ")
loc(x,y)
write(text, "o")
popclip()
poppos() |
def restartGame():
common.joinFlag = True # to block joining patrticipants after 60 seconds
# common.chat_type = None
common.gameCounter = 0
common.game_creater = {}
common.participants = []
common.nextButtonCount = False
common.nextEditButton = None
common.editJoinMsg = None
common... | This function manages user participation in a jumble word game, handling join requests, participant tracking, game initialization, and timer logic. It checks mode parameters to determine automatic/manual joining, validates user eligibility, updates game state, and triggers game actions like word distribution or winner ... | def join_game(game, message, mode='auto', time=60):
skip = False
if mode == 'skip':
skip = True
elif mode == 'mannual':
chat_id = message.json['message']['chat']['id']
else:
chat_id = message.json['chat']['id']
if not (skip):
global current_word_Message
use... |
def check_tongue_visible(self):
"""This animates the tongue. It stays in or out of the mouth for random periods
of time using a cooldown. Once the cooldown expires, we move it either in or out,
the opposite of where it currently is then start a new random cooldown."""
if self.tongue_cooldown.expired():
se... | The main task of the code is to handle the snake's movement and collision checks during each game tick. If the game is not over and the cooldown expires, the snake moves in its current direction. Subsequent checks determine if the snake hit a wall, bit itself, or ate the steak. The cooldown is then reset to maintain co... | def tick(self):
"""If enough time has passed, we will move the snake.
We then check to see if he hit a wall, ate the steak or bit himself!"""
if not self.game_over:
self.check_tongue_visible()
if self.cooldown.expired():
self.snake.move(self.snake.direction)
self.check_hit_wall()
self.check_bit_... |
def __rescale(self, img: np.ndarray) -> np.ndarray:
"""
Rescale image
Parameters
----------
img : np.ndarray
Numpy array of shape (W, H, C)
Returns
-------
np.ndarray
Rescaled copy of the image
"""
return cv2.resiz... | The main task of the code is to extract tiles from an image by rescaling annotations and canvases, binarizing the image, identifying contours and holes, extracting coordinate grids, and saving tiles. It processes annotations, generates a paletted canvas image, and returns tile information. The method logs progress and ... | def tile(self):
"""
(Entrypoint) Extract tiles from image
"""
log.info(f"Tiling annotation {self.sample_id}")
# rescale annotation to find grid faster
img = self.__rescale(self.annot)
# rescale empty canvas
self.canvas = self.__rescale(self.canvas)
... |
def switch_player(self):
# Switch the current player and set the piece
self.current_player = self.players[1] if self.current_player == self.players[0] else self.players[0]
self.piece = 2 if self.current_player == self.players[1] else 1
self.time_left = 30
def draw(self):
# Draw ... | This function handles game events like timer decrements, player moves via mouse clicks, button interactions (pause/back), and AI moves. It updates game state, checks for winners, manages game over transitions, and switches between players or game states based on events. | def handle_events(self, event):
# Timer event
if event.type == self.timer_event and not self.timer_paused:
self.time_left -= 1
if self.time_left == 0:
self.switch_player()
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_... |
def inDisk(self,page):
return page in self
def delete(self, page):
if self.inDisk(page) :
index = self.location[page]
self.deleted[index] = True
self.update(index+1,-1) ## decrease ranks of all the pages after index
self.page_in_disk_count -= 1
... | The main task of the code is to move a specified page back by deleting it from storage and re-adding it, but only if it exists in the disk. If successful, it returns True; otherwise, it prints an error message and returns False. This function likely manages page operations in a system requiring data persistence and ret... | def moveBack(self,page):
if self.inDisk(page) :
self.delete(page)
self.add(page)
return True
print('moveBack failed')
return False |
def _parse_results_as_timeserie(rows):
results = []
entries = {}
for row in rows:
timestamp = row.timestamp
name = row.name
if row.value is None:
continue
try:
value = float(row.value)
except ValueErr... | This code processes multiple targets by querying a Cassandra database with dynamic time ranges, parsing results as time series or tables, applying aggregations, and returning JSON-formatted outputs. It handles errors like missing parameters, authorization issues, and connection failures, setting appropriate HTTP status... | def post(self):
targets = self.args.get('targets')
if not targets:
self.set_status(400)
return
if not self._extract_time_range():
self.set_status(400)
return
results = []
try:
cassandra_client = Client.get_client()
... |
def decrease_width(params: Parameters, num_pixels):
img = params.image.copy() # copiaza imaginea originala
for i in range(num_pixels):
print('Eliminam drumul numarul %i dintr-un total de %d.' % (i+1, num_pixels))
# calculeaza energia dupa ecuatia (1) din articol
E = comp... | The function `resize_image` adjusts an image based on the `resize_option` parameter. It either reduces width, height, amplifies content by resizing and cropping, or deletes a selected object using ROI. The operation uses helper functions like `decrease_width`, `decrease_height`, and `delete_object`, with OpenCV for res... | def resize_image(params: Parameters):
# redimensioneaza imaginea pe latime
if params.resize_option == 'micsoreazaLatime':
resized_image = decrease_width(params, params.num_pixels_width)
return resized_image
# redimensioneaza imaginea pe inaltime
elif params.resize_option == '... |
def hebrew_leap(year):
if ((((year*7)+1) % 19) < 7):
return True
else:
return False
def _long_heshvan(year):
if ((days_in_hebrew_year(year) % 10) == 5):
return True
else:
return False
def _short_kislev(year):
if ((days_in_hebrew_year(year) % 10) == 3):
return True
else:
return False | The function determines the number of days in a specified Hebrew month of a given year, returning 29 or 30 days based on predefined rules. It checks if the month is one of the fixed 29-day months (2, 4, 6, 10, 13), adjusts for non-leap years (month 12), and applies variable-length rules for months 8 (Heshvan) and 9 (Ki... | def hebrew_month_days(year, month):
if ((month == 2) or \
(month == 4) or \
(month == 6) or \
(month == 10) or \
(month == 13)):
return 29
if ((month == 12) and (not hebrew_leap(year))):
return 29
if ((month == 8) and (not _long_heshvan(year))):
return 29
if ((month == 9) and... |
def hebrew_year_months(year):
if hebrew_leap(year):
return 13
else:
return 12
def hebrew_month_days(year, month):
if ((month == 2) or \
(month == 4) or \
(month == 6) or \
(month == 10) or \
(month == 13)):
return 29
if ((month == 12) and (not hebrew_leap(year))):
return ... | This function converts a Hebrew calendar date (year, month, day) to an absolute day count by summing days from months, adding the elapsed days for the year, and subtracting a fixed offset (1373429) to align with a specific reference date. | def hebrew_to_absdate(year, month, day):
value = day
returnValue = value
if month < 7:
for m in range(7,hebrew_year_months(year)+1):
value = hebrew_month_days(year, m)
returnValue += value
for m in range(1,month):
value = hebrew_month_days(year, m)
returnValue += value
else:
... |
def hebrew_to_absdate(year, month, day):
value = day
returnValue = value
if month < 7:
for m in range(7,hebrew_year_months(year)+1):
value = hebrew_month_days(year, m)
returnValue += value
for m in range(1,month):
value = hebrew_month_days(year, m)
returnValue += value
else:
... | The code converts an absolute date (absdate) into a Hebrew calendar date, returning the year, month, day, and the name of the Hebrew month. It approximates the year, iterates to find the correct year, determines the starting month, identifies the specific month, calculates the day, and retrieves the month's name. | def absdate_to_hebrew(absdate): # year, month, day
approx = (absdate+1373429) // 366
y = approx
while 1:
temp = hebrew_to_absdate(y+1, 7, 1)
if absdate < temp:
break
y += 1
year = y
temp = hebrew_to_absdate(year, 1, 1)
if absdate < temp:
start = 7
else:
start = 1
m = start
... |
def get_index_finger_coordinates(results):
if results.multi_hand_landmarks and results.multi_hand_landmarks[0].landmark:
hand_landmarks = results.multi_hand_landmarks[0]
index_finger_landmark = hand_landmarks.landmark[8]
return remap_to_pixel_coordinates(index_finger_landmark.x, index_finger... | The code implements hand gesture-based mouse control using Mediapipe for hand tracking. It processes video frames to detect index finger coordinates, applies smoothing via exponential moving average, and maps these to mouse movements. A thumb-index finger touch triggers simulated mouse clicks (down/up) with a delay mec... | def main_loop():
global cursor_manager;
global IS_MOUSE_DOWN
global past_coordinates_window, smoothed_coordinates
while True:
# Read a frame from the video capture
ret, frame = vid.read()
# Break the loop if unable to read a frame
if not ret:
break
#... |
def read_stdin():
l_stdin = []
for line in sys.stdin:
l_stdin.append(line)
return l_stdin;
def parse_stdin(l_stdin):
len_stdin = []
ant.append(int(l_stdin[0]))
l_stdin.pop(0)
for tmp in l_stdin:
len_stdin.append(len(tmp))
for line in l_stdin:
if line[0] == '#' and line[1] != '#':
continue
if len(line... | The main task of the code is to read and parse standard input into a room structure, append an ant count, retrieve the starting position of the first ant, and print the map if parsing succeeds. The program then exits immediately after. | def main():
ant_num.append(1)
l_stdin = read_stdin()
room = parse_stdin(l_stdin)
ant_start = ant[0]
if (room):
print_map(room, ant_start)
sys.exit() |
def split_list(data):
number_of_splits = int(len(data) / 5)
for i in range(0, len(data), number_of_splits):
yield data[i:i + number_of_splits]
def ask_k_value():
while True:
try:
k_value = int(input('Geef een K waarde voor het algoritme: '))
break;
except Val... | The code splits a dataset into five equal parts, generates subsets by combining four parts each, and evaluates model accuracy (using a given k-value) on both subsets and individual splits. It compares total accuracy across all subsets versus individual splits, then prints whether the k-value performs better on subsets ... | def train_test_split(data):
""""dataset wordt in 5 gesplits in gelijke lengtes"""
split = list(split_list(data))
k_value = ask_k_value()
a = split[0]
b = split[1]
c = split[2]
d = split[3]
e = split[4]
accuracy_values_sets = []
subset_1 = a + b + c + d
subset_2 = a + b + ... |
def load_csv(filename):
file = open(filename, "r")
lines = reader(file)
dataset = list(lines)
return dataset
def prepare_data(dataset):
dataframe = []
for data in dataset[1:]:
coordinate_x_abv = float(data[1])
coordinate_y_ibu = float(data[2])
type_of_beer = data[3]
"""Afro... | The main task of the code is to provide a menu-driven interface for testing machine learning tasks on beer dataset. It allows users to input custom data for prediction, test algorithm accuracy with k-value, or split data into training/test sets. The loop handles user choices, executes corresponding functions, and break... | def mainloop():
dataset = load_csv("NewDatasetBeers.csv")
data = prepare_data(dataset)
while True:
try:
print("1: Zelf input testen")
print("2: Algoritme testen")
print("3: Train split methode")
choice = int(input("Ik kies voor optie: "))
... |
def get_input():
FiledirList = tf.train.match_filenames_once(VALID_PATH)
filename_queue = tf.train.string_input_producer(FiledirList, shuffle=False)
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
... | This code evaluates a neural network model (OEN) by processing batches of input data, computing deviation (Dev_total) and BL15 metrics, and generating histograms for output statistics. It loads a pre-trained model, runs inference, and calculates performance metrics across NUM_BATCH iterations, printing average deviatio... | def main():
with tf.Graph().as_default():
image_batch, theta_batch, label_batch = get_input()
with tf.variable_scope("OEN") as scope:
logit_batch = inference(image_batch)
saver = tf.train.Saver()
init = (tf.global_variables_initializer(), tf.local_variables_initializer... |
def get_input():
FiledirList = tf.train.match_filenames_once(TRAIN_PATH)
filename_queue = tf.train.string_input_producer(FiledirList, shuffle=False)
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
... | The main task of the code is to train a neural network model for joint regression (predicting sin/cos values) and classification tasks on image data. It defines a loss function combining regression loss (loss_train) and classification cross-entropy (loss_class), performs gradient-based optimization via training(), and ... | def main():
with tf.Graph().as_default():
image_batch, label_batch, sin_cos_batch = get_input()
#regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)
with tf.variable_scope("OEN") as scope:
logits_reg, logits_cls = inference(image_batch, regularizer=None)
... |
def identify_user(use_user_name=True):
"""Returns a string that identifies the user ("fgentner (192.0.2.1)", "192.0.2.1")."""
if use_user_name and flask.request.authorization:
return '{} ({})'.format(flask.request.authorization.username, flask.request.remote_addr)
else:
return flask.request.... | The function authenticates a user via LDAP using provided credentials, retrieves their associated roles from the directory, and returns a set of role names including any implied roles. It handles LDAP connection, role search, and role name extraction, while logging authentication attempts and potentially raising an exc... | def get_roles(user_name, password):
"""Returns a set of the blockip roles of the user with the given credentials. May raise NotAuthorized."""
context.logger.info('Connecting to LDAP to authenticate user %s.', identify_user(use_user_name=False))
ldap_user = context.settings.get('ldap', 'user_name_template').... |
def parse_command_line_arguments(args=None):
return create_command_line_argument_parser().parse_args(args)
def maybe_drop_existing_schema(context):
if context.drop_schema_even_if_the_database_is_not_local_yes_i_am_absolutely_sure_i_want_to_do_that:
drop_existing_schema(context)
elif context.drop_sch... | The main task of the code is to parse command-line arguments, configure logging, read settings from specified configuration files, create a context object, and initialize a database schema (dropping existing schema if needed) along with other components using the context. It orchestrates setup流程 including argument pars... | def main(args=None):
global LOGGER
command_line_arguments = parse_command_line_arguments(args)
LOGGER = utilities.create_logger(command_line_arguments.log_level)
configuration_settings = utilities.read_configuration_files(command_line_arguments.configuration_file_paths)
configuration_file_paths_read... |
def get_roles(user_name, password):
"""Returns a set of the blockip roles of the user with the given credentials. May raise NotAuthorized."""
context.logger.info('Connecting to LDAP to authenticate user %s.', identify_user(use_user_name=False))
ldap_user = context.settings.get('ldap', 'user_name_template').... | This function checks if a user has the required role for access, bypassing LDAP exception handling. It adjusts the role if 'for_network' is True and the role exists in ROLES. If permission checks are skipped, it logs a debug message. Otherwise, it verifies the role against the user's roles, logging access allowance or ... | def check_permission_unsafe(role, for_network):
"""As `check_permission()`, but does not handle LDAP exceptions."""
authorization = flask.request.authorization
if for_network and 'range-' + role in ROLES:
role = 'range-' + role
if context.arguments.no_permission_checks:
context.logger.... |
def __read_source_code(self) -> str:
"""
Reads and returns LUA source code from path or url given in the data.
Returns
--------
str
original LUA source code which was preprocessed and stored in
JSON file
"""
# if there's path provided rea... | The main task of the code is to initialize an object by loading preprocessed LUA source code data from a JSON file path, URL, or provided data dictionary. If no valid source is given, it raises an error. It then initializes attributes like byte dimensions, source code, tag table, and image dimensions, while building th... | def __init__(self, path=None, url=None, data=None):
"""
According to the parameters given, the preprocessed data are read
from JSON file (parameter path) or from the given url or
simply copied from the given parameter data. If none of
the parameters is provided, the function rais... |
def __get_terminal_pairs(self) -> Any:
terminals = self.get_terminals()
pairs = np.asarray(list(itertools.combinations(terminals, 2)))
return pairs
def __find_path(self, start: str, end: str, visited=None) -> PATH or None:
if start == end:
return [start]
visited = v... | The code generates paths between terminal pairs by finding routes using `__find_path`, adding arrows via `__add_arrows`, and returning a list of sliced paths (excluding start/end points). It processes each terminal pair, constructs paths, and collects them into a list for output. | def get_paths(self) -> List[PATH]:
terminal_pairs = self.__get_terminal_pairs()
paths = list()
for pair in terminal_pairs:
path = self.__find_path(pair[0][0], pair[1][0])
path = self.__add_arrows(path)
paths.append(path[1:-1])
return paths |
def __get_terminal_pairs(self) -> Any:
terminals = self.get_terminals()
pairs = np.asarray(list(itertools.combinations(terminals, 2)))
return pairs
def __find_path(self, start: str, end: str, visited=None) -> PATH or None:
if start == end:
return [start]
visited = v... | The main task of the code is to generate context paths between terminal pairs by finding routes between nodes, adding directional arrows to the path, and structuring the result with start and end terminals. It processes terminal pairs, extracts path segments, and returns a list of formatted context paths for further us... | def get_context_paths(self) -> List[PATH_CONTEXT]:
terminal_pairs = self.__get_terminal_pairs()
context_paths = list()
for pair in terminal_pairs:
terminal_from = (str(pair[0][0]), str(pair[0][1]))
terminal_to = (str(pair[1][0]), str(pair[1][1]))
path = self._... |
def sceneInfo(context, f):
dataobjs = {}
scene = context.scene
for obj in scene.objects:
thisobj = {
"name": str(obj.name),
"type": str(obj.type)
}
if(obj.parent != None):
thisobj["parent"] = {
"name": str(obj.parent.name),
... | The main task of the code is to generate a Lua file containing scene data (info, objects, meshes, animations) for Defold, based on specified commands. It cleans a temporary directory, creates necessary folders, and writes structured data to 'syncdata.lua' by invoking functions like sceneInfo, sceneObjects, sceneMeshes,... | def getData( context, clientcmds, dir, config):
temppath = os.path.abspath(dir + '/defoldsync/temp')
try:
shutil.rmtree(temppath, ignore_errors=True)
except OSError as e:
print("Error: %s : %s" % (dir_path, e.strerror))
defoldUtils.ClearErrors( config )
# Make temp folder if it doesnt exist
... |
def kitchen_title(self):
kitchen_title = \
'<div class="row">' \
'<div class="col-lg-12 col-12">' \
'<div>' \
f'<h1 class="font-weight-bold font-italic">{self.pos_id.name}</h2>' \
'</div>' \
'<div class="mt32">' \
'<button class... | The main task of the code is to generate an HTML-formatted "kitchen" string for each record by aggregating components like kitchen title, screens, bar displays, and product sections. It combines these elements using nested div tags to create a structured layout, likely for rendering kitchen-related data in a web interf... | def compute_kitchen(self):
for record in self:
kitchen_title = self.kitchen_title()
kitchen_screen = self.kitchen_screen()
bar_screen = self.bar_screen()
ready_products = self.ready_products()
togo_products = self.togo_products()
record.kit... |
def build_opcua_string(st):
return {"str_length":len(st), "str":st}
def send_recv(self, msg, count=1, should_recv=True, hold_final_chunk=False):
msg_length = len(msg)
msg = bytearray(msg)
msg_type = msg[0:3]
msg[4:8] = struct.pack("I", msg_length)
for i in range(count):
... | This code creates and activates an OPC UA session by sending HEL, OPN, Create, and Activate messages. It configures session parameters like timestamps, session names, and security tokens, handling different program types (e.g., Open62541, Ignition). It returns secure channel ID, authentication token, sequence number, a... | def create_session(self, open_timestamp=None, session_name=None, create_malformed_utf8_session=False):
hel_raw, opn_raw, create_raw, activate_raw = get_raw_open_session_messages(self.program_type)
msg_opn_parsed = OPCUA_MESSAGE.parse(opn_raw)
self.seq_number = msg_opn_parsed.opc_data.sequence_n... |
def _init_folder(self, folder_name=None):
"""
Initializes all folders to be used during training
Saves the folder locations as class attributes
Args:
folder_name: str
if not None, the logdir will be set to this folder
"""
#... | This code tests a machine learning model by loading trained encoder and predictor components, evaluating performance on training/validation/testing datasets using Monte Carlo dropout, exporting loss metrics to TensorBoard, and optionally generating attention weight visualizations or UMAP plots for data representation. ... | def test(self, folder_name, mc_samples_test=40, export_attention_weights=False, export_umap=False):
"""
Tests the model in runs/folder_name directory, printing losses and exporting several plots depending on args
Args:
folder_name: str
name of folder ... |
def _init_folder(self, folder_name=None):
"""
Initializes all folders to be used during training
Saves the folder locations as class attributes
Args:
folder_name: str
if not None, the logdir will be set to this folder
"""
#... | The code performs two-stage training as described in the paper. It first trains an encoder in stage 1, saves losses, and checks for user interruption. If continued, stage 2 trains a predictor using the stage 1 encoder, loads data without augmentation, and saves final losses. The process handles interruptions between st... | def train_two_stage(self):
"""
Does two-stage training as described in paper
"""
self._init_folder()
# First stage training
stage = "s1"
print("\nInitiating first stage training")
self.load_dataset(self.folder_name_data, self.apply_augmentation)
... |
def _init_folder(self, folder_name=None):
"""
Initializes all folders to be used during training
Saves the folder locations as class attributes
Args:
folder_name: str
if not None, the logdir will be set to this folder
"""
#... | This function resumes or initiates the second stage of training using pre-trained models from the first stage, avoiding redundant computation. It loads saved first-stage data, initializes the encoder and predictor, executes the second-stage training loop, records losses, and saves parameters. Interrupts are handled gra... | def train_stage_2(self, folder_name):
"""
In case the first stage training got interrupted, and you (accidentally) did not continue for second stage
training, this function can be used to train second stage without having to redo the
(computational intensive) first stage trai... |
def openingMessage(self):
self.coloriser.coloriseCommunication("Welcome to the expenses app")
self.coloriser.coloriseCommunication(str(date.today()))
def overview(self):
self.expenseController.getDaysOfTheWeekExpenses()
self.coloriser.coloriseExpense(self.expenseController.getLastWeekExp... | The code defines an application loop for an expense tracking system, displaying a menu with options to insert expenses, view totals, check purchase history, or quit. It uses user input to trigger corresponding methods: insertExpense(), getPurchases(), getPurchaseHistory(), or exit (return True). | def app(self):
self.openingMessage()
self.overview()
string = "1. Insert expense\n2. Total expenses\n3. Purchase history\n4. Quit\n"
switcher = self.switch(string)
if switcher == 1:
self.insertExpense()
elif switcher == 2:
self.getPurchases()
... |
def flying_stage_moves(self, player):
moves_list = []
for i in range(5):
for j in range(5):
if self.board[i][j] == player:
for x in range(5):
for y in range(5):
if self.board[x][y] == 0 and (i == x or j =... | This code handles an agent's turn in a board game, placing/moving pieces based on game stages (placement, flying). It selects random legal moves, updates the board, checks for new mills, removes opponent's pieces if mills are formed, and increments move counters. The agent manages three phases: placing initial pieces, ... | def agent_turn(self):
if self.agent_pieces == 3 and self.agent_pieces_not_placed == 0:
legal = self.flying_stage_moves(1)
if len(legal) < 2:
random_move = legal[0]
else:
random_move = legal[rnd.randint(0, len(legal) - 1)]
self.board... |
def flying_stage_moves(self, player):
moves_list = []
for i in range(5):
for j in range(5):
if self.board[i][j] == player:
for x in range(5):
for y in range(5):
if self.board[x][y] == 0 and (i == x or j =... | This function handles an opponent's turn in a board game by generating legal moves, selecting a random move, updating the board with piece placements or movements, checking for new mills, and removing opponent pieces if mills are formed, while tracking game state and move counts. | def opp_turn(self):
if self.opp_pieces == 3 and self.opp_pieces_not_placed == 0:
legal = self.flying_stage_moves(2)
if len(legal) < 2:
random_move = legal[0]
else:
random_move = legal[rnd.randint(0, len(legal) - 1)]
self.board[rando... |
def flying_stage_moves(self, player):
moves_list = []
for i in range(16):
if self.board[i] == player:
moves_list.extend(
(i, x)
for x in range(16)
if self.board[x] == 0 and (i == x or abs(i - x))
)
... | This function handles an agent's turn in a board game, managing piece placement and movement. It randomly selects legal moves for placing initial pieces, moving existing ones, or flying pieces. After each move, it updates the board, checks for newly formed mills, removes opponent's pieces if mills are detected, and inc... | def agent_turn(self):
if self.agent_pieces == 3 and self.agent_pieces_not_placed == 0:
legal = self.flying_stage_moves(1)
random_move = legal[0] if len(legal) < 2 else rnd.choice(legal)
self.board[random_move[1][rnd.randint(0, 1)]] = 0
self.board[random_move[1][0]... |
def flying_stage_moves(self, player):
moves_list = []
for i in range(16):
if self.board[i] == player:
moves_list.extend(
(i, x)
for x in range(16)
if self.board[x] == 0 and (i == x or abs(i - x))
)
... | This function handles an opponent's turn in a board game, selecting random legal moves based on the game phase (placing or flying pieces), updating the board state, checking for new mills, and removing opponent pieces if mills are formed, while tracking move counts and rankings. | def opp_turn(self):
if self.opp_pieces == 3 and self.opp_pieces_not_placed == 0:
legal = self.flying_stage_moves(2)
random_move = legal[0] if len(legal) < 2 else rnd.choice(legal)
self.board[random_move[0]] = 0
self.board[random_move[1][rnd.randint(0, 1)]] = 2
... |
def agent_turn(self):
if self.agent_pieces == 3 and self.agent_pieces_not_placed == 0:
legal = self.flying_stage_moves(1)
if len(legal) < 2:
random_move = legal[0]
else:
random_move = legal[rnd.randint(0, len(legal) - 1)]
self.board... | The main task of the code is to generate and evaluate potential board states for an agent's turn in a game, prioritizing moves based on precomputed rankings. It creates new board configurations by placing or moving pieces, checks for valid moves/adjacent positions, and selects the highest-ranked state from existing dat... | def smart_agent_turn(self):
boards_list = []
flattened_board = [str(item) for row in self.board for item in row]
if self.agent_pieces == 3 and self.agent_pieces_not_placed == 0:
for i in range(len(flattened_board)):
if flattened_board[i] == '1':
t... |
def agent_turn(self):
if self.agent_pieces == 3 and self.agent_pieces_not_placed == 0:
legal = self.flying_stage_moves(1)
random_move = legal[0] if len(legal) < 2 else rnd.choice(legal)
self.board[random_move[1][rnd.randint(0, 1)]] = 0
self.board[random_move[1][0]... | The function generates possible board states based on the agent's available moves, evaluates them using pre-existing data, and selects the optimal move. It handles piece placement, mill detection, and opponent piece removal, prioritizing high-ranked variations to update the board state and proceed with the game strateg... | def smart_agent_turn(self):
boards_list = []
if self.agent_pieces == 3 and self.agent_pieces_not_placed == 0:
boards_list.extend(
''.join(['0' if x == i else '1' if x == j else str(x) for x in self.board])
for i, x in enumerate(self.board)
if ... |
def get_face(dir):
im = PIL.Image.open(dir)
im = im.convert('RGB')
image = np.array(im)
features = face_encodings(image)
return features
def get_iris(dir):
template, mask, _ = iris_extract(dir)
return template, mask
def get_face_scores_nm(face_encoding, data_dir):
files = glob(os.pa... | The code computes fused scores by combining face and iris recognition results from specified directories, then returns the fused scores and the index of the maximum score. It retrieves face and iris data, calculates individual scores, merges them, and identifies the highest score's position for identification purposes. | def get_fusion_scores(face_dir, iris_dir, data_dir):
face_encoding = get_face(face_dir)
template, mask = get_iris(iris_dir)
face_scores = get_face_scores_nm(face_encoding, data_dir)
iris_scores = get_iris_scores_nm(template, mask, data_dir)
fusion_scores = cal_fusion_scores(face_scores, iris_scores)... |
def load_input(use_test_input=False):
global RAW_INPUT
path = f'inputs/day{DAY:02}.txt'
if use_test_input:
path = f'inputs/day{DAY:02}_test.txt'
with open(path) as f:
RAW_INPUT = f.read()
def parse_input():
global INPUT
INPUT = []
for line in RAW_INPUT.split('\n'):
if... | The main task of the code is to process input data by loading and parsing it, then compute and print the results of two distinct parts (part1 and part2) of a solution. The `main()` function orchestrates these steps sequentially, outputting the outcomes of each part with labeled messages. | def main():
load_input()
parse_input()
print('PART 1:', part1())
print('PART 2:', part2()) |
def load_input(use_test_input=False):
global RAW_INPUT
path = f'inputs/day{DAY:02}.txt'
if use_test_input:
path = f'inputs/day{DAY:02}_test.txt'
with open(path) as f:
RAW_INPUT = f.read()
def parse_input():
global INPUT
instrs = tuple(0 if c == 'L' else 1 for c in RAW_INPUT.split... | The main task of the code is to execute the `main()` function, which loads and parses input data, then computes and prints results for two parts of a problem. It calls `part1()` and `part2()` to process the parsed input, outputting their results with labels "PART 1:" and "PART 2:". The code structure separates input ha... | def main():
load_input()
parse_input()
print('PART 1:', part1())
print('PART 2:', part2()) |
def fetch_filter_criteria(self, filter_id, action_result):
endpoint = "{}/{}".format(IXIA_GET_FILTERS_ENDPOINT, filter_id)
ret_val, response = self._make_rest_call_helper_oauth2(action_result, endpoint, verify=self._verify)
if phantom.is_fail(ret_val):
return action_result.get_stat... | This function updates MAC address criteria for a network filter by processing input parameters like source/destination MACs, administration types, and flow pairs. It validates JSON inputs, constructs appropriate MAC data structures, handles overwrites, and sends the updated criteria via a REST API PUT request to apply ... | def _handle_update_mac(self, param): # noqa:C901
action_result = self.add_action_result(ActionResult(dict(param)))
filter_id = param['filter_id_or_name']
criteria_type = param['type']
overwrite = param.get('overwrite', False)
criteria = dict()
mac_add_dict = dict()
... |
def fetch_filter_criteria(self, filter_id, action_result):
endpoint = "{}/{}".format(IXIA_GET_FILTERS_ENDPOINT, filter_id)
ret_val, response = self._make_rest_call_helper_oauth2(action_result, endpoint, verify=self._verify)
if phantom.is_fail(ret_val):
return action_result.get_stat... | This function updates port criteria for a network filter by processing input parameters, validating port data, constructing appropriate data structures, and making a PUT request to an API endpoint to apply the changes. It handles both single-port and port-flow configurations, ensuring data integrity and correct formatt... | def _handle_update_port(self, param):
action_result = self.add_action_result(ActionResult(dict(param)))
filter_id = param['filter_id_or_name']
criteria_type = param['type']
overwrite = param.get('overwrite', False)
criteria = dict()
port_dict = dict()
params = d... |
def fetch_filter_criteria(self, filter_id, action_result):
endpoint = "{}/{}".format(IXIA_GET_FILTERS_ENDPOINT, filter_id)
ret_val, response = self._make_rest_call_helper_oauth2(action_result, endpoint, verify=self._verify)
if phantom.is_fail(ret_val):
return action_result.get_stat... | The main task of the code is to update IPv4 criteria for a network filter by parsing input parameters, validating IP addresses, handling overwrite logic, and making a REST API PUT request to modify the filter's criteria. It ensures correct JSON formatting, checks input validity, and updates the filter's configuration o... | def _handle_update_ip(self, param):
action_result = self.add_action_result(ActionResult(dict(param)))
filter_id = param['filter_id_or_name']
criteria_type = param['type']
overwrite = param.get('overwrite', False)
criteria = dict()
ip_add_dict = dict()
params = d... |
def print_python_exe(self):
return self.python_cmd(
"import sys; print(sys.executable{})".format(
"" if six.PY3 or IS_PYPY else ".decode(sys.getfilesystemencoding())",
),
)
def print_os_env_var(self, var):
val = '"{}"'.format(var)
return self.pytho... | The main task of the code is to generate a list of commands for testing virtual environment activation. It captures the Python executable path, checks the VIRTUAL_ENV variable, activates the specified script, re-checks the environment, runs pydoc, deactivates, and verifies final states. This validates virtualenv behavi... | def _get_test_lines(self, activate_script):
commands = [
self.print_python_exe(),
self.print_os_env_var("VIRTUAL_ENV"),
self.activate_call(activate_script),
self.print_python_exe(),
self.print_os_env_var("VIRTUAL_ENV"),
self.print_prompt(),... |
def _generate_test_script(self, activate_script, tmp_path):
commands = self._get_test_lines(activate_script)
script = ensure_text(os.linesep).join(commands)
test_script = tmp_path / "script.{}".format(self.extension)
with open(ensure_text(str(test_script)), "wb") as file_handler:
... | This method tests an activation script by verifying its line endings and execution output. It reads the script, checks line endings against system/version settings, generates a test script, invokes it with environment modifications, captures output, and asserts expected results. The test ensures correct script behavior... | def __call__(self, monkeypatch, tmp_path):
activate_script = self._creator.bin_dir / self.activate_script
# check line endings are correct type
script_content = activate_script.read_bytes()
for line in script_content.split(b"\n")[:-1]:
cr = b"\r" if sys.version_info.major ==... |
def preprocess(file, vcf, seqclass_names=[], signed=True):
"""Processes data so that there is a single row per position representing the alteration with the maximum average score at that position.
Parameters
----------
file : string
Filename of NumPy sequence class scores.
vcf : Pandas Data... | The function `plot_max_from_scores` processes Sei prediction data by preprocessing scores, identifying maximum values (by class or category), and generating a plot. It loads scores from a file, applies preprocessing if needed, computes maxima using `find_max` or `find_max_by_category`, and visualizes results with `plot... | def plot_max_from_scores(filename, file, vcf, TSS={}, signed=True, plot_by="class", pre=False, seqclass_names=[]):
"""Preprocesses Sei prediction data, finds the maximum, and then plots the results. Runs `preprocessing`, `find_max` or `find_max_by_category`, and then `plot_max`.
Parameters
----------
... |
def advance(self):
"""Read one char from input and skip white spaces"""
self.read()
self.skip_ws()
def read(self, n=1):
"""Read n chars from input and return them"""
new_pos = self.pos + n
res = self.expr[self.pos:new_pos]
self.pos = new_pos
self.next_unr... | This function parses a non-negative integer from the input stream. It returns 0 if the next character is '0', otherwise reads a 1-9 digit followed by any subsequent digits to form the full number. If no valid digit is found, it raises an error. | def parse_one_or_more_digits(self) -> int:
if self.next_unread_char == '0':
self.advance()
return 0
if self.next_unread_char in self.one_nine:
return int(self.read()+self.read_digits(0))
self.error("parse number") |
def parse_int(self):
"""Parse integer and return it"""
if self.next_unread_char == "-":
self.read()
return -1*self.parse_one_or_more_digits()
return self.parse_one_or_more_digits()
def parse_fraction(self) -> float:
if self.next_unread_char == '.':
ret... | The main task of the code is to parse a number by combining its integer part (parse_int()), fractional part (parse_fraction()), and exponent (parse_exponent()), then calculating the final value as (integer + fractional) × 10^exponent. This constructs a numerical value from its components, such as converting "123.45e6" ... | def parse_number(self):
return (self.parse_int() + self.parse_fraction()) * 10 ** self.parse_exponent() |
def _testsendMail():
sender = "dnglk@example.com"
psswrd = "qsqjkepmxcgipmux"
to = "mwijw@example.com"
cc = "wzsmm@example.com"
sub = "mail sub"
body = "Dear body"
files = ["Thinking.jpg"]
filesPath = "D:\\Projects\\Momentix\\mailApp\\attachments\\"
print ("testsendMail")
... | The main task of the code is to call the _testsendMail() function and immediately return, making the rest of the mail-sending logic (argument parsing, email configuration, and sending) unreachable due to the early return statement. | def main(args):
_testsendMail()
return
mailArgs = _parseArgs()
print("mail app called",mailArgs)
#1.
sender = mailArgs.sender
#2.
subject = mailArgs.subject
#3. msg = getMailText()
msg = mailArgs.body
#4. account app key
password = mailArgs.password
... |
def generate_random_fourier_matrix(num_params, unit_sphere, cuda):
if unit_sphere:
v = randn(num_params, 784, cuda)
v /= norm(v, cuda=cuda)
else:
v = randn(num_params, 784, cuda) + 1/25
return v
def transform_inputs(random_fourier_matrix, inputs, relu=False, cuda=False):
transfor... | The function `compute_random_fourier_features` trains a model using random Fourier features for regression/classification. It generates a random Fourier matrix, transforms input data, solves a least squares problem to find coefficients, and evaluates predictions on training and test sets using MSE and zero-one loss. It... | def compute_random_fourier_features(num_params, input_train, target_train, input_test, target_test, relu=False, cuda=False, one_hot=False, unit_sphere=False):
v = generate_random_fourier_matrix(num_params, unit_sphere, cuda)
x = transform_inputs(v, input_train, relu, cuda)
a = lstsq(x, target_train, cuda)
... |
def createP(self):
list = random.sample(range(self.size ** 2), self.size ** 2)
if (self.size == 4):
return self.createP15(list)
index = 0
for i in range(self.size):
for j in range(self.size):
self.board[i][j] = list[index]
index +=... | The code initializes a sliding puzzle (e.g., 8-puzzle) of size n×n, creates a solvable board configuration if 'new' is True, and computes initial heuristic values (h1, h2, h3) for problem-solving algorithms. It sets up the board matrix, ensures solvability through iterative generation, and stores heuristics for pathfin... | def __init__(self, size, new):
# n x n size of puzzle 3,4,5(8,15,24)
self.size = int((size + 1) ** (1 / 2))
self.board = [[0 for x in range(self.size)]
for y in range(self.size)] # matrix
self.f1 = 0
self.new = new
if (new):
solvable = ... |
def import_data(self):
with tf.name_scope("data"):
train_data, test_data = utils.get_dataset(self.batch_size)
iterator = tf.data.Iterator.from_structure(train_data.output_types,
train_data.output_shapes)
self.game, self.labe... | The main task of the code is to construct a machine learning model's computation graph by importing data, setting up the inference process, defining the loss function, optimizing the model, evaluating performance, and generating summaries for monitoring training progress and model behavior. | def build(self):
'''
Build the computation graph
'''
self.import_data()
self.inference()
self.create_loss()
self.optimize()
self.eval()
self.summary() |
def debug_message(self, message):
if self.debug:
print('debug_message', repr(message))
def enquire(self):
self.write(C['ENQ'])
def read(self):
data = ""
max_tries = 100
while max_tries > 0:
max_tries -= 1
x = self.connection.read().decode()
... | This function reads a response from a MaxiGauge controller, checks for expected status codes (ACQ/NAK), handles NAK by raising a detailed error with system/gauge codes, and returns the processed response. It logs warnings for unexpected responses and trims line termination characters before returning the result. | def get_ACQ_or_NAK(self):
return_code = self.connection.readline()
self.debug_message(return_code)
# The following is usually expected but our MaxiGauge controller sometimes forgets this parameter...
# That seems to be a bug with the DCC command.
# if len(return_code)<3: raise Ma... |
def write(self, what):
self.debug_message(what)
self.connection.write(what.encode())
def get_ACQ_or_NAK(self):
return_code = self.connection.readline()
self.debug_message(return_code)
# The following is usually expected but our MaxiGauge controller sometimes forgets this paramete... | The code sends a mnemonic command to a device, flushes input, and waits for an acknowledgment (ACQ/NAK). It then sends multiple enquires, collects responses, and returns them as a list. The function handles communication with a device, ensuring proper command transmission and response retrieval based on the specified n... | def send(self, mnemonic, num_enquiries=0):
self.connection.flushInput()
self.write(mnemonic + LINE_TERMINATION)
# if mnemonic != C['ETX']: self.read()
# self.read()
self.get_ACQ_or_NAK()
response = []
for i in range(num_enquiries):
self.enquire()
... |
def initialize_runner(args):
"""Sets up the Runner class with static attributes."""
Runner.unlink = print_filename if args.dry_run else remove_file
Runner.rmdir = print_dirname if args.dry_run else remove_directory
Runner.ignore = args.ignore
def descend_and_clean(directory, file_types, dir_names):
... | The code performs cross-platform cleaning of Python bytecode by removing compiled files (e.g., .pyc, .pyo) and associated directories from specified directories. It also handles debris (temporary files) for given topics and optionally deletes freeform targets based on flags. The function logs removal counts and failure... | def pyclean(args):
"""Cross-platform cleaning of Python bytecode."""
initialize_runner(args)
for dir_name in args.directory:
dir_path = Path(dir_name)
log.info("Cleaning directory %s", dir_path)
descend_and_clean(dir_path, BYTECODE_FILES, BYTECODE_DIRS)
for topic in args.d... |
def get_max_vr(self):
start = self.IR_LIST.head
max = 0
while (start != None):
if (start.arg1[VR_IDX] != None and start.arg1[VR_IDX] > max):
max = start.arg1[VR_IDX]
if (start.arg2[VR_IDX] != None and start.arg2[VR_IDX] > max):
max = start.... | This method performs register allocation by mapping virtual registers (VRs) to physical registers (PRs), managing register spilling, and handling rematerializable values. It initializes data structures for tracking allocations, processes each instruction in the IR list, and dynamically assigns PRs using a stack. For ea... | def dif_alloc(self, k):
# -----------initialization-----------
self.max_vr_num = self.get_max_vr()
self.k = k
self.VRToPR = {i: None for i in range(self.max_vr_num + 1)}
self.PRToVR = {i: None for i in range(self.k - 1)} # keep it as normal k
self.VRToSpillLoc = {}
... |
def emphasis(content):
return Fore.BLUE + content + Fore.RESET
def error(content):
return Fore.RED + content + Fore.RESET
def login():
os.system('clear')
while True:
username = input('Enter ' + emphasis('login') + ': ')
password = getpass('Enter ' + emphasis('password') + ': ')
... | The code defines a menu-driven interface for a Zoo Shop application, connecting to a database, displaying login/register/exit options, validating user input, and executing corresponding actions like login, registration, or exiting while managing database connections. | def hello():
Database.connect()
while True:
os.system('clear')
print('Welcome to ' + emphasis('Zoo Shop\n'))
print('What do you want?\n' +
emphasis('1') + ' Login\n' +
emphasis('2') + ' Register\n' +
emphasis('3') + ' Exit\n')
while Tr... |
def login(raise_error=False):
usr = os.environ.get("DOCKER_USERNAME", "")
pwd = os.environ.get("DOCKER_PASSWORD", "")
registry = os.environ.get("DOCKER_REGISTRY", "") or "index.docker.io"
if not (usr and pwd):
error_msg = (
"Could not login to docker registry."
"Missing e... | The main task of the code is to build a Docker image from a Dockerfile, intelligently deciding whether to build locally, pull from remote, or retag existing images. It handles caching, tag management, and optional pushing to remote repositories, with parameters to control build steps, tagging, and cache behavior. | def smart_build(
dockerfile_path: str,
tag_as=None,
push_core=True,
push_final=False,
with_login=False,
addl_args=None,
ignore_caches=False,
):
"""
Builds the dockerfile if needed but pulls it from the remote if possible.
"""
if bool(with_login):
login()
tag_as = ... |
def get_ecs_task_detail_url(region, task_arn, cluster_name):
task_id = task_arn.split("/")[-1]
return (
f"https://{region}.console.aws.amazon.com/ecs/home?"
f"region={region}#/clusters/{cluster_name}/tasks/{task_id}/details"
)
def get_ecs_log_url(
region,
task_arn,
container_name... | This function submits an ECS task using AWS CLI, configuring launch type, environment variables, command overrides, and date parameters. It runs the task, validates output, handles errors, and returns the task ARN, optionally waiting for task start/stop. | def ecs_submit(
task_name: str,
cluster: str,
region: str,
container_name: str = None,
cmd_override: dict = None,
env_overrides: dict = None,
use_fargate: str = False,
wait_for_start=True,
wait_for_stop=False,
max_wait=None,
yyyymmdd=None,
):
cmd = (
f"aws ecs run... |
def load_classes(path):
# Loads *.names file at 'path'
with open(path, 'r') as f:
names = f.read().split('\n')
return list(filter(None, names))
def letterbox_image(img, inp_dim):
'''resize image with unchanged aspect ratio using padding'''
img_w, img_h = img.shape[1], img.shape[0]
w, h =... | The main task of the code is to perform object detection on multiple input images using a Redis AI client. It loads class labels, resizes images to a specified size, sends them to a model via Redis for inference, and returns detection results with confidence thresholds and IoU filtering. The function processes each ima... | def predict_from_files(filenames, key,
img_size=512, names_file='data/coco.names',
conf_thresh=0.3, iou_thresh=0.6,
host=DEFAULT_HOST,
port=DEFAULT_PORT):
names = load_classes(names_file)
r = redisai.Client(host=host, ... |
def search_zooconf(query):
matches = search_models(query)
zooconf = None
if matches and len(matches) == 1:
_, zooconf = matches[0]
return zooconf
def interp_path(zooconf):
return os.path.join(predict_env_dir(zooconf), 'bin', 'python')
def predict_dir(zooconf):
return os.path.join(sour... | This function predicts by loading a configuration file, handling arguments, setting up a Python environment if needed, and executing a script with specified parameters like host, port, and prefix. | def predict(c,
name='',
zooconf='',
arg=[],
args=False,
prefix='',
language='python',
docker=False,
host=DEFAULT_HOST,
port=DEFAULT_PORT):
if not zooconf:
zooconf = search_zooconf(name)
if not z... |
def __init_fss(self):
self.optimum_cost_tracking_iter = []
self.optimum_cost_tracking_eval = []
def __init_school(self):
self.best_fish = Fish(self.dim)
self.best_fish.cost = np.inf
self.curr_weight_school = 0.0
self.prev_weight_school = 0.0
self.school = []
... | The code implements an optimization algorithm using fish swarm behavior. It initializes fish swarm and school structures, then iterates over n_iter steps to update individual movements, track the best fish solution, simulate feeding, and apply collective instinctive/volitive movements. The best fish's cost is recorded ... | def optimize(self):
self.__init_fss()
self.__init_school()
for i in range(self.n_iter):
self.individual_movement()
self.update_best_fish()
self.feeding()
self.collective_instinctive_movement()
self.collective_volitive_movement()
... |
def cumulative_stats(self):
"""
method to find the cumulative case count and rename dataframe values
"""
# initialize
old_df = pd.DataFrame(self.db_retrieve(table="case_counts"))
# formatting
old_df.rename(columns={0:"confirmed_date", 1: "state_name", 2:"num_cas... | The code predicts next two-week case counts for each U.S. state using linear regression on historical cumulative case data. It processes each state's data, applies a 14-day rolling regression to forecast trends, generates predicted values for 14 future days, compiles results into a DataFrame, and updates a database tab... | def prediction_engine(self):
"""
method to predict case counts for next two weeks
"""
# initialize
predDf = self.cumulative_stats()
states=["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Haw... |
def write_all_to_file(media_name, quotes):
global all_characters_path
with open(all_characters_path + media_name.lower() + '.json', 'w', encoding = 'utf8') as f:
json.dump(quotes, f, ensure_ascii = False)
def write_to_file(character_name, quotes):
global character_path
with open(character_path + character_name.lo... | The code extracts quotes from screenplay text files, associating each with character names. It scans directories, identifies character lines, cleans text (removing parentheses, extra spaces), and stores quotes in a dictionary. It then writes the structured data to files for further use, including triggers and context m... | def extract_quotes(media_name, character_name):
global screenplay_path
quotes = {}
with os.scandir(screenplay_path + media_name) as target:
for entry in target:
if entry.name.endswith(".txt") and entry.is_file():
file = open(screenplay_path + media_name + "/" + entry.name, "r")
lines = file.readlines(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.