dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def devnet_l1_genesis(paths):
log.info('Generating L1 genesis state')
init_devnet_l1_deploy_config(paths)
geth = subprocess.Popen([
'anvil', '-a', '10', '--port', '8545', '--chain-id', '1337', '--disable-block-gas-limit',
'--gas-price', '0', '--base-fee', '1', '--block-time', '1'
])
... | (The main task of the code is to deploy a development blockchain network (Devnet) by generating L1/L2 genesis files, configuring rollup settings, and launching Docker-based nodes (L1, L2, op-node, proposer, batcher) with required dependencies. It ensures necessary artifacts are created, initializes network components, ... | def devnet_deploy(paths):
if os.path.exists(paths.genesis_l1_path):
log.info('L1 genesis already generated.')
else:
log.info('Generating L1 genesis.')
if os.path.exists(paths.allocs_path) == False:
devnet_l1_genesis(paths)
# It's odd that we want to regenerate the de... |
def devnet_test(paths):
# Check the L2 config
run_command(
['go', 'run', 'cmd/check-l2/main.go', '--l2-rpc-url', 'http://localhost:9545', '--l1-rpc-url', 'http://localhost:8545'],
cwd=paths.ops_chain_ops,
)
# Run the two commands with different signers, so the ethereum nonce management ... | The main task of the code is to deploy a development network (devnet) by configuring paths, building Docker images with git metadata, and executing deployment processes based on command-line arguments, including testing, allocation generation, or full deployment. | def main():
args = parser.parse_args()
monorepo_dir = os.path.abspath(args.monorepo_dir)
devnet_dir = pjoin(monorepo_dir, '.devnet')
contracts_bedrock_dir = pjoin(monorepo_dir, 'packages', 'contracts-bedrock')
deployment_dir = pjoin(contracts_bedrock_dir, 'deployments', 'devnetL1')
op_node_dir ... |
def reset(self):
self.data = np.array([self.initial[:-1]])
self.timeline = np.array([0.0])
self.eps_const = self.initial[-1]
def iter_implicit_Euler(self, offset_to_break_out=None):
vector = self.current_vector()
shift = self.shift
eps = self.eps_const
if shift is... | This method performs explicit Euler integration for a specified number of iterations or until the timeline reaches 2000, recording execution time and iteration count. It first resets the system, executes an implicit Euler step for initialization, then iteratively applies explicit Euler steps, adjusting iterations dynam... | def method_explicit_Euler(self, iterations_num=None):
self.reset()
start = time.time()
self.iter_implicit_Euler(10**(-5))
if iterations_num is None:
iterations_num = 0
while self.timeline[-1] < 2000:
self.iter_explicit_Euler()
itera... |
def reset(self):
self.data = np.array([self.initial[:-1]])
self.timeline = np.array([0.0])
self.eps_const = self.initial[-1]
def iter_implicit_Euler(self, offset_to_break_out=None):
vector = self.current_vector()
shift = self.shift
eps = self.eps_const
if shift is... | This method performs explicit Euler integration with recalculation, either for a specified number of iterations or until the simulation time reaches 2000. It initializes with an implicit Euler step, then iteratively advances the simulation using explicit Euler steps, tracking execution time and iteration count before s... | def method_explicit_Euler_recalc(self, iterations_num=None):
self.reset()
start = time.time()
self.iter_implicit_Euler(10**(-5))
if iterations_num is None:
iterations_num = 0
while self.timeline[-1] < 2000:
self.iter_explicit_Euler_recalc()
... |
def reset(self):
self.data = np.array([self.initial[:-1]])
self.timeline = np.array([0.0])
self.eps_const = self.initial[-1]
def iter_implicit_Euler(self, offset_to_break_out=None):
vector = self.current_vector()
shift = self.shift
eps = self.eps_const
if shift is... | The method performs a time simulation using the explicit Runge-Kutta 4 method, either for a fixed number of iterations or until the timeline reaches 2000. It initializes with an implicit Euler step, tracks execution time, and writes results including duration and iteration count. | def method_explicit_Runge_Kutta4(self, iterations_num=None):
self.reset()
start = time.time()
self.iter_implicit_Euler(10**(-5))
if iterations_num is None:
iterations_num = 0
while self.timeline[-1] < 2000:
self.iter_explicit_Runge_Kutta4()
... |
def reset(self):
self.data = np.array([self.initial[:-1]])
self.timeline = np.array([0.0])
self.eps_const = self.initial[-1]
def iter_implicit_Euler(self, offset_to_break_out=None):
vector = self.current_vector()
shift = self.shift
eps = self.eps_const
if shift is... | The method performs implicit Euler integration for a numerical simulation, running either a specified number of iterations or until the timeline reaches 2000. It resets the system, executes integration steps with adaptive time-stepping, and records the total time and iteration count for performance analysis. | def method_implicit_Euler(self, iterations_num=None):
self.reset()
start = time.time()
self.iter_implicit_Euler(10**(-5))
if iterations_num is None:
iterations_num = 0
while self.timeline[-1] < 2000:
self.iter_implicit_Euler()
itera... |
def reset(self):
self.data = np.array([self.initial[:-1]])
self.timeline = np.array([0.0])
self.eps_const = self.initial[-1]
def iter_implicit_Euler(self, offset_to_break_out=None):
vector = self.current_vector()
shift = self.shift
eps = self.eps_const
if shift is... | This method performs numerical integration using the implicit trapezoidal method. It initializes the process, runs an implicit Euler step, then iteratively applies the trapezoidal method either for a specified number of iterations or until the simulation time reaches 2000. It measures execution time and records results... | def method_implicit_trapezoid(self, iterations_num=None):
self.reset()
start = time.time()
self.iter_implicit_Euler(10**(-5))
if iterations_num is None:
iterations_num = 0
while self.timeline[-1] < 2000:
self.iter_implicit_trapezoid()
... |
def open_image(self, image_path):
return Image.open(str(image_path)) if image_path is not None else None
def get_dimensions(self, image):
original_width, original_height = image.size
print(
f"Original dimensions: Width: {original_width}, Height: {original_height}"
)
r... | The main task of the code is to resize input images, masks, and controlnet images based on a specified sizing strategy. It checks if the strategy corresponds to an image in the input dictionary, adjusts dimensions accordingly, resizes all images to the determined width/height, and returns the updated dimensions along w... | def apply(
self,
sizing_strategy,
width,
height,
image=None,
mask=None,
control_1_image=None,
control_2_image=None,
control_3_image=None,
):
image_dict = {
"input_image": self.open_image(image),
"mask_image": sel... |
def _compute_gradient(self, input_vector, target):
layer1 = np.dot(input_vector, self.weights) + self.bias
layer2 = self._sigmoid(layer1)
prediction = layer2
derror_dprediction = 2 * (prediction - target)
dprediction_dlayer1 = self._sigmoid_der(layer1)
d... | The code trains a model using stochastic gradient descent by randomly selecting data instances, computing gradients, and updating parameters. It accumulates errors every 100 iterations by summing squared prediction errors across all data points, returning the cumulative error history for monitoring training progress. | def train(self, input_vectors, targets, iterations):
cumulative_errors = []
for current_iteration in range(iterations):
# pick a data instance at random
random_index_data = np.random.randint(len(input_vectors))
input_vector = input_vectors[random_index_data]... |
def conv_bn(self, intensor, in_channels, out_channels, filter_size, step, is_act, alpha, lock, istraining, scope):
with tf.variable_scope(scope):
if lock:
ini_filters= tf.truncated_normal([filter_size, filter_size, in_channels, out_channels], 0.0, 0.001)
filters = tf.... | The code constructs a YOLOv3-based neural network with three detection heads (yolov3_1-3) for multi-scale object detection, using residual blocks, skip connections, and upsampling. It processes input images through convolutional layers, generates detection predictions, and includes a mask subnet for instance segmentati... | def build_network(self, images, depth_outputs, alpha, is_training, scope='yolo'):
with tf.variable_scope(scope):
# Training Stage 1: heads only: "lock=True" for layers 1-52, "lock=False" for other layers
# Training Stage 2: all layers: "lock=False" for all layers
... |
def build_network(self, images, depth_outputs, alpha, is_training, scope='yolo'):
with tf.variable_scope(scope):
# Training Stage 1: heads only: "lock=True" for layers 1-52, "lock=False" for other layers
# Training Stage 2: all layers: "lock=False" for all layers
... | This code initializes a YOLO object detection model by setting parameters, building a neural network for predicting bounding boxes and class logits, and configuring training loss functions. It prepares placeholders for inputs, labels, and masks, computes YOLO and mask losses during training, and enables evaluation for ... | def __init__(self, training=False):
# 1. Initialize parameters
# yolo parameters
self.batchsize = cfg.BATCH_SIZE
self.classes = cfg.CLASSES
self.num_class = len(self.classes)
self.anchors = cfg.ANCHORS
self.num_anchor = 3
... |
def _send_signed_request(self, http_method: str, url_path: str, payload={}) -> typing.Dict:
'''
Sends a signed request to the exchange
:param http_method:
:param url_path:
:param payload:
:return:
'''
query_string = urlencode(payload, True)
if que... | The main task of the code is to place a trade order with specified parameters (contract, order type, quantity, side, etc.), adjusting quantity and price according to contract specifications (lot size, tick size), sending a signed request to the appropriate trading API endpoint (futures or spot), handling order executio... | def place_order(self, contract: Contract, order_type: str, quantity: float, side: str, price=None, tif=None) -> \
typing.Union[OrderStatus, None]:
data = dict()
data['symbol'] = contract.symbol
data['side'] = side.upper()
data['quantity'] = round(int(quantity / contract.lot_... |
def padding_function(self, message):
# Convert the message to a string
binary_message = self.text2bin(message)
# Record the initial message length for later
message_length = len(binary_message)
# Add one to the end of the message string
p = binary_message + '1'
# ... | This code implements the SHA-256 cryptographic hash function by processing message blocks through 64 rounds of bitwise operations, updating initial hash values with round constants and message schedules, then converting final hash values to hexadecimal format. | def SHA_256(self, message):
# Initialise the first h values
h0 = 0x6a09e667
h1 = 0xbb67ae85
h2 = 0x3c6ef372
h3 = 0xa54ff53a
h4 = 0x510e527f
h5 = 0x9b05688c
h6 = 0x1f83d9ab
h7 = 0x5be0cd19
# Initialise the round constants
k = [0x428... |
def symbol(self):
try:
symbol = self.tree.find(".//small[@class='bold hidden-xs']")
# Strip Parenthesis
symbol = symbol.text[1:-1]
except:
return None
return symbol
def price(self):
today = self.today()
return today['Open*'][0]
def... | This code generates a structured dictionary containing cryptocurrency data such as name, URL, symbol, price, volume, market cap, and GitHub link. It aggregates attributes and method outputs into a JSON-like format for serialization or API responses, leaving the timestamp as None for potential future use. | def json(self):
coin_data = {
'name': self.name,
'url': self.url,
'symbol': self.symbol(),
'price': self.price(),
'volume': self.volume(),
'marketcap': self.marketcap(),
'timestamp': None,
... |
def goodBye(did_suc):
'''a little funtion to say goodbye to my dear users :)'''
if did_suc:
print('Plotting process succeeded.')
print('Congratulations! GoodBye~ :)')
sys.exit(0)
else:
print('Sorry for that:( Maybe try again with another data file. \nGood luck next time! Good... | The main task of the code is to read a CSV file with specific formatting, parse its header and data columns, and return a dictionary mapping headers to their corresponding data lists along with the original header order as a list. The function handles file operations, error checking, and ensures proper closure of the f... | def readJCMB(file_name):
'''reading file JCMB_2011.csv
This function is wirtten originally to read data in JCMB_2011.csv, but file with
similar data storing format can also be read using this funciton.
The required format is as follows:
elements in each line are seperated by ',', lines... |
def impute(self, data : pd.DataFrame, no_decode = False):
data = self.encode(data)
out = pd.DataFrame(columns=self.features)
for patient in data["id"].unique():
out = pd.concat([out, data.loc[data.id == patient][self.features].ffill().fillna(data[self.features].mean())]).astype(int)... | The code evaluates the performance of an imputation method by introducing artificial missing values (10% random NaNs) in specified features of a DataFrame, imputing them, and calculating the root mean squared error (RMSE) between original and imputed values. It returns error metrics and decoded imputed data. | def evaluate_imputation(self, data : pd.DataFrame):
# copy data, so nothing happens to it
# maybe not necessary in hindsight
new_df = data[self.features].copy(deep=True)
if self.need_ids: new_df["id"] = data.id
# list is for holding the random samples
# dict is for holdin... |
def calc_chroma(x, fs, hop=512, n_octaves=5, bins_per_octave=36, fmin=65.40639132514966):
"""
calculate chroma values with constant q-transfrom and tuning of the HPCP
"""
import librosa
# ctq
C = np.abs(librosa.core.cqt(x, sr=fs, hop_length=hop, fmin=fmin, n_bins=bins_per_octave * n_octaves, bins_per_octa... | The code generates a smoothed beat-synchronized chromagram by: 1) Calculating a chromagram using CQT with specified tuning parameters, 2) Removing transient noise via median filtering, 3) Detecting beat frames, and 4) Averaging chromagram features over detected beats to create a tempo-aligned representation of the audi... | def smoothed_beat_chroma(x, fs, hop=1024, n_octaves=4, fmin=65.40639132514966, n_med=6):
"""
smoothed beat chromagram
"""
import librosa
# chroma with cqt with tuning
c = calc_chroma(x, fs, hop=hop, n_octaves=n_octaves, bins_per_octave=36, fmin=fmin)
# remove transient noise
c = matrix_median(c, n_me... |
def SFS_Search(x, y, start_features=None, depth=None):
"""
Sequential forward search
"""
# get shape of things: n samples, m features
n, m = x.shape
# limit for search
if depth is None:
depth = m
# start with zero set [m x n]
x_h = np.empty(shape=(0, n), dtype=x.dtype)
# dp_list, actual indi... | This function performs feature dimensionality reduction using specified search algorithms (SFS, SBS, or LRS) to select relevant features from input data x based on labels y. It returns filtered features, mutual information, depth metrics, and labels (for LRS). The method iteratively adds/removes features via forward/ba... | def feature_filter(x, y, algorithm='SFS', L=2, R=1, max_it=2):
"""
feature filter uses the filter approach to reduce feature dimensions
x: [n x m] n samples, m features
choose algorithm:
sfs - forward search
sbs - backward search
lrs - left/right search
"""
# get shape of things
n, m = x.sha... |
def sse(actual, predicted):
return (residuals(actual, predicted) **2).sum()
def mse(actual, predicted):
n = actual.shape[0]
return sse(actual, predicted) / n
def rmse(actual, predicted):
return sqrt(mse(actual, predicted)) | The function `reg_error_metrics` calculates and compares regression error metrics (SSE, MSE, RMSE) between a model's predictions (`yhat`) and a baseline (using the target's mean). It returns a DataFrame containing these metrics for both the model and baseline, along with a boolean indicating whether the model outperfor... | def reg_error_metrics(target, yhat):
'''
reg_error_metrics takes in target and prediction series
and returns a dataframe that contains the SSE/MSE/RMSE metrics
for. both model and baseline
and answers if the model is better than the baseline.
'''
df = pd.DataFrame(np.array(['SSE', 'MS... |
def update_screen(self, cards=True, enemies=True, health=True):
label = self.renderfont.render(f"Round {self.round_number} of {self.max_rounds}", True, (0,0,0))
self.screen.blit(label, (self.screen.get_width()//2-12, 30))
if enemies:
self.screen.fill((0,0,0))
self.screen.... | The code handles card selection and interaction in a game, allowing the player to drag a card from their hand and drop it on an enemy. It updates the screen, processes mouse events for dragging, and returns the selected card and target enemy when the mouse is released, along with their attributes. | def choose_card(self):
self.update_screen()
pygame.image.save(self.screen,"screenshot.jpg")
# return information ((name, damage, cost),enemy) about the card
redraw = False
re_health = True
re_enemies = True
re_cards = True
while True:
if redraw... |
def set_rect_enemies(self):
for i,enemy in enumerate(self.enemies):
enemy.set_rect(pygame.Rect(640 -70- (100*i+i),175,50,100))
def update_health_bars(self):
for enemy in self.enemies:
pygame.draw.rect(self.screen, (255,0,0), (enemy.rect.x, 175 - 20, 50, 10)) # HP bar
... | The code manages a game round by initializing positions, handling player and enemy turns, updating health bars, and checking survival status. It alternates between player and enemy actions, returning False if the player dies or True if the enemy dies, thus determining the round's outcome. | def start_round(self):
self.player.hero.set_rect(pygame.Rect(50,175,50,100))
self.set_rect_enemies()
self.update_health_bars()
while True:
self.player_turn()
self.update_health_bars()
self.enemy_turn()
self.update_health_bars()
... |
def parse(filename):
with open(filename, "r") as f:
C = []
for line in f.readlines():
if isClause(line.rstrip()):
C.append([int(l) for l in line.rstrip().split()[:-1]])
return C
def variables(cls):
vrs = []
for cl in cls:
for l in cl:
if l ... | The code transforms a given SAT problem into a new formula with auxiliary variables (X0, X1, Xp) and clauses to enforce constraints. It encodes original clauses, links variables, and adds soft constraints (Xp) to find a maximum satisfiable subset. The main task is to compute an autarky (a partial assignment satisfying ... | def findMaxSat(filename, target):
C = parse(filename)
X = variables(C)
n = len(X)
X1 = [n + i + 1 for i in range(n)]
X0 = [2*n + i + 1 for i in range(n)]
Xp = [3*n + i + 1 for i in range(n)]
F = []
#clauses 1 (equations (6) and (7))
for c in C:
for l in c:
cl = ... |
def parse(filename):
C = []
B = []
with open(filename, "r") as f:
lines = f.readlines()
if filename[-5:] == ".gcnf":
for line in lines[1:]:
if line[0] in ["p","c"]: continue
line = line.split(" ")
cl = [int(i) for i in line[1:-1]]
... | This code initializes a solver for handling logical clauses (C and B) from a file, setting up data structures like hitmaps for efficient clause lookups, configuring temporary files for processing, and preparing variables for clause selection and evidence tracking. It also prepares parameters for autarky and IMU process... | def __init__(self, filename, useAutarky, useImu):
self.filename = filename
self.C, self.B = parse(filename)
self.imu = useImu
self.autarky = useAutarky
self.rid = randint(1,10000000)
self.debug = False
if self.imu or self.autarky:
self.imuAutarkyTrim(... |
def rimeWMCSes(self):
hard = self.B[:]
soft = self.C[:]
open(self.rimeFileW, "w").write(renderWcnf(hard, soft))
cmd = "timeout {} ./tools/rime -v 1 --mcs-limit {} {}".format(self.rimeTimeout, self.rimeMCSLimit, self.rimeFileW)
out = run(cmd, self.rimeTimeout)
mcses = []
... | This method executes the RIME tool to identify Maximum Common Subgraphs (MCSes) from a CNF file. It checks the input file type, exports constraints to a temporary CNF file, runs the RIME command with timeout and MCS limits, parses output lines starting with "MCS", converts valid indices to integers, stores them in `sel... | def rimeMCSes(self):
if self.filename[-5:] == ".gcnf":
return self.rimeWMCSes()
exportCNF(self.C + self.B, self.rimeFile)
cmd = "timeout {} ./tools/rime -v 1 --mcs-limit {} {}".format(self.rimeTimeout, self.rimeMCSLimit, self.rimeFile)
out = run(cmd, self.rimeTimeout)... |
def W1(self):
clauses = []
for i in range(self.dimension):
for j in range(self.dimension):
if j == i: continue
clauses.append(offsetClause(self.C[j], self.evidenceVarsOffsets[i]) + [-self.activators[j], -self.activators[i]])
for cl in self.B:
... | The main task of the code is to construct a set of logical clauses by conditionally combining outputs from multiple methods (W1-W11) based on flags (w4-w11). It then applies cardinality constraints (lower/upper bounds) on the MUS cardinality using CardEnc if enabled, and returns the aggregated clauses along with indice... | def wrapper(self):
clauses = self.W1()
if self.w4:
self.W4() #internally sets up self.min_size
if self.w6:
act = maxVar(clauses)
clauses += self.W6(act)
if self.w7:
clauses += self.W7()
if self.w8:
self.W8()
... |
def wrapper(self):
clauses = self.W1()
if self.w4:
self.W4() #internally sets up self.min_size
if self.w6:
act = maxVar(clauses)
clauses += self.W6(act)
if self.w7:
clauses += self.W7()
if self.w8:
self.W8()
... | The code computes the Minimal Unsatisfiable Subset (MUS) count by exporting wrapper and remainder clauses to files, running SAT solvers (ganak/projMC) with timeout, parsing results, and calculating the difference between wrapper and remainder sizes. It enforces size limits, handles file cleanup, and supports ganak for ... | def runExact(self):
self.ganak = True #currently, we support only ganak (we do not distribute projMC)
WrapperClauses, WrapperInd = self.wrapper()
if len(WrapperClauses) > 5200000:
print("Too large wrapper,", str(len(WrapperClauses)), "terminating")
sys.exit()
expo... |
def _row_by_month(self, month_number, account):
month_name = date(2022, month_number, 1).strftime('%B')
return self._row(
month_name,
account.transactions_amount_on(month_number),
account.average_debit_on(month_number),
account.average_credit_on(month_numb... | This code generates an HTML-formatted email body summarizing an account's monthly transaction details. It creates a table with 12 rows (one per month) showing transaction counts, average debits, and credits, using data from the `_row_by_month` method. The output includes the account's description, ID, and a logo, struc... | def _mail_body(self, account):
monthly_details = [self._row_by_month(month, account) for month in range(1, 13)]
return f'Dear {account.description},<br><br>' + \
f'Detail of the transactions of your account with ID {account.id}:<br>' + \
''.join(
[
... |
def _create_clusters(self, centroids):
# Assign the samples to the closest centroids to create clusters
clusters = [[] for _ in range(self.K)]
for idx, sample in enumerate(self.X):
centroid_idx = self._closest_centroid(sample, centroids)
clusters[centroid_idx].append(idx)... | This code implements K-means clustering by initializing centroids, iteratively assigning data points to the nearest centroid, recalculating centroids, and tracking objective function values. It returns cluster labels for each sample after completing specified iterations. | def predict(self, X):
self.X = X
self.n_samples, self.n_features = X.shape
# initialize
random_sample_idxs = np.random.choice(self.n_samples, self.K, replace=False)
self.centroids = [self.X[idx] for idx in random_sample_idxs]
# Optimize clusters
for _ in range(se... |
def createClusters(self, centroids):
# Assign the samples to the closest centroids to create clusters
clusters = [[] for _ in range(self.K)]
for idx, sample in enumerate(self.X):
centroid_idx = self.closestCentroid(sample, centroids)
clusters[centroid_idx].append(idx)
... | The code implements the K-means clustering algorithm to group data points into K clusters. It initializes centroids randomly, iteratively assigns samples to the nearest centroid, recalculates centroids based on cluster means, and tracks the sum of squared distances (error) as the objective function. The process repeats... | def kmeansAlgo(self, X):
self.X = X
self.n_samples, self.n_features = X.shape
# initialize
random_sample_idxs = np.random.choice(self.n_samples, self.K, replace=False)
self.centroids = [self.X[idx] for idx in random_sample_idxs]
# Optimize clusters
for _ in range... |
def parse_args():
"""Parse commandline arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--uses-library', dest='uses_libraries',
action='append',
help='specify uses-library entries known to the build system')
parser.add_argument('--optional-uses-l... | The code processes an XML file by parsing command-line arguments, enforcing specified libraries, extracting target SDK versions, and writing modified XML to an output file. It handles errors by printing messages and exiting on failures. | def main():
"""Program entry point."""
try:
args = parse_args()
doc = minidom.parse(args.input)
if args.enforce_uses_libraries:
enforce_uses_libraries(doc,
args.uses_libraries,
args.optional_uses_libraries)
if args.extract_target_sdk... |
def get_latest_heroku_release(app: str, api_key: str) -> HerokuRelease:
return release_from_response(get_response(app, api_key, Endpoint.RELEASES)[0])
def get_response(app: str, api_key: str, endpoint: str, payload: Optional[dict] = None):
headers = {
"Accept": "application/vnd.heroku+json; version=3",
... | The main task of the code is to deploy a Heroku app by checking if the provided Git commit hash matches the latest release's commit. If it matches, it retries the existing release; otherwise, it triggers a new deployment. After deployment, it verifies the release status, raising an error if it fails, and outputs the su... | def main(heroku_app: str, heroku_api_key: str, git_commit_hash: str):
assert heroku_app and heroku_api_key and git_commit_hash, "app, API key and commit hash required!"
print(f"Heroku app name: {heroku_app}")
latest_release = get_latest_heroku_release(heroku_app, heroku_api_key)
latest_slug = get_resp... |
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Exception as e:
... | The main task of the code is to process SQLite database tables by filling data gaps, creating temporary tables, and replacing original tables with processed data. It connects to a specified database, iterates through non-"tmp" tables, fills gaps using interpolation, saves results to temporary tables, drops original tab... | def main():
args = sys.argv
db_file=args[1]
global start_date
if len(args) == 3:
start_date = args[2]
print("Set start date = ", start_date)
print(db_file)
try:
conn = create_connection(db_file)
tables = get_all_tables(conn)
print(tables)
for i... |
def RandomModel(structure, mode, out_channels, exp_ratio, kernel, P, max_LS, max_LR, minibatch_loader):
population = []
n_blocks = sum(structure)
l = len(structure)
#create splits in the out_channel list proportional to the number of blocks in each stage of the structure
splits = [0]
for i in range(l):
... | This function implements a genetic algorithm to optimize neural network models. It initializes a population, iteratively selects parents via tournament selection, generates children through mutation/crossover, updates the population, normalizes model scores, and returns the best-performing model and final population af... | def Genetic(structure, mode, out_channels, exp_ratio, kernel, P, k, N_iter, minibatch_loader):
#population = []
history = []
max_LS = 0
max_LR = 0
#initialize the population
population, max_LS, max_LR = RandomModel(structure, mode, out_channels, exp_ratio, kernel, P, max_LS, max_LR, minibatch_loader)
... |
def match_language_to_model(lang):
'''Try mapping a specified language to a language model
:param lang: The language string to map
:type lang: str
:return: Absolute path to language model
'''
# check if we have an old language dir for this language first
language_dir = f'/usr/share/vosk/lan... | The main task of the code is to parse command-line arguments for transcribing a media file into WebVTT subtitles using speech recognition. It handles model selection based on language codes or specified models, detects the optimal model if 'auto' is used, and executes transcription by calling the `transcribe` function ... | def main():
'''
Define arguments for command line usage and carry out transcription.
'''
parser = argparse.ArgumentParser(
description='Creates WebVTT from media file using speech recognition.',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=EXAMPLE_HELP_SECTION
... |
def compare_cow_transport_algorithms():
"""
Using the data from ps1_cow_data.txt and the specified weight limit, run your
greedy_cow_transport and brute_force_cow_transport functions here. Use the
default weight limits of 10 for both greedy_cow_transport and
brute_force_cow_transport.
Print out... | The code compares two cow transport algorithms (greedy and brute-force) by executing both with a given cows dictionary and a transport limit. It prints the results of each method, showcasing their outputs for analysis. The main task is to evaluate and contrast the efficiency and outcomes of the greedy approach versus t... | def start_cow_transport_optimization(cows_dict):
compare_cow_transport_algorithms()
print('greedy', greedy_cow_transport(cows_dict, limit))
print('brute', brute_force_cow_transport(cows_dict, limit)) |
def get_update_set(connection, id):
sql = """select padctn_id from (
select padctn_id, neighborhoods_id, property_use, ROW_NUMBER() OVER (partition by padctn_id order by sale_date desc) rn
from real_estate_info_scrape) r1
where rn = 1 and neighborhoods_id = %s
and pr... | The main task of the code is to process and update records in a database for a given neighborhood. It retrieves a list of update IDs, checks if each entry's 'map_parcel' field is non-empty, and updates the database if valid. It stops processing if it encounters over 1000 consecutive blank entries, assuming data complet... | def main(neighborhood_id):
creds_json = getAWSCreds.secretjson
cnx = get_connection(creds_json["username"], creds_json["password"], creds_json["host"], creds_json["dbname"])
update_list = get_update_set(cnx, neighborhood_id)
blank_count = 0 #count number of blanks in a row to try to figure out where t... |
def fac(x):
if x < 2: return 1
return x * fac(x - 1)
def reduce_perms(G, label_set):
"""Cut down on permutations required to check by ruling out perms that fail themselves"""
vals = [ label_set[k] for k in sorted(label_set.keys()) ] # get label sets sorted by edge labels
# try every permutation of t... | The function determines if a valid ordering exists for a graph by checking constraints on incoming labels, cycles, and permutation limits. It partitions nodes by labels, verifies feasibility against MAX_ORDERS and MAX_ITERATIONS, generates permutations, and returns the first valid ordering if it meets Wheeler graph cri... | def find_ordering(G, MAX_ITERATIONS=2**20, MAX_ORDERS=fac(8)):
"""Given a graph G, finds an ordering on the graph is possible. Will not try if the number of iterations over
graph elements is greater than MAX_ITERATIONS. Finds all permutations within equivalence classes as long
as it will not need to try mor... |
def simple(self):
test(self, GOOD_MESSAGE, 'simple_true1.txt')
test(self, GOOD_MESSAGE, 'simple_true2.txt')
test(self, GOOD_MESSAGE, 'simple_true3.txt')
test(self, CYCLE_MESSAGE, 'simple_false1.txt')
test(self, DIFF_LABELS_MESSAGE, 'simple_false2.txt')
def complex_orderable(self)... | The code defines a test_suite method that executes multiple test cases, including simple, complex orderable, complex unorderable, and large-scale tests, likely to validate functionality, ordering, handling of unorderable types, and performance under heavy load. | def test_suite(self):
self.simple()
self.complex_orderable()
self.complex_unorderable()
self.large() |
def get_empty_row(self, a, b):
row=list()
for k in range(9):
if self.is_empty_val(a,k):
row.append(k)
return row
def add_possible_row_col(self, a, b):
row = list()
col = list()
row = self.get_empty_row(a,b)
col = self.get_empty_... | The function identifies hidden single values in a row by checking if a value is possible in only one cell within that row. If found, it updates the board, records the hint, and clears the cell's possible values. It returns a message indicating the hidden single's position and value. | def check_possible_with_row(self, a, check_next=False, if_check=False):
#E.g board [6,7,0,9,0,0,4,2,3]
# possible [[],[],[5,8],[],[1,5,8],[5,8],[],[],[]]
# index [0,1,2,3,4,5,6,7,8]
# here 4th index col can only have value '1'
row=list()
row=self.get_empty_row(a,0)... |
def get_empty_col(self, a, b):
col=list()
for k in range(9):
if self.is_empty_val(k,b):
col.append(k)
return col
def add_possible_row_col(self, a, b):
row = list()
col = list()
row = self.get_empty_row(a,b)
col = self.g... | This function identifies a "hidden single" in a specified column of a Sudoku board. It checks if a value can only be placed in one cell within the column by examining possible values across all rows. If found, it updates the board with that value, clears the cell's possible values, and records the change. The function ... | def check_possible_with_col(self, b, check_next=False, if_check=False):
#E.g board [6, possible [[], index [0,
# 7, [], 1,
# 0, [5,8], 2,
# 9, [], 3,
# ... |
def get_empty_square(self,a,b):
sq = list()
k=0
for i in range(a*3,(a*3)+3):
for j in range(b*3, (b*3)+3):
if self.result[i][j] ==0:
sq.append([i,j])
return sq
def add_possible_row_col(self, a, b):
row = list()
col = list()
... | This function identifies a "hidden single" in a Sudoku square by checking if a value appears only once in the possible values of the square's empty cells. If found, it updates the grid with that value, clears the cell's possibilities, and returns a message indicating the hidden single's position and value. It also trac... | def check_possible_square_each(self, a, b, check_next=False, if_check=False):
# if possible 1 available only one time in a square, value '1' can be on that cell only
sq = list()
sq = self.get_empty_square(a,b)
val=0
for i,j in sq:
for val1 in self.possible[i][j]:
... |
def get_row_with_only_2_possible(self, a):
rowPair = list()
row = list()
row = self.get_empty_row(a,0)
for i in row:
if len(self.possible[a][i]) == 2:
rowPair.append(i)
row.clear()
return rowPair
def add_possible_except_pair_row(self,a, b1, b... | This function identifies "naked pairs" in Sudoku rows and columns—pairs of cells with identical two-value possibilities—by iterating through rows and columns. When found, it either returns the pair's position and values or removes those values from other cells in the same row/column to solve the puzzle. | def check_naked_pair(self, check_next=False, if_check=False):
rowPair = list()
sum1=0
sum2=0
for i in range(9): # check row
rowPair = self.get_row_with_only_2_possible(i)
for col1 in rowPair:
for col2 in rowPair:
if col... |
def get_empty_row_less_than_4_possible(self,a):
row=list()
for k in range(9):
if self.is_empty_val(a,k) and len(self.possible[a][k])<4 and len(self.possible[a][k])>1:
row.append(k)
return row
def get_combination_3(self,arr,n,r):
c = int(self.fact(n)/(s... | This function identifies "naked triples" in Sudoku puzzles—three cells in a row, column, or 3x3 box containing exactly three shared possible values. It checks each row/column/square for cells with 3-4 possible values, counts value frequencies, and validates combinations. If three values appear ≥2 times across three cel... | def check_naked_triple(self, check_next=False, if_check=False):
row=list()
rowPoss= list()
col=list()
colPoss = list()
fun=lambda a : [val+1 for val in a]
for a in range(9): #check row
row = self.get_empty_row_less_than_4_possible(a)
if len(row)>=3... |
def check_event(self):
"""Check events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
sys.exit()
el... | The code runs a game loop that handles events, updates the game state, renders the game board and UI elements, checks for errors, and maintains a 60 FPS frame rate. It creates the game board if not already created, draws the board, numbers, input buttons, and error lines when active, or displays the menu when inactive.... | def run_game(self):
"""Start the game"""
while True:
self.check_event()
self.screen.fill(self.settings.bg_color)
if self.game_status:
#create board
if self.board_created == False:
self.board.create_board_play(s... |
def strained(self, st1 = 0, st2 = 0, st3 = 1, st4 = 0, st5 = 0, st6 = 0):
#if the sample is not rotated, set values to unrotated crystal
if self.rMatrix is None:
self.rotate_tensor(rot_mat = None, x_dir = None, z_dir=None)
strain = np.zeros((3,3))
#... | The function calculates the amplitude of the reflected electric field when light interacts with a strained crystal, considering polarization angle and effective refractive indices. It preprocesses strain and refractive data, normalizes polarization, computes interaction terms using the dielectric tensor, and returns th... | def inLight(self, polAng = 0):
#if the crystal is not strained, it will need to be strained
if self.strain is None or self.diTensor is None:
self.strained()
if self.effdelN is None:
self.LightWave()
#check how the polarization an... |
def _current_price(self):
return self.df['Close'].values[self.current_step]
def _current_index(self):
return self.df.index[self.current_step]
def _current_timestamp(self):
return self.df['Date'].values[self.current_step]
def set_qty(self, price):
self.qty = int(self.balance / price)
... | The code executes trading actions (buy, sell, hold) based on the input `action`, manages stock positions, calculates profits/rewards, logs transactions, handles market timing (e.g., auto-square-off at 3:20 PM), updates account metrics (net worth, balance, profits), and returns a reward value. It tracks position records... | def _take_action(self, action):
current_price = self._current_price()
action_type = int(action) # [0, 1, 2]
reward = 0
profit_percent = float(0)
self.position_record = ""
self.action_record = ""
# set next time
self.t = self._current_index()
if ... |
def _set_optimal_box_size(self):
current_idx = self.current_step
past_data = self.stationary_df[-self.look_back_window_size + current_idx:current_idx]
self.set_brick_size(auto=False, brick_size=get_optimal_box_size(past_data))
def _set_history(self):
current_idx = self.current_step
... | The `reset` method initializes the environment's state for a reinforcement learning agent, resetting balance, stock holdings, counters (wins/losses), and data structures (net worth tracking, trades, positions). It sets the initial step size, prepares historical data, and returns the transformed observation from a gener... | def reset(self):
self.balance = self.initial_balance
self.stock_held = 0
if int(self.look_back_window_size / 375) > 1:
self.current_step = int(375) * int(self.look_back_window_size / 375)
else:
self.current_step = int(375)
self._set_optimal_box_size()
... |
def do_next(self, last_price):
if len(self.renko_prices) == 0:
self.source_prices.append(last_price)
self.renko_prices.append(last_price)
self.renko_directions.append(0)
return 1
else:
self.source_prices.append(last_price)
return se... | The function `_next_observation` advances through the dataset to find the next valid Renko bar, incrementing the step and performing a 'hold' action if no valid bar is found. It terminates when reaching the dataset's end or a valid bar is identified, then transforms the observation into a color-coded graph for return. | def _next_observation(self):
while True:
observations = self.stationary_df.iloc[self.current_step]
new_renko_bars = self.do_next(pd.Series([observations['Close']]))
if new_renko_bars > 0:
break
else:
if self.current_step + 1 <= len(... |
def _take_action(self, action):
current_price = self._current_price()
action_type = int(action) # [0, 1, 2]
reward = 0
profit_percent = float(0)
self.position_record = ""
self.action_record = ""
# set next time
self.t = self._current_index()
if ... | The code defines a `step` method in a reinforcement learning environment. It executes the given `action`, updates the environment state, computes a reward, increments the step count, checks if the episode is done, and returns the next observation, reward, done status, and an empty info dictionary. | def step(self, action):
reward = self._take_action(action)
self.current_step += 1
obs = self._next_observation()
# reward = self._reward()
self._done()
return obs, reward, self.done, {} |
def load(image_file):
image = tf.io.read_file(image_file)
image = tf.image.decode_jpeg(image)
w = tf.shape(image)[1]
w = w // 2
real_image = image[:, :w, :]
input_image = image[:, w:, :]
input_image = tf.cast(input_image, tf.float32)
real_image = tf.cast(real_image, tf.float32)
return input_image,... | The main task of the code is to load an image pair, apply random jittering for data augmentation, normalize pixel values, and return processed input and real images for training a machine learning model. | def load_image_train(image_file):
input_image, real_image = load(image_file)
input_image, real_image = random_jitter(input_image, real_image)
input_image, real_image = normalize(input_image, real_image)
return input_image, real_image |
def my_creatures(self):
return [c for c in self.player.creatures if c.tile]
def nearest_prey_dist(self, my_creature):
nearest_prey = self.find_nearest_prey(my_creature)
if not nearest_prey or not nearest_prey.tile:
return 9999
return self.dist(my_creature.tile, nearest_prey.tile)
def b... | The main task of the code is to manage an AI player's turn by deciding which creatures attack prey and which seek plants, while also handling breeding. It calculates a desired number of carnivores, assigns attackers based on proximity to prey, and directs other creatures to forage and breed. The function returns True t... | def run_turn(self) -> bool:
"""This is called every time it is this AI.player's turn.
Returns:
bool: Represents if you want to end your turn. True means end your turn, False means to keep your turn going and re-call this function.
"""
# if self.game.current_turn < 75:
... |
def tokenize(self, s):
s = s.replace(',', ' , ')
s = s.replace('[', ' [ ')
s = s.replace(']', ' ] ')
s = s.replace(':', ' : ')
s = s.replace('*', ' * ')
s = s.replace('(', ' ( ')
s = s.replace(')', ' ) ')
s = s.replace('{', ' { ')
s = s.replace('}'... | The code extracts features from disassembled x86-64 machine code for function analysis. It reads input JSON files containing code and stack data, disassembles opcodes using Capstone, tokenizes instructions, and maps operands to parameters via register/stack location analysis. Features like static values, instruction po... | def extract(self):
md = Cs(CS_ARCH_X86, CS_MODE_64)
function_file = {field: open(os.path.join(self.output_dir, f'input0.{field}'), 'w') for field in self.fields}
function_label = open(os.path.join(self.output_dir, 'input1.label'), 'w')
with open(os.path.join(self.stack_dir, f'input1_st... |
def _sqlite_table_has_rowid(self, table: str) -> bool:
try:
self._sqlite_cur.execute(f'SELECT rowid FROM "{table}" LIMIT 1')
self._sqlite_cur.fetchall()
return True
except sqlite3.OperationalError:
return False
def _create_table(self, table_name: str, tran... | This code transfers data from an SQLite database to MySQL by selecting tables, creating corresponding MySQL tables, inserting data using specified methods (e.g., UPDATE or IGNORE), and adding indexes/foreign keys. It handles both specific and all-table transfers, disables MySQL foreign key checks during migration, and ... | def transfer(self) -> None:
"""The primary and only method with which we transfer all the data."""
if len(self._sqlite_tables) > 0:
# transfer only specific tables
self._sqlite_cur.execute(
f"""
SELECT name FROM sqlite_master
WHERE ... |
def startup():
update_viewport(None, 400, 400)
glClearColor(0.0, 0.0, 0.0, 1.0)
glEnable(GL_DEPTH_TEST)
def render(time):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
axes()
angle = time*(180/pi)
spin(angle)
egg()
glFlush()
def shutdown():
pass | The main task of the code is to initialize a GLFW window, set up a rendering loop with vsync, handle framebuffer size changes, and render graphics using the current time. It starts up resources, continuously renders frames until the window closes, then cleans up and terminates GLFW. | def main():
if not glfwInit():
sys.exit(-1)
window = glfwCreateWindow(400, 400, __file__, None, None)
if not window:
glfwTerminate()
sys.exit(-1)
glfwMakeContextCurrent(window)
glfwSetFramebufferSizeCallback(window, update_viewport)
glfwSwapInterval(1)
startup()
... |
def parse_number(number, parent=None):
result = Node(None, None, parent)
result.left = number[0] if type(number[0]) == int else parse_number(number[0], result)
result.right = number[1] if type(number[1]) == int else parse_number(number[1], result)
return result
def reduce(number):
return reduce_expl... | The code processes a file containing snailfish numbers, sequentially adds them by creating a binary tree structure, applies reduction rules (explosions and splits) iteratively until the number is fully reduced, and finally calculates and prints the magnitude of the resulting snailfish number. The main task is to comput... | def solution_part1():
with open('inputs/day18.txt', 'r') as f:
sum = None
for line in f:
list_number = json.loads(line[:-1])
# print(list_number)
number = parse_number(list_number)
if sum is None:
sum = number
continue
... |
def parse_number(number, parent=None):
result = Node(None, None, parent)
result.left = number[0] if type(number[0]) == int else parse_number(number[0], result)
result.right = number[1] if type(number[1]) == int else parse_number(number[1], result)
return result
def reduce(number):
return reduce_expl... | The code computes the maximum magnitude of any sum of two numbers from a list of JSON numbers, considering all pairs in both forward and reverse orders. It reads input numbers, parses them into nodes, combines pairs into sums, reduces them iteratively, calculates their magnitudes, and tracks the highest value. The fina... | def solution_part2():
with open('inputs/day18.txt', 'r') as f:
lines = [json.loads(line[:-1]) for line in f.readlines()]
max_magnitude = float('-inf')
for i in range(len(lines)):
for j in range(i, len(lines)):
sum = Node(parse_number(lines[i]), parse_number(lines... |
def read_data_from_file_imdb(self):
"""
This method reads data from the various files in the imdb dataset
:return: None
"""
positive_path = "aclImdb/train/pos/"
negative_path = "aclImdb/train/neg/"
positive_files = os.listdir(positive_path)
negative_files ... | The main task of the code is to initiate data processing by reading IMDb and Rotten Tomatoes dataset files, then committing the retrieved data to a database. The method serves as the entry point for loading and storing movie-related data from two sources into a persistent storage system. | def start(self):
"""
Starting point
:return: None
"""
# imdb
self.read_data_from_file_imdb()
# rotten tomatoes
self.read_data_from_file_rt()
self.commit_to_db() |
def get_ffmpeg_binary(
binary_url: str = BINARY_URL,
binary_path: str = BINARY_ARCHIVE_PATH,
build_path: str = BUILD_PATH,
bin_path: str = BIN_PATH,
overwrite_bin: bool = False,
) -> bool:
""" Get static binary of ffmpeg """
assert_check(
{
binary_url: str,
b... | The main task of the code is to create an AWS Lambda layer for static ffmpeg binaries by retrieving the binaries, packaging them, uploading the package to Amazon S3, and logging the generated S3 object URL. The process avoids overwriting existing binaries and skips cleaning temporary files during packaging. | def main() -> None:
""" Creates Lambda layer for ffmpeg static """
get_ffmpeg_binary(overwrite_bin=False)
package(clean_bin=False)
object_url = upload_to_s3()
logger.info("Lambda layer created:")
logger.info(object_url) |
def eigenvalues(A):
return eigvals(A)
def eigenvectors(A, evalues):
if not A.shape[0] == A.shape[1]:
raise ValueError('The matrix is not square')
x = np.zeros(A.shape)
for i, labda in enumerate(evalues):
x[:, [i]] = nullspace(A - labda * np.eye(A.shape[0]))
return x
def inverse(A)... | The code computes the power of a matrix $ A $ using eigen decomposition. It calculates $ A^n $ by diagonalizing $ A $: extracting eigenvalues and eigenvectors, raising eigenvalues to the specified power, and reconstructing the result via $ V \Lambda^n V^{-1} $, where $ V $ is the eigenvector matrix and $ \Lambda $ is t... | def matrix_power(A, power=1):
""" Power of a matrix A using eigenvalues if A is diagonalizable
return A^n """
evalues = eigenvalues(A)
evectors = eigenvectors(A, evalues)
LAMBDA = np.eye(A.shape[0])
LAMBDA[np.diag_indices(A.shape[0])] = np.power(evalues, power)
return evectors @ LAMBD... |
def eigenvalues(A):
return eigvals(A)
def eigenvectors(A, evalues):
if not A.shape[0] == A.shape[1]:
raise ValueError('The matrix is not square')
x = np.zeros(A.shape)
for i, labda in enumerate(evalues):
x[:, [i]] = nullspace(A - labda * np.eye(A.shape[0]))
return x
def inverse(A)... | The function computes the matrix exponential of a square matrix A using eigen decomposition. It diagonalizes A by finding its eigenvalues and eigenvectors, applies the exponential function to the eigenvalues scaled by t, and reconstructs the result via matrix multiplication with the eigenvectors and their inverse. This... | def matrix_exponential(A, t=1):
""" Exponential of a matrix A using eigenvalues if A is diagonalizable
return e^A """
evalues = eigenvalues(A)
evectors = eigenvectors(A, evalues)
LAMBDA = np.eye(A.shape[0])
LAMBDA[np.diag_indices(A.shape[0])] = np.exp(np.multiply(evalues, t))
return e... |
def shufflenet_stage1(self, activations):
with tf.name_scope("shufflenet_stage1"):
kernels = self.trained_model['conv1/W:0']
res = tf.nn.conv2d(activations, kernels, padding = 'SAME', strides = [1, 2, 2, 1], data_format = 'NHWC', name = 'Conv1')
res = self.batch_normalization... | This code processes an input image through a ShuffleNet neural network architecture. It normalizes the image channels, applies multiple ShuffleNet stages for feature extraction, performs global average pooling, and outputs class probability distributions via a softmax activation function. | def build(self, image):
red, green, blue = tf.split(axis=3, num_or_size_splits=3, value=image)
bgr = tf.concat(axis=3, values=[(blue - SHUFFLENET_MEAN[0])*NORMALIZER, (green - SHUFFLENET_MEAN[1])*NORMALIZER, (red - SHUFFLENET_MEAN[2])*NORMALIZER])
stage1 = self.shufflenet_stage1(bgr)
sta... |
def __set_game(self):
"""
Resets vizdoom game.
"""
self.game = vzd.DoomGame()
def __load_scenario(self, scenario_idx=0):
"""
Set the games scenario.
scenario_idx = None: Don't try and set scenario (i.e. keep current scenario loaded).
scenario_idx < 0: rand... | Your returnThe code initializes a highly customizable Gym environment for ViZDoom, allowing configuration of scenarios, assets, rendering buffers, action spaces, and observation spaces. It sets up parameters for frame skipping, stacking, image resolution, normalization, and action encoding, while handling default value... | def __init__(self,
scenarios: Union[str, Tuple[str, ...]],
assets: Union[str, Tuple[str, ...]] = None,
ini: str = None,
no_single_channel=False,
frame_skip: int = 1,
frame_stack: int = 1,
image_size: U... |
def close(self):
if self.window_surface:
pygame.quit()
self.is_open = False
if self.has_audio_buffer:
buffer_idx = 1 + self.has_depth_buffer + self.has_labels_buffer + self.has_audio_buffer
if self.render_buffers[buffer_idx]:
self.audio_vis... | The main task of the code is to reset and configure a VizDoom game instance. It closes the current session, initializes the game, loads either a randomized scenario or a default configuration, applies INI settings, resets internal buffers, and defines the observation and action spaces for the environment. | def __reset_game(self, randomize=False):
"""
Resets and configures vizdoom instance.
"""
self.close()
self.__set_game()
if randomize:
self.__randomize_scenario()
else:
self.__load_scenario()
self.__set_default_configs()
... |
def __build_env_action(self, agent_action):
"""
Only used if encode_action.
Encodes the given agent_action to the environment_action that is sent to the vizdoom instance.
"""
# encode users action as environment action
env_action = np.array([0 for _ in range(self.num_delt... | This function executes a given action in the environment, computes the resulting reward, checks if the episode is finished, updates the observation with new frames, and returns the observation, reward, done status, and an empty dictionary. It validates the action if encoding is enabled and processes the action to inter... | def step(self, action):
if self.encode_action:
assert self.action_space.contains(action), f"{action!r} ({type(action)}) invalid"
action = self.__build_env_action(action)
reward = self.game.make_action(action, self.frame_skip)
done = self.game.is_episode_finished()
... |
def __reset_game(self, randomize=False):
"""
Resets and configures vizdoom instance.
"""
self.close()
self.__set_game()
if randomize:
self.__randomize_scenario()
else:
self.__load_scenario()
self.__set_default_configs()
... | The code resets the environment, optionally randomizing scenario, asset, or difficulty with specified probabilities. It reconfigures the VizDoom instance if changes are applied, initializes a new episode, sets a seed if provided, stacks frames, and returns the observation (and empty info dict if requested). | def reset(self, *, seed=None, return_info=False, options=None):
super().reset(seed=seed)
if self.shuffle_scenarios or self.shuffle_assets or self.shuffle_difficulty:
# with probability shuffle_scenarios, change the scenario
shuffle_scenario = self.shuffle_scenarios and torch.rand... |
def handle_movement(self):
# MOVE THE BAR AUTOMATICLY
if self.elapsed_dropdown_time > self.dropdown_speed and self.direction is not DIRECTION_DOWN:
self.current_bar.move(DIRECTION_DOWN)
self.elapsed_dropdown_time = 0
self.has_move = True
# MOVE THE BAR ON INP... | This code updates a game's state by handling block movement, collision detection, and grid updates. It checks elapsed time to trigger actions like moving/dropping blocks, detecting boundary/block collisions, reversing direction, placing blocks, and updating the grid. The function manages game physics, timing, and state... | def on_update(self, delta_time):
if not self.is_playing:
return False
if self.elapsed_time >= self.game_speed:
self.elapsed_time -= self.game_speed
if len(self.blocks_to_drop) == 0:
self.handle_movement()
has_collide_left_and_right_bo... |
def loadGame(fileName):
file = open(fileName, 'r')
lines = file.readlines()
fileNum = int(lines[0])
currentObstacleMap = lines[1]
backgroundLocation = [int(lines[2]), int(lines[3])]
playerLocation = [int(lines[4]), int(lines[5])]
file.close()
return (fileNum, currentObstacleMap, backgro... | The main task of the code is to run a game loop that initializes and manages a game state from a saved file, processes user inputs (mouse clicks, escape key), updates game variables, and transitions between screens (e.g., starting the game). It loads map data, adjusts player position, and maintains game variables for r... | def main():
gameVariables = ''
saveFile = 'saves\\save_data.txt'
loadedGame = loadGame(saveFile)
mouse1Held = mouse1Init = False
mouse3Held = mouse3Init = False
mouseButton1 = (mouse1Held, mouse1Init)
mouseButton3 = (mouse3Held, mouse3Init)
escapeKeyHeld = escapeKeyInit = False
escap... |
def set_background_and_resize(sizeX, sizeY, background):
"""resizes the frame and sets its background"""
global screen;
screen = pygame.display.set_mode((int(sizeX*FRAMESIZE),
int(sizeY*FRAMESIZE)));
skyColour = background.skyColour;
groundColour = background.... | The code renders a frame by setting its background and resizing, then draws characters and their dialogues based on actions listed in the frame. It processes each action to render visual elements and corresponding text, ensuring the frame is fully populated with interactive components and narrative elements. | def draw_frame(frame):
set_background_and_resize(frame.sizeX, frame.sizeY, frame.background);
#draw the characters
for i in frame.actions:
draw_action(i, (frame.sizeX, frame.sizeY));
#draw their dialogue
for i in frame.actions:
draw_dialogue(i, (frame.sizeX, frame.sizeY)); |
def perform_simanneal(shotons, expected_value, max_cost, steps, Tmax, Tmin, stagnation, linear_result, max_range):
result = 0
errors = 0
all_steps = 0
temp_max = 0
temp_min = 0
wrong_results = list()
for i in range(0, max_range):
resultSimanneal = simulated_annealing(shotons, expecte... | The main task of the code is to run and compare simulated annealing (SA) tests with varying parameters (Tmax, Tmin, stagnation) for the SHOTONS problem. It executes multiple SA runs, records metrics like iterations, time, and error rates, and logs results in a table and file. The function evaluates how different SA con... | def all_simanneal_tests_shotons(max_price, linear_result):
x = PrettyTable()
x.field_names = ["Steps", "Tmax", "Tmin", "Stagnation", "Avg time", "Wrong results", "Iterations"]
result = perform_simanneal(True, linear_result[1], max_price, 30000, -1, -1, -1, linear_result, 10)
x.add_row([result[0], resu... |
def perform_simanneal(shotons, expected_value, max_cost, steps, Tmax, Tmin, stagnation, linear_result, max_range):
result = 0
errors = 0
all_steps = 0
temp_max = 0
temp_min = 0
wrong_results = list()
for i in range(0, max_range):
resultSimanneal = simulated_annealing(shotons, expecte... | The code runs multiple simulated annealing tests with varying parameters (Tmax, Tmin, stagnation limits) to evaluate performance metrics like time, iterations, and error rates. It collects results into a formatted table, prints them, and appends the output to a file for logging. The tests compare different configuratio... | def all_simanneal_tests_goals(max_price, linear_result):
x = PrettyTable()
x.field_names = ["Steps", "Tmax", "Tmin", "Stagnation", "Avg time", "Wrong results", "Iterations"]
result = perform_simanneal(False, linear_result[1], max_price, 30000, -1, -1, -1, linear_result, 10)
x.add_row([result[0], resul... |
def create_connection(db_file):
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return None
def get_unique_players_and_avg_score(conn, shotons):
matches_dictionary = dict()
matches = select_all_matches_with_player_stats_and_goals(conn, shotons)
... | The function processes a SQLite database to extract player statistics, calculates average goals and shot-on-target metrics, merges these datasets, and exports the results into two CSV files for further analysis or storage. | def create_data_csv_files():
database = "./database.sqlite"
conn = create_connection(database)
players_goals = get_unique_players_and_avg_score(conn, False)
players_shotons = get_unique_players_and_avg_score(conn, True)
save_to_csv('players_with_avg_goals_2.csv', players_goals)
players_shoton... |
def update_cv(self, **kwargs):
"""This method is used to update an existing CV to the DB"""
try:
data = kwargs
user_id_ = int(data['userID'])
cv_skills = data['skills']
cv = self.session.query(self.cvs).filter(self.cvs.user_id == user_id_)
if ... | This function processes incoming messages from a consumer by parsing JSON payloads. It checks for 'cv', 'job', or 'job_application' keys, validates instances for 'create' actions, and triggers corresponding methods (update/delete/create) based on the 'status' field. Invalid payloads are logged and aborted. | def receive_data(self, ch, method, properties, body):
"""This function is enabled when a message is received from CV Consumer"""
data_payload = json.loads(body)
log.info(data_payload)
if 'cv' in data_payload.keys():
instance = data_payload['cv']
if "status" in dat... |
def set_interface(self, p_dl, p_lines, p_res):
print("setting interface (x lines, resolution, data length)...")
byte = 0b00100000
byte |= p_dl <<4
byte |= p_lines <<3
byte |= p_res <<2
GPIO.output(self.enable_pin, 1)
self.send_instruction(byte)
time.sleep(0.01)
GPIO.output(self.enable_pin, 0)
def d... | The main task of the code is to initialize a screen by configuring interface parameters and display settings. It processes input parameters `p_pars_interface` and `p_pars_display`, calling methods to set the interface, adjust display settings, and clear the display, starting with a log message "initialise started...". | def init_screen(self, p_pars_interface, p_pars_display):
print("initialise strated ...")
self.set_interface(p_pars_interface[0], p_pars_interface[1], p_pars_interface[2])
self.display_settings(p_pars_display[0], p_pars_display[1], p_pars_display[2])
self.clear_display() |
def kies_cursor_opties(self, p_onoff=1, p_blink=1, p_home=None, p_position=None):
#on/off
self.send_instruction((0b00001100|(p_onoff<<1))|p_blink)
#home
if p_home is not None:
self.send_instruction(0b10&(p_home<<1))
#position
if p_position is not None:
self.send_instruction(0b1<<7|p_position)
def send... | The code retrieves IP addresses for 'wlan0' and 'eth0' interfaces by executing a system command, processes the output to extract addresses, and sends them using `send_message` after setting cursor positions. It splits the output string to handle multiple IPs, then transmits each interface's IP separately for display or... | def show_ip(self):
ips = str(check_output(['hostname', '-I']))
first_space = ips.find(' ')
self.kies_cursor_opties(p_position=0x00)
self.send_message(p_message = self.get_ip('wlan0'))
self.kies_cursor_opties(p_position=0x40)
str_after = ips[first_space+1:]
self.send_message(p_message = self.get_ip('eth0')... |
def get_census_block_group_features(
self, state_fips: str, county_fips: str
) -> dict[str, Any]:
where_str = f"STATE='{state_fips}' AND COUNTY='{county_fips}'"
return self.census_arcgis.get_all_by_attribute(where_str)
def get_arcgis_features(self, where_str="1=1") -> dict[str, Any]:
... | The main task of the code is to generate geographic matches by identifying overlaps between census block groups (defined by state/county FIPS codes) and ArcGIS features, using a specified relationship type. It returns a GeoMatchedResults object containing the overlap results and a unique geometry column from ArcGIS. | def generate_geo_matched_results(
self,
/,
*,
state_fips: str,
county_fips: str,
relationship: CensusBlockRelationship,
):
census_block_group_features = self.get_census_block_group_features(
state_fips=state_fips, county_fips=county_fips
)
... |
def process_getreq(database, collection, action, **kwargs):
# Q4
if action == 'get_one':
collection_query = cmd_execute(database,
f"select * from Collection where collection_name = '{collection}' AND collection_id = {kwargs['collection_id']};")
entries_quer... | This function routes database operations by dispatching requests to appropriate processing functions based on the 'action' parameter. It handles 'get_all', 'get_one', 'get_one_by_year_country', 'get_t_b' (with top/bottom ranking logic), 'post', and 'delete' actions, passing relevant parameters and validating inputs lik... | def action_dispatching(database, collection, action, **kwargs):
if action == 'get_all':
return process_getreq(database, collection, 'get_all')
elif action == 'get_one':
return process_getreq(database, collection, 'get_one', collection_id=kwargs['collection_id'])
elif action == 'get_one_by_ye... |
def init(cds_address):
encrypted_shares_json = call_keyring(cds_address, "StartInit", 2)
encrypted_mk_shares = json.loads(encrypted_shares_json)
result = None
shares = {}
for encrypted_mk_share in encrypted_mk_shares:
shareholder_id = encrypted_mk_share['id']
encrypted_share = enc... | The main task of the code is to handle command-line arguments for a keyring tool, allowing users to initialize, unlock, or check the state of a system. It parses input parameters, processes optional address specifications, and delegates actions to corresponding functions (`init`, `unlock`, `get_state`) based on the pro... | def main(argv):
address = os.environ.get("CDS","kds")
help_promt = "usage: keyring.py {init | unlock | state}" \
" [-h | --help | -a <woorl address>| --address <woorl address>]"
try:
opts, args = getopt.getopt(argv, "ha:", ["help", "address="])
except getopt.GetoptError:
... |
def start(self):
self.start_with_name(self._configuration.domain_name)
def __configure_network_listener(self):
""" Create the network listener configuration for the application server """
self.__add_command(self.call_asadmin(['delete-network-listener', 'http-listener-1']))
self.__add_co... | The code's main task is to configure a service by checking configuration flags and applying corresponding setup steps, such as starting/stopping the service, installing JDBC drivers, configuring database connections, LDAP, and system properties, based on the provided settings. | def setup(self):
if (self._configuration.recreate_network_listener or
self._configuration.file_jdbc_jar_path):
self.start()
if self._configuration.recreate_network_listener:
self.__configure_network_listener()
if self._configuration.file_jdbc_jar_path:
... |
def stop(self):
self.stop_with_name(self._configuration.domain_name)
def stop_all_domains(self):
_cmd = self.call_asadmin(['stop-all-domains'])
self.__add_command(_cmd)
def __delete(self, domain_name):
_cmd = self.call_asadmin(['delete-domain', domain_name])
self.__add_command(_c... | The `recreate` method stops the current instance and all domains, deletes the default domain if configured, removes the instance, and then re-creates and sets it up anew. Its main task is to reset the instance and its domains by terminating existing processes, removing configurations, and reinitializing the system from... | def recreate(self):
self.stop()
self.stop_all_domains()
if self._configuration.delete_default_domain:
self.__delete(Constants.Payara.DEFAULT_DOMAIN_NAME)
self.delete()
self.create()
self.setup() |
def before_build(self):
self._create_build_version_folder()
if self.configuration.tokens_before_build:
self._setup_tokens_before_build()
def after_build(self):
if self.configuration.tokens_after_build:
self._setup_tokens_after_build()
self.copy_build()
def clean_u... | The code's main task is to orchestrate the application build process by sequentially executing preparation (`before_build`), construction (`build_application`), post-processing (`after_build`), and cleanup (`clean_up_files`) steps, ensuring a structured workflow for building and maintaining the application's components... | def build(self):
self.before_build()
self.build_application()
self.after_build()
self.clean_up_files() |
def usage():
print('\nUsage:\n-i --input: path/link of file (if link use url flag)\n-o --output: path name of output, if left out will convert in this folder using its name as output\n-u --url: url flag indicating input is a url and should be treated as such\n-f --folder: flag indicating input is directory/folder a... | The code parses command-line arguments to process CSV files, determining whether to handle URLs, local folders, or single files. It uses getopt to manage options like input/output paths, URL mode, and folder mode, then executes corresponding functions (urlCSV, localCSV, or singleCSV) based on the parsed arguments. | def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'hi:o:uf', ['help', 'input=','output=', 'url', 'folder'])
except getopt.GetoptError as err:
print(str(err))
usage()
sys.exit(2)
csvFile = None
output = None
url = False
folder = False
if len(opts) == 0:... |
def has_integration(self, path, method):
"""
Checks if an API Gateway integration is already present at the given path/method
:param string path: Path name
:param string method: HTTP method
:return: True, if an API Gateway integration is already present
"""
metho... | This function retrieves the logical ID of a Lambda function from an API Gateway integration URI. It checks if an integration exists for the specified path and method, normalizes the method name, parses the integration URI (handling conditionals if present), extracts the Lambda ARN, and returns the logical ID by removin... | def get_integration_function_logical_id(self, path_name, method_name):
"""
Retrieves the function logical id in a lambda integration if it exists
If it doesn't exist, returns false
:param path_name: name of the path
:param method_name: name of the method
"""
if no... |
def _normalize_method_name(method):
"""
Returns a lower case, normalized version of HTTP Method. It also know how to handle API Gateway specific methods
like "ANY"
NOTE: Always normalize before using the `method` value passed in as input
:param string method: Name of the HTTP M... | This method adds an AWS Proxy API Gateway integration to a specified HTTP method and path, handling conditional logic and ensuring proper structure in the Swagger definition. It normalizes method names, avoids duplicates, wraps integration URIs in conditions if provided, and configures default route settings. | def add_lambda_integration(self, path, method, integration_uri,
method_auth_config=None, api_auth_config=None, condition=None):
"""
Adds aws_proxy APIGW integration to the given path+method.
:param string path: Path name
:param string method: HTTP Method
... |
def __create_url_with_params(params: dict[str, str|int]) -> str:
"""Creates a full url containing the search parameters"""
url_params = ""
for key, value in params.items(): url_params += f"&{key}={value}"
return f"{URL}?{url_params.lstrip('&')}"
def __get_session(self, url: str) -> req... | The code's main task is to retrieve and save NFT data in batches by repeatedly sending requests with updated parameters. It creates a URL, establishes a session, iterates through pages by incrementing an offset, extracts NFT information from responses, and saves the results until all data is retrieved. | def run(self) -> None:
url = self.__create_url_with_params(PARAMS)
session = self.__get_session(url)
offset, end_reached = 0, False
while not end_reached:
response = self.__request(session, url)
end_reached = self.__extract_nfts(response)
offset +... |
def display_title(self):
title = Label(self.window, text='Quiz Game', width= 50, bg='green', fg = 'White', font=('Roboto', 20, 'bold')).place(x = 0, y =2 )
def display_question(self):
qtext =self.quiz.go_to_next()
self.canvas.itemconfig(self.question_text, text = qtext)
def radio_buttons (self):... | This code initializes a graphical user interface (GUI) for a quiz game using Tkinter. It sets up the window, displays the quiz question on a canvas, creates radio buttons for answer options, and includes buttons and feedback labels. The main task is to provide an interactive GUI where users can answer quiz questions an... | def __init__(self,quiz_brain: QuizBrain) ->None:
self.quiz = quiz_brain
self.window = Tk()
self.window.geometry("1080x720")
self.window.title('The Quiz Game')
self.window.title()
self.display_title()
self.canvas = Canvas()
self.question_text =self.canvas.... |
def setup_clubs(self):
for owner in self.club_owners:
self.buy_club(owner)
def stake_to_club(self, wallet: Wallet, club_name: str):
logger.info(f"Initiating Staaking for {wallet.key.acc_address} On Club {club_name}")
self.increase_allowance(wallet, self.club_staking_address, self.amo... | The code simulates a test scenario involving user wallets, club staking, and reward distribution. It generates wallets, funds them, stakes them into predefined clubs, queries stakes, calculates rewards based on user count and staking amounts, distributes rewards in batches, and re-queries stakes to validate the process... | def run_test_1(self, number_of_users):
self.setup_clubs()
logger.info(f"Loading {number_of_users} Users for Test")
wallets_for_test = self.generate_wallets(number_of_users)
self.fund_wallets(wallets_for_test)
for wallet in wallets_for_test:
for owner in self.club_owne... |
def calc_moment_matrix(ip_im):
im_ar = np.asarray(ip_im)
im_x_ar = grad_x(im_ar)
im_y_ar = grad_y(im_ar)
r, c = im_x_ar.shape
im_xx_ar = np.zeros((r, c))
im_yy_ar = np.zeros((r, c))
im_xy_ar = np.zeros((r, c))
for i in range(r):
for j in range(c):
im_xx_ar[i][j] = im_... | The main task of the code is to compute disparity maps between two images (teddyR.pgm and teddyL.pgm) using corner detection and Sum of Absolute Differences (SAD). It calculates moment matrices, detects corners via corner_response, computes SAD between matched corners, and reports the disparity against the provided dis... | def main():
og_im_tr = Image.open('teddy/teddyR.pgm')
og_im_tl = Image.open('teddy/teddyL.pgm')
og_im_disp = Image.open('teddy/disp2.pgm')
tr_mm = calc_moment_matrix(og_im_tr)
tr_co = corner_response(og_im_tr, tr_mm, 0.05, 12000000)
tl_mm = calc_moment_matrix(og_im_tl)
tl_co = corner_respons... |
def _most_common_label(self, y):
counter = Counter(y)
most_common = counter.most_common(1)[0][0]
return most_common
def _best_criteria(self, X, y, feat_idxs):
best_gain = -1
split_idx, split_thresh = None, None
for feat_idx in feat_idxs:
X_column = X[:, feat_i... | The main task of the code is to recursively build a decision tree node by splitting data based on the best feature and threshold, following stopping criteria (max depth, pure node, or insufficient samples) to create leaf nodes with the most common label. Random feature selection is used for splitting, and the tree grow... | def _grow_tree(self, X, y, depth=0):
n_samples, n_features = X.shape
n_labels = len(np.unique(y))
# stopping criteria
if (depth >= self.max_depth or
n_labels == 1 or
n_samples < self.min_samples_split):
# now we are on the leaf node
l... |
def _create_clusters(self, centroids):
clusters = [[] for _ in range(self.K)]
for idx, sample in enumerate(self.X):
centroid_idx = self._closest_centroid(sample, centroids)
clusters[centroid_idx].append(idx)
return clusters
def _get_centroids(self, clusters):
cen... | This code performs K-means clustering by initializing centroids randomly, iteratively updating cluster assignments and centroids until convergence, then returning cluster labels for input data. It assigns samples to nearest centroids, recalculates centroids as cluster means, and stops when centroid positions stabilize. | def predict(self, X):
self.X = X
self.n_samples, self.n_features = X.shape
# intialize centroids
random_sample_idxs = np.random.choice(
self.n_samples, self.K, replace=False)
self.centroids = [self.X[idx] for idx in random_sample_idxs]
# optimization
... |
def refresh_gui():
# Resetting the preview label.
preview_label.config(image=None)
# Resetting the image in the preview label.
preview_label.image=None
# Resetting the message label.
message_label.config(text="")
# Resetting the results label.
results_label.config(text="")
def allowed_fi... | The code opens a file dialog to select an image, validates the file and bucket name, disables the bucket entry field, displays the image preview, and uploads the file to the specified bucket in a GUI application. | def open_file_dialog():
# Refresh the GUI each time a new file dialog is opened.
refresh_gui()
file_path = filedialog.askopenfilename()
bucket_name = bucket_entry.get()
# Check if the file is an allowed image
if file_path and bucket_name and allowed_file(file_path):
# Disable the bucket_... |
def find(root, key):
v = root
last = root
next = None
while v != None:
if v.key >= key and (next == None or v.key < next.key):
next = v
last = v
if v.key == key:
break
if v.key < key:
v = v.right
else:
v = v.left
root = splay(last)
return (next, ro... | This function splits a splay tree into two subtrees based on a given key. It first searches for the key, splays the found node to the root, then separates the tree into left and right subtrees by disconnecting the splayed node's left child. Both subtrees are updated and returned, allowing the original tree to be divide... | def split(root, key):
(result, root) = find(root, key)
if result == None:
return (root, None)
right = splay(result)
left = right.left
right.left = None
if left != None:
left.parent = None
update(left)
update(right)
return (left, right) |
def load_pic(self, filepath, fobj=None):
"""
load_pic loads the image located at 'filepath' into a numpy array. It is
expecting a NxMx3 image (e.g. PNG or JPG).
"""
if fobj is not None:
self._filepath = None
self._imagename = 'no_name'
pic = f... | The main task of the code is to process an EKG image by loading, transforming, filtering, rotating, and cropping it to isolate leads and extract waveforms. It further isolates heart rate data and retrieves the heart rate, preparing the image for visualization via plot_ekg. The process involves conditional steps based o... | def process_image(self, filepath):
"""
This runs through the necessary steps to extract all waveforms from an
ekg image.
Use plot_ekg after this to visualize.
"""
self.load_pic(filepath)
if self._doTransform:
transformedpic, approx = transform_pic(se... |
def add_rad_mask(image):
"""Mask out all pixels that are radiometrically saturated using the QA_RADSAT
QA band.
Args:
image: ee.Image of an ee.ImageCollection
Returns:
ee.Image with additional band called "radsat", where pixels with a value
of 0 are saturated for at least one SR band and a ... | This function processes Landsat 4-7 imagery by applying masks (radsat, cfmask, SR cloud) and the DSWE algorithm to extract band statistics for high-confidence water (DSWE=1). It computes hillshade/shadow, combines masked bands, and applies reducers (median, mean, stdDev, etc.) to generate summary statistics for water a... | def ref_pull_457_DSWE1(image):
""" This function applies all functions to the Landsat 4-7 ee.ImageCollection, extracting
summary statistics for each geometry area where the DSWE value is 1 (high confidence water)
Args:
image: ee.Image of an ee.ImageCollection
Returns:
summaries for band data withi... |
def add_rad_mask(image):
"""Mask out all pixels that are radiometrically saturated using the QA_RADSAT
QA band.
Args:
image: ee.Image of an ee.ImageCollection
Returns:
ee.Image with additional band called "radsat", where pixels with a value
of 0 are saturated for at least one SR band and a ... | The function processes Landsat 4-7 imagery to extract statistical summaries of specific bands (e.g., median, mean, standard deviation) for pixels classified as high-confidence vegetated (DSWE=3), applying multi-layer masks (clouds, saturated pixels, cloud shadows) and hillshade corrections. It combines masked data with... | def ref_pull_457_DSWE3(image):
""" This function applies all functions to the Landsat 4-7 ee.ImageCollection, extracting
summary statistics for each geometry area where the DSWE value is 3 (high confidence
vegetated pixel)
Args:
image: ee.Image of an ee.ImageCollection
Returns:
summaries for ban... |
def add_rad_mask(image):
"""Mask out all pixels that are radiometrically saturated using the QA_RADSAT
QA band.
Args:
image: ee.Image of an ee.ImageCollection
Returns:
ee.Image with additional band called "radsat", where pixels with a value
of 0 are saturated for at least one SR band and a ... | The main task of the code is to process Landsat 8 and 9 image collections by applying masks (e.g., cloud, saturation, aerosol) and the DSWE algorithm to extract summary statistics (median, mean, std dev, etc.) of specific bands within high-confidence water areas (DSWE=1). It combines masked pixel data with hillshade/sh... | def ref_pull_89_DSWE1(image):
""" This function applies all functions to the Landsat 8 and 9 ee.ImageCollection, extracting
summary statistics for each geometry area where the DSWE value is 1 (high confidence water)
Args:
image: ee.Image of an ee.ImageCollection
Returns:
summaries for band data wi... |
def add_rad_mask(image):
"""Mask out all pixels that are radiometrically saturated using the QA_RADSAT
QA band.
Args:
image: ee.Image of an ee.ImageCollection
Returns:
ee.Image with additional band called "radsat", where pixels with a value
of 0 are saturated for at least one SR band and a ... | This function processes Landsat 8/9 image collections to extract summary statistics (median, mean, standard deviation, etc.) of key bands and masks for areas classified as high-confidence vegetated pixels (DSWE=3). It applies multiple masks (clouds, saturated pixels, illumination) to isolate valid pixels, combines band... | def ref_pull_89_DSWE3(image):
""" This function applies all functions to the Landsat 8 and 9 ee.ImageCollection, extracting
summary statistics for each geometry area where the DSWE value is 3 (high confidence vegetated
pixels)
Args:
image: ee.Image of an ee.ImageCollection
Returns:
summaries for... |
def initialize(self):
for i in range(self.nrFoodSources):
food=self.createFoodSource()
self.foodSources.append(food)
self.trial.append(0)
self.p.append(0)
fx=self.f(food)
self.fValues.append(fx)
self.fit.append(self.fitness(fx))... | The code implements the Artificial Bee Colony (ABC) algorithm for optimization. It iterates for a set number of steps, executing phases where worker bees explore solutions, onlooker bees exploit promising ones, and scout bees abandon poor solutions. The best solution is tracked and printed at each iteration to monitor ... | def ABCalgorithm(self):
self.initialize()
for i in range(self.maxIterations):
self.WorkerbeesPhase()
self.OnlookerbeesPhase()
self.ScoutbeesPhase()
self.memorizeBestValue()
self.printSolution(i) |
def __img_preprocessing(self, orginal_img, auto=True, scaleFill=False, scaleup=True):
# Resize and pad image while meeting stride-multiple constraints
img = orginal_img.copy()
shape = orginal_img.shape[:2] # current shape [height, width]
new_shape = (self.__img_shape, self.__img_shape)
... | The main task of the code is to process a video frame through three stages: image preprocessing, model prediction, and post-processing. It takes a frame, converts it into a suitable format for prediction, runs the model to detect objects, and then refines the results to return a list of detected objects or predictions.... | def detect_from_frame(self, frame) -> list:
img = self.__img_preprocessing(frame)
pred = self.__predict(img)
pred_list = self.__prediction_postprocessing(pred, img, frame)
return pred_list |
def launch_stack(stack_name, launch_params):
capabilities = ["CAPABILITY_NAMED_IAM"]
stack_output = "Empty"
try:
print(f"Creating stack: {stack_name}")
stack_output = cfn.create_stack(
StackName=stack_name,
DisableRollback=True,
TemplateBody=render_templat... | The code processes a stream record by retrieving a DynamoDB entry for a stack, executing a 'Create' or 'Delete' action based on the stored 'Action' field, updating the stack status, and logging results to another DynamoDB table. It extracts stack details, triggers cloud operations, waits for completion, and records the... | def process_stream(record_values):
print(f"Record: {record_values}")
stream_result = "Failed"
stack_name = record_values.get("Stackname").get("S")
timestamp = record_values.get("Timestamp").get("S")
print(f"Stackname: {stack_name}")
print(f"Timestamp: {timestamp}")
table = dynamodb.Table(... |
def load_image(self, indiv):
# handle = self.population[indiv]._Phone
# print(handle)
return vrep.simxCallScriptFunction(self._clientID, "Frontal_Camera#" + str(indiv), vrep.sim_scripttype_childscript, "loadImage",
[indiv],[],[],bytearray(), vrep.simx_opm... | The code processes an image to detect red and green regions using HSV color thresholds, applies border padding, creates masks for these colors, and combines results from `useMask` based on gender input. The function returns a combined output of red and green mask analyses, differentiated by gender. | def useCamera(self, indiv, gender):
# IMPORTANT! `image` returned by the simulator is BGR, not RGB
self.load_image(indiv)
image = self.get_image_front(indiv)
# cv2.imwrite("test_pictures.png", image)
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
image = cv2.copyMakeBorde... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.