dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def generateBy(self, startWords: str, charsLenght: int):
states = None
next_char = tf.constant([startWords+' '])
result = [next_char]
for n in range(charsLenght):
next_char, states = self.model.generate_one_step(next_char, states=states)
result.append(next_char)
... | The code generates news content by creating a text string of specified length, extracting key elements from it, and combining them with a fixed image URL into a structured dictionary. It uses helper methods to generate text, parse articles, extract keywords, and provide a preview image, returning a formatted response w... | def getNews(self, charsLenght: int, words = ''):
text = self.generateBy(words, charsLenght)
article = self.getArticle(text)
keys = self.getKeyWords(text)
# preview = self.findImg(article)
preview = "https://img-9gag-fun.9cache.com/photo/aRrgE7B_460s.jpg"
return {'text': t... |
def get_zone_id(zone_name):
conn, headers = get_https_conn()
conn.request('GET', '/client/v4/zones', headers=headers)
res = conn.getresponse()
zones = json.loads(res.read().decode())['result']
zones_filtered = list(filter(lambda zone: zone['name'] == zone_name, zones))
if len(zones_filte... | This function updates an existing A record's IPv4 address. It retrieves the zone ID and record ID for the given name, checks if the record exists, and if so, calls a helper function to update the record with the new IPv4 address. If the record is not found, it returns False after notifying the user. | def update_Arecord(name, ipv4):
zone_id = get_zone_id(name)
record_id = get_record_id(name, zone_id)
if record_id == None:
print(f'No record found with name {name} !')
return False
return update_Arecord_by_id(zone_id, record_id, ipv4) |
def get_https_conn():
load_dotenv()
STACK_HOST = os.getenv('STACK_HOST')
STACK_API_TOKEN = os.getenv('STACK_API_TOKEN')
try:
conn = http.client.HTTPSConnection(STACK_HOST, context=ssl._create_unverified_context())
except Exception as e:
print(e)
return None
he... | This function creates a server using provided parameters (name, region, image, plan) via an API, associates an SSH key, and optionally adds the server to a database after verifying its readiness. It handles exceptions and returns server details or None on failure. | def create_server(name, region, image, plan, add_db):
conn, headers = get_https_conn()
ssh_key_uuid = get_ssh_key_uuid()
payload = (
f'{{\n "hostname": "{name}",'
f'\n "label": "{name}",'
f'\n "region": {region},'
f'\n "image": {image},'
f'\n "plan": {plan},'
... |
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def q_sample(self, x_start, t, noise = None):
noise = default(noise, lambda: torch.randn_like(x_start))
return (
extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
extra... | This function calculates the loss for a diffusion model during training by comparing the reconstructed noise (x_recon) with the original noise. It generates noisy samples (x_noisy) from x_start, processes conditional inputs (cond) via BERT embedding, and computes either L1 or L2 loss between the noise and the model's r... | def p_losses(self, x_start, t, cond = None, noise = None, **kwargs):
b, c, f, h, w, device = *x_start.shape, x_start.device
noise = default(noise, lambda: torch.randn_like(x_start))
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
if is_list_str(cond):
cond = bert... |
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def q_sample(self, x_start, t, noise = None):
noise = default(noise, lambda: torch.randn_like(x_start))
return (
extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
extra... | This function interpolates between two input tensors x1 and x2 by creating a weighted combination (using lam) of their time-step t samples, then iteratively denoising the result from time t to 0 using p_sample, producing an interpolated image that blends features of both inputs while following the diffusion model's rev... | def interpolate(self, x1, x2, t = None, lam = 0.5):
b, *_, device = *x1.shape, x1.device
t = default(t, self.num_timesteps - 1)
assert x1.shape == x2.shape
t_batched = torch.stack([torch.tensor(t, device=device)] * b)
xt1, xt2 = map(lambda x: self.q_sample(x, t=t_batched), (x1,... |
def is_list_str(x):
if not isinstance(x, (list, tuple)):
return False
return all([type(el) == str for el in x])
def exists(x):
return x is not None
def p_sample_loop(self, shape, cond = None, cond_scale = 1.):
device = self.betas.device
b = shape[0]
img = torch.randn(shape, ... | This function generates samples from a diffusion model, handling conditional inputs by embedding text via BERT if provided. It adjusts batch size based on input conditions and invokes p_sample_loop to produce outputs with specified dimensions and conditioning scale. | def sample(self, cond = None, cond_scale = 1., batch_size = 16):
device = next(self.denoise_fn.parameters()).device
if is_list_str(cond):
cond = bert_embed(tokenize(cond)).to(device)
batch_size = cond.shape[0] if exists(cond) else batch_size
image_size = self.image_size
... |
def get_ooo_requests_in_month_case1(user_id, year, month):
"""
When month_of_start_date = month and month_of_end_date = month
"""
first_date_of_month = get_first_date_of_month(year, month)
first_date_of_next_month = get_first_date_of_next_month(year, month)
return RequestModel.query.filter(
... | The function generates a report aggregating each user's days off (OOO) for each month of the current year. It queries all users, initializes monthly counters, collects OOO requests from four cases, counts days off per month, and compiles user-specific monthly data into a structured list for reporting. | def get_ooo_report_data():
year = datetime.datetime.now().year
data = []
for user in UserModel.query.all():
days_off_in_month = OrderedDict(
{
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0,
... |
def get_days_off_in_month_case1(user_id, mon):
filter_rule = and_(
RequestModel.start_date >= first_date_of_month(mon),
RequestModel.end_date <= last_date_of_month(mon),
)
ooo_requests = (
RequestModel.query.filter(RequestModel.user_id == user_id)
.filter(filter_rule)
... | This function aggregates total days off per user for each month by summing results from four case-specific functions, then returns a dictionary mapping user IDs to their monthly days-off counts across 12 months. | def get_ooo_request_data():
data = dict()
for user in UserModel.query.all():
days_off_in_month = {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0,
7: 0,
8: 0,
9: 0,
10: 0,
11: 0,
... |
def playerName():
global player1
global player2
player1=input("Enter Player1 Name, for \"X\" \n")
player2=input("Enter Player2 Name, for \"O\" \n")
def Turn(currentPlayer):
global exit
if currentPlayer=="X":
print("\n"+player1 +" s turn ")
else:
print("\n"+player2 +" s turn"... | The code manages a tic-tac-toe game between two players, handling turn-taking, win/tie detection, and updating a database with results. It resets the board, displays the game state, switches players, checks for game-ending conditions, and prints a winner or tie message with ASCII art. Global variables track players and... | def playGame():
global player1
global player2
global winPlayer
playerName()
while not exit:
bd.board=[
"-","-","-",
"-","-","-",
"-","-","-",
]
bd.playing=True
bd.displayBoard()
winner=None
while bd.playing:
Turn(c... |
def moveQueen(self,queen,newX,newY):
if self.__isPositionEmpty(newX,newY):
queenPosition = self.queenPositions[queen]
self.board[queenPosition[0],queenPosition[1]] = POSITION_EMPTY
self.board[newX,newY] = POSITION_QUEEN
self.queenPositions[queen] = (newX,newY)
def... | The function `solveWithHillClimbing` solves the N-Queens problem using a hill-climbing algorithm with random restarts. It iteratively moves queens to minimize conflicts (attacks), evaluates board states, and tracks moves/restarts. If no improvement is found, it restarts randomly. Upon reaching a conflict-free state, it... | def solveWithHillClimbing(self):
startTime = time.clock()
randomRestartCount = 0
moveCount = 0
stuck = 0
while True:
moveFound = None
newScore = self.score
for queen in range(0,self.queenCount):
oldPosition = self.queenPositions... |
def load_model(model_name):
script_dir = os.path.dirname(os.path.abspath(__file__))
path = script_dir + '/' + model_name
base_model = tf.keras.models.load_model(path)
return base_model
def load_image(path):
img = tf.keras.preprocessing.image.load_img(path, target_size=[255,255,])
img = np.array... | This code generates a "deep dream" image by iteratively enhancing features at different scales (octaves) using a specified neural network model. It loads a pre-trained model and input image, constructs a model focused on specific layers, resizes/rotates the image across octaves, applies optimization steps to amplify fe... | def generate(iters, step, scale, model, image, gui, octaves, rotate=0):
base_model = load_model(model)
original_img = load_image(image)
names = layer_dict[model]
layers = [base_model.get_layer(name).output for name in names]
dream_model = tf.keras.Model(inputs=base_model.input, outputs=layers)
... |
def iter_slider_change(self):
value = self.iterSlider.value()
nv = str(self.iter_min + (self.iter_max - self.iter_min) * value / 99)
self.iterVal.setText(nv.split('.')[0])
def step_slider_change(self):
value = self.stepSlider.value()
nv = str(self.step_min + (self.step_max - self... | The code initializes a GUI interface for an image processing application, loading a UI file and setting up components like labels, sliders, checkboxes, and buttons. It configures parameters for iterations, step size, scale, and model selection, connects user interactions to functions for file input, processing, and sav... | def __init__(self):
super(QtGui, self).__init__()
ui_file = os.path.dirname(os.path.abspath(__file__)) + '/mainwindow.ui'
uic.loadUi(ui_file, self)
self.image = self.findChild(QLabel, 'imageLabel')
self.image_path = ''
self.data_path = noise_file
self.feedback_la... |
def newStack():
""" Function to create an empty stack"""
stack = []
return stack
def push(stack, item):
"""Add an item to stack"""
stack.append(item)
def pop(stack):
"""Remove an item from stack"""
if isEmpty(stack): return
return stack.pop() | The main task of the code is to reverse a given string using a stack data structure. It pushes each character of the input string onto the stack and then pops them in reverse order to construct the reversed string. | def reverse(string):
n = len(string)
stack = newStack()
for i in range(0, n, 1):
push(stack, string[i])
string = ""
for i in range(0, n, 1):
string += pop(stack)
return string |
def FindAllPaths(path):
files = os.listdir(path)
folders = []
for file in files:
if file[-4:] == "meta":
files.remove(file)
for file in files:
if not '.' in file:
folders.append(file)
else:
allPaths.append(path + "/" + file)
for ... | The main task of the code is to generate a class diagram text file by collecting type information from specified folders. It identifies relevant file paths, extracts types, constructs diagram elements, and writes them into "./Documentation/ClassDiagram.txt" for documentation purposes. | def CreateClassDiagram(typesFolder, foldersToDiagram):
FindAllPaths(typesFolder)
FindAllPathsToDiagram(foldersToDiagram)
FindAllTypes(allPaths)
fileString = ""
for i in pathsToDiagram:
fileString += CreateElement(i)
file = open("./Documentation/ClassDiagram.txt", "w")
file... |
def ignition_handler(ignition):
if ignition != state["ignition"]:
state["ignition"] = ignition
send_dig_call(state["ignition"], IGNITION_CODE)
def button_handler(value, key):
if value != local_state[key]:
local_state[key] = value
if value:
if state[key]:
... | The function `update_state()` reads digital and analog inputs from multiple sensors (ignition, buttons, joystick, potentiometer) and passes their values to corresponding handler functions for processing. It checks the ignition status, button presses (hb/hz), joystick coordinates (X/Z), and potentiometer position, enabl... | def update_state():
ignition, _ = board.digital_read(IGNITION_PIN)
ignition_handler(ignition)
hb, _ = board.digital_read(BUTTON_HB_PIN)
button_handler(hb, "hb")
hz, _ = board.digital_read(BUTTON_HZ_PIN)
button_handler(hz, "hz")
x, _ = board.analog_read(X_PIN)
z, _ = board.digital_read... |
def clone_weights(self,weights):
weights_clone=OrderedDict()
for name,_ in weights.items():
weights_clone[name]=weights[name].clone()
return weights_clone
def get_characters(self,sentence):
max1=0
for word in senten... | The code performs gradient updates on model parameters using a data loader, accumulating loss over N*K samples per epoch. It computes gradients via autograd, updates weights_clone with a learning rate of 0.01, and returns either the updated weights, gradients, or both based on flags. A final pass computes meta-gradient... | def train(self,weights,data_loader,N,K,return_weights=False,return_grads=False):
weights_clone=self.clone_weights(weights)
self.load_state_dict(weights_clone)
for _ in range(self.epochs):
loss=0
for _ in ran... |
def u_least_squares(self, params, compute_method):
"""
:param params: a liest of model parameters
:param compute_method: 'jor', 'fim', 'new_fim1', 'new_fim2'
:return: the Unweighted Least-Squares descripency function
"""
cov_ml = self.md.load_data()
if compute_met... | The function `loss_func` computes a loss value by calculating the distance between the empirical covariance matrix and the implied covariance matrix, based on the specified `loss_method` and `compute_method`. It acts as a dispatcher, routing to different methods (`uls`, `gls`, `ml`) for computing the loss, each of whic... | def loss_func(self, params, loss_method='uls', compute_method='fim'):
"""
:param params: a list of model parameters
:param loss_method: 'uls', 'gls', 'ml'
:param compute_method: 'jor', 'fim', 'new_fim1', 'new_fim2'
:return: the loss function, distance between empirical covarianc... |
def load_data(self):
"""
gets output of structure methods
:return:
the covariance matrix of manifest variables
"""
if type(self.data) == DataFrame:
data = self.data.loc[:, self.structure()[0]['observed']]
return data... | This function computes the maximum likelihood discrepancy function using specified methods ('fim', 'jor', 'new_fim1', 'new_fim2') by calculating the trace of the product of the covariance matrix and the inverse of a method-specific sigma matrix, plus the log determinant of the sigma matrix. It returns the discrepancy v... | def max_likelihood(self, params, compute_method):
"""
:param params: a liest of model parameters
:param compute_method: 'jor', 'fim', 'new_fim1', 'new_fim2'
:return: the maximim likelihhod descripency function
"""
cov_ml = self.load_data()
if compute_method == "fi... |
def load_data(self):
"""
gets output of structure methods
:return:
the covariance matrix of manifest variables
"""
if type(self.data) == DataFrame:
data = self.data.loc[:, self.structure()[0]['observed']]
return data... | The function `g_least_squares` computes the Generalized Least-Squares discrepancy function using specified methods ('fim', 'jor', 'new_fim1', 'new_fim2'). It takes model parameters and a method, loads covariance data, calculates the matrix size `m`, and computes the trace of $(I - \Sigma \cdot \text{inv}(cov\_ml))$, wh... | def g_least_squares(self, params, compute_method):
"""
:param params: a liest of model parameters
:param compute_method: 'jor', 'fim', 'new_fim1', 'new_fim2'
:return: the Generalized Least-Squares descripency function
"""
cov_ml = self.load_data()
m = self.get_mat... |
def load_data(self):
"""
gets output of structure methods
:return:
the covariance matrix of manifest variables
"""
if type(self.data) == DataFrame:
data = self.data.loc[:, self.structure()[0]['observed']]
return data... | The function `u_least_squares` computes the **Unweighted Least-Squares discrepancy** between a model's predicted covariance matrix (calculated via methods like FIM, JOR, or variants) and empirical data covariance. It subtracts the empirical covariance (`cov_ml`) from the model's computed covariance (using `compute_meth... | def u_least_squares(self, params, compute_method):
"""
:param params: a liest of model parameters
:param compute_method: 'jor', 'fim', 'new_fim1', 'new_fim2'
:return: the Unweighted Least-Squares descripency function
"""
cov_ml = self.load_data()
if compute_method... |
def test_z8(self,
exposure: str = "X",
outcome: str = "Y",
candidate: str = "Z",
alpha: float = 0.005,
verbose: bool = False) -> bool:
# Test marginal independence of X and Z.
if candidate in self.x_ind_z_dict:
... | This function classifies candidate variables into causal categories (Z8, Z4, Z5/Z7, or not identifiable) by sequentially testing statistical conditions. It first checks if a variable is isolated (Z8), then if it's a cause of the outcome (Z4), and finally if it's a child of the exposure or instrument (Z5/Z7). Variables ... | def partition_z_steps_1_2_3(self,
exposure: str = "X",
outcome: str = "Y",
alpha: float = 0.005,
verbose: bool = False):
for candidate in self.z_names:
#-----------------... |
def partition_z_steps_1_2_3(self,
exposure: str = "X",
outcome: str = "Y",
alpha: float = 0.005,
verbose: bool = False):
for candidate in self.z_names:
#-----------------... | The method `partition_z` partitions a dataset into subsets (Z1, Z4, Z5, etc.) based on relationships with exposure and outcome variables, identifying confounders, instrumental variables, and other categories. It performs statistical tests to classify variables, detect adjustment sets, and handle causal inference tasks.... | def partition_z(self,
exposure: str = "X",
outcome: str = "Y",
instrument: str = None,
causes_outcome: list = None,
discrete: bool = False,
use_random_z4: bool = False,
use_random_... |
def get_pair_data(self):
if not self.mode in ['train_data', 'test_data', 'all_data']:
raise ValueError("Panic::Unvalid mode")
if self.mode == 'train_data':
top_paths, dsm_paths = self.get_train_image_paths()
elif self.mode == 'test_data':
top_paths, dsm_paths... | The main task of the code is to load and process image and ground truth data from `top_data` and `dsm_data` lists. It checks data consistency, ensures index validity, extracts specific image blocks, applies data augmentation (if not in test mode), and returns the processed image-label pair. | def load_item(self, idx):
if (self.top_data == []) and (self.dsm_data == []):
self.get_pair_data()
else:
pass
idx_bound = len(self.top_data)
try:
assert idx_bound == len(self.dsm_data)
except AssertionError:
print("AssertionError: ... |
def generateImages(indices):
# indices (int): generates (indices) random tsumego
# indices (list): uses (indices) as the tsumego to look at
if type(indices) == type(1):
indices = [random.randint(1, MAX_IMG) for _ in range(indices)]
imgs = [read(i) for i in indices]
return imgs, indices
def drawCircles(img, circl... | The main task of the code is to test a circle-detection/drawing function by generating images, applying the provided function to detect/draw circles, visualizing results, and displaying outputs with indices. It prints parameters, processes images, and shows annotated images for validation. | def _test_circleFunc(indices, func, **kwargs):
print("Testing", func.__name__, ":", indices)
imgs, indices = generateImages(indices)
print(kwargs)
circles = [func(img, **kwargs) for img in imgs]
drawn = [drawCircles(img, circ) for (img, circ) in zip(imgs, circles)]
for (pic,i) in zip(drawn,indices):
show(pic, i... |
def findBlackStones(img):
param2 = 10
# Experimentally determined
circles = findCircles(img,param2=param2)[0]
avgFill = [findAvgFill(img, circ) for circ in circles]
return np.array([circ for (circ, fill) in zip(circles, avgFill) if fill < GRAY_THRES])
def getGrid(img, blackStones):
# Assumes that top right cor... | The function predicts the positions and colors of stones (black, white, or empty) in a Go board image. It identifies black stones, determines the grid layout, and maps coordinates to predict stone placements. If `drawStones` is True, it visually marks predicted stones on the image with colors (blue for black, red for w... | def predictStonesByImg(img, drawStones=True):
blackStones = findBlackStones(img)
topLeft, gridLen = getGrid(img, blackStones)
imgCoords = getImageCoords(topLeft, gridLen)
predicted = "".join([colorAtCoords(img, c, gridLen) for c in imgCoords])
if not drawStones:
return predicted
for (p,c) in zip(predicted, img... |
def generateImages(indices):
# indices (int): generates (indices) random tsumego
# indices (list): uses (indices) as the tsumego to look at
if type(indices) == type(1):
indices = [random.randint(1, MAX_IMG) for _ in range(indices)]
imgs = [read(i) for i in indices]
return imgs, indices
def predictStonesByImg(img... | The main task of the code is to test a stone prediction model by generating images from given indices, processing each image to predict stone-related data, and visualizing the results. It iterates through generated images, applies prediction, prints outcomes, and displays annotated images with corresponding indices for... | def _test_predictStones(indices):
imgs, indices = generateImages(indices)
for (img,i) in zip(imgs,indices):
predicted, drawn = predictStonesByImg(img)
print("Predicted:", predicted)
show(drawn, i) |
def get_doc_opts(readme):
'Check if README file is setting options via a mark, and return options.'
m = MARK_OPTS_RE.search(readme)
opts = {}
if not m:
return opts
try:
for o in m.group(1).split():
k, v = o.split(':')
opts[k] = bool(int(v))
except (TypeError, ValueError) as e:
raise ... | The main task of the code is to generate documentation by parsing a module's files, variables, and outputs, with optional overrides from a README file. It collects parsed data, handles I/O errors, and formats the results into structured documentation based on parameters like `files`, `show_extra`, and `exclude_files`.) | def create_doc(module_path, files=False, show_extra=False, exclude_files=None,
readme=None):
if readme:
# check for overrides in doc
opts = get_doc_opts(readme)
files = opts.get('files', files)
show_extra = opts.get('show_extra', show_extra)
try:
mod_files = list(parse_files(modul... |
def get_readme(readme_path):
'Open and return README.md in module.'
try:
return open(readme_path).read()
except (IOError, OSError) as e:
raise SystemExit(f'Error opening README {readme_path}: {e}')
def create_doc(module_path, files=False, show_extra=False, exclude_files=None,
readme=None):
... | (The code generates or updates a README.md file by processing module documentation. It reads the existing README, creates a new document using `create_doc`, and either replaces the original file or prints the result based on the `replace` flag. Parameters control file exclusion, content inclusion, and output method.) | def main(module_path=None, exclude_file=None, files=False, replace=True,
show_extra=True):
'Program entry point.'
readme_path = os.path.join(module_path, 'README.md')
readme = get_readme(readme_path)
doc = create_doc(module_path, files, show_extra, exclude_file, readme)
if replace:
replace_doc(re... |
def beta(eeg,wavelet, freqoi, timeoi,tapM,k,length):
results= beta_bursts(eeg, wavelet, freqoi, timeoi,tapM, k,length)
column=["bp","trial","det","avFreq","pkFreq","avMag","pkMag","tDur","tStart","tEnd"]
res= np.array(results)
res= pd.DataFrame(res, columns=column)
res=res.sort_values('tStart')... | The code processes EEG data from neural recordings, handling different file formats (RAM vs. mat73). It extracts electrode coordinates, applies wavelet transforms for beta/high-gamma frequency analysis, and associates detected features with electrode metadata (names, types, coordinates). Results are aggregated across s... | def detect_b(subject):
if 'RAM' in subject:
T= scipy.io.loadmat(subject)
BP=pd.DataFrame(T['bpElec'][0])
BIPOLAR= T['BIPOLAR'][0]
filename=subject[6:-10]
b=T['BIPOLAR'][0][0].shape[1] #last trial
BP['x']=BP['x_tal'].astype(float)
BP['y']=BP['y_tal'].a... |
def add_rules(rules_0, rules_1):
for r in rules_1:
if r not in rules_0:
rules_0.append(r)
return rules_0
def get_rules(model, feature_names, node=0, parent_name=None, parent_decision=False, parent_prev_rule=None):
parent_rule = map_rule(str(parent_name), parent_decision) if parent_name !... | The main task of the code is to generate firewall rules by aggregating rules from multiple models, then compiling them into a firewall configuration using device, prefix, and application data. It iterates through input models to collect rules, combines them, and constructs a firewall structure for network security poli... | def generate(models, feature_names, device_data, prefix_data, app_data):
rules = []
for model in models:
add_rules(rules, get_rules(model, feature_names))
firewall = create_firewall_rules(rules, device_data, prefix_data, app_data)
return firewall |
def greeting():
title = " * U.S. Notify Python Client Demo * "
short_stripe = " " * 26
long_stripe = " " * 37
c = Console()
print("")
c.print(" ********* ", style="white on navy_blue", end="")
c.print(short_stripe, style="black on white")
c.print(" ********* ", style="white on navy_blue... | The code's main task is to send SMS or email notifications using a NotificationsAPIClient. It prompts the user to select a template type, chooses a template and personalization details, then asks for confirmation to send the message. The base URL and API key are required for client initialization, and the process inclu... | def main():
# must pass in base_url, as the default is notify.uk's production URL
client = NotificationsAPIClient(concat_api_key, base_url=base_url)
# introduce yourself
greeting()
# and ask if SMS or email template is desired
template_type = intro()
# present selections for SMS/email tem... |
def test_aug(img, mask, aug_name, args):
"""
Try a particular augmentation.
"""
imgnew, masknew = img, mask
if aug_name == "flip":
imgnew, masknew = flip(imgnew, masknew)
if aug_name == "brightness":
imgnew, masknew = brightness(imgnew, masknew)
if aug_name == "rotate":
... | This code applies data augmentation to inputs x and y with probability self.p. If triggered, it selects augmentation methods based on self.aug_name (specific method) or self.aug_type (multiple/robust). It returns augmented or original data depending on the random check and configured augmentation parameters. | def forward(self, x, y):
# Apply augs to 75% samples.
if np.random.random_sample() < self.p:
if self.aug_name is not None:
x, y = test_aug(x, y, self.aug_name, self.args)
elif self.aug_type == "multiple":
x, y = multi_augs(x, y, self.args)
... |
def remove_space(M, weight_of_dark = -1, weight_of_light = 100):
# Converting to np array
M = np.array(M)
height = M.shape[0]
width = M.shape[1]
# Converting picture to binary
vf = np.vectorize(convert_to_binary)
binary_image = vf(M)
# Reweight matrix
assign_weight = lambda x: weight_of_light if x ... | The code processes an image of a sentence by converting it to grayscale, applying noise reduction, removing extra spaces, splitting the sentence into individual words using k-means clustering, resizing each word image to a standard height, and saving them as separate PNG files. It returns the list of file paths for the... | def split_sentence(image_location):
# Variables
blur_amount_factor = 50
# Opening image
current_image = cv2.imread(image_location)
# Converting it to greyscale
current_image = cv2.cvtColor(current_image,cv2.COLOR_BGR2GRAY)
# Saving height and width
orig_height , orig_width = current_image.shape
# ... |
def _add_build_log(build_id, app_id, log, state="building", log_type="build"):
with BUILD_LOGS_TABLE as logs_db:
app_data = logs_db.get(app_id, dict())
build_data = app_data.get(build_id, dict())
app_logs = build_data.get("logs", [])
app_logs.append(log)
if "created_at" not ... | The main task of the code is to build an application from a git repository by cloning it, checking for a required configuration file (`paatr.yaml` or `Dockerfile`), generating a Docker configuration if needed, and building a Docker image. It logs build progress and handles errors, returning a success or failure message... | def build_app(build_id, git_url, app_name, app_id, repo_url):
"""
Builds an app from a git repository and generates
a docker config file from the app `paatr.yaml` config file
Args:
git_url (str): URL of the git repository
app_name (str): Name of the app
Returns:
str: B... |
def get_device_detail(device_info):
full_path = get_device_full_path(device_info)
mask = iot_v1.types.FieldMask(paths=['num_id', 'name', 'blocked'])
return iot_client.get_device(full_path, mask)
def add_file_to_device_bucket(device_info, download_file):
download_bucket = check_create_device_download_buc... | The function initializes a file download for a device by validating the device's status, adding the file to the device's bucket, generating an access token, and sending a download message. If the device is blocked or disconnected, it returns an error; otherwise, it confirms the message was sent. | def initialize_download_for_device(request):
request_json = request.get_json()
device_info = request_json['device']
device_detail = get_device_detail(device_info)
if device_detail.blocked:
return 'Device blocked'
device_info['num_id'] = device_detail.num_id
download_file = request_json['... |
def create_EDS_PhaSe_cache(sample, channel_extraction_method="max_variance", save_cache=True):
"""
function to analyze and create cache with EDS_PhaSe analyzed data
INPUT:
sample: (str) name of directory containing sample information
channel_extraction_method: (str) method to be used fo... | This function analyzes EDS data when the 'W_AnalyzeOutput' button is clicked. It clears output, checks the 'cache' mode, generates or loads EDS phase data/cache, then triggers interactive composition analysis of cropped regions using the retrieved data. | def on_AnalyzeButton_clicked(b):
"""funtion to analyze EDS data. It is executed when 'W_AnalyzeOutput' button is clicked.
"""
W_AnalyzeOutput.clear_output()
with W_AnalyzeOutput:
global dict_EDS_PhaSe, dict_EDS_PhaSe_markerMaps
if W_cac... |
def follow_flows(dP, mask=None, niter=200, interp=True, use_gpu=True, device=None):
shape = np.array(dP.shape[1:]).astype(np.int32)
niter = np.uint32(niter)
p = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing="ij")
p = np.array(p).astype(np.float32)
inds = np.array(np.nonzero(np.abs... | The function computes cell masks from cell probability maps and flow dynamics, applying thresholding, morphology operations, and flow-based segmentation to generate labeled cell masks while handling resizing and GPU acceleration. | def compute_masks(
dP,
cellprob,
p=None,
niter=200,
cellprob_threshold=0.4,
flow_threshold=0.4,
interp=True,
resize=None,
use_gpu=False,
device=None,
):
"""compute masks using dynamics from dP, cellprob, and boundary"""
cp_mask = cellprob > cellprob_threshold
cp_mask... |
def _remove_boundary_cells(mask):
"""Remove cells on the boundary from the mask"""
# Identify boundary cells
W, H = mask.shape
bd = np.ones((W, H))
bd[2 : W - 2, 2 : H - 2] = 0
bd_cells = np.unique(mask * bd)
# Remove cells on the boundary
for i in bd_cells[1:]:
mask[mask == i]... | The function evaluates the F1 score for cell segmentation by calculating true positives (TP), false positives (FP), and false negatives (FN) from true and predicted masks. For small images, it removes boundary pixels and computes confusion elements directly. For large images, it divides masks into patches, processes ea... | def evaluate_f1_score_cellseg(masks_true, masks_pred, threshold=0.5):
"""
Get confusion elements for cell segmentation results.
Boundary pixels are not considered during evaluation.
"""
if np.prod(masks_true.shape) < (5000 * 5000):
masks_true = _remove_boundary_cells(masks_true.astype(np.in... |
def get_patches(img, random_state, patch_size=(11, 11), n_patches=250):
'''Extracts subimages from an image\n
Parameters
img_file: path for an image
patch_size: size of each patch
n_patches: number of patches to be extracted
'''
# Extract subimages
patch = extract... | This function extracts features from a query image based on the specified feature name. For "BOVW", it processes image patches, computes LBP features, generates visual words via k-means, and returns a histogram descriptor. For "MPEG7" and "SIFT", it directly retrieves MPEG-7 and SIFT features, respectively. The functio... | def extract_feature_query(f_name, query_img):
'''Extracts features from given query image\n
Parameters
f_name: Feature Name
query_img: query image
'''
if(f_name == "BOVW"):
query_patches = get_patches(
query_img, random_state, tam_patch, n_patches)
qu... |
def encodemat(mat, code): # encoding matrix mat menggunakan dictionary kode huffman 'code'
encoded = [[' ' for j in range(len(mat[0]))] for i in range(len(mat))]
for i in range(len(mat)):
for j in range(len(mat[0])):
a = str(code[mat[i][j]])
encoded[i][j] = a
encoded = np.ar... | The code compresses an input image using Huffman coding by encoding each RGB channel separately, then reconstructing the image from decoded channels and saving it to the output file. | def huffmancompression(inputFile, outputFile):
# Mengompresi gambar dengan nama file 'inputFile' menggunakan metode huffman lalu menuliskannya kembali menjadi gambar dengan nama file 'outputFile' pada folder 'out'
red, green, blue = img_to_rgb(inputFile)
encoded_red = encodemat(red, getHuffmanDict(red))
encoded_... |
def createMasterArray(Arr, reps):
C = list();
for i in range(len(Arr)):
C.extend(list([Arr[i]] * int(reps[i])));
return C;
def createX(idx, lenSeq, maxReps, C):
return windowAlg(C[idx: idx+lenSeq], maxReps);
def createY(idx, lenPred, maxReps, C):
Y_n = list()
if (len(C[idx:idx+lenPred])... | The function `saveSetGroupBy` processes chord sequences into input-output pairs for machine learning. It creates a master array from chords, generates input (`X`) and output (`Y`) sequences by slicing and padding, then converts them into one-hot encoded tensors. The goal is to prepare structured training data for a mod... | def saveSetGroupBy(chords, reps, maxReps, lenSeq, lenPred):
#print(chords)
C = createMasterArray(chords, reps);
#pprint.pprint(C)
X = list();
Y = list();
for i in range(len(C)):
X_n = createX(i, lenSeq, maxReps, C);
Y_n = createY(i+lenPred, lenPred, maxReps, C);
#pprint.... |
def generate(length):
global password
password = ""
for i in range(length):
password+=random.choice(possible)
print("Your Generated password is : " + password)
return password
def choice_fun(password):
choice = int(input('''1). Copy AND Save
2). Regenerate
Enter Your Choice : '''))
i... | The main task of the code is to present a menu allowing users to either generate a new password (specifying site name and length) or view saved passwords, with input validation and routing to corresponding functions like generate() and view_saved_pass(). | def main_menu():
choice = int(input('''1). Generate new password
2). View saved passwords
Enter Your Choice : '''))
if (choice == 1 ):
global site
site = input("Enter the site name for which you're saving the password : ")
global length
length = int(input('''Enter the length of y... |
def create_first_table(self):
file = open('files/first_table.txt', 'r')
lines = file.readlines()
title = lines[0].strip('\n').split('\t')
for i in range(1, len(lines)):
line = lines[i].strip('\n').split('\t')
set = []
for j in range(1, len(line)):
... | This code generates a parse table for a grammar using FIRST and FOLLOW sets. It reads production rules from a file, computes FIRST/FOLLOW sets, and populates the table with productions for terminal symbols in FIRST sets, or 'synch' for terminals in FOLLOW sets when no production exists. | def create_parse_table(self):
self.create_first_table()
self.create_follow_table()
file = open('files/grammer.txt', 'r')
lines = file.readlines()
self.starting_symbol = lines[0].split(' ')[0]
for line in lines:
line = line.strip('\n').split(' ')
ta... |
def create_first_table(self):
file = open('first_table.txt', 'r')
lines = file.readlines()
title = lines[0].strip('\n').split('\t')
for i in range(1, len(lines)):
line = lines[i].strip('\n').split('\t')
set = []
for j in range(1, len(line)):
... | This code constructs a parse table for a grammar using FIRST and FOLLOW sets. It reads grammar rules from files, determines start symbol, populates the table with productions based on FIRST sets, and adds 'synch' entries for missing FOLLOW set symbols to handle errors. | def create_parse_table(self):
self.create_first_table()
self.create_follow_table()
file = open('grammer.txt', 'r')
file_raw = open('grammer_raw.txt', 'r')
lines = file.readlines()
lines_raw = file_raw.readlines()
self.starting_symbol = lines_raw[0].split(' ')[0]
... |
def create_first_table(self):
file = open('files/first_table.txt', 'r')
lines = file.readlines()
title = lines[0].strip('\n').split('\t')
for i in range(1, len(lines)):
line = lines[i].strip('\n').split('\t')
set = []
for j in range(1, len(line)):
... | This function constructs a parse table for a context-free grammar using FIRST and FOLLOW sets. It reads grammar rules from files, computes production rules' FIRST sets, and populates the table with corresponding productions. For epsilon productions, it uses FOLLOW sets to determine valid entries. Missing table entries ... | def create_parse_table(self):
self.create_first_table()
self.create_follow_table()
file = open('files/grammer.txt', 'r')
file_raw = open('files/grammer_raw.txt', 'r')
lines = file.readlines()
lines_raw = file_raw.readlines()
self.starting_symbol = lines_raw[0].spl... |
def create_parse_table(self):
self.create_first_table()
self.create_follow_table()
file = open('files/grammer.txt', 'r')
lines = file.readlines()
self.starting_symbol = lines[0].split(' ')[0]
for line in lines:
line = line.strip('\n').split(' ')
ta... | This code parses input using a predictive parser with a parse table, constructing a syntax tree while checking for syntax errors. It processes tokens from 'input.txt', builds a tree structure, and writes results to 'parse_tree.txt' and 'syntax_errors.txt'. | def parse(self):
self.create_parse_table()
root_node = None
stack = [('$', root_node), (self.starting_symbol, None)]
top = stack[-1][0]
scanner = Scanner('input.txt')
token, line_no = scanner.get_next_token()
eof = True
while True:
if top == 'E... |
def create_parse_table(self):
self.create_first_table()
self.create_follow_table()
file = open('grammer.txt', 'r')
file_raw = open('grammer_raw.txt', 'r')
lines = file.readlines()
lines_raw = file_raw.readlines()
self.starting_symbol = lines_raw[0].split(' ')[0]
... | This code parses input using a stack-based algorithm with a parse table, generating a syntax tree and detecting errors. It handles terminals, synchronization, and epsilon rules, writes parse trees to "parse_tree.txt", syntax errors to "syntax_errors.txt", and semantic errors to "semantic_errors.txt". It also checks for... | def parse(self):
self.semantic_errors = []
self.func_decl = {}
self.create_parse_table()
root_node = None
stack = [('$', root_node), (self.starting_symbol, None)]
top = stack[-1][0]
scanner = Scanner('input.txt')
token, line_no = scanner.get_next_token()
... |
def create_parse_table(self):
self.create_first_table()
self.create_follow_table()
file = open('files/grammer.txt', 'r')
file_raw = open('files/grammer_raw.txt', 'r')
lines = file.readlines()
lines_raw = file_raw.readlines()
self.starting_symbol = lines_raw[0].spl... | This code parses an input file using a predictive parser, constructs a syntax tree, handles errors, and generates output files including the parse tree, error log, and modified program code. It processes tokens, applies the parse table, manages a stack for parsing, and writes results to 'parse_tree.txt', 'syntax_errors... | def parse(self):
self.create_parse_table()
root_node = None
stack = [('$', root_node), (self.starting_symbol, None)]
top = stack[-1][0]
scanner = Scanner('input.txt')
token, line_no = scanner.get_next_token()
eof = True
while True:
if top[0].st... |
def folderpath():
folder_path = input("\nYeastGenes is the default folder, leave this box blank or\nenter the name of the folder containing genes in FASTA file format that you want to analyze: ") #Validate if the provided path is a directory
if folder_path == "":
folder_path = "./YeastGenes"
else:
... | The main task of the code is to process user commands for bioinformatics analysis, such as calculating GC percentage, searching codons, and translating DNA sequences from files in a specified folder. It handles inputs like 'hello', 'exit', 'help', and specific tools like 'third codon' or 'codon finder', validating inpu... | def main():
foldername = folderpath()
while True:
command = input("\nEnter a command or type help for more resources: ")
if command == 'hello':
print(f'Hello, World! and {os.getlogin()} of course!')
elif (command =='exit' or command == 'e'):
print('Exiting the pr... |
def load_active_trail(trail, timezone):
try:
markers = list_from_marker_class(trail.markers, timezone)
active_trail = {
"id": trail.id,
"name":trail.name,
"hidden": trail.hidden,
"date":"",
"time":"",
"markers": markers
}
if markers:
active_trail['date'] = ma... | The function retrieves a user's trail data based on mapId, determines the active trail, handles user interactions (check-in, trail creation, selection), and renders a map view with user-specific settings and trail information, redirecting or updating based on POST requests. | def user_trail(user_mapId):
user_match = User.query.filter_by(mapId=user_mapId).first()
if user_match:
settings = json.loads(user_match.settings)
user_time = settings['timezone']
if current_user.is_authenticated:
user_trails = Trail.query.join(User, Trail.user_id==user_match.id).all()
if ... |
def load_user_trails(sql_trails, timezone):
user_trails = []
for trail in sql_trails:
local_time = convert_utc(trail.datetime, timezone)
print(f"local time {local_time}")
user_trails.append(
{
"id": trail.id,
"name": trail.name,
"hidden": trail.hidden,
"date":local... | The main task of the code is to manage user trails by displaying them, handling deletion, hiding, and search requests. It checks user authentication, loads trails with timezone settings, processes POST actions like deleting or hiding trails, updates the current trail if needed, and renders the 'manage_trails.html' temp... | def manage_trails():
if current_user.is_authenticated:
settings = json.loads(current_user.settings)
user_time = settings['timezone']
user_trails = Trail.query.join(User, Trail.user_id==current_user.id).all()
trail_list = load_user_trails(user_trails, user_time)
if request.method == 'POST':
... |
def char_frequency(self):
count = {}
for char in self.string:
if char not in count:
count[char] = 0
count[char] += 1
for char,value in count.items():
node = Node(value=char,frequency=value)
self.q.append(node)
self.q.sort(k... | The code performs Huffman encoding on input data. It first calculates character frequencies, constructs a Huffman tree, generates binary codes for each character, and finally prints the resulting encoding table. | def encode(self):
self.char_frequency()
self.build_tree()
self.huffman_encoding()
self.print_encoding() |
def find_core_points(self):
for point in self.points:
if self.is_core_point(point):
self.core_points.append(point)
def find_noise_points(self):
for point in self.points:
if point not in self.core_points:
noise = True
for core_point... | This code implements the DBSCAN clustering algorithm by identifying core points, border points, and noise points. It groups core points and their neighboring points into clusters, excluding noise points. The algorithm iterates through core points, assigns unprocessed points to clusters if they are within the neighborho... | def dbscan(self):
self.find_core_points()
self.find_noise_points()
self.find_border_points()
self.points = self.core_points + self.border_points
self.assigned = set()
# print("Core", self.core_points)
# print("Noise", self.noise_points)
# print("Border", s... |
def get_3rd_point_distance(self):
dis = []
for point in self.points:
distances = []
for other_point in self.points:
if point != other_point:
distances.append(
(self.manhattan_distance(point, other_point)))
di... | The main task of the code is to plot third-point distances, execute DBSCAN clustering, identify noise points, calculate cluster SSE, and return these results. It visualizes data, applies clustering, evaluates noise, and quantifies cluster compactness for analysis. | def main(self):
values = self.get_3rd_point_distance()
plt.plot(values)
plt.show()
return self.dbscan(), self.noise_points, self.get_SSE(self.clusters), self.get_3rd_point_distance() |
def get_pandas_df(
df: DataFrame,
lowercase_columns: bool = False,
show_sql: bool = False,
show_time: bool = False,
) -> pd.DataFrame:
"""Converts a Snowpark DataFrame to Pandas DataFrame
Args:
df (DataFrame): Snowpark DataFrame
Returns:
pd.DataFrame: Pandas DataFrame
"... | This function generates a Streamlit tile with tabs displaying a chart, dataframe preview, SQL query, description, and download button. It handles Spark/pandas DataFrames, validates chart types, and conditionally skips the chart tab. The context manager allows adding notes to the chart section while managing data visual... | def tile_ctx(
df: sp.DataFrame | pd.DataFrame,
description: str,
sql: str | None = None,
chart: alt.Chart | alt.LayerChart | Figure | None = None,
skip_chart: bool = False,
):
"""Create a tile with a chart, a dataframe preview, the SQL query and a description.
This is the context manager ver... |
def find_dir_with_toc(input: str = "."):
"""paligo exports content in one folder per language, each one with a toc-<lang>.html file"""
curdir = Path(input)
for sub_folder in sorted(curdir.iterdir()):
if not sub_folder.is_dir() or str(sub_folder).startswith("."):
continue
## TOC ... | This function processes Paligo HTML5 content by extracting metadata from TOC and index files, organizing topics into a structured map, zipping content, and publishing to a portal using provided credentials and parameters. It identifies topics, constructs metadata, generates a file map, compresses files, and uploads the... | def publish_paligo_html5_files(user: None, password: None, tenant: None, ft_source: None, customer: None, start_dir: None):
print(user, password, tenant, ft_source, customer, start_dir)
raise Exception('function entered')
for folder, toc_file, index_file in find_dir_with_toc(start_dir):
# 1. find t... |
def _rebinlc(time, rate, dt):
# check for finite values
rate = rate[np.isfinite(time)]
time = time[np.isfinite(time)]
# rebin lc/psd to evenly spaced time binning, from rebinlc.pro
t = time
ts = t[0]
num = int((t[-1] - ts) / dt + 1)
minnum = 1
tn = np.empty([num])
rn = np.emp... | The function computes the power spectral density (PSD) of a light curve using the PSRESP method, estimating the slope of an unbroken power law model. It simulates artificial light curves (via Timmer & Koenig's algorithm) to compare observed PSDs with simulated ones, calculating success fractions for each slope. The bes... | def psresp(t, y, dy, slopes, dt, df, percentile, oversampling=10, number_simulations=100):
"""
Compute power spectral density of a light curve assuming an unbroken power law with the PSRESP method.
The artificial light curves are generated using the algorithm by Timmer and Koenig (1995).
For an introdu... |
def handshake(self):
if(debug):
print(__name__ + ".py")
print("Sending handshake")
resp = self.make_handshake(
self.torr.meta_struct['info_hash'], CONFIG['peer_id'])
self.send_msg(resp)
def pass_msg(self, **arguments):
msg = self.make_msg(**arguments)
... | The main task of the code is to manage the download process from a peer in a BitTorrent client. It checks if a handshake is needed, sends an "interested" message if the peer is choking, and requests a piece block when unchoked. It prioritizes rarest pieces, selects a valid piece index, links the piece to the peer, and ... | def downloading(self):
# check if is handshake is done or not
if not self.connect_start:
self.handshake()
elif self.peer_choking:
if(debug):
print(__name__ + ".py")
print("send interested")
# try to send the msg to peer that we ... |
def get_object_id(self):
return self.get_inventory_number()
def get_identifiers(self):
if self.get_inventory_number():
return [
self.get_inventory_number(),
self.get_manifest_id(),
hashlib.md5(self.get_manifest_id().encode()).hexdigest(),
... | This method generates a manifest-type dictionary containing identifiers and metadata for an entity. If an object ID exists, it includes it; otherwise, it omits it. The structure standardizes entity representation with conditional inclusion of object-specific identifiers. | def as_elody_entity(self):
if self.get_object_id():
return {
"type": "manifest",
"object_id": self.get_object_id(),
"identifiers": self.get_identifiers(),
"metadata": self.get_metadata(),
}
return {
"type... |
def convertTuple(tup):
str=''.join(tup)
return str
def processKey(keyString):
if len(keyString)!=keyLength:
print("Error! Key must be exactly "+str(keyLength)+" characters long.")
return 0
else:
global keyBit
keyBit=[]
for x in keyString: keyBit.append(firstNinetyPrimes[keyBase.index(x)])
global leafMul... | The code performs a brute-force cryptographic attack to decrypt a ciphertext by generating all possible keys from a specified character set. It iterates through each key combination, decrypts the ciphertext, and checks if the target string is present. If found, it logs the success, key, and decrypted result. The attack... | def snagFish(ciphertext,target):
attackLog=open('snagFishLog.txt','w',encoding='utf8')
attackLog.write(str(datetime.datetime.now())+" Initiating snagFish attack...\r")
attackLog.close()
attemptNumber=0
cartesianKey = product(config['snagFish']['KeyString'],repeat=keyLength)
print("SnagFish attack started. This wi... |
def generateRandomKey():
keyString=''
for x in range(keyLength):
keyBit=secrets.choice(keyBase)
keyString=keyString+keyBit
return keyString
def processKey(keyString):
if len(keyString)!=keyLength:
print("Error! Key must be exactly "+str(keyLength)+" characters long.")
return 0
else:
global keyBit
keyBi... | The main task of the code is to perform a brute-force decryption attack on a given ciphertext by generating random keys for a specified number of attempts. It logs each attempt's results in a file, tracks the attack's progress, and calculates/prints the decryption rate in keys per second. The function aims to decrypt t... | def flyFish(ciphertext,attemptNumber):
attackLog=open('flyFishLog.txt','w',encoding='utf8')
attackLog.write(str(datetime.datetime.now())+" Initiating flyFish attack...\r")
print("FlyFish attack started. This will take time, depending on the length of your ciphertext and number of attempts...")
flyClock=0
ClockInt=... |
def processKey(keyString):
if len(keyString)!=keyLength:
print("Error! Key must be exactly "+str(keyLength)+" characters long.")
return 0
else:
global keyBit
keyBit=[]
for x in keyString: keyBit.append(firstNinetyPrimes[keyBase.index(x)])
global leafMultiplier
leafMultiplier={
'crypt1':int(math.fmod(k... | The code defines a function `runTask` that handles cryptographic operations based on user input. It processes tasks like key input, encryption, decryption, key generation, clipboard copying, and attack methods (snagFish, flyFish). The function uses global variables and external functions to execute operations, validate... | def runTask(selectedTask):
global cache1
if selectedTask=='key':
userKey=input("Enter "+str(keyLength)+"-bit key: ")
check=processKey(userKey)
if check==1:print("Key accepted.")
elif selectedTask=='encrypt':
encryptedText=processString(str(input("Enter plaintext to be encrypted: ")),'encrypt')
print("Encry... |
def load_key_file(self):
# loading key and cert
if os.path.isfile(f"{util.CA_data_path}{self.name}.key"):
# print("load")
# load private key
self.rsa_private_key=util.load_rsa_private_key(util.CA_data_path,self.name)
else:
self.rsa_private_key=util... | The code revokes a certificate by verifying it was issued by the same CA, checking its signature, and updating the Certificate Revocation List (CRL) if not already revoked. It returns success if the certificate is newly revoked or an error if it's already revoked or invalid. | def revocate_certificate(self,cert_to_revoke):
#check cert issuer same as this ca
cert_issuer=cert_to_revoke.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value
if cert_issuer!= self.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value:
return False, f"The certificate ... |
def window_center():
container.update()
# lines below this:
x = container.winfo_screenwidth()/2 - container.winfo_width()/2
y = container.winfo_screenheight()/2 - container.winfo_height()/2
container.geometry("+%d+%d" % (x, y))
def game():
remove()
button_battle.grid(row=0,column=0)
butt... | This code handles combat mechanics in a game, updating player and enemy health, checking for victory or defeat conditions, displaying outcomes via message boxes, awarding stat boosts, loot, and triggering game state transitions like restarting or advancing to the next phase, with specific logic for different rooms and ... | def attack():
global result
if which_room==1:
enemy1.health=enemy1.health-p.damage
p.health=p.health-enemy1.damage
label_player_health.configure(text=p.health)
label_enemy_health.configure(text=enemy1.health)
container.update()
window_center()
if enemy1.health<=0... |
def wait_for_turn(self):
print("waiting for my turn!!")
while not self.my_turn:
pass
def draw_grid(self, grid):
self.pen.setheading(0)
self.pen.goto(-350, 130)
for rower in range(0, 6):
for col in range(0, 7):
if grid[rower][col] == 0:
... | This code simulates a Connect4 game loop, handling player input, validating moves, updating the game grid, checking for a winner, and displaying results. It iterates through turns, ensures columns aren't full, places player tokens, and terminates when a winner is detected or the board fills, using socket communication ... | def test_game_loop(self):
print("entering game loop")
for i in range(1, 43):
self.wait_for_turn()
self.draw_grid(self.connect4_cell_list)
if self.winner > 0:
if self.winner == 2:
self.winner_screen("RED")
bre... |
def test(self, X):
""" X: matrix of dimensions n x indim """
G = self._calcAct(X)
Y = np.dot(G, self.W)
return Y
def _EstimateWeight(self, X, Y_predict, Y):
dEdW = np.zeros((self.numCenters, Y.shape[1]), float)
for ci, c_val in enumerate(self.centers):
dEdW[ci... | This function performs gradient descent optimization to update model parameters (weights, centers, sigma) by iteratively computing gradients from prediction errors and adjusting them using specified learning rates (eta1, eta2, eta3) over a given number of iterations. | def train_NLPB(self, X, Y, iter_num, eta1, eta2, eta3):
"""
Method #3
This function uses non-linear optimization method
based on error-correction learning (using GD).
X: matrix of dimensions n x indim
Y: column vector of dimension n x 1
iterati... |
def _calcAct(self, X):
# calculate activations of RBFs
G = np.zeros((X.shape[0], self.centers.shape[0]), float)
for ci, c_val in enumerate(self.centers):
for xi, x_val in enumerate(X):
G[xi, ci] = self.basisfunc(c_val, x_val)
return G
def test(self, X):
... | This function employs sequential forward selection to iteratively choose optimal RBF center locations by evaluating model accuracy for each candidate. It selects the candidate yielding the highest accuracy, adds it to the center list, removes it from candidates, and repeats until the predefined number of centers is rea... | def train_MS(self, X, Y):
"""
Method #4
This function uses model selection method to choose center location
(sequential forward selection algorithm). And the stopping criterion
is pre-defined accuracy.
X: matrix of dimensions n x indim
Y: colum... |
def find_primes(n):
multiples = set()
for i in range(2, n+1):
if i not in multiples:
yield i
multiples.update(range(i*i, n+1, i))
def generate_prime(keysize = 1024):
while True:
num = random.randrange(2 ** (keysize - 1), 2 ** (keysize))
if is_prime(num):
r... | The main task of the code is to generate RSA cryptographic keys. It selects two large primes, computes the modulus `n` and Euler's totient `phi`, then searches for a valid private exponent `d` as the multiplicative inverse of a public exponent `e` modulo `phi`. Once successful, it prints the public key (`n`) and privat... | def generate_keys():
primes = list(find_primes(1024))
while (didFindInverse == False):
global n
global d
p = generate_prime() #Choose random larger prime for p
q = generate_prime() #Choose random larger prime for q
n = p * q
phi = (p - 1) * (q - 1)
d = m... |
def download_all_log_files(self):
"""Download all log files, filter by audit type"""
self.db_logs = self.rds_client.describe_db_log_files(
DBInstanceIdentifier=DB_IDENTIFIER,
FileLastWritten=self.s3_instance.last_written_time,
FilenameContains='audit',
Mar... | The code's main task is to continuously download and copy log files to Amazon S3 until all logs are processed. It tracks the number of copied files, updates configuration settings if logs were written during the run, and logs completion status. The loop ensures all remaining logs are handled, with timestamps and file c... | def run(self):
"""loop the logs and save on s3"""
backup_start_time = datetime.datetime.now()
while self.more_logs_remaining:
self.download_all_log_files()
# loop all files and save logs
self.copy_logs(backup_start_time=backup_start_time)
logging.info... |
def takeCommand():
command=sr.Recognizer()
with sr.Microphone() as source:
print('listening...')
command.adjust_for_ambient_noise(source)
command.pause_threshold = 1
audio=command.listen(source)
try:
print('recognizing...')
query=command.recognize_go... | This code defines an AI assistant that processes voice commands to perform tasks like greetings, time/date checks, web searches, website/app launches, media control, and automation. It uses libraries like webbrowser, pywhatkit, and keyboard for execution, with a loop to continuously listen for user inputs and respond a... | def taskExe():
# wishme()
while True:
query = takeCommand()
if 'hello ' in query:
speak("hello... ma'am")
speak("your persnoal AI assistan")
speak("hoe can i help you")
elif 'how are you' in query:
speak("I'm fine ma'am")... |
def _build_microcode(self, files):
label_map = {}
instructions = []
def assign_addresses():
assigned_addresses = {}
last_addr = max([i.address if i.address else 0 for i in instructions])
for instr in instructions:
if instr.address is None:
... | The main task of the code is to generate and output microcode instructions from input files. It builds microcode using `_build_microcode`, then writes the result into binary format (`_write_bin`), MIF file (`_write_mif`), Verilog code (`_write_microcode_verilog`), and type definitions for Verilog and C++ (`_write_types... | def assemble(self):
instructions = self._build_microcode(self._infiles)
self._write_bin(self._bin_output, instructions)
self._write_mif(self._mif_output, instructions)
self._write_microcode_verilog(self._verilog_output, instructions)
self._write_types(self._verilog_types_output, ... |
def fetch_image_manipulation_information(
reference_image_path: Path, left: int, top: int, right: int, bottom: int
):
(
resize_width,
_,
left_border,
top_border,
right_border,
bottom_border,
) = get_border_information(
reference_image_path=reference_im... | The function generates and displays tables summarizing image template dimensions, regions, and locations based on specified coordinates. It calculates transformed regions (normal, from center, from right) and locations, saves this information, and optionally draws these regions/locations on the reference image. The out... | def print_table_of_information(
reference_image_path: Path,
template_image_path: Path,
left: int,
top: int,
right: int,
bottom: int,
draw_information: bool = False,
):
(
left_border,
top_border,
right_border,
bottom_border,
width_template,
... |
def is_empty(self):
return self.head is None
def count_node(self):
if self.is_empty():
print('Empty Linked List')
return
count = 1
current = self.head
while current.next != self.head:
count += 1
current = current.next
re... | This function deletes a node at a specified position in a circular linked list. It handles edge cases like empty lists and invalid positions, then traverses the list to remove the target node by adjusting pointers, finally deleting the node. | def delete_at_position(self, position):
if self.is_empty():
print('Cannot delete from Empty circular linked list')
elif position <= 0 or position > self.count_node():
print('Invalid position')
elif position == 1:
self.delete_from_beginning()
else:
... |
def socket_initilization(self):
# Create a UDP socket at client side
self.clientSocket = socket.socket(
family=socket.AF_INET, type=socket.SOCK_DGRAM)
self.clientSocket.bind(self.clientAddressPort)
self.clientSocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
... | This code initializes a UDP client to send data to a server, setting up socket parameters, preparing a file for writing, and initiating communication by broadcasting and listening for responses. | def __init__(self, port, file_path):
self.localIP = "0.0.0.0"
self.clientAddressPort = (self.localIP, 10005)
self.bufferSize = 32768
self.serverIP = None
self.serverPort = port
self.filePath = file_path
self.current_seq = 200
self.next_seq = 200
t... |
def get_input_filenames(self, filename):
"""
read input file and return list of arXiv metadata full filenames
:param filename:
:return:
"""
filenames = []
try:
with open(filename, 'r') as fp:
for filename in fp.readlines():
... | This function processes a batch of input files by matching each against a publication, scoring the matches, and writing results incrementally to a specified output file. It handles each file individually, pauses briefly between operations, and ensures results are saved progressively. | def batch_match_to_pub(self, input_filename, result_filename):
"""
:param input_filename: contains list of filenames
:param result_filename: name of result file to write to
:return:
"""
filenames = self.get_input_filenames(input_filename)
if len(filenames) > ... |
def check_for_exit(self):
Timer(Chichi.CHECK_FOR_EXIT_INTERVAL, self.check_for_exit).start()
# print('check for exit ...')
try:
psutil.Process(self.pid)
except:
import os
os._exit(0)
def process_request(self):
Timer(Chichi.REQUEST_INTERVAL, sel... | The main task of the code is to execute a sequence of operations: checking for exit conditions, processing requests, handling movie output, and managing movie input. This method orchestrates these steps in order to perform a coordinated workflow, ensuring proper termination, request handling, and data processing relate... | def run(self):
self.check_for_exit()
self.process_request()
self.process_movie_output()
self.process_movie_input() |
def display_board():
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])
def handle_turn(player):
global position
print(player + " 's turn")
position=input("Choose position from 1-9: ")
... | This code defines a function to play a game, displaying the board, handling player turns, checking game status, and flipping players until the game ends. It then declares the winner or a tie based on the final state. | def play_game():
display_board()
#loop for next turn
while game_still_going:
handle_turn(current_player)
check_if_game_over()
flip_player()
if winner=="X" or winner=="O":
print(winner + " is the winner")
elif winner==None:
print("Tie") |
def generate_real_samples2(ix, n_samples, patch_shape, dir_, img_shape):
# retrieve selected images
X1, X2 = load_real_samples(ix, dir_, img_shape)
# generate 'real' class labels (1)
y = ones((n_samples, 4, patch_shape, patch_shape, 1))
return [X1, X2], y
def generate_fake_samples(g_model, samples, ... | The code trains a GAN (Generative Adversarial Network) using real and generated images. It initializes training and validation datasets, iterates over epochs, and trains the discriminator on real and fake samples while updating the generator. Losses are recorded and periodically evaluated. The generator and discriminat... | def train(d_model, g_model, gan_model, img_shape, train_dir, val_dir, n_epochs=200, n_batch=1):
# validation patches and training patches
n_patches_val = len(os.listdir(os.path.join(val_dir, 'images/')))
n_patches_train = len(os.listdir(os.path.join(train_dir, 'images/')))
print('Number of Training ... |
def check_types(config, types):
for type in types:
if type not in config:
raise ValueError(f'Required field {type} not found in config')
def get_clip(self, config):
if 'path' in config: # config['type'] == 'wav':
# load the binary data (WAV)
self.check... | This method constructs a Song object using provided configuration parameters. It validates the config structure, initializes the song with BPM and sample rate, then populates clips, instruments, and patterns by processing each item in the config through respective helper methods, finally returning the assembled Song in... | def get_song(self, config):
self.check_types(config, ['bpm', 'sample_rate', 'clips', 'instruments', 'patterns'])
song = Song(config['bpm'], config['sample_rate'])
for key, value in config['clips'].items():
song.clips[key] = self.get_clip(value)
for key, value in config['instr... |
def _generate_prime(keysize: int = 1024) -> int:
"""
function to generate a large prime number
:param keysize: keysize to look the prime number for (int)
:return: large prime number between 2^(keysize-1) and 2^keysize (int)
"""
while True:
x = random.randrange(2**(keysize-1), 2**keysize)... | The function generates RSA public and private key pairs, saves the private key (n, d) to a specified file, and returns the public key (n, e). It calculates primes, computes modular inverse for the private exponent, ensures file uniqueness, and stores key components in a text file. | def generate_rsa_key(filename: str, keysize: int = 1024) -> tuple:
"""
generate public, private key pairs using RSA cipher, save the private key in file of given filename
:param keysize: keysize to generate key (int)
:param filename: filename to save private key as (str)
:return: public, private key... |
def _text_to_matrix(text):
# before encrypting, we need to convert the plain text into a matrix
matrix = []
# for a 4x4 matrix, run the loop 16 times
for i in range(16):
# convert the text into a byte object
entry = (text >> (8 * (15 - i))) & 0xFF
if i % 4 == 0:
# mak... | This function decrypts a hexadecimal cipher text using AES with a given master key. It processes the cipher text through inverse AES operations in reverse encryption order, applying inverse substitution, shift rows, mix columns, and round keys derived from the master key. The decrypted text is returned as an integer af... | def aes_decrypt(master_key: hex, cipher_text: hex):
"""
Frontend AES Decryption Function
:param master_key: the key to be used for decryption (int)
:param cipher_text: the text to be decrypted, in integer form
:return: the decrypted text, in integer form
"""
# it is basically the encryption ... |
def generate_rsa_key(filename: str, keysize: int = 1024) -> tuple:
"""
generate public, private key pairs using RSA cipher, save the private key in file of given filename
:param keysize: keysize to generate key (int)
:param filename: filename to save private key as (str)
:return: public, private key... | The main task of the code is to demonstrate a complete digital signature workflow: generating RSA keys, signing a message with a private key, and verifying the signature using the public key. It showcases encryption/decryption processes to validate message integrity and authenticity, confirming successful key generatio... | def demo_everything() -> None:
"""
USE THIS CODE TO RUN A DEMO OF ALL THE ABOVE FUNCTIONS
"""
message = "Hello, this is the digital signature of Goddard Guryon. " \
"If you can read this message, it means you have successfully decoded my digital signature. " \
"Congratulation... |
def setup_combobox(self, data_function):
combo = QComboBox(self)
combo.setEditable(True)
completer = QCompleter(self)
completer.setCaseSensitivity(Qt.CaseInsensitive)
completer.setFilterMode(Qt.MatchContains)
combo.setCompleter(completer)
data = data_function()
... | This code initializes a GUI interface for managing tenant data, featuring a menu bar with file options, input forms for tenant details (house, room, CTS numbers, name, mobile, gender, etc.), a table to display entries, and buttons for saving, clearing, deleting records. It includes search functionality, dynamic column ... | def init_ui(self):
main_layout = QVBoxLayout(self)
# Create a menu bar
menubar = QMenuBar(self)
menubar.setStyleSheet(
"""
QMenuBar {
background-color: white;
border-bottom: 1px solid #c1c1c1;
}
QMenuBar::it... |
def get_scanrefer(args):
scanrefer = SCANREFER_TRAIN if args.use_train else SCANREFER_VAL
all_scene_list = sorted(list(set([data["scene_id"] for data in scanrefer])))
if args.scene_id:
assert args.scene_id in all_scene_list, "The scene_id is not found"
scene_list = [args.scene_id]
else:
... | The code's main task is to visualize a neural network model's predictions on a specific 3D scene ("scene0164_00") using a validation dataset. It loads preprocessed data, configures a model in evaluation mode, processes batches through the model without gradients, and dumps visualization results. The focus is on renderi... | def visualize(args):
# init training dataset
print("preparing data...")
scanrefer, scene_list = get_scanrefer(args)
scanrefer = [s for s in scanrefer if s["scene_id"] in [
"scene0164_00",
... |
def _log(self, info_str):
self.log_fout.write(info_str + "\n")
self.log_fout.flush()
print(info_str)
def _feed(self, dataloader, phase, epoch_id):
# switch mode
self._set_phase(phase)
# Reset log
for key in self.log[phase]:
self.log[phase][key] = []
... | This code defines a training loop that runs for a specified number of epochs, processes training and validation data, saves model checkpoints, and handles interruptions. It initializes total iterations, logs progress, trains the model using `_feed`, saves the latest model state, and terminates gracefully on keyboard in... | def __call__(self, epoch, verbose):
# setting
self.epoch = epoch
self.verbose = verbose
self._total_iter["train"] = len(self.dataloader["train"]) * epoch
self._total_iter["val"] = len(self.dataloader["val"]) * self.val_step
for epoch_id in range(epoch):
... |
def check_args():
"""!@brief Parse command line arguments.
Print usage information and exit if user inputs help arguments or inputs too many arguments.
Declare path_to_image and path_to_data variables based on provided arguments.
"""
# Print usage information if user input -h or --help as an argumen... | The main task of the code is to perform steganography by hiding data from a file within an image. It parses command-line arguments to obtain file paths, validates and reads the image and data files, embeds the data into the image, and sends the modified image to a server. The process involves checking file existence, c... | def main():
"""!@main Orchestrates hiding file data in an image and sending that image to server
"""
# Parse arguments that user submitted through command line
# Returns the paths to the image and data files to use
path_to_image, path_to_data = check_args()
# Check if image and data files exis... |
def class_train(self):
pass
def class_predict(self):
pass
def evaluate_results(self):
self.confusion = cm(self.test_y, self.result)
self.accuracy = accuracy_score(self.test_y, self.result)
self.cross_validate()
self.roc_plot()
return | The main task of the code is to classify data by first training a model using `class_train()`, measuring the training time, then predicting results with `class_predict()`, measuring prediction time, and finally evaluating the classification outcomes via `evaluate_results()`. The method records both training and testing... | def classify(self):
start_t = 0
end_t = 0
start_t = time.time()
self.class_train()
end_t = time.time()
self.train_time = end_t - start_t
start_t = time.time()
self.result = self.class_predict()
end_t = time.time()
self.test_time = end_t - start_t
self.evaluate_results() |
def get_index(x: int, y: int):
return x + (y * row_size)
def calculate_basin(all_nodes: Dict[int, Node], first_node: Node) -> Set[Node]:
basin: Set[Node] = {first_node}
while True:
unexplored_node = next((n for n in basin if not n.explored), None)
if unexplored_node:
new_neighbou... | The code processes a heightmap to identify low points (local minima) and calculates the total risk level by summing each low point's value plus one. It then determines the three largest basins, multiplies their sizes for Part 2. The main tasks are: finding low points, computing risk levels, and identifying basin sizes ... | def day_9():
# The input is a heightmap - find the lowest points in the sequence (which is lower than its adjacent neighbours)
# The score "risk level" is the value + 1, summed
input_lines = get_input(day=9)
heightmap: List[List[int]] = [[int(val) for val in line.strip()] for line in input_lines]
gl... |
def leeg_scherm():
os.system('cls')
def print_header():
print("-"*SCHERMBREEDTE)
print(f"|{' ':{SCHERMBREEDTE-2}}|")
def print_header_regel(inhoud=''):
print(f"| {inhoud:^{SCHERMBREEDTE-4}} |")
def print_footer():
print(f"|{' ':{SCHERMBREEDTE-2}}|")
print("-"*SCHERMBREEDTE)
def overhorenmenu(key... | The code defines a function `overhoren` that quizzes users on translating words from a dictionary (`woordenlijst`), where values are original words and keys are translations. It loops through each item, displays the original word, prompts the user for its translation, and provides feedback (correct/incorrect). If the u... | def overhoren(woordenlijst):
dingle = True
while dingle == True:
for key, value in woordenlijst.items(): #kappuuttt
leeg_scherm()
print_header()
print_header_regel('Wat is de vertaling van "' + value + '".')
print_footer()
answer = input()
... |
def get_blur_mask(image: np.ndarray, padding: int):
blurred = add_padding(image, padding)
blurred = remove_artefacts(blurred)
kernel = get_kernel_size(blurred)
blurred = cv2.medianBlur(blurred, kernel) # pylint: disable=no-member
blurred = cv2.threshold( # pylint: disable=no-member
blurred... | The function `blur_bbox` applies a blur effect to an input image using a generated mask and median thresholding. If additional images are provided, it processes them similarly. The core task involves creating a blur mask, computing a threshold, and applying the blur to the image(s) while stripping black regions, return... | def blur_bbox(image: np.ndarray, padding: int = 50, others: List[np.ndarray] = None) -> Union[np.ndarray, Tuple[np.ndarray, List[np.ndarray]]]:
mask = get_blur_mask(image, padding)
result = strip_black(image, mask, *compute_median_threshold(mask))
if others is None:
return result
return result... |
def _check_events(self):
"""Respond to key presses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == py... | The code defines a method `run_game` that initiates an infinite loop to manage the game's main operations. It continuously checks for user input events, updates the player's ship position, handles laser (projectile) updates, and refreshes the game screen. This loop sustains real-time interaction, movement, and renderin... | def run_game(self):
"""Start the main loop for the game."""
while True:
self._check_events()
self.ship.update()
self._update_lasers()
self._update_screen() |
def sentences2idx(sentences, words):
"""
Given a list of sentences, output array of word indices that can be fed into the algorithms.
sentences: a list of sentences
words: a dictionary, where words['str'] is the indices of the word 'str'
return: x1, m1.
x1[i, :] is the word indices in sentenc... | The function `allSIFSimilarities` computes pairwise SIF-weighted cosine similarities between all sentences in a list. It converts sentences into indexed sequences, calculates word weights, generates SIF embeddings using these weights, and then computes cosine similarity between embeddings. The output is a matrix where ... | def allSIFSimilarities(sentences, word_dict, word_embeddings,
word_weights, rmpc=1):
"""
Compute the SIF-weighted cosine similarity between all sentences in a list
Similarity scores are between -1 and 1, a score of -1 meaning the sentences are
completely dissimilar, and 1 meanin... |
def checkInfo(Name, varN):
loadfromjson()
try:
return replist[Name][varN]
except:
return "Error"
def addentry(Name):
replist[Name] = {}
savetojson(replist)
return "done"
def addInfo(Name, varN, data):
loadfromjson()
if Name in replist:
replist[Name][varN] = data
savetojson(replist)
... | This code handles adding or checking user information in a database. If the action is "add", it checks if the user exists; if not, it creates a new entry and adds the data. For "check", it verifies the user's existence and returns the result. The function uses helper functions to manage database operations, ensuring da... | def Handle(Name, action, varname = None, data = None):
if action == "add":
o = checkInfo(Name, varname)
if o == "Error":
addentry(Name)
addInfo(Name, varname, data)
else:
addInfo(Name, varname, data)
elif action == "check":
o = checkInfo(Name, varname)
if o == "Error":
re... |
def delete_currency_service(code: str):
"""Deletes currency based on its code."""
updated_currencies = get_last_updated_document(currency_rate_collection)
del updated_currencies["_id"]
db_currency_list_obj = DatabaseCurrencyList(**updated_currencies)
if code not in db_currency_list_obj.get_currencie... | The main task of the code is to update a custom currency's USD exchange rate by first deleting the existing currency entry, then adding the updated rate, fetching external data, removing the second-to-last document, and returning the revised list of available currencies. | def update_custom_currency_rate_service(code: str, usd_rate: float):
"""Updates custom currency usd_rate."""
delete_currency_service(code)
add_custom_currency_service(code, usd_rate)
fetch_external_api()
delete_penultimate_document()
updated_currencies_obj = get_available_currencies_service()
... |
def input_fn_builder(input_file, seq_length, is_training, drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"unique_ids": tf.FixedLenFeature([], tf.int64),
"example_index": tf.FixedLenFeature([], tf.int64),
"input_ids": tf.FixedLenFeature([seq... | The code evaluates multiple model checkpoints by predicting on evaluation data, computes performance metrics, and retains only the best-performing checkpoint based on a specified metric. It iterates through all checkpoints, processes predictions, compares results, and replaces the original checkpoint files with the bes... | def evaluate_checkpoints(estimator, eval_examples, eval_dataset, eval_features,
eval_tf_filename):
"""Evaluate all checkpoints, and keep only the best one."""
best_result, best_checkpoint = None, None
checkpoints = tf.train.get_checkpoint_state(
estimator.model_dir).all_model_checkp... |
def _get_element_name_with_module(self, element: Union[type, Any]) -> str:
# The element can be a string, for example "def f() -> 'SameClass':..."
if isinstance(element, str):
return element
elif isinstance(element, type):
module = inspect.getmodule(element)
i... | This function generates a Python class stub from a target class, including its parent classes, attributes, and methods. It separates functions and non-special attributes, processes `__init__` parameters for imports, and constructs a string representation with proper syntax and placeholders for method implementations. | def _generate_class_stub(self, class_name: str, tar_class: type) -> str:
parent_class = [self._get_element_name_with_module(_) for _ in tar_class.__bases__]
if tar_class.__class__ != type:
parent_class.append('metaclass=' + self._get_element_name_with_module(tar_class.__class__))
pur... |
def _read_class_init_variable(self):
with self._file_path.open(mode='r', encoding=self._encoding) as file:
file_text = file.read()
class_text = re.findall(r'\nclass (.*?)(\(|:)((.|\s)*?)(\n\S|$)', file_text)
for class_one in class_text:
class_name = class_one[... | This code initializes by loading a Python module from a specified file, analyzes its components (classes, functions, imports), generates stubs for these elements, and writes the resulting import statements and stub code into a file. It handles custom 'movoid_package' attributes to dynamically generate import paths and ... | def init(self):
if not self._file_path.is_file():
raise FileNotFoundError(f'{self._file_path} is not a file.')
self._stub_file = self._stub_path.open(mode='w', encoding=self._encoding)
loader = importlib.machinery.SourceFileLoader('imported', str(self._file_path))
spec = impo... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("N", type=int, help="Max FFT size")
return parser.parse_args()
def emit_header():
print("//! This file was generated with gen_tables.py.")
print()
print(f"#![allow(clippy::excessive_precision)]")
print(f"#![allow(clippy... | The main task of the code is to process command-line arguments, generate a sine wave with N points, reverse the bits of numbers up to N, and output these results sequentially. The functions `emit_header()`, `emit_sine()`, and `emit_bitrev()` handle header emission, sine wave generation, and bit-reversal, respectively, ... | def main():
args = parse_args()
emit_header()
emit_sine(args.N)
emit_bitrev(args.N) |
def create_bst(nums: list) -> TreeNode:
# take in list of numbers and return the root node
root = TreeNode(val=nums[0])
for i in nums[1:]:
insert_bst(root, i)
return root
def insert_rebalance(root: TreeNode) -> None:
# shifts every node where either right or left are None
"""
5
... | The code constructs a binary search tree (BST) from a list of numbers, rebalances it, and performs a level-order traversal. It stores node values in a dictionary by their depth, then prints each level's values sequentially. The main task is to build, balance, and display the BST's nodes level by level. | def run_bst():
nums = [5, 2, 1, 7]
root = create_bst(nums)
print(root)
res = {}
insert_rebalance(root)
traverse(root, 0, res)
done = False
layer = 0
while not done:
still_goin = False
for i in res.keys():
if res[i] == layer:
print(i.val, en... |
def stem(inputs, num_filters):
# Construct the Stem Convolution Group
# inputs : input vector
# First Convolutional layer, where pooled feature maps will be reduced by 75%
conv = Conv_2D_Block(inputs, num_filters, 7, 2)
if conv.shape[1] <= 2:
pool = tf.keras.layers.MaxPooling2D(pool_size=(1,... | The main task of the code is to construct a ResNet18 neural network model using TensorFlow/Keras. It defines an input layer, applies a stem convolution group for initial feature extraction, processes features through the `learner18` function (likely containing residual blocks), and concludes with an MLP (Multi-Layer Pe... | def ResNet18(self):
inputs = tf.keras.Input((self.length, self.width, self.num_channel)) # The input tensor
stem_ = stem(inputs, self.num_filters) # The Stem Convolution Group
x = learner18(stem_, self.num_filters) # The learner
outputs = self.MLP(x)
# Instantiate the Model
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.