dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def lookup_token(broadcaster_id):
db = firestore.Client()
tokens = db.collection("auth-tokens")
result = tokens.where("broadcaster_id", "==", broadcaster_id)
document = result.get()[0]
token_data = document.to_dict()
now = datetime.utcnow().replace(tzinfo=pytz.UTC)
if token_data.get("expires... | The main task of the code is to handle the connection and disconnection of rewards for a broadcaster's subscription. It retrieves rewards, checks active subscriptions, and either subscribes to a reward, updates the subscription with new rewards, or disconnects rewards. It manages subscription records, generates secrets... | def handler(request):
broadcaster_id = request.args.get("broadcaster_id")
access_token = lookup_token(broadcaster_id)
rewards = get_rewards(broadcaster_id, access_token)
message_banner = None
active_subscription = get_active_subscription(broadcaster_id)
if active_subscription:
LOGGER.in... |
def get_active_subscription(broadcaster_id):
db = firestore.Client()
subscriptions = db.collection("subscriptions")
result = subscriptions.where("broadcaster_id", "==", broadcaster_id)
return next((x.to_dict() for x in result.get()), None)
def calculate_message_signature(secret, message_id, timestamp, r... | This code handles Twitch EventSub webhook notifications by validating subscription data, verifying message signatures, and responding to two message types: webhook verification and reward redemptions. When a valid reward redemption is detected, it retrieves a random quote and sends it to the broadcaster's chat. It retu... | def handler(request):
# look up the secret from the broadcaster id (along with other subscription data)
LOGGER.info(request.data.decode("utf-8"))
broadcaster_id = (
request.json.get("subscription", {})
.get("condition", {})
.get("broadcaster_user_id")
)
active_subscription = ... |
def build_config(run_cache_path: Optional[str] = None) -> Sequence[ClusterToCheck]:
if run_cache_path is None:
wiki_state = make_all_wiki_state()
else:
# Collecting wiki state can take a few minutes for ~900 wikis.
# A common use case will be to run script, change same state in
#... | The main task of the code is to validate clusters based on a configuration built from the provided run cache path, report any identified problems in JSON format, and exit with a success status code (0). It constructs cluster configurations, checks for issues, generates a problem report, and outputs it as a JSON string ... | def main(run_cache_path: Optional[str]) -> int:
clusters_to_check = build_config(run_cache_path)
problems = validate_clusters(clusters_to_check)
print(json.dumps(report_problems(problems)))
return 0 |
def returnR(x):
R=[[0 for col in range(N+1)] for row in range(N+1)]
sum=0
for n1 in range(N+1):
for n2 in range(N+1-n1):
R[n1][n2]=L(n1,n2,x)
sum+=R[n1][n2]
for n1 in range(N+1):
for n2 in range(N+1-n1):
R[n1][n2]=R[n1][n2]/sum
return R
def ... | The function computes a vector `b` by iterating over indices `n1` and `n2`, combining elements from matrices `R` and `ax`, and applying conditional adjustments based on boundary checks (`notE`, `E`). It uses parameters `x`, `q`, `m1`, `m2`, `r2`, and `l` to modify entries in `b`, enforcing constraints at grid edges. Th... | def returnRight(x):
R=returnR(x)
ax=returnA(x)
b=[0 for row in range(sN)]
for n1 in range(N+1):
for n2 in range(N+1-n1):
b[index(n1,n2)]=R[n1][n2]*ax
if notE(0, n1)==1:
b[index(n1,n2)]+=x*q*R[n1-1][n2]
if notE(0, n2)==1:
b[ind... |
def returnR(x):
R=[[0 for col in range(N+1)] for row in range(N+1)]
sum=0
for n1 in range(N+1):
for n2 in range(N+1-n1):
R[n1][n2]=L(n1,n2,x)
sum+=R[n1][n2]
for n1 in range(N+1):
for n2 in range(N+1-n1):
R[n1][n2]=R[n1][n2]/sum
return R
def ... | The function `returnB(x)` computes a result by summing multiple terms derived from arrays `R` and `g`, which are obtained from `returnR(x)` and `returnG(x)`. It accumulates values through nested loops involving coefficients `l`, `m1`, `m2`, `r2`, and `x`, applying additions and subtractions. Finally, it adds the output... | def returnB(x):
R=returnR(x)
g=returnG(x)
result=0
for i in range(N+1):
j=N-i
result+=2*l*g[round((i+j)*(i+j+1)/2)+i]
for i in range(1, N+1):
for j in range(N+1-i):
result+=2*m1*r2*i*g[round((i+j)*(i+j+1)/2)+i]
for i in range(N):
for j in range(1, N+... |
def returnR(x):
R=[[0 for col in range(N+1)] for row in range(N+1)]
sum=0
n1=0
while n1<=N:
n2=0
while n2<=N-n1:
R[n1][n2]=L(n1,n2,x)
sum=sum+R[n1][n2]
n2=n2+1
n1=n1+1
n1=0
while n1<=N:
n2=0
while n2<=N-n1:
... | The function `returnB(x)` computes a complex mathematical result by summing multiple terms derived from precomputed arrays `R` and `g`, along with parameters `l`, `m1`, `m2`, `r2`, and `x`. It accumulates values through nested loops, applying indices calculated via triangular number-like formulas, and combines contribu... | def returnB(x):
R=returnR(x)
g=returnG(x)
result=0
for i in range(N+1):
j=N-i
result=result+2*l*g[round((i+j)*(i+j+1)/2)+i]
for i in range(N+1):
for j in range(N+1-i):
result=result+2*m1*r2*i*g[round((i+j)*(i+j+1)/2)+i]
for i in range(N+1):
for j in ra... |
def convert(self, expression):
for i in expression:
if i.isalpha():
raise ValueError('no alphabets allowed')
elif self.isoperand(i):
self.postfix_string += i
self.postfix_arr.append(i)
elif i == '(':
self.stac... | The main task of the code is to evaluate an arithmetic expression using postfix notation. It processes each element in the postfix array, pushing operands onto a stack and applying operators to the top two elements, calculating results step-by-step. The final result is returned after all operations are completed. | def calculate(self):
self.convert(self.expression)
for i in self.postfix_arr:
if self.isoperand(i):
self.stack.push(i)
elif self.isoperator(i):
A = int(self.stack.pop())
B = int(self.stack.pop())
result = self.calc_... |
def calculate_all_means(df_data: pd.DataFrame):
""" Calculate the mean rating per movie as well as the average user offset
:param df_data: All training data
:return: Arrays containing the calculated values for each user and movie
"""
user_ids = (df_data['row_id'] - 1).values
movie_ids = (df_dat... | This code processes a dataset for collaborative filtering by splitting it into training and test sets, initializes user and movie feature matrices, trains a model using matrix factorization with mean predictions as a baseline, and generates final predictions to write as a submission file. | def run():
logging.config.fileConfig("logging_config.ini")
print("Processing data")
df_data: pd.DataFrame = dh.read_data(paths.total_dataset_location)
data_dict: dict = dh.split_original_data(df_data, 0.1)
df_train_data: pd.DataFrame = data_dict["train_data"]
df_test_data: pd.DataFrame = data_d... |
def get_args():
"""Parameters"""
parser = argparse.ArgumentParser(
description="Arguments to modify Json file"
)
parser.add_argument('--action',
required=True,
action='store',
help='Enter the action (create or delete)'),
... | The main task of the code is to retrieve command-line arguments, validate parameters related to environment, action, and resource, and then route the request to an appropriate handler using a switcher mechanism based on the validated inputs. | def main():
args = get_args()
checkparams(args.env,args.action,args.resource)
switcher(args.env,args.action,args.resource) |
def process_audio(song):
audio = song[1]
sample_rate = song[0]
logging.debug("Processing to mono")
audio = np.mean(audio, axis=1)
logging.debug("Trimming zeros")
audio = np.trim_zeros(audio)
logging.debug("Resampling")
sample_rate, audio = resample(audio, sample_rate, 16000)
logging.debug("Chunking")... | The main task of the code is to convert audio songs into TFRecord format. It processes each song into audio chunks, serializes each chunk's data (including raw audio bytes and sample rate) into TensorFlow Example protos, and writes them to an output file. Logging tracks progress every 30 songs. | def write_records(songs, out_file):
with tf.python_io.TFRecordWriter(out_file) as writer:
for i, song in enumerate(songs):
if i % 30 == 0:
logging.debug('Processesed: {}/{}'.format(i, len(songs)))
chunks = process_audio(song)
logging.debug('Processing chunks: {}'.format(len(chunks)))
... |
def tempCheck(self):
self.lastTemp = self.curTemp
self.curTemp = getTemp()
returnData = ("0", "not changed")
if self.curTemp > self.maxTemp:
returnData = self.lowerTemp(self.curTemp)
if self.curTemp < self.minTemp:
returnData = self.raiseTemp(self.curTemp)... | The code's main task is to check temperature, humidity, and moisture levels using respective methods, append their status messages to a string, save the data with helper functions, and return a consolidated status message describing all three checks. | def runChecks(self):
returnMessage = "Temperature was "
tempData = self.tempCheck()
returnMessage += tempData[1]
saveTemp(self.curTemp, tempData)
returnMessage += ". Humidity was "
humidityData = self.humidityCheck()
returnMessage += humidityData[1]
saveHu... |
def identity(self):
return ECPoint(0, 0, 1)
def modinv(self, a, m):
g, x, y = self.egcd(a, m)
if g != 1:
raise Exception('Modular inverse does not exist')
else:
return x % m
def neg(self, p):
return ECPoint(p.x, self.p - p.y) | This code performs elliptic curve point addition, handling cases where points are identity elements, distinct points with different x-coordinates (using slope formula), or same x-coordinates (checking for negatives/doubling via tangent formula). It calculates lambda for slope, derives new coordinates (x3, y3), and retu... | def add(self, p1, p2):
if p1.inf == 1 and p2.inf == 1:
return self.identity()
if p1.inf == 1:
return p2
if p2.inf == 1:
return p1
if p1.x != p2.x:
lam = ((p2.y - p1.y) * self.modinv((p2.x - p1.x) % self.p, self.p))% self.p
else:
... |
def cluster_center(self, points, centers):
distances = np.sqrt(((points - centers[:, np.newaxis]) ** 2).sum(axis=2))
return np.argmin(distances, axis=0)
def new_centers(self, points, cluster):
return np.array([points[cluster==k].mean(axis=0) for k in range(self.k)])
def silhouette_coef(self, x, ... | The code performs K-means clustering by initializing random centroids, iteratively updating them until convergence, and returning clusters along with the silhouette coefficient for evaluation. | def fit(self, x):
idx = np.random.choice(len(x), size=self.k, replace=False)
centers = x[idx]
while True:
cluster = self.cluster_center(x, centers)
new_centers = self.new_centers(x, cluster)
if (centers == new_centers).all():
break
... |
def read(inpput_file):
with open(inpput_file, encoding=FILE_ENCODING) as f:
return json.load(f)
def process_no_context(train_words, train_tags, tokenizer, seq_len):
train_tokens, train_labels, train_lengths = tokenize_and_split_sentences(train_words, train_tags, tokenizer,
... | The function reads and processes text data from a JSON file, extracting sentences and labels. Depending on the configuration, it applies different preprocessing strategies: no context, sequential processing, or similarity-based processing using a matrix. It returns processed data for tasks like modeling or analysis, ad... | def read_process(data_dir, mode, config: PreprocessConfig):
lines = read(os.path.join(data_dir, mode + ".json"))
orig_sentences = []
orig_labels = []
for (i, ids) in enumerate(lines):
orig_sentences.append(lines[ids]['sentence'])
orig_labels.append(lines[ids]['label'])
if config.no_... |
def read_process(data_dir, mode, config: PreprocessConfig):
lines = read(os.path.join(data_dir, mode + ".json"))
orig_sentences = []
orig_labels = []
for (i, ids) in enumerate(lines):
orig_sentences.append(lines[ids]['sentence'])
orig_labels.append(lines[ids]['label'])
if config.no_... | This function reads and preprocesses text data, tokenizes it, converts it into model-ready features (input IDs, masks, labels), and creates a data loader for batched input. It handles data loading, preprocessing configuration, and transformation into PyTorch-compatible formats for training or evaluation. | def read_preprocess_load(data_dir, mode, preprocess_config: PreprocessConfig, loader_config: LoaderConfig):
preprocessed_data = read_process(data_dir, mode, preprocess_config)
combined_sentences = preprocessed_data.combined_sentences
combined_labels = preprocessed_data.combined_labels
tag_map = {l: i f... |
def get_repo_owner(url):
return url.split('/')[-2]
def get_repo_name(url):
return url.split('/')[-1]
def get_main_sha(path):
branch_names = get_branch_names(path)
if 'main' in branch_names:
main_name = 'main'
else:
main_name = 'master'
return rget(f"https://api.github.com/repos/{... | The main task of the code is to retrieve the contents of a GitHub repository's tree structure (files/directories) using either a URL or explicit owner/name parameters. It fetches the main branch's commit SHA, constructs an API request with recursive depth control, and returns the tree data, issuing a truncation warning... | def get_repo_content(url = None, owner = None, name = None, recursive = True):
if url:
owner, name = get_repo_owner(url), get_repo_name(url)
path = f"{owner}/{name}"
sha = get_main_sha(path)
if recursive:
recursive = "recursive=1"
else:
recursive = ""
contents = rget(f"ht... |
def valid_repo_url(url):
pat = r"https?:\/\/github\.com\/[a-zA-Z0-9\-\_]+\/[a-zA-Z0-9\-\_]+\/?$" # regex pattern
structure = bool(re.match(pat, url))
resp = requests.get(url).status_code == 200
return structure and resp
def get_repo(url = None, path = None, owner = None, name = None):
if url:
... | This function retrieves repository information by validating input parameters (URL, owner, or name). If inputs are invalid, it prints error messages. Otherwise, it calls `get_repo` using either provided owner/name or a parsed path from the URL to fetch repository data. | def get_repo_info(url = None, owner = None, name = None):
if not (owner and name) and not valid_repo_url(url):
err_msgs = [f"Repo url: {url} is not valid",
"Please check the url and try again",
"Please ensure the repo exists and is public"]
for msg in err_ms... |
def _split_xz(fn, directory):
log(f"Dumping node block fasta files")
shell("true", directory)
def _get_node_from_header(line):
#print( line.lstrip("@"))
name, _, _ = line.partition("@")
assert (len(name) > 1)
return name[1:]
def _print_buffer(buf, directory):
if... | This function processes a cluster by decompressing its data into blocks, organizing them, compressing nodes, generating a tree structure, and finalizing node processing using the tree. | def _prep_one(cluster):
bl = f"cache/blocks/{cluster}"
_split_xz(f"cache/downloads/{cluster}.fa.xz", directory=bl)
_compress_nodes(bl)
tree = get_tree(cluster)
_complete_nodes(bl, tree) |
def log(*args):
dt = datetime.datetime.now()
print(f"[{dt}]", *args, file=sys.stderr)
def print_clusters(header=False, urls=True, accessions=False):
du = get_clusters_urls()
if accessions:
da = get_clusters_accs()
if header:
header = ["cluster"]
if urls:
header.a... | This code defines a command-line interface (CLI) for a tool named "MoF" that processes genomic data. It allows users to fetch, preprocess, and build k-mer sets from genomic clusters, with subcommands to list clusters, search genomes, and retrieve detailed information. The CLI handles arguments for specifying objects (a... | def main():
log("MoF starting")
#print_clusters()
#sys.exit()
desc1 = f"Example:\n mof get {EXAMPLE_ACC}"
desc2 = """ main command:
get Get genomes
substeps:
fetch Download cluster binary
prep Preprocess node blocks
build Build k-mer sets... |
def handle_uploaded_file(f, name, ocr_framework, request):
print("top of handle_upload_file")
# Capture start time
run_start_time = datetime.datetime.now(timezone.utc).astimezone()
filename = os.path.join(DATA_DIR, name)
os.makedirs(os.path.dirname(filename), exist_ok=True)
if f != "":
w... | This code handles OCR job processing and result display. It processes POST requests for OCR runs, validates input files, and manages job logs. If no job ID is provided, it aggregates and organizes all OCR jobs by input file, categorizing them by service (Azure, Google Vision, Tesseract). For a specific job ID, it retri... | def results(request, job_id = None):
# Process OCR through quick run button
if request.method == "POST":
ocr_framework = request.POST['action']
input_file = request.POST['input_file']
file_exist = os.path.exists(input_file)
# Check that file is valid
if file_exist:
... |
def preprocessData(filename):
with cd.open(filename, 'r', 'utf-8-sig') as file:
data = pd.read_json(file, lines=True)
#raw = []
#for line in file:
# raw.append(pd.io.json.loads(line))
file.close()
#data = pd.io.json.json_normalize(raw)
#data = pd.read_json()
da... | The code's main task is to preprocess training and test data, train a classifier using 'lang' and 'text' features, predict test outcomes, and save predictions to a CSV file. It loads data from specified JSON paths, processes it, trains a model, applies it to test data, and exports results to 'output.csv'. | def main():
trainData = 'Kaggle/project2/dev.json'
testData = 'Kaggle/project2/test.json'
outputData = 'Kaggle/project2/output.csv'
data = preprocessData(trainData)
lib = trainClassifier(data[['lang', 'text']])
test = preprocessData(testData)
predict = testClassifier(lib, test)
writeOut... |
def load_archive(filename, direction=0):
"""
stream in data batch by batch from given archive data
"""
with open(filename, 'r') as fi:
reader = csv.DictReader(fi)
batch = []
item = 0
for row in reader:
# seq number retrieved within each 30-sec query
... | The code visualizes a bus simulation from an archive, plotting real-time bus positions and updating metrics like headway and bunching. It streams data in intervals, simulates bus movement, and generates performance reports including average headway, holding time, and bunching. The function returns a summary report whil... | def plot_sim(filename, direction, live_bus, active_bus, stops, links, stop_pos, control=0, sim_time=10, rate=0.1):
"""
visualize a simulation streaming from an archive
sim_time: minutes to simulate
rate: simulate a second per "X" real-world second
please reset route before each sim ##### to incorpor... |
def load_archive(filename, direction=0):
"""
stream in data batch by batch from given archive data
"""
with open(filename, 'r') as fi:
reader = csv.DictReader(fi)
batch = []
item = 0
for row in reader:
# seq number retrieved within each 30-sec query
... | The main task of the code is to simulate bus operations over a specified time period, calculating metrics like vehicle bunching, average headway, and hold times. It loads bus data, updates bus positions and states at intervals, evaluates performance statistics, and returns a report containing these metrics for analysis... | def simulate(filename, direction, live_bus, active_bus, stops, links, stop_pos, control=0, sim_time=10):
"""
simply simulate to get data (i.e., plot_sim w/o plot)
sim_time: minutes to simulate
please reset route before each sim ##### to incorporate auto-check
"""
data = load_archive(filename, di... |
def get_File_Dataframe(self, feed):
file_suffix = "_" + self.busdate + ".csv"
file_path = self.get_Input_Output_path(self.input_path, feed)
df_list = list()
file_list = list()
if ";" in feed:
feed_list = feed.split(";")
for filename in feed_list:
... | This function applies customized data quality (DQ) rules to data files based on a configuration DataFrame. It iterates through each rule, extracts parameters, retrieves relevant files, and executes corresponding checks like record counts, attribute sums, delta percentages, and uniqueness validations. Results are logged... | def execute_BespokeDQ_Rules(self, rule_df):
# Running DQ Rules from config_file
for index, row in rule_df.iterrows():
rule_dict = dict(row)
feed = rule_dict['Feed']
level = rule_dict['Level']
severity = rule_dict['Severity']
rule = rule_dict['... |
def _join(self):
df_exposure_orig = self._read_idp_exposure()
df_exposure = self._extract_exposure_cols(df_exposure_orig)
df_osfi_orig = self._read_osfi_file()
df_osfi = self._extract_osfi_cols(df_osfi_orig)
df_osfi['SRC_SYS_CD'] = df_osfi['SRC_SYS_CD'].str.replace('NONCORE_IBG'... | The code processes and transforms a DataFrame through a series of operations: joining data, renaming columns, adding new columns, changing data types, reordering columns, and formatting. It then exports the final DataFrame to a CSV file at a specified output path and saves log data to another CSV file. The main task is... | def map(self):
df = self._join()
df = self._rename_cols(df)
df = self._add_cols(df)
df = self._change_type(df)
df = self._order_cols(df)
df = self._format(df)
df.to_csv(os.path.join(self.path_out, self.saccr_trade_file), index=False, header=False)
self.log... |
def checkFileExists(self, file):
try:
if os.path.isfile(file):
logging.info("File exist...: {0} Continue...".format(file))
file_flag = 1
else:
print("File not exist, please check the directory: {0}".format(file))
logging.in... | The code's main task is to process a configuration file by checking its existence, converting it into a DataFrame, applying bespoke data quality rules, generating a summary, and saving the results to a CSV file. It handles I/O errors by logging them and exiting if the file is missing. | def executeRule(self, config):
try:
rule_file = os.path.join(config_dir, config)
flag = self.checkFileExists(rule_file)
if flag == 1:
rule_df = self.convertCSVToDataFrame(rule_file, ',')
self.execute_BespokeDQ_Rules(rule_df)
pri... |
def mask_unused_argument_samples(actions):
"""Replace sampled argument id by -1 for all arguments not used
in a steps action (in-place).
"""
fn_id, arg_ids = actions
for n in range(fn_id.shape[0]):
a_0 = fn_id[n]
unused_types = set(ACTION_TYPES) - set(FUNCTIONS._func_list[a_0].args)
for arg_type i... | The main task of the code is to collect trajectories from the environment for a single batch, compute returns and advantages, and train the agent if enabled. It gathers observations, actions, rewards, and done flags over multiple steps, preprocesses data, and either returns training results or None based on the 'self.t... | def run_batch(self, train_summary=False):
"""Collect trajectories for a single batch and train (if self.train).
Args:
train_summary: return a Summary of the training step (losses, etc.).
Returns:
result: None (if not self.train) or the return value of agent.train.
"""
shapes = (self.step... |
def get_data_from_socket(self):
"""
Accepts data sent to it and returns
the communication point and data
"""
com, _ = self.sock.accept()
data = com.recv(4096)
data = data.decode()
if data != 'Alive': # alive check
data = loads(data)
re... | The code defines a method that runs a slave node in an infinite loop, accepting and processing requests from a webserver. It retrieves data from a socket, checks for an 'Alive' signal, assigns non-alive data to a job list, sends results back to the client, and handles shutdowns or errors (e.g., KeyboardInterrupt, OSErr... | def run(self): # pragma: no cover
"""
Run the slave in an infinite loop of accepting and executing
requests from the webserver.
"""
while True:
try:
self.log.debug('Getting new data')
data, com = self.get_data_from_socket()
... |
def start_time(self):
s_start = sys.float_info.max
r_start = sys.float_info.max
if len(self.sen_list) != 0:
s_start = self.sen_list[0].packet_time
if len(self.rec_list) != 0:
r_start = self.rec_list[0].packet_time
return min(s_start, r_start)
def end_time... | The code computes and aggregates network flow parameters, including source/destination addresses, MAC/IP ranges, protocol, time stamps, packet/byte statistics (sum, max, min, avg), payload metrics, TCP flags (ACK, URG, FIN, etc.), and acknowledgment delays. These features are stored in a dictionary for network traffic ... | def compute_parameters(self):
# flow features
self.parameters.clear()
self.parameters["sAddress"] = self.src
self.parameters["rAddress"] = self.des
self.parameters["sMACs"] = '/'.join(self.src_mac_list)
self.parameters["rMACs"] = '/'.join(self.dst_mac_list)
s... |
def __forward_pass(self, x):
# We want to essentially 'fit' the model and get predictions on our input
# We can now reshape x to make sure it fits the correct shape
# ------------ Initialize/reset hidden and output layers
self.__outputs = []
# ------------ Iterate through every l... | The main task of the code is to train a neural network model using input data (x, y) and validate it with trial data (trialX, trialY). It performs forward and backward passes, updates weights via backpropagation with cross-entropy loss, monitors validation performance, and optionally displays progress bars or plots. Tr... | def fit(self, x, y, trialX, trialY, iterations, learningRate=1, pBar=True, plot=False, validation_clip=1.0, batch_fitting=True):
# -------------------- Make sure that x matches the shape of our weights
# X has to be a 2d array
if not type(x) == list and type(x[0]) == list:
raise Type... |
def normalize_dtype(dtype):
assert not isinstance(dtype, list), (
"Expected a single dtype-like, got a list instead.")
return (
dtype.dtype
if ia.is_np_array(dtype) or ia.is_np_scalar(dtype)
else np.dtype(dtype)
)
def get_value_range_of_dtype(dtype):
dtype = normalize_dty... | This function converts a numpy array's data type to a specified dtype, with optional rounding of float values to integer/boolean types and clipping to ensure values fit within the target dtype's range. It returns the modified array with the new dtype, avoiding unnecessary copying when possible. | def change_dtype_(arr, dtype, clip=True, round=True):
# pylint: disable=redefined-builtin
assert ia.is_np_array(arr), (
"Expected array as input, got type %s." % (type(arr),))
dtype = normalize_dtype(dtype)
if arr.dtype.name == dtype.name:
return arr
if round and arr.dtype.kind == ... |
def normalize_dtype(dtype):
assert not isinstance(dtype, list), (
"Expected a single dtype-like, got a list instead.")
return (
dtype.dtype
if ia.is_np_array(dtype) or ia.is_np_scalar(dtype)
else np.dtype(dtype)
)
def get_value_range_of_dtype(dtype):
dtype = normalize_dty... | This function validates and clips an array's values to fit within the specified data type's value range. It normalizes the dtype, checks if the array's min/max values fall within the dtype's allowable range (raising errors if not), and then clips the array to these bounds. Validation can be customized via parameters, e... | def clip_to_dtype_value_range_(array, dtype, validate=True,
validate_values=None):
dtype = normalize_dtype(dtype)
min_value, _, max_value = get_value_range_of_dtype(dtype)
if validate:
array_val = array
if ia.is_single_integer(validate):
assert vali... |
def normalize_dtypes(dtypes):
if not isinstance(dtypes, list):
return [normalize_dtype(dtypes)]
return [normalize_dtype(dtype) for dtype in dtypes]
def normalize_dtype(dtype):
assert not isinstance(dtype, list), (
"Expected a single dtype-like, got a list instead.")
return (
dtyp... | This function converts input images (numpy arrays or iterables) to specified data types, ensuring dtype consistency across images. It normalizes dtypes, validates input sizes, and applies dtype changes with optional clipping/rounding. For single arrays, all images must share the same dtype; for iterables, each image ge... | def change_dtypes_(images, dtypes, clip=True, round=True):
# pylint: disable=redefined-builtin
if ia.is_np_array(images):
if ia.is_iterable(dtypes):
dtypes = normalize_dtypes(dtypes)
n_distinct_dtypes = len({dt.name for dt in dtypes})
assert len(dtypes) == len(images)... |
def normalize_dtypes(dtypes):
if not isinstance(dtypes, list):
return [normalize_dtype(dtypes)]
return [normalize_dtype(dtype) for dtype in dtypes]
def get_minimal_dtype(arrays, increase_itemsize_factor=1):
assert isinstance(arrays, list), (
"Expected a list of arrays or dtypes, got type %s.... | This function promotes arrays to a common data type by determining the minimal dtype that can accommodate all input arrays, optionally adjusted by a size factor, and converts the arrays to this dtype without clipping or rounding. | def promote_array_dtypes_(arrays, dtypes=None, increase_itemsize_factor=1):
if dtypes is None:
dtypes = normalize_dtypes(arrays)
elif not isinstance(dtypes, list):
dtypes = [dtypes]
dtype = get_minimal_dtype(dtypes,
increase_itemsize_factor=increase_itemsize_fac... |
def normalize_dtypes(dtypes):
if not isinstance(dtypes, list):
return [normalize_dtype(dtypes)]
return [normalize_dtype(dtype) for dtype in dtypes]
def increase_itemsize_of_dtype(dtype, factor):
dtype = normalize_dtype(dtype)
assert ia.is_single_integer(factor), (
"Expected 'factor' to ... | The main task of the code is to increase the resolution of input arrays by modifying their data types. It normalizes the array data types, increases their item size based on the given factor, and then applies these new data types to the arrays without rounding or clipping, effectively enhancing their precision or resol... | def increase_array_resolutions_(arrays, factor):
dts = normalize_dtypes(arrays)
dts = [increase_itemsize_of_dtype(dt, factor) for dt in dts]
return change_dtypes_(arrays, dts, round=False, clip=False) |
def change_name(entry, root, head):
# validate change name string
if entry.get() != "":
if messagebox.askquestion("Access Required", "Are you sure?") == "yes":
head.name = entry.get()
entry.delete(0, tk.END)
root.title(head.name)
head.history.append("name ... | The code creates an admin interface with options to change names, add, remove, and repair vehicles via Tkinter GUI elements. It includes input fields, buttons, and callbacks for managing vehicle data, along with navigation buttons to return to the admin home, exit, or go to the landing page. | def admin_action(root, head):
print("admin action")
clear.clear(root)
change_name_label = tk.Label(text="change name :- ",
width="15",
bg="deep sky blue",
font=("Arial", 12))
change_name_label.place(re... |
def gain(root, head, bts):
frame = tk.Frame(root, width="1000", height="500", bg="white")
frame.place(relx=0.05, rely=0.1)
# list to show
listbox = []
global start_index_b
for i in range(len(head.all_cars)):
# insert to list
listbox.insert(i, [head.all_cars[i].id, head.all_cars[i... | The function `change_frame` switches between different UI frames ("gain", "cars", or "customers") by updating button backgrounds and invoking corresponding management functions based on the `txt` parameter. It modifies the background color of buttons in `bts` to highlight the active section and calls `gain`, `manage_ca... | def change_frame(root, head, txt, bts):
if txt== "gain":
bts[0].config(bg="red")
bts[1].config(bg="gray40")
bts[2].config(bg="gray40")
gain(root, head, bts)
elif txt == "cars":
bts[1].config(bg="red")
bts[0].config(bg="gray40")
bts[2].config(bg="gray40")
... |
def findConjunc(concept_name, concept_total, curr_lvl, rows_list, and_counts, target_combs, create_df):
''' Given a concept_name, a list of conjunctions (rules in curr_lvl), and a rows_list,
calculate its precision, recall, and F1 for predicting that concept_name. Add this information
to the rows_list.'''... | The function evaluates how well each rule (OR of ANDs) predicts concepts in [final_targets], calculating F1 score, precision, recall, and other metrics. It generates DataFrames for each concept, saves results as CSVs, and aggregates findings into a total DataFrame, periodically writing to files. The output includes per... | def getResultsANDOR(and_counts_dict, target_combs_dict, final_targets, create_df=True):
""" Determines how well each rule (OR of ANDs) predicts each concept in [final_targets]. """
if len(and_counts_dict) != len(final_targets):
print("dict_counts_lst do not match final_targets -- please double chec... |
def checkRelImgConsistencyWithObjAttrib(img_i, rel_img):
''' Given a representation for an image's objects/attributes (its index, to be specific,
because its representation is a list that doesn't contain image_id info),
and a representation for an image's relationships, check that the two refer to the same... | The code's main task is to count label occurrences in images, determine each label's type (object, attribute, or relationship) based on frequency, and track co-occurrence of label pairs across images. It returns three structures: co-occurrence counts, individual label frequencies, and inferred label types. | def countAllCoLabels(images, rel_imgs, img_start_i=0, img_end_i=OBJS_BY_IMG.size-1):
''' Go through all the images and do the following:
1. Tally the number of images in which each label appear (img_counts);
2. Determine the type of each label (object, attribute, or relationship) by getting
the type tha... |
def getCandidateRules(target_labels_list):
''' Given a list of groups (each group being a smaller list containing several target labels),
for each group:
1. Identify all possible conjunctions that can be constructed from this group of target labels,
which is just the powerset of the group;
2. Gene... | The code counts how many images satisfy the largest possible conjunctive label combinations (e.g., "A & B") for each target concept. It processes each image's labels, checks all possible label combinations (from largest to smallest) for each target concept, and increments counts for the biggest valid combination found ... | def countTargetLabels(total_imgs, target_labels_list):
''' Given a list (target_labels_list) of several lists, each smaller list containing potential
terms (labels) to form a conjunction rule, count the number of images that satisfy this rule.
Args:
total_imgs = number of images we want to analyze; ta... |
def getMaxCoLabels(concept):
""" Given a concept (which is a label), sort the list of co-occurring labels ("colabels")
for this concept by decreasing order of F1 score when using the co-occurring label as a
rule to predict concept's presence in an image"""
max_colabels_cols = ["Co-Label for Conc... | The code generates and evaluates rules predicting each concept in a list, calculating precision, recall, and F1 scores. It selects top co-labels per concept, sorts rules by descending F1, and outputs results as DataFrames. Special co-labels can be specified, and results are saved in a directory. | def genResults(concepts, special=[], start=0, end=5):
""" Given a list of concepts (strs), determine the rules that best predict each of them, and the
precision/recall/F1 scores of these rules. Sort the rules by decreasing order of F1 score."""
os.makedirs(RESULTS_DIR, exist_ok=True)
# lst of ls... |
def convertToSynset(s, d): # d = synsets dict
''' After preprocessing the string s (see getWord()),
check if it has a synset using the synsets dictionary d.
Return the word part of the synset if it does, else
check try to find its aliases/synonyms. '''
new_s = getWord(s)
if new_s in d:
... | The code processes user study data to identify the 5 most frequently co-occurring words for each concept (e.g., "eat," "old," "nightstand," "intersection") and generates boolean rules to predict concept presence in Visual Genome images. It cleans and maps words to standardized forms, filters repetitive/nonsensical term... | def applyUserStudyData():
''' Determine the 5 most commonly used words for each concept in the user study.
Output the best rules for predicting each concept in Visual Genome images based on boolean
combinations of these words.'''
study1_data = pd.read_csv('data/study1_data.csv')
# study1_d... |
def isCollectionPresent(self, collection_name, db_name):
"""
This checks if collection is present or not.
:param collection_name:
:param db_name:
:return:
"""
try:
database_status = self.isDatabasePresent(db_name=db_name)
if database_status... | The main task of the code is to save a pandas DataFrame into a specified collection in a database. It checks if the collection exists, creates the database and collection if they don't, converts the DataFrame to a JSON-compatible dictionary, and inserts the data. The function returns "Inserted" upon success or raises a... | def saveDataFrameIntoCollection(self, collection_name, db_name, dataframe):
"""
"""
try:
collection_check_status = self.isCollectionPresent(collection_name=collection_name, db_name=db_name)
dataframe_dict = json.loads(dataframe.T.to_json())
if collection_check... |
def isCollectionPresent(self, collection_name, db_name):
"""
This checks if collection is present or not.
:param collection_name:
:param db_name:
:return:
"""
try:
database_status = self.isDatabasePresent(db_name=db_name)
if database_status... | The main task of the code is to update a record in a specified MongoDB collection by applying a given query. It checks if the collection exists, retrieves all existing records, and uses `update_one` to modify the collection with new data from the query. However, the implementation may be flawed, as `update_one` typical... | def updateOneRecord(self, db_name, collection_name, query):
"""
"""
try:
collection_check_status = self.isCollectionPresent(collection_name=collection_name, db_name=db_name)
if collection_check_status:
collection = self.getCollection(collection_name=collec... |
def isCollectionPresent(self, collection_name, db_name):
"""
This checks if collection is present or not.
:param collection_name:
:param db_name:
:return:
"""
try:
database_status = self.isDatabasePresent(db_name=db_name)
if database_status... | This function updates multiple records in a specified MongoDB collection by applying the given query as an update operation. It checks if the collection exists, retrieves all existing records, and uses `update_many` to apply the update. It returns the result of the update operation or raises an exception if an error oc... | def updateMultipleRecord(self, db_name, collection_name, query):
"""
"""
try:
collection_check_status = self.isCollectionPresent(collection_name=collection_name, db_name=db_name)
if collection_check_status:
collection = self.getCollection(collection_name=c... |
def _isPosOnGrid(self, row, col):
return row > 0 and row < self._size() and col > 0 and col < self._size()
def _getTile(self, row, col):
return self._grid[row - 1][col - 1]
def _getAdjOppTiles(self, row, col):
tiles = []
for xOff in range(-1,2):
for yOff in range(-1,2):
... | The function identifies valid move vectors from a given grid position (row, col) by checking adjacent opponent tiles. It calculates directional vectors to these tiles, verifies if a clear path exists using `_searchPathForEnd`, and collects valid vectors for potential moves. | def _getPlayableVectors(self, row, col):
validVectors = []
if self._isPosOnGrid(row, col) and self._getTile(row, col) == " ":
adjOppTiles = self._getAdjOppTiles(row, col)
print("\nadjOppTiles: ", adjOppTiles)
for tile in adjOppTiles:
vec = (tile[0] - r... |
def _getPlayableVectors(self, row, col):
validVectors = []
if self._isPosOnGrid(row, col) and self._getTile(row, col) == " ":
adjOppTiles = self._getAdjOppTiles(row, col)
print("\nadjOppTiles: ", adjOppTiles)
for tile in adjOppTiles:
vec = (tile[0] - r... | The play method checks playable moves from a given position, places a tile, applies all valid directional moves, and ends the turn using helper methods for vector retrieval, tile placement, and turn management. | def play(self, row, col):
vectors = self._getPlayableVectors(row, col)
print("vectors: ", vectors,"\n")
if len(vectors) > 0: #isPlayable
self._setTile(row, col)
for vec in vectors:
self._setTiles(row, col, vec)
self._endTurn() |
def ft_mean(*args: Any) -> float:
"""Function for calculating Mean"""
mean = sum(args) / len(args)
return mean
def ft_median(*args: Any) -> float:
"""Function for calculating Median"""
median = sorted(args)[len(args) // 2]
return median
def ft_quartile(*args: Any) -> float:
"""Function for c... | This code defines a function `calculate` that executes different statistical operations based on the input `value` parameter. It dispatches calls to helper functions like `ft_mean`, `ft_median`, etc., and prints their results. The main task is to perform and display statistical calculations such as mean, median, quarti... | def calculate(value: Any, *args: Any) -> None:
"""Function for executing the right functions"""
if value == 'mean':
print("mean : ", ft_mean(*args))
elif value == 'median':
print("median : ", ft_median(*args))
elif value == 'quartile':
print("quartile : ", ft_quartile(*args))
... |
def authentication(username, password):
with psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST) as conn:
with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
cur.execute("SELECT user_password FROM registeredvoter WHERE voter_id = %s;", [uuid.UUID(userna... | The main task of the code is to securely cast a vote in an electronic voting system. It authenticates the voter, generates a cryptographic key, blinds it using RSA, signs it with an online verifier, unblinds the signature, verifies its validity, and registers the vote on Ethereum using the voter's Ethereum address and ... | def start():
user_id = input("Please enter your voter_id : ")
passwd = getpass.getpass("Enter your password : ")
ballot_id = int(input("Enter your ballot id : "))
authentication(user_id, passwd)
key = int(secrets.token_hex(16), 16)
public_ballot_key = serialization.load_pem_public_key(readPublic... |
def get_state(self):
"Get the state of the controller represented by this object"
state = XINPUT_STATE()
res = xinput.XInputGetState(self.device_number, ctypes.byref(state))
if res == ERROR_SUCCESS:
return state
if res != ERROR_DEVICE_NOT_CONNECTED:
raise ... | The main task of the code is to monitor and handle joystick state changes. It retrieves the current joystick state, checks if it has changed since the last recorded state (via packet number comparison), updates the packet count and processes the new state if changed, and updates the last state reference. The function e... | def dispatch_events(self):
"The main event loop for a joystick"
state = self.get_state()
if not state:
raise RuntimeError(
"Joystick %d is not connected" % self.device_number)
if state.packet_number != self._last_state.packet_number:
# state has ch... |
def getprevduedate(d, h, m):
"""Get the previous date for meeting.
INPUT:
d: datetime object day of the week to meet
h: datetime object hour of day to meet (24h)
m: datetime object minute of hour to meet
OUTPUT:
datetime of the previous meeting
"""
import dateti... | The function `docoffeepage` generates an HTML page listing arXiv papers for a scheduled meeting, including discussed papers, upcoming papers, and volunteer assignments. It reads paper IDs from input files, checks against discussed/next lists, fetches paper details, creates an archive of previous meetings, and writes th... | def docoffeepage(file, discussed_file, next_file, volunteers_file, url, day, hour, min, sleep=60, idid=False, php=False):
"""Read in arxiv IDs from a specified ASCII file, and write HTML.
INPUTS:
file: (str) path of ASCII file with arxiv IDs
discussed_file: (str) path of ASCII file with IDs of d... |
def _ufl_solve(self, cr, w, cback=None, disp=True):
# Don't print out Newton iterations.
if not disp:
orig_log_level = get_log_level()
set_log_level(LogLevel.CRITICAL)
# Set up the weak form.
u, p = split(w)
sigma = cr(sym(grad(u)))
# mu = cr(sym(... | This function solves a problem using different methods based on parameters. It initializes a solution variable 'w', selects a solver (_ufl_solve, _rte_solve, or _solve) depending on flags, computes 'w', and applies an observer if provided. The main task is to compute a solution using specified solver logic and return i... | def run(self, cr, observer=None, initial_w=None, ufl=False, cback=None, solver_parameters=None, disp=True, quad_params=None):
if solver_parameters is None:
solver_parameters = {}
# Define u.
if initial_w is None:
w = Function(self.W, name='w')
else:
w... |
def inspect(self, choiceF, choice, index, i, indexS):
if indexS == ' help ':
print('------------------------Inspect------------------------')
print('Inspect [item]')
print(' [item]')
print(' item is any item found in the room you are in')
pri... | The function processes user input to determine the next action by matching it against predefined commands in `self.CW`. It converts input to lowercase, checks for command matches, and executes corresponding methods (e.g., `inspect`, `help`, `grab`). If a valid command is found, it returns the method's result; otherwise... | def what_next(self):
choiceF = input(str("what next? "))
result = '[w]'
choiceF = choiceF.lower()
choice = ' ' + choiceF + ' '
for index in self.CW:
for i in self.CW[index]:
for indexS in index.split('/'):
if indexS in choice:
... |
def _get_iam_name(stack=None, user=None, logical_id=None, region=None):
opts = '--stack-name {stackname} --logical-resource-id {resource}'.format(
stackname=stack,
resource=logical_id
)
resource = _run_aws("cloudformation describe-stack-resource", region, opts, user)
return resource.get(... | This function uploads an SSH public key to AWS IAM and stores the key and username in AWS SSM, returning a status dictionary indicating success/failure of each step. It uses hardcoded test values for IAM username and stack name, constructs AWS CLI commands, and tracks whether the SSH key, secret, and username were succ... | def upload_secret(name, sshkey=None, stackname=None, cf_resource=None, region=None, user=None):
iam_username = _get_iam_name(
stack=stackname,
user=user,
logical_id=cf_resource,
region=region
)
##### DUMMY CALL ######
iam_username = 'test_custom_apps_trial'
stackname... |
def sample_IC(self, N=128):
'''
Provides random samples of IC with N data points
IC: u = sin(pi * x / L)
'''
# IC coordinates (t=0)
x_ticks = np.random.rand(N) * self.x_range
X_IC = self.array2tensor([[x, 0] for x in x_ticks],
... | The main task of the code is to generate datasets for initial conditions (IC), boundary conditions (BC), collocation points, and test points based on predefined numbers from the configuration. It calls specific sampling methods for each dataset type, compiles them into a dictionary with corresponding keys, and returns ... | def sample_datasets(self):
'''
Provides datasets for IC/BC, collocation and test points
Uses number of data points as specified in the config file
'''
X_IC, u_IC = self.sample_IC(N=self.N_IC)
X_BC, u_BC = self.sample_BC(N=self.N_BC)
X_col, u_col = self.sample_doma... |
def recruit_steps(player: Player, areas: dict):
print(f'Max amount of troops to add: {player.calc_possible_troops()}')
n_troops = input('Amount of troops to add:')
player.add_troops(int(n_troops))
while player.unplaced_troops > 0:
print('Available areas: ' + ' '.join(player.player_areas))
... | The function manages a player's turn in a game by allowing them to recruit units, build structures, or attack opponents. It processes resource gathering, checks for victory, and updates hunger/trust states. The loop handles repeated recruitment, followed by building or attacking actions, ensuring player interactions an... | def player_turn(player: Player, areas: dict, players: list):
player.check_win()
player.gather_resources()
choice = input("Choose Action (Recruit, Build or Attack):")
choice = choice.lower()
while choice == 'recruit':
recruit_steps(player, areas)
choice = input("Choose Action (Recrui... |
def select_3(s):
while True:
sample = select_3_random(s)
d1 = d(sample[0], sample[1])
d2 = d(sample[1], sample[2])
d3 = d(sample[2], sample[0])
if has_fermat_point(d1, d2, d3):
return sample
def cal_min_span_tree(points):
e = []
points_list = list(points)
mat = [[round(math.sqrt((q[0]-p[0])*(q[0]-p[0])... | The code adds a new point to a set of control points by selecting three existing points, generating a new point via a function, recalculating the minimum spanning tree (MST) with the updated set, and updating the MST and total length if the new configuration yields a shorter length. The main task is to iteratively opti... | def add_point(t):
global edges, length, c_pts, n_pts
triangle = select_3(c_pts)
new_point = tuple(f(triangle[0], triangle[1], triangle[2]))
n_c_pts = c_pts | set([new_point])
n_edges = cal_min_span_tree(n_c_pts)
n_length = cal_length(n_edges)
if(should_accept(length, n_length, t)):
edges = n_edges
length = n... |
def Gametitle(self, txt: str) -> None:
pygame.display.set_caption(txt)
def MessageWrite(self, _Font: (str, int), _Msg: str, _X: float, _Y: float) -> None:
self.TargetText = pygame.font.Font(_Font[0], _Font[1])
self.TextSurf, self.TextRect = self.Text_Objects(_Msg, self.TargetText)
self.T... | This method displays a game intro screen with a title, a welcoming message, and two buttons ("Go!" and "Exit!"). It handles user input to either start the game or quit, updates the display, and maintains the intro loop until the user interacts with the buttons or closes the window. | def GameIntro(self) -> None:
pygame.mixer.music.stop()
self.Gametitle(self.Game_Name)
while self.Intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
self.Game_Display.fill(... |
def MessageWrite(self, _Font: (str, int), _Msg: str, _X: float, _Y: float) -> None:
self.TargetText = pygame.font.Font(_Font[0], _Font[1])
self.TextSurf, self.TextRect = self.Text_Objects(_Msg, self.TargetText)
self.TextRect.center = (_X, _Y)
self.Game_Display.blit(self.TextSurf, self.Te... | This method handles the "Game Over" state by stopping music, playing a crash sound, displaying a "Game Over!" message, and presenting two buttons: "Play Again" to restart the game and "Menu" to return to the main menu. It continuously checks for mouse clicks to trigger these actions, updating the display until the user... | def GameLose(self):
pygame.mixer.music.stop()
pygame.mixer.Sound.play(self.Crash_Sound)
self.MessageWrite(('freesansbold.ttf', 90), 'Game Over!', (self.Display_Width / 2), (self.Display_High / 2))
while True:
self.Handle = CarModule.Click.HandleClick(self)
if ... |
def Gametitle(self, txt: str) -> None:
pygame.display.set_caption(txt)
def SetCubeValues(self) -> []:
self.Cube_Class_Values = CarModule.Cubes(
(random.randint(0, (self.Screen_Class_Values.GetDisplaySize()[0] - 100))
, -500)
, (random.randint(50, 100)
... | The code's main task is to run a car racing game loop, handling user input for car movement, updating game elements like cubes and score, checking for collisions, and rendering visuals. It initializes game settings, processes clicks/mouse events, updates car and cube positions, displays the score, and triggers game ove... | def RunGame(self) -> None:
pygame.mixer.music.play(-1)
self.Car_Speed = 0
self.Car_X_Pos = self.Display_Width * 0.45
self.Init_Score_Count = 0
self.Init_Cube_Speed = 8
self.Gametitle(self.Game_Name)
# self.CarPicture(self.CarFeature[0])
self.SetCubeVa... |
def get_selectable_index(self, player):
pos_list = []
for i in range(8):
for j in range(8):
if self.board_arr[i][j].color == 'none':
lookup = self.lookup(i, j, color=player)
if lookup:
pos_list.append(lookup)
... | This function processes a board move in a game (likely Othello/Reversi). It validates the position, updates the board by setting the color and flipping opponent's pieces, switches players, checks for game-ending conditions, calculates the winner, and returns the current scores of both players. | def handle_board_changes(self, position):
if position not in self.get_selectable_index(self.player):
return self.white, self.black
self.set_color(position)
self.make_flip(position)
self.change_player()
if len(self.get_selectable_index(self.player)) == 0:
s... |
def buildGCDMatrix(m):
# Build a matrix with a size less than max number
# Initial size setup
matrix = [[0 for x in range(m)] for y in range(m)]
# Populate
for i in range(m):
for j in range(i, m):
if i == 0 or j == 0:
matrix[i][j] = 1
mat... | The function calculates the number of distinct colorings of a grid with $ w $ columns and $ h $ rows using $ s $ colors, accounting for symmetries via **Polya's Enumeration Theorem**. It computes cycle indices for partitions of $ w $ and $ h $, sums contributions from GCD-based symmetries, and normalizes by dividing by... | def solution(w, h, s):
# Determine the largest number
m = 0
if w > h:
m = w
else:
m = h
# and get the greatest common denominator for them in a matrix
gcdmatrix = buildGCDMatrix(m)
# precalculate the factorials to save us time
factorialMatrix = buildFactorialMatrix(m)
... |
def applyProbability(m):
for r in range(len(m)):
total = 0
for each in range(len(m[r])):
total += m[r][each]
if total != 0:
for each in range(len(m[r])):
m[r][each] /= float(total)
return m
def rqCalc(m, absorbingStates, nonAbsorbingStates):
r = []
q = []
for i in nonAbsorbingS... | The code calculates the absorption probabilities in a Markov chain, determining the likelihood of reaching each absorbing state from every non-absorbing state. It identifies absorbing and non-absorbing states, constructs transition matrices (R and Q), computes the fundamental matrix (I-Q)^-1, and multiplies it by R to ... | def solution(m):
n = len(m)
#address the unique case of just 1 state
if n==1:
if len(m[0]) ==1 and m[0][0] == 0:
return [1,1]
absorbingStates = []
nonAbsorbingStates = []
#First discover which states are absorbing and which are not
for r in range(len(m)):
count = 0
for each in ra... |
def findParent(self, key):
# We are effectively repeating the search algorithm here
# but this time we want to return the parent of the node found
if self.root.key == key:
return None
else:
return self.findParentRecursively(None, self.root, key)
def findMin(self, ... | This function deletes a node from a binary tree, handling three cases: no children (removes the node), one child (replaces the node with its child), or two children (replaces the node with the minimum value in its right subtree and recursively deletes that node). It also tracks the parent node to correctly update tree ... | def deleteNode(self, node, parent=None):
# Delete is the most complicated of the three operations
# It's the trickiest because a) we have three cases to consider, and b)
# we also need to maintain information on the parent of the node to be
# deleted.
# We have three cases, depen... |
def _get_competitor():
print("\nParsing competitor...")
input_competitor = os.environ['INPUT_INDIVIDUAL_EVALUATION']
competitor = Competitor(
id = input_competitor.split(":")[0],
controller_repository = input_competitor.split(":")[1].strip()
)
print("done parsing competitor")
... | The code benchmarks a competitor's performance by initializing Git, cloning their Docker container, running it with world configuration, then committing/pushing results to track benchmark outcomes. | def benchmark(config):
# get world configuration
world_config = config['world']
# Initialise Git
git.init()
# Parse input competitor
competitor = _get_competitor()
# Clone and run Docker containers
_clone_competitor_controller(competitor)
_run_competitor_controller(world_config, c... |
def get_arguments(): # pragma: no cover
"""Retrieves the arguments of the program.
:return: An object that contains the arguments
"""
# Parsing arguments
parser = argparse.ArgumentParser(description=__doc__, usage=
"{0} -h"
.... | The main task of the code is to perform abundance-based greedy clustering of amplicon sequences into OTUs (Operational Taxonomic Units). It reads input sequences from a FASTA file, filters them by minimum length and abundance thresholds, clusters similar sequences greedily, and writes the resulting OTU assignments to a... | def main(): # pragma: no cover
"""
Main program function
"""
# Get arguments
args = get_arguments()
# Votre programme ici
#print(list(read_fasta(args.amplicon_file, args.minseqlen)))
list_otus = abundance_greedy_clustering(args.amplicon_file, args.minseqlen,
... |
def render_usage(e):
timer = time.time()
first = True
destination_label = e.control.destinations[e.control.selected_index].label
ram_progress = get_usage_chart()
cpu_progress = get_usage_chart()
while True:
if destination_label != e.control.destinations[e.con... | This function updates the UI body content based on user-selected navigation tabs. It checks the selected tab's label and renders corresponding sections (Usage, Temp, Info, etc.) using dedicated rendering functions. If no match, it displays the label directly. The global variable tracks the last selected index to avoid ... | def change_body(e):
global last_page_index
destination_label = e.control.destinations[e.control.selected_index].label
if last_page_index != e.control.selected_index:
last_page_index = e.control.selected_index
if destination_label == 'Usage':
render_usage(e... |
def unify_job_titles(df: pd.DataFrame) -> pd.DataFrame:
data_scientists = [
"Lead Data Scientist",
"Data Science Consultant",
"Director of Data Science",
"Principal Data Scientist",
"Data Science Manager",
"Head of Data",
"Applied Data Scientist",
"Da... | The main task of the code is to load and preprocess a dataset by removing irrelevant columns, converting categorical variables, handling high-cardinality features, filtering outliers using Z-score, encoding features, and returning transformed data along with a ColumnTransformer for future predictions. It prepares the d... | def read_and_transform_data(
file_name: os.path = os.path.join(MAIN_DIR, "data/ds_salaries.csv")
) -> Tuple[np.ndarray, pd.core.series.Series, ColumnTransformer]:
df = pd.read_csv(file_name, index_col=0)
cols_to_remove = ["salary", "work_year"]
df.drop(cols_to_remove, axis=1, inplace=True)
df["rem... |
def read_and_transform_data(
file_name: os.path = os.path.join(MAIN_DIR, "data/ds_salaries.csv")
) -> Tuple[np.ndarray, pd.core.series.Series, ColumnTransformer]:
df = pd.read_csv(file_name, index_col=0)
cols_to_remove = ["salary", "work_year"]
df.drop(cols_to_remove, axis=1, inplace=True)
df["rem... | The function `setup` loads or retrains a LightGBM model using transformed data, returning the trained model and a ColumnTransformer. If no existing model is found or if `retrain` is True, it trains a new model, exports it, and returns both the model and the data transformer for future use. | def setup(retrain=False) -> Tuple[lgbm.basic.Booster, ColumnTransformer]:
x, y, ct = read_and_transform_data()
model = load_model()
if model is None or retrain:
model = prepare_model(x, y)
export_model(model)
return model, ct |
def get_mean(self) -> float:
""" Menghitung daftar rata-rata perbedaan waktu. """
mean = -1
if len(self.get_dif()) != 0:
mean = numpy.mean(self.get_dif())
return mean
def get_median(self) -> float:
""" Menghitung daftar median perbedaan waktu. """
... | The code calculates the skewness of a dataset by computing the difference between three times the mean and the median, then dividing by the standard deviation. If the standard deviation is zero, it returns -10 as a default. This measures the asymmetry of the data distribution. | def get_skew(self) -> float:
""" Skew dari daftar perbedaan waktu. """
mean = self.get_mean()
median = self.get_median()
dif = 3 * (mean - median)
std = self.get_std()
skew = -10
if std != 0:
skew = dif / std
return skew |
def get_mean(self) -> float:
""" Menghitung daftar rata-rata perbedaan waktu. """
mean = -1
if len(self.get_dif()) != 0:
mean = numpy.mean(self.get_dif())
return mean
def get_mode(self) -> float:
""" Menghitung modus dari daftar perbedaan waktu. """
... | This function calculates the skewness of a dataset using the formula (mean - mode) / standard deviation. It retrieves the mean, mode, and standard deviation from the object, computes their difference, and divides by the standard deviation (if non-zero) to return the skewness value. If the standard deviation is zero, it... | def get_skew2(self) -> float:
mean = self.get_mean()
mode = self.get_mode()
dif = float(mean) - mode
std = self.get_std()
skew2 = -10
if std != 0:
skew2 = dif / float(std)
return skew2 |
def get_mean(self, packet_direction=None) -> float:
""" Rata-rata panjang paket dalam aliran. """
mean = 0
if len(self.get_packet_length(packet_direction)) > 0:
mean = numpy.mean(self.get_packet_length(packet_direction))
return mean
def get_median(self) -> float:
... | This code calculates the skewness of a dataset using the median and standard deviation. It computes the difference between three times the mean and the median, divides this by the standard deviation (if non-zero), and returns the result as the skewness measure. | def get_skew(self) -> float:
""" Skew panjang paket dalam aliran menggunakan median. """
mean = self.get_mean()
median = self.get_median()
dif = 3 * (mean - median)
std = self.get_std()
skew = -10
if std != 0:
skew = dif / std
return... |
def get_mean(self, packet_direction=None) -> float:
""" Rata-rata panjang paket dalam aliran. """
mean = 0
if len(self.get_packet_length(packet_direction)) > 0:
mean = numpy.mean(self.get_packet_length(packet_direction))
return mean
def get_mode(self) -> float:
... | The function calculates the skewness of a data stream using the formula (mean - mode) / standard deviation, returning a float. It first retrieves the mean, mode, and standard deviation, then computes the difference between mean and mode. If standard deviation is non-zero, it divides this difference by the standard devi... | def get_skew2(self) -> float:
""" Skew panjang paket dalam aliran menggunakan modus. """
mean = self.get_mean()
mode = self.get_mode()
dif = mean - mode
std = self.get_std()
skew2 = -10
if std != 0:
skew2 = dif / std
return skew2 |
def get_mean(self):
""" Menghitung rata-rata waktu paket dalam aliran. """
mean = 0
if self._get_packet_times() != 0:
mean = numpy.mean(self._get_packet_times())
return mean
def get_median(self):
""" Median waktu paket dalam aliran. """
retu... | The code calculates the skewness of a network packet stream using the median and standard deviation. It computes the difference between the mean and median, scales it by 3, and divides by the standard deviation to determine skewness. If the standard deviation is zero, it returns -10 to avoid division by zero. | def get_skew(self):
""" Skew waktu paket dalam aliran jaringan menggunakan median. """
mean = self.get_mean()
median = self.get_median()
dif = 3 * (mean - median)
std = self.get_std()
skew = -10
if std != 0:
skew = dif / std
return s... |
def get_mean(self):
""" Menghitung rata-rata waktu paket dalam aliran. """
mean = 0
if self._get_packet_times() != 0:
mean = numpy.mean(self._get_packet_times())
return mean
def get_mode(self):
""" Modus waktu paket dalam aliran. """
mode = ... | The code calculates the skewness of a network packet flow using the mode. It computes the difference between the mean and mode, divides it by the standard deviation (if non-zero), and returns the result as skew2. This measures the asymmetry of the data distribution around the mode. | def get_skew2(self):
""" Skew waktu paket dalam aliran jaringan menggunakan modus. """
mean = self.get_mean()
mode = self.get_mode()
dif = float(mean) - mode
std = self.get_std()
skew2 = -10
if std != 0:
skew2 = dif / float(std)
retu... |
def get_email_body(self, msg):
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
if content_type == 'text/plain' and 'attachment' not in str(part.get('Content-Disposition')):
return part.get_payload(decode=True).... | This code processes incoming emails by fetching and parsing email content, filtering out unwanted messages, analyzing each sentence for response necessity using AI, and generating appropriate replies or tool interactions when required. | def process_email(self, mail_id, parser):
_, data = self.imap_server.fetch(mail_id, '(RFC822)')
for response_part in data:
if isinstance(response_part, tuple):
msg = parser.parsebytes(response_part[1])
email_from = msg['from']
email_subject = m... |
def confirm_card(card_0):
"""
List of all possibel cards
"""
d_val = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8,
'9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10, 'A': 11, 'A.': 1}
if card_0 in d_val:
return True
else:
return False
def add_card_list(players_... | The main task of the code is to simulate a Blackjack game where players receive and manage cards, validate card inputs, and make decisions to "hit" or "stay" while tracking the remaining deck and rotating turns. It initializes player hands, distributes cards, processes player actions, and returns updated hands and deck... | def blackjack(players, deck_num, degrees_between):
"""
Playing Blackjack
"""
card_0 = ''
n_of_cards=0
players_list=[[] for _ in range(players)]
#gives the first two cards from this round
while n_of_cards < 2 :
for i in range(players):
print(players_list)
... |
def initial_game():
"""
asks if they ant to play blackjack
"""
while True:
# Asking the player to play again or not
play = input("Do you want to play a new game of BlackJack? \n").lower()
if play == 'yes' or play == 'y':
print("\n------------ Blackjack -------------\... | The code simulates a Blackjack game with multiple players, using card counting to adjust betting strategies based on remaining deck composition. It initializes game parameters, tracks card counts, determines betting advice (higher/lower bets) via true count calculations, and manages rounds until the player quits. | def play_blackjack():
ply=initial_game()
if not ply:
print("You dont want to play blackjack so i will exit the game!")
return False
"""
basic feutures
"""
players=int(input("How many players? "))
deck= int(input("How many deck? "))
"""
machine turns arou... |
def is_rpm_installed(name):
'''
Check if an rpm package is installed.
'''
stdoutdata = x("rpm -q " + name)
if stdoutdata.strip().find(name) == 0:
return True
else:
return False
def _yum_protect_base():
'''
Enable yum protect base
http://wiki.centos.org/PackageManagement/Yum/P... | The main task of the code is to install the RPMForge repository on a CentOS system by downloading and verifying the rpmforge-release package, importing its GPG key, checking its checksum, and installing it if not already present. It ensures secure setup by validating package integrity before installation. | def rforge_repo():
'''
Install RPMForge
http://wiki.centos.org/AdditionalResources/Repositories/RPMForge/#head-f0c3ecee3dbb407e4eed79a56ec0ae92d1398e01
'''
package = "rpmforge-release-0.5.2-2.el6.rf.x86_64"
fn = "http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.x86_64.rpm"
if not ... |
def key_gen(shellcode):
Valid_key=False
New_lenght=True
st_len=16
byist=[chr(i) for i in range(1,256)]
while Valid_key == False:
Valid_key = True
key=""
if New_lenght==True:
st_len=st_len*2
keysize=random.randint(st_len,st_len*2)
N... | The function `Xor_stub2` encrypts shellcode using XOR with a generated key, formats both the encrypted shellcode and key as C-style byte arrays, and generates a randomized C stub to decrypt the shellcode at runtime. It produces two outputs: a buffer declaration for the encrypted shellcode and a stub implementing XOR de... | def Xor_stub2(shellcode,bufname):
key=key_gen(shellcode)
encrypted_shellcode=xor_encryption(shellcode.decode('string-escape'),key)
encrypted_shellcode= binascii.hexlify(encrypted_shellcode)
printable_shellcode = ""
for i in range(0,len(encrypted_shellcode)-1,2):
printable_shellcode += "\\... |
def doublekey_gen(shellcode):
Valid_key=False
New_lenght=True
st_len=16
if len(shellcode) > 10000:
st_len=st_len*2
if len(shellcode) > 200000:
st_len=st_len*2
byist1=[chr(i) for i in range(1,256)]
byist2=[chr(i) for i in range(1,256)]
while Valid_key == False:
... | The code encrypts shellcode using XOR with two generated keys, formats them as C-style strings, and generates a C stub to decrypt the shellcode at runtime using randomized loop structures and variable names. | def Doublexor_stub2(shellcode,bufname):
keys=doublekey_gen(shellcode)
key1=keys[0]
key2=keys[1]
Realkey=xor_encryption(key1,key2)
encrypted_shellcode=xor_encryption(shellcode.decode('string-escape'),Realkey)
encrypted_shellcode= binascii.hexlify(encrypted_shellcode)
printable_shellcode = ""... |
def triplekey_gen(shellcode):
Valid_key=False
New_lenght=True
st_len=16
if len(shellcode) > 10000:
st_len=st_len*2
if len(shellcode) > 100000:
st_len=st_len*2
if len(shellcode) > 1000000:
st_len=st_len*4
byist1=[chr(i) for i in range(1,256)]
byist2=[chr... | The main task of the code is to encrypt shellcode using XOR with three dynamically generated keys, convert the encrypted shellcode and keys into C-style hex strings with obfuscation, and generate a C stub that decrypts the shellcode at runtime using the keys through XOR operations. The stub is randomly selected from fo... | def Triplexor_stub2(shellcode,bufname):
keys=triplekey_gen(shellcode)
key1=keys[0]
key2=keys[1]
key3=keys[2]
Realkey=xor_encryption(key1,key2)
Realkey=xor_encryption(Realkey,key3)
encrypted_shellcode=xor_encryption(shellcode.decode('string-escape'),Realkey)
encrypted_shellcode= binascii.... |
def _infer_image_data(self, path_to_data):
"""
Infer the image data from the target point.
Parameters:
path_to_data: The path to dataset.
"""
statistics = calculate_dataset_statistics(path_to_data)
self._image_stats = statistics
if statistics.num_cla... | The function `run_inference` processes input data by training shadow models, fitting Gaussian distributions to model outputs, calculating target model confidence, and performing a likelihood ratio test to compute a confidence ratio. It manages temporary data storage, tracks progress, and returns the final ratio after c... | def run_inference(self, path_to_data, n, epochs, batch_size, lr, request_token, progress_callback):
self._max_epochs = self._N * epochs
self._infer_image_data(path_to_data)
# Load data to pytorch image folder
extract_folder = 'temp_folder'
data = self._load_data(path_to_data, ex... |
def parse_subject(word_list):
skip(word_list, 'stop')
next_word = peek(word_list)
if next_word == 'noun':
return match(word_list, 'noun')
elif next_word == 'verb':
return ('noun', 'player')
else:
raise ParserError("Expected a verb next.")
def parse_verb(word_list):
skip(... | The code parses a sentence by extracting its subject, verb, and object from a word list using helper functions, then constructs and returns a `Sentence` object with these components. | def parse_sentence(word_list):
subj = parse_subject(word_list)
verb = parse_verb(word_list)
obj = parse_object(word_list)
return Sentence(subj, verb, obj) |
def websocket_connect(config):
try:
ws = websocket.WebSocket()
ws.connect(slobs_url)
send(ws, slobs_json.get_connect_json(config["TOKEN"]))
ws.recv()
return ws
except ConnectionError:
gui.status_event_text.set("Error: Could not connect to Streamlabs OBS")
... | The code establishes a WebSocket connection using a config file to monitor and switch OBS scenes based on the active screens in StarCraft II (SC2). It continuously checks SC2's active screens, compares them with predefined scene IDs, and triggers scene switches in OBS (via SLOBS) when transitions occur between in-game ... | def websocket_loop():
with open("config.yaml") as read_file:
config = yaml.safe_load(read_file)
ws = websocket_connect(config)
while not controller.stop:
gui.running_status_text.set("Running")
send(ws, slobs_json.get_scenes)
scene_dict = load(rcv(ws))
if not scene_di... |
def drawInventoryCloseButton(app):
#app.inventoryXButton: (x, y, size, size)
drawRect(app.inventoryXButton[0], app.inventoryXButton[1],
app.inventoryXButton[2], app.inventoryXButton[3],
align = "center", fill = "white", border = "black")
drawLabel("X", app.inventoryXButton[0], ap... | The main task of the code is to render an inventory interface by drawing a centered white rectangle with instructions, a close button, grid layout, and interactive buttons. It displays "Inventory" text, user guidance for selection/interaction, and calls sub-functions to render the inventory grid, close button, and cont... | def drawInventory(app):
drawRect(app.width/2, app.height/2, 500, 500, align = "center",
fill = "white", border = "black",
borderWidth = 2 * app.cellBorderWidth)
drawLabel("Inventory", app.width/2, app.height/2 - 150, size = 100)
drawLabel("Click on a cell to select. Click outside... |
def drawInventory(app):
drawRect(app.width/2, app.height/2, 500, 500, align = "center",
fill = "white", border = "black",
borderWidth = 2 * app.cellBorderWidth)
drawLabel("Inventory", app.width/2, app.height/2 - 150, size = 100)
drawLabel("Click on a cell to select. Click outside... | This function redraws the game screen by drawing the background, player character, visible dots (with health checks), inventory/equip/craft UI elements, stamina/health status, and a "Game Over" message if triggered. It handles rendering based on app state, including conditional UI elements and player status indicators. | def planet_redrawAll(app):
#draw player at center, or playerCoords if usePlayerCoords is True
drawRect(0, 0, app.width, app.height, fill = app.planet.backgroundColor)
drawImage(app.playerImage, app.playerCoords[0] - app.playerSize/2,
app.playerCoords[1] - app.playerSize/2, width = app.playerS... |
def isEndPointSet():
return closedSet.get((endPoint.x, endPoint.y))
def drawPath():
end = closedSet.get((endPoint.x, endPoint.y))
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.add_patch(
patches.Rectangle(
(2, 4), # (x,y)
6, # width
1, ... | This function implements a pathfinding algorithm by iterating through nodes in the openSet. It checks if the end point is reached, selects the node with the lowest cost (getSmallOne()), adds it to the closedSet, and explores its neighbors. The process continues until the path is found, at which point it draws the path ... | def moveNodes():
while openSet:
if isEndPointSet():
drawPath()
break
current = getSmallOne()
closedSet[(current.x, current.y)] = current
addNeighborNodeInOpen(current) |
def __get_json(gameid: str = 'None') -> dict:
"""This function requests steam API, converts it into a JSON and returns it
Args:
gameid (str): If empty this function will request API with all id's associated with a gamename,
if id is provided it will return dict with data ass... | The function retrieves a random free game from Steam's app list by iterating through entries until a valid free game is found, then returns a dictionary containing the game's name and app ID. It checks if the selected app is free, a game type, and successfully fetched, with potential delays due to data retrieval. A TOD... | def random_free_game() -> dict[str, str]:
"""Get random free game from steam applist, checks if it is a game and returns dict with name and id.
NOTE -> This function can take some time before returning a value.
Keys: 'name' | 'appid'
"""
# TODO Create possibilty to gene... |
def about():
"""
prototype::
return = dict ;
this function gives informations used by the function ``install`.
The dictionary returned looks like the following one. In this example, we are
on a ¨mac computer where ¨texlive has been installed by ¨mactex.
python::
{
'osname' : 'mac'... | The function `install` installs a homemade LaTeX package from a specified directory into the local LaTeX distribution. It allows specifying the package name, filtering files via `regpath`, and optionally removing an existing version. Key steps include validating the source directory, cleaning the old package if request... | def install(
ppath,
regpath = "file::**",
name = "",
clean = True
):
"""
prototype::
see = os_use._ppath_regpath2meta , about
arg = PPath: ppath;
the path of folder containg the package
arg = str: name = "" ;
you can use this variable so as to give explicitly th... |
def about():
"""
prototype::
return = dict ;
this function gives informations used by the function ``install`.
The dictionary returned looks like the following one. In this example, we are
on a ¨mac computer where ¨texlive has been installed by ¨mactex.
python::
{
'osname' : 'mac'... | The code defines a function to remove a specified LaTeX package from the local system. It checks if the package exists in the local directory, deletes it if found, and refreshes the package list. If the package is not present, it issues a warning. The function requires "Super User" mode for execution. | def remove(name):
"""
prototype::
arg = str: name ;
the name of a local ¨latex package
action = the package is removed from the local ¨latex distribution
warning::
This function can only be used with the "Super User" mode.
"""
print("Deletion of the package locally.")
# Can we do t... |
def add_platoons(step):
for lane in LANE_NUM: # lane a,b,c,d
if lane == 'a_2' or lane == 'a_3' or lane == 'c_1' or lane == 'c_3':
if random.random() < ADD_PLATOON_PRO_NS:
add_single_platoon(step, lane)
if lane == 'd_1' or lane == 'd_2':
if random.random() ... | This code simulates traffic control in SUMO by managing vehicle platoons. It tracks vehicle positions, adjusts speeds based on distance thresholds, and uses an algorithm to determine output actions. Vehicles are added to serving lists when entering specific zones, and their speeds are modified upon crossing predefined ... | def main():
sumo_cmd = ['sumo-gui', '--duration-log.statistics', '--tripinfo-output', 'my_output_file.xml', '-c', 'my_confg.sumo.cfg']
traci.start(sumo_cmd)
step = 0
topology = []
serving_list = []
action_list = []
#output_list_ids=[]
while step < 360000: # 1 hour
... |
def getTile(x,y,zoom,connection):
cursor = connection.cursor()
statement = """SELECT tile_image, image_hash, latest_hash FROM tile_images WHERE x = ? AND y = ? AND zoom = ? LIMIT 1"""
data_tuple = (x,y,zoom)
cursor.execute(statement,data_tuple)
result = cursor.fetchone()
if(result is None):
... | This function updates a tile in the database by comparing its hash with an existing tile. If the tile doesn't exist, it inserts it. If the hash differs, it generates and stores incremental diffs between versions, using the highest existing refresh index to determine new diff indices. The process involves retrieving old... | def updateTile(new_tile, timestamp, connection):
cursor = connection.cursor()
db_tile = getTile(new_tile.x,new_tile.y,new_tile.zoom,connection)
if(db_tile == None):
#insertTile should only be used for the very first scan
print("tile does not exist - inserting tile into database")
ins... |
def decode(t1):
t1 = tnot(t1)
u1 = nti(t1)
u3 = nti(pti(t1))
u2 = ntnor(u1,u3)
return u1,u3,u2
def inc(t1):
out = t1 + 1
out = out % 3
return out
def tand(t1,t2):
if t1 <= t2:
out = t1
else:
out = t2
return out
def tor(t1,t2):
if t1 >= t2:
out = t1... | The main task of the code is to compute a complex transformation combining decoded components of `t1` and processed versions of `t2` using functions `inc`, `tand`, and `tor`, ultimately returning a result derived from nested logical or arithmetic operations on these elements. | def tsum(t1,t2):
decodetuple = decode(t1)
u1 = decodetuple[0]
u2 = decodetuple[1]
u3 = decodetuple[2]
v1 = inc(inc(t2))
v2 = tand(u2,t2)
v3 = inc(t2)
w1 = tand(u3,v3)
w2 = tand(u1,v1)
w3 = tor(v2,w1)
out = tor(w2,w3)
return out |
def tnot(t1):
if t1 == 0:
out = 2
elif t1 == 2:
out = 0
else:
out = 1
return out
def pti(t1):
if t1 == 2:
out = 0
else:
out = 2
return out
def txor(t1,t2):
u1 = tnot(tand(t1,t2))
u2 = tor(t2, t1)
out = tand(u1,u2)
return out
def tnand(t... | The code computes a logical function combining inputs t1 and t2 through NOT, XOR, NAND, and SUM operations, ultimately returning the negation of their aggregated result. | def AA(t1,t2):
a = tnot(pti(t1))
b = tnot(pti(t2))
c = txor(a,b)
d = tnand(t1,t2)
e = tsum(c,d)
out = tnot(e)
return out |
def tnot(t1):
if t1 == 0:
out = 2
elif t1 == 2:
out = 0
else:
out = 1
return out
def tand(t1,t2):
if t1 <= t2:
out = t1
else:
out = t2
return out
def tor(t1,t2):
if t1 >= t2:
out = t1
else:
out = t2
return out
def Neg(t1):
... | The code computes a logical expression involving inputs t1 and t2 using NOT, AND, OR operations, combines results with arithmetic sums, and returns a final value derived from negated intermediate terms and summed components. | def control(t1,t2):
a = tnot(t2)
b = tand(t1,t2)
c = tor(t1,t2)
d = tand(tand(t2,a),b)
e = Neg(d)
f = tsum(c,t1)
out = tsum(e,f)
return out |
def AA(t1,t2):
a = tnot(pti(t1))
b = tnot(pti(t2))
c = txor(a,b)
d = tnand(t1,t2)
e = tsum(c,d)
out = tnot(e)
return out
def pti(t1):
if t1 == 2:
out = 0
else:
out = 2
return out
def idkno(t1):
if t1 == 0:
out = 1
else:
out = 0
return o... | This code defines a function `halfadder` that takes two inputs `a` and `b`, processes them through a series of helper functions (`AA`, `pti`, `idkno`, `tsum`), and returns two values: `s` (sum) and `c` (carry). The primary task is to compute the sum and carry of two inputs, mimicking a half-adder circuit's behavior, th... | def halfadder(a,b):
"""s = sumdec(a,b)
c = cons(a,b)"""
u1 = AA(a,b)
u2 = pti(u1)
c = idkno(u2)
s = tsum(a,b)
return s,c |
def say_name(self):
self.speak("My name is " + self.name)
return True
def say_date(self):
date = datetime.now().strftime("%d %m %Y")
self.speak("Today is " + date)
return True
def say_time(self):
time = datetime.now().time().strftime("%H %M").split()
time_as_ints ... | The main task of the code is to process user input text by checking for specific keywords and routing the request to corresponding methods like say_name(), say_date(), or quit(), while returning an unrecognized response for unmatched inputs. | def reply(self, text):
if "name" in text:
return self.say_name()
elif "date" in text:
return self.say_date()
elif "time" in text:
return self.say_time()
elif "search" in text:
return self.search()
elif "status" in text and "report" ... |
def greet(self):
time = datetime.now().time().strftime("%H %M")
hour = int(time.split()[0])
time_of_day = ''
if (hour < 12):
time_of_day = "good morning"
elif (hour < 18):
time_of_day = "hello"
else:
time_of_day = "good evening"
... | The code's main task is to continuously listen for voice commands starting with the assistant's name, process them by calling the `reply` method with the command's arguments, and respond with a sorry message if no valid command is detected. It initiates a greeting, pauses briefly, and loops until the `cont` flag is set... | def assist(self):
self.greet()
sleep(1)
cont = True
while cont:
voice = self.recognize_voice()
words = voice.split()
if len(words) > 0:
if words[0] == self.name:
if len(words) > 1:
cont = self... |
def get_projection_grid(b, grid_type="Driscoll-Healy"):
''' returns the spherical grid in euclidean
coordinates, where the sphere's center is moved
to (0, 0, 1)'''
#equidistribution#
theta, phi = S2.meshgrid(b=b, grid_type=grid_type)
x_ = np.sin(theta) * np.cos(phi)
y_ = np.sin(theta) * np.s... | The main task of the code is to preprocess HDR image data by loading, resizing, and converting them to luminance values, then projecting them onto a spherical grid with optional rotation. It splits the data into training/test sets, applies chunk-based projections, and saves the processed dataset (with labels) into a co... | def main():
''' '''
parser = argparse.ArgumentParser()
parser.add_argument("--bandwidth",
help="the bandwidth of the S2 signal",
type=int,
default=30,
required=False)
parser.add_argument("--noise",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.