dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def print_farewell_message(self, width=30, height=10, density=0.5):
# Calculate the position to print the farewell message
farewell_msg = "Until our stars align again!!"
start_x = (width - len(farewell_msg)) // 2
start_y = height // 2
star_colors = [
"cyan",
... | The code provides an interactive command menu, prompting users to select actions like entering commands, viewing results, processing Nmap data, selecting models, searching, or quitting. It handles running command states, validates input, executes corresponding methods, and includes error handling for robust user intera... | def get_user_prompt(self) -> str:
"""
Interactively prompt the user for an action or command input.
Returns:
str: The user's command input.
"""
style = Style.from_dict({"prompt": "cyan", "error": "red"})
while True:
try:
if self.c... |
def get_user_prompt(self) -> str:
"""
Interactively prompt the user for an action or command input.
Returns:
str: The user's command input.
"""
style = Style.from_dict({"prompt": "cyan", "error": "red"})
while True:
try:
if self.c... | This method initiates an interactive session where users input prompts, triggers text generation, displays results, and handles exits via 'exit' commands or interrupts. It validates non-empty inputs, processes generated text, logs errors with context, and ensures graceful termination on exceptions. | def start_interactive_mode(self) -> None:
"""
Start an interactive session for the user to input prompts and receive generated text.
In the interactive session:
- The user is prompted to enter text.
- The model generates text based on the user's input.
- The generated te... |
def params_select(self):
console.log("--> Parameters select")
if self.params_test == None:
model_opt = LGBMOptimizator(
self.X_train,
self.y_train,
self.target,
self.features,
self.categorical_features,
... | The main task of the code is to execute a machine learning pipeline by first selecting parameters, then fitting a model using training and test data, and finally generating a performance summary. This method orchestrates parameter selection, model training with cross-validation, and evaluation metrics calculation to as... | def run_pipe(self):
self.params_select()
self.fit_model(
self.params,
self.X_train.copy(),
self.X_test.copy(),
self.y_train,
self.y_test,
)
self.performance_resume() |
def find_tables(self, next_day, out=False):
'''Returns a list of table slots. Takes the day of the week you are searching for and
searches the next instance of that day'''
self.browser.get(self.config['url'])
party_element = self.browser.find_element_by_xpath(".//select[@data-auto='part... | The code's main task is to check for available restaurant tables on specific days (this Friday, Saturday, and next Friday/Saturday), search for time slots if no prior reservation exists, reserve the latest available time slot, and update the configuration with the reserved time. It logs progress and errors, handles exc... | def reserve(self):
''' Check which days we already have reservations for. We only search on dates where we don't have a
reservation for that restaurant'''
if not self.config['reservations']['this_friday']:
log.info("Searching for tables this Friday")
time_slots = self.fi... |
def val(tree):
leaf_list=get_leaf_list(tree)
#print(leaf_list)
return( min(leaf_list))
def is_leaf(tree):
return( type(tree) != list ) | The code recursively reorders a binary tree so that each node's left child has a value less than or equal to its right child. It compares left and right subtrees, swaps them if the left's value exceeds the right's, and recursively applies the same logic to non-leaf children, ensuring hierarchical ordering from root to ... | def reorder(tree):
left,right=tree
if val(left) > val(right):
left,right=right,left
if not is_leaf(left):
left=reorder(left)
if not is_leaf(right):
right=reorder(right)
return([left,right]) |
def val(tree):
leaf_list=get_leaf_list(tree)
#print(leaf_list)
return( min(leaf_list))
def is_leaf(tree):
return( type(tree) != list ) | The function `reroot` restructures a binary tree so that each node's left child has a smaller value than its right child. It recursively swaps left and right subtrees, ensuring left children are smaller, and reorganizes non-leaf nodes to maintain this order. The process continues until all subtrees meet the criteria, e... | def reroot(tree):
left,right=tree
if val(left) > val(right):
left,right=right,left
if is_leaf(left):
return([left,right])
else :
ll,lr=left
if val(ll) > val(lr):
ll,lr=lr,ll
tree=[ll,[lr,right]]
return(reroot(tree)) |
def first_follow(G):
def union(set_1, set_2):
set_1_len = len(set_1)
set_1 |= set_2
return set_1_len != len(set_1)
first = {symbol: set() for symbol in G.symbols}
first.update((terminal, {terminal}) for terminal in G.terminals)
follow = {symbol: set() for symbol in G.nontermina... | This code initializes a parser for a context-free grammar by constructing a modified grammar (G_prime), computing FIRST and FOLLOW sets, generating LR(1) items, and building a parse table for syntax analysis. It prepares action and goto symbols, indexes productions, and structures data for parsing decisions. | def __init__(self, G):
self.G_prime = Grammar(f"{G.start}' -> {G.start}\n{G.grammar_str}")
self.max_G_prime_len = len(max(self.G_prime.grammar, key=len))
self.G_indexed = []
for head, bodies in self.G_prime.grammar.items():
for body in bodies:
self.G_indexed.... |
def __add_line_legend_wide(self, figure, y_max, y_lasts):
"""# `__add_line_legend_wide`
Take a plotly express line plot and adds a special legend to it that is a label at the end of each line with the same colour as that line.
THIS WORKS FOR WIDE TABLE FORMATS. I.E. THE DATA IS STORED ACROSS A R... | The main task of the code is to generate a Plotly line plot based on the `Plotter`'s parameters. It creates a figure, adds scatter traces for specified columns or categories, adjusts legends, customizes layout (margins, axes fonts), applies user-defined ticks, and returns the finalized plot. The function handles two mo... | def __get_line_figure(self):
"""# `__get_line_figure`
Based on the `Plotter`'s `PlotParamters` return a line plot
## Returns:
`Figure`: A plotly express line plot
"""
figure = go.Figure()
if self.plot_parameters.based_on == COLUMNS:
x_vals = self.... |
def __get_line_figure(self):
"""# `__get_line_figure`
Based on the `Plotter`'s `PlotParamters` return a line plot
## Returns:
`Figure`: A plotly express line plot
"""
figure = go.Figure()
if self.plot_parameters.based_on == COLUMNS:
x_vals = self.... | The code generates a plotly.express figure based on the `plot_type` specified in `self.plot_parameters`, using a match-case structure to select between line, bar, or pie chart creation methods. It returns the generated figure or None if no valid plot type is specified. | def plot(self):
"""# `plot`
## Returns:
`Figure | None`: Returns a `plotly.express` plot based on the plot parameters
"""
figure = None
match self.plot_parameters.plot_type:
case "Line":
figure = self.__get_line_figure()
case "... |
def compute_bounding_box(homography, w, h):
"""
computes bounding box of warped image under homography, without actually warping the image
:param homography: A 3x3 homography matrix transforming an image to common coordinate system.
:param w: width of the image
:param h: height of the image
:ret... | The code generates multiple panoramas by warping input images using homographies, computing bounding boxes, adjusting coordinates, and combining image strips. It creates a specified number of panoramas by slicing and stitching warped images, then crops unused regions to ensure coverage from multiple angles. | def generate_panoramic_images(self, number_of_panoramas):
"""
combine slices from input images to panoramas.
:param number_of_panoramas: how many different slices to take from each input image
"""
assert self.homographies is not None
# compute bounding boxes of all warpe... |
def find_features(pyr):
"""
Detects and extracts feature points from a pyramid.
:param pyr: Gaussian pyramid of a grayscale image having 3 levels.
:return: A list containing:
1) An array with shape (N,2) of [x,y] feature location per row found in the image.
These coord... | The code aligns multiple images into a common coordinate system by computing homographies between successive image pairs. It extracts features, matches them using RANSAC, accumulates homographies from a central reference point, and filters out invalid transformations to prepare for panorama stitching. | def align_images(self, translation_only=False):
"""
compute homographies between all images to a common coordinate system
:param translation_only: see estimte_rigid_transform
"""
# Extract feature point locations and descriptors.
points_and_descriptors = []
for fi... |
def get_loss(X):
# sample z from Q(z|x)
Z_mu, Z_var = encoder_network(X)
Z_sample, _ = get_sample_z(Z_mu, Z_var)
_, logits = dencoder_network(Z_sample)
# E[log P(X|Z)]
E_loss = tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(targets=X, logits=logits), 1)
# D_KL(Q(z|X) || P(z))
KL... | The main task of the code is to train and evaluate a Variational Autoencoder (VAE) model on the MNIST dataset using TensorFlow. It initializes a session, runs a training loop with periodic evaluation, records training and test losses, saves the trained model, and visualizes results. The code includes loss computation, ... | def main():
loss = get_loss(X_ph)
solver = get_solver(loss)
saver = tf.train.Saver()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
train_loss = []
test_loss = []
for i in range(Total_Train_Step):
if i % (10*Train_Epoch_Step) == 0:
print("<<<<<<<<<... |
def get_Wake_Phase_loss(X):
# sample z from Q(z|x)
Z_mu, Z_var = encoder_network(X)
Z_sample, _ = get_sample_z(Z_mu, Z_var)
_, logits = dencoder_network(Z_sample)
# -E[log P(X|Z)] so we need to minimize the following term
E_loss = tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(targets=X,... | The code trains a model with two alternating phases—wake and sleep—using TensorFlow. It initializes solvers for each phase, iteratively updates model parameters with real data during the wake phase and generated samples during the sleep phase. It tracks training/test losses, evaluates periodically, saves the model, and... | def main():
# Get wake solver
wake_loss = get_Wake_Phase_loss(X_ph)
wake_solver = get_Wake_Phase_solver(wake_loss)
# Get sleep solver
sleep_loss = get_Sleep_Phase_loss(X_ph, Z_ph)
sleep_solver = get_Sleep_Phase_solver(sleep_loss)
saver = tf.train.Saver()
sess = tf.Session()
sess.r... |
def tree(label, branches=[]):
"""Construct a tree with the given label value and a list of branches."""
if change_abstraction.changed:
for branch in branches:
assert is_tree(branch), "branches must be trees"
return {"label": label, "branches": list(branches)}
else:
for br... | The function `copy_tree` creates a deep copy of a given tree structure. It recursively duplicates each node's label and all its branches, ensuring modifications to the original tree do not affect the copy. This is essential for testing, allowing isolated operations on the copied tree without altering the original. The ... | def copy_tree(t):
"""Returns a copy of t. Only for testing purposes.
>>> t = tree(5)
>>> copy = copy_tree(t)
>>> t = tree(6)
>>> print_tree(copy)
5
"""
return tree(label(t), [copy_tree(b) for b in branches(t)]) |
def is_leaf(tree):
"""Returns True if the given tree's list of branches is empty, and False
otherwise.
"""
return not branches(tree)
def tree(label, branches=[]):
"""Construct a tree with the given label value and a list of branches."""
if change_abstraction.changed:
for branch in branch... | The main task of the code is to recursively square the label of each node in a tree structure. If the input tree is a leaf, it returns a new tree with the squared label. For non-leaf nodes, it creates a new tree with the same structure but all labels squared, applying the same operation to each branch recursively. This... | def square_tree(t):
if is_leaf(t):
return tree(label(t) ** 2)
return tree(label(t) ** 2, [square_tree(b) for b in branches(t)]) |
def is_leaf(tree):
"""Returns True if the given tree's list of branches is empty, and False
otherwise.
"""
return not branches(tree)
def label(tree):
"""Return the label value of a tree."""
if change_abstraction.changed:
return tree["label"]
else:
return tree[0]
def tree(labe... | The function `prune_binary` recursively prunes a binary tree `t` by retaining only the branches that match sequences in `nums`. It checks if a leaf node's label exists in `nums`, returning it if so. For non-leaf nodes, it filters `nums` to sequences starting with the node's label, then recursively prunes each branch. V... | def prune_binary(t, nums):
if is_leaf(t):
if label(t) in nums:
return tree(label(t))
return None
next_valid_nums = [x[1:] for x in nums if x[0] == label(t)]
new_branches = []
for b in branches(t):
pruned_brach = prune_binary(b, next_valid_nums)
if pruned_brac... |
def parse_categories(path):
"""
Reads all the categories from categories.csv file and inserts them
into categories table in database specified by path.
:param path: The path to the database
:type path: str
"""
conn = _sqlite3.connect(db_path + path)
cursor = conn.cursor()
with ope... | The main task of the code is to insert all data for a given month into a specified database by calling three parsing functions: `parse_categories`, `parse_queries`, and `parse_ads`, each of which processes and inserts respective data types into the database identified by `db_name`.) | def fill_db(db_name):
"""
Inserts all the data for given month into the database specified by the db_name.
:param db_name: The name of the database
"""
parse_categories(db_name)
parse_queries(db_name)
parse_ads(db_name)
return |
def inhalfplane(pt, q):
"""Return True if point pt is in half-plane defined by q."""
signTail = computeAngleSign(pt.x(), pt.y(),
q.head().x(), q.head().y(),
q.tail().x(), q.tail().y())
return signTail >= 0
def aim (p, q):
"""Return true if ... | The code computes the intersection of two convex polygons, `p` and `q`, by iteratively checking edge intersections, tracking polygon boundaries, and determining which polygon's edges to advance. It constructs the resulting intersection polygon by adding intersection points and verifying containment cases (e.g., one pol... | def convexIntersect(p, q):
"""
Compute and return polygon resulting from the intersection of
two convext polygons, p and q.
"""
intersection = Polygon()
pn = p.numEdges()
qn = q.numEdges()
k = 1
inside = None # can't know inside until intersection
first = None ... |
def usage():
sys.stdout.write('Usage:\n')
sys.stdout.write('Solve pow: {} solve $challenge\n')
sys.stdout.write('Check pow: {} ask $difficulty\n')
sys.stdout.write(' $difficulty examples (for 1.6GHz CPU) in fast mode:\n')
sys.stdout.write(' 1337: 1 sec\n')
sys.stdout.write(' ... | The code implements a command-line tool for handling proof-of-work (PoW) challenges. It accepts commands 'ask' or 'solve'. For 'ask', it generates a challenge based on difficulty, prompts user input, and verifies the solution. For 'solve', it takes a challenge, computes its solution, verifies it, and outputs the result... | def main():
if len(sys.argv) != 3:
usage()
sys.exit(1)
cmd = sys.argv[1]
if cmd == 'ask':
difficulty = int(sys.argv[2])
if difficulty == 0:
sys.stdout.write("== proof-of-work: disabled ==\n")
sys.exit(0)
challenge = get_challenge(difficult... |
def _get_keys(self, number: int = 1) -> List[float]:
rows = self.connection.execute(f"SELECT idx FROM {self.table} ORDER BY idx LIMIT ?", (number,)).fetchall()
return [row[0] for row in rows]
def chunkify(iterable: Iterable, max_size: int) -> Iterator[List]:
"""Split an iterable into chunks of a max... | The main task of the code is to remove a specified number of items (default: 1) from a FIFO bucket by deleting corresponding database records, update the bucket's size, and return the count of removed items. It uses SQLite's batch deletion with parameterized queries to handle large datasets efficiently. | def get(self, number: int = 1) -> int:
"""Get items and remove them from the bucket in the FIFO fashion.
Return the number of items that have been removed.
"""
keys = [str(key) for key in self._get_keys(number)]
for chunk in chunkify(keys, SQLITE_MAX_VARIABLE_NUMBER):
... |
def player_best_match(self, player):
return self.matches[self.matches['id'] == self.best_match_id(player)].iloc[0]
def best_match_deliveries(self, player):
match_deliveries = self.deliveries[self.deliveries['id'] == self.best_match_id(player)]
return match_deliveries[match_deliveries['batsman'] ... | The code generates and displays a sorted DataFrame of key batting statistics (runs, balls faced, strike rate, fours, sixes) along with match context (city, season) for each player's best performance, ordered by highest runs scored. | def player_match_stats(self, players):
stats = []
for player in players:
best_match = self.player_best_match(player)
match_deliveries = self.best_match_deliveries(player)
row = [self.runs_scored(match_deliveries), self.balls_faced(match_deliveries), self.strike_rate... |
def ready(self):
return not (self._as_busy or (self._busy() == 1))
def hw_reset(self):
self._rst(1)
sleep_ms(200)
self._rst(0)
sleep_ms(200)
self._rst(1)
self.wait_until_ready()
def wait_until_ready(self):
sleep_ms(50)
while not self.ready():
... | This method updates a display by sending pixel data to a driver, handling orientation modes (landscape/portrait), refresh commands, and power-saving states (fast refresh, light sleep, deep sleep). It processes a byte array, applies inversion, sends commands for display refresh, and optionally enters sleep modes to redu... | def show(self, buf1=bytearray(1),
fast_refresh=False, # USELESS for this driver, doesn't work well at all
deepsleep_after_refresh=False,
lightsleep_while_waiting_for_refresh=False):
if not self.ready():
# Hardware reset to exit deep sleep mode
self... |
def time_print(text):
time.sleep(1)
print(text)
def day1_wr1():
time_print("'Alright, you're all set to use the weight room'")
time_print("You head over to the weight room\n")
print("1: Start lifting iron and pumping weights")
print("2: Head over to the treadmill and start running")
print("S... | The function `day1_gym()` presents a narrative-driven choice where the player selects between the weight room or pool, with a chance to find 2 MNY based on luck. It includes interaction with a character (Natalie), stat viewing, and handles invalid inputs by retrying the selection. The task revolves around branching gam... | def day1_gym():
chance = 0
time_print("You make your way over to the gym")
if random.randint(1,(10 - player.luck)) == 1 and chance == 0:
time_print("On your way to the gym, you find 2 MNY")
player.money += 2
time_print("How lucky!")
pass
time_print("When you enter the bui... |
def time_print(text):
time.sleep(1)
print(text)
def day1_5_1():
time_print("You decide to go to the library")
if random.randint(1,(10 - player.luck)) == 1:
time_print("On your way to the library, you find 2 MNY")
player.money += 2
time_print("How lucky!")
pass
time_pr... | The function presents a narrative crossroads, offering four free-time choices (library, gym, dorm, town) and a stats option. It processes user input to direct gameplay to specific branches or display stats, with invalid inputs restarting the menu. The main task is to facilitate player decision-making in a text-based ga... | def day1_5():
print()
time_print("You leave the building and come to a crossroads")
time_print("Not really, but you do have some free time.")
time_print("And with some free time, comes some 'free' choices\n")
print("1: Go to the library")
print("2: Go the the gym")
print("3: Go to your dorm ... |
def time_print(text):
time.sleep(1)
print(text)
def day1_5():
print()
time_print("You leave the building and come to a crossroads")
time_print("Not really, but you do have some free time.")
time_print("And with some free time, comes some 'free' choices\n")
print("1: Go to the library")
p... | The code simulates a shopping interaction where the player can purchase items like SAARMS pills, beer, or a scratch-off ticket, each affecting stats or money. The player uses Mny to buy items, which update their attributes (e.g., strength, alcohol) or trigger random events. The loop continues until the player exits, af... | def day1_sam_wares():
shopping = 1
while shopping == 1:
time_print("'Hurry up and pick somefink, yeah'")
print("1: A bottle of SAARMS (2 Mny)")
print("2: A can of 'Statty Lite' beer (2 Mny)")
print("3: A Shadey Sam scratch off (1 Mny)")
print("4: Nothing")
time_pr... |
def time_print(text):
time.sleep(1)
print(text)
def day1_5():
print()
time_print("You leave the building and come to a crossroads")
time_print("Not really, but you do have some free time.")
time_print("And with some free time, comes some 'free' choices\n")
print("1: Go to the library")
p... | The code presents a dialogue interaction with Stacy where the player chooses a response (1 or 2) to affect HP and relationship outcomes. If Stacy's HP is 15, the scene includes specific dialogue and consequences; otherwise, a slightly altered version unfolds. Both choices grant +5 HP, while choice 1 also increases Stac... | def day1_4_1_stacy():
time_print("You see that Stacy is sitting alone, so you go to sit next to her")
if Stacy.hp == 15:
time_print("As you sit down, she looks at you")
time_print("'Oh hi', she says")
time_print("'Thanks for lending me that money'\n")
print("1: 'You're Welcome'")... |
def retrieve_file_dict(_all_files, src_lang, tgt_lang):
"""
retrieve the filename form a nmt based naming files.
example:
input : gnome.en-ms.en
output : gnome
:param _all_files: the nmt bas named file in a list.
:param src_lang: the src_language short form.
:param tgt_lang: the... | The main task of the code is to accumulate and process multilingual dataset files into structured "dev", "test", and "train" datasets. It reads source and target language files from input directories, skips restricted files, validates file pairs, and writes aligned lines to output files while tracking line counts, skip... | def data_set_accumulation(params):
print("Arg values")
print(params)
print("")
all_files = os.listdir(params.dir)
all_files.sort(key=lambda x: x.lower())
dataset_line = {}
params.restrict = list(map(str, params.restrict.split()))
(file_dict,
output_file_name) = retrieve_file_dict(... |
def printBoard(board):
# print('-------------------------')
print(' | | ')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3] + ' ')
print(' | | ')
print('-------------------------')
print(' | | ')
print(' ' + board[... | This code implements a Tic-Tac-Toe game where a player and computer alternate turns. It initializes the board, checks for wins, handles player moves, and executes computer moves. The loop continues until a player or computer wins, or the board fills with no winner, resulting in a tie. The game prints updates after each... | def main():
print("Welcome to the game!") # printing the starting message
printBoard(board)
while not(isBoardFull(board)):
if not(IsWinner(board , 'O')):
playerMove()
printBoard(board) # printing the updated board
else:
print("Sorry you loose!")
... |
def _parse_kedro_pipeline(self) -> None:
"""Extract the Kedro pipeline from the project"""
metadata = bootstrap_project(self.project_path)
self.project_name = metadata.project_name
self.pipeline = pipelines.get("__default__")
def _set_ecr_repository(self) -> None:
"""Set the ECR... | The code initializes a construct by parsing a Kedro pipeline, configuring AWS ECR repositories and images, setting up an S3 data bucket, and converting the Kedro pipeline into an AWS Step Functions state machine to orchestrate data processing workflows. | def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
self._parse_kedro_pipeline()
self._set_ecr_repository()
self._set_ecr_image()
self._set_s3_data_bucket()
self._convert_kedro_pipeline_to_step_functions_state_machi... |
def getReadSearchOutput(self,read_tuple,SEQ,gen_loc,GEN_DEL_len):
read_id,read = read_tuple[0],read_tuple[1]
#print("fetching reach search output for read: {0}".format(read_id))
#st1 = time.clock()
#print("read",read)
read_results = self.searchPattern(read)
#end1 = time.clock()
#check if read pattern was ... | This function processes paired-end reads to search for genomic matches, applying strict matching rules if enabled. It skips invalid reads containing 'N', checks matches for both reads, enforces strict alignment (both reads must map to the same genome), and writes results to a CSV file. The output includes read identifi... | def performPairEndSearch(self,pairedReads,SEQ,gen_loc,GEN_DEL_len,readOut_file,debug = False,applyStrictMatching=False):
readOut_file = readOut_file + "_pairedEndReadSearch.csv"
print("performing paired end read search with outfile: {0}".format(readOut_file))
st1 = time.clock()
with open(readOut_file,"w") as f:... |
def tilda_mu(theta, alpha):
r"""
The normalized quantity
:math:`\tilde{\mu} = \alpha \mu(\theta)`
Parameters
----------
theta : `~numpy.ndarray`
Angle :math:`\theta`
alpha : float
Dimensionless fluid number :math:`\alpha`
"""
return alpha * mu(theta)
def mu(theta):
... | The function computes the $ h_{m\ell} $ basis function using spherical harmonics. It calculates a prefactor involving $ C_{11} $, drag ($ \omega_{\text{drag}} $), fluid number ($ \alpha $), and $ m $, then combines it with terms of $ \mu(\theta) $, $ H(l, \theta, \alpha) $, and trigonometric functions of $ \phi $. The ... | def h_ml(omega_drag, alpha, theta, phi, C_11, m=1, l=1):
r"""
The :math:`h_{m\ell}` basis function.
Parameters
----------
omega_drag : float
Dimensionless drag
alpha : float
Dimensionless fluid number
m : int
Spherical harmonic ``m`` index
l : int
Spheric... |
def tilda_mu(theta, alpha):
r"""
The normalized quantity
:math:`\tilde{\mu} = \alpha \mu(\theta)`
Parameters
----------
theta : `~numpy.ndarray`
Angle :math:`\theta`
alpha : float
Dimensionless fluid number :math:`\alpha`
"""
return alpha * mu(theta)
def mu(theta):
... | This function computes the $ h_{m\ell} $ basis function using spherical harmonics, combining parameters like drag ($ \omega_{\text{drag}} $), fluid number ($ \alpha $), and coordinates ($ \theta, \phi $) with exponential, trigonometric, and custom $ H $-function terms. It applies a prefactor involving $ C_{11} $, $ \om... | def h_ml(omega_drag, alpha, theta, phi, C_11, m=1, l=1):
r"""
The :math:`h_{m\ell}` basis function.
Parameters
----------
omega_drag : float
Dimensionless drag
alpha : float
Dimensionless fluid number
m : int
Spherical harmonic ``m`` index
l : int
Spheric... |
def h_ml_sum_theano(hotspot_offset, omega_drag, alpha,
theta2d, phi2d, C_11):
"""
Cythonized implementation of the quadruple loop over: theta's, phi's,
l's and m's to compute the h_ml_sum term
"""
phase_offset = half * pi
hml_sum = h_ml(omega_drag, alpha,
... | The function `thermal_phase_curve` computes the thermal phase curve fluxes and temperature map of an exoplanet as a function of orbital phase angle `xi`. It integrates blackbody radiation over the visible hemisphere, accounting for hotspot offset, atmospheric drag, fluid dynamics, and Bond albedo. The result includes s... | def thermal_phase_curve(xi, hotspot_offset, omega_drag,
alpha, C_11, T_s, a_rs, rp_a, A_B,
theta2d, phi2d, filt_wavelength,
filt_transmittance, f):
r"""
Compute the phase curve evaluated at phases ``xi``.
.. warning::
Assumes ... |
def dir(self, create=True):
result = os.path.join(FOLDER, self.day)
if create and not os.path.exists(result):
os.mkdir(result)
return result
def article(self, i):
path = self.path("article", i)
if not os.path.exists(path):
self.parse()
assert o... | This function downloads input data, either an example or regular input, based on the 'example' flag. It checks if the file exists, and if not, fetches it from an article's HTML (for examples) or a URL endpoint ('/input'). For examples, it locates a specific <pre> tag containing "example" text, saves it, and returns the... | def download_input(self, example=False):
filename = "j" if example else "i"
save_path = os.path.join(self.dir(), filename)
if os.path.exists(save_path):
return open(save_path, "r").read()
if example:
article = self.article(1)
assert "example" in str(a... |
def article(self, i):
path = self.path("article", i)
if not os.path.exists(path):
self.parse()
assert os.path.exists(path), path
return bs(open(path, "rb").read(), features="lxml").article
def download_input(self, example=False):
filename = "j" if example else "i"... | The code extracts answers from HTML articles by parsing specific tags (code/em) or list items, returning matched text. If 'example' is True, it searches for example inputs in lists; otherwise, it reads preprocessed answers from files, ensuring they exist via parsing. | def answer(self, i, example=False):
if example:
article = self.article(i)
last = None
for par in article.find_all("p", recursive=False):
for part in par.find_all(["code", "em"], recursive=False):
last = part.em or part.code or last
... |
def change_decimal(function):
@functools.wraps(function)
def _change_decimal(*args, **kwargs):
for k, v in list(kwargs.items()):
if isinstance(v, str):
kwargs[k] = v.replace('.', constants.DECIMAL_SEPARATOR)
return function(*args, **kwargs)
return _change_decima... | The main task of the code is to process a unit conversion query by cleaning input data, retrieving conversion parameters, and yielding formatted results. It iterates through unit conversions, skips blacklisted units, and formats outputs using either unit-based or numerical formatting based on input validity. The functi... | def main(units: Units, query: str, create_item):
create_item = change_decimal(create_item)
query = clean_query(query)
left = get_units_left()
max_magnitude = get_max_magnitude()
for from_, quantity, to in units.convert(query):
if to and to.is_blacklisted(): # pragma: no cover
c... |
def generate_universe_map(routes: List[Route]) -> UniverseMap:
universe_map = defaultdict(list)
for route in routes:
universe_map[route.destination].append(route)
return universe_map
def generate_bounty_hunters_map(bounty_hunters: BountyHunters) -> BountyHuntersMap:
bounty_hunters_map = defaultd... | The function determines the optimal escape route for the Millennium Falcon by generating possible plans based on its autonomy and the Empire's countdown, then selecting the best plan that avoids bounty hunters using maps of the universe and bounty hunter locations. | def give_me_the_odds(
millennium_falcon: MillenniumFalcon,
empire: Empire,
routes: List[Route],
):
universe_map = generate_universe_map(routes)
bounty_hunters_map = generate_bounty_hunters_map(empire.bounty_hunters)
plans = generate_plans(
start=millennium_falcon.departure,
end=... |
def win_probabilities(dice: tuple, board: tuple):
"""
Calculate the probability of each camel winning
"""
first_place = np.zeros(len(WIN_CAMELS), dtype=int)
second_place = np.zeros(len(WIN_CAMELS), dtype=int)
total_landings = np.zeros(N_TILES, dtype=int)
rounds = get_rounds(dice)
for rou... | The function `optimal_move` calculates the best strategic action for a player by evaluating four options: placing bets, selecting allies, boosting tiles, or rolling dice. It uses win probabilities from the board and dice state to score each move, then ranks and prints the top choices with their scores, prioritizing hig... | def optimal_move(self, player_id: int):
"""
Get the optimal move for player_id
Moves available:
1. Choose available bet
2. Choose ally
3. Place tile
4. Roll dice (+1)
# TODO
5. Bet on overall winner
6. Bet on overall loser
"""
... |
def check_user_input(self, curr_player: int, move: str) -> tuple:
"""Check user input for formatting and validity. Return tuple of move or None if invalid"""
if len(move) == 0:
return None
move = move.lower().strip().split(" ")
# help
if move[0] == "help":
... | The main task of the code is to parse and execute a player's move command in a board game, updating game state based on the input. It handles actions like placing bets, forming alliances, applying boosts, rolling dice, and concluding rounds, returning True if the move is valid and False otherwise, while managing game p... | def parse_move(self, curr_player: int, move: list) -> bool:
"""Parse move from player. Return 0 if no valid move was made, 1 otherwise"""
cmd = self.check_user_input(curr_player, move)
if cmd is None:
return False
# optimal
if cmd == "optimal":
self.optim... |
def raw(self, msg):
self.sock.send(bytes(msg + '\r\n', 'utf-8'))
def event_connect(self, name, daemon):
debug(f'Connected to {0} ({1}) running ({2}) with {3} users & {4} channels'.format(self.data['network'], self.data['server'],self.data['ircd'], self.data['users'], self.data['channels']))
... | The function `handle_events` processes incoming IRC server data by parsing responses, updating internal state (e.g., server info, user counts, channels), and triggering events. It handles PING requests, extracts metadata (network, server details), tracks channel listings, manages nickname conflicts, and logs errors lik... | def handle_events(self, data):
args = data.split()
if data.startswith('ERROR :Closing Link:'):
raise Exception('Connection has closed.')
elif args[0] == 'PING':
self.raw('PONG ' + args[1][1:])
elif args[1] == '004' and len(args) >= 5: # RPL_MYINFO
... |
def handle_events(self, data):
args = data.split()
if data.startswith('ERROR :Closing Link:'):
raise Exception('Connection has closed.')
elif args[0] == 'PING':
self.raw('PONG ' + args[1][1:])
elif args[1] == '004' and len(args) >= 5: # RPL_MYINFO
... | The main task of the code is to continuously listen for incoming data from a socket, decode it, split into lines, filter valid lines with at least two words, and process them via `handle_events`. It handles Unicode errors gracefully, logs unexpected exceptions, and triggers a disconnection event upon termination. | def listen(self):
while True:
try:
data = self.sock.recv(1024).decode('utf-8')
for line in (line for line in data.split('\r\n') if len(line.split()) >= 2):
self.handle_events(line)
except (UnicodeDecodeError,Unicode... |
def create_socket(self):
if settings.proxy:
proxies = settings.proxy
for proxy in proxies:
proxy_server, proxy_port = proxy.split(':')
self.sock = socks.socksocket()
self.sock.setproxy(socks.PROXY_TYPE_SOCKS5, proxy_server, int(... | The code establishes an IRC connection by creating a socket, connecting to a server/port, sending authentication/identity commands, and handling connection errors by switching ports if necessary, then initiating listening for incoming data. | def connect(self):
try:
self.create_socket()
self.sock.connect((self.server, self.port))
self.raw('USER {rnd()} 0 * :{rnd()}')
self.raw('NICK ' + rnd())
except socket.error:
if self.port == 6697:
self.port... |
def are_coinciding_candidates(request):
new_candidates_name = request.POST['name']
candidates_list = Candidate.objects.order_by('id')
for candidate in candidates_list[:len(candidates_list) - 1]:
if candidate.name == new_candidates_name:
return True
else:
return False
def swi... | The code checks if a candidate already exists in the request. If so, it updates the user's status to 'Application Draft' and notifies them of the existing candidate. Otherwise, it processes the form to change the group associated with the request. | def check_candidate(request, form):
if are_coinciding_candidates(request):
switch_users_candidate_status(request.user, 'Application Draft')
return notice_participate_candidate_already_exists(request)
else:
return change_group_by_button(request, form) |
def standard_context(request):
context = {
'username': request.user.username,
}
if request.user.is_superuser:
context['role'] = 'Admin'
else:
context['role'] = request.user.ROLE_CHOICES[request.user.role - 1][1]
if is_user_voted(request):
context['voted'] = True
... | This Django view creates a candidate application form, assigns the user to the 'Application Process' group with candidate role, handles form submission by saving candidate data, and redirects based on form input. It renders the 'participate.html' template with the form, processing POST requests to validate and store ca... | def create_participate_form(request):
form = CreateCandidateForm()
new_group = Group.objects.get(name='Application Process')
request.user.groups.add(new_group)
request.user.role = User.CANDIDATE
request.user.save()
context = standard_context(request)
context['form'] = form
if request.... |
def standard_context(request):
context = {
'username': request.user.username,
}
if request.user.is_superuser:
context['role'] = 'Admin'
else:
context['role'] = request.user.ROLE_CHOICES[request.user.role - 1][1]
if is_user_voted(request):
context['voted'] = True
... | This Django view function allows a user to update their candidate participation form. It checks if the current user matches the author, fetches the candidate data, and displays an edit form. If the user is a moderator, additional context is added. On POST, it validates and saves form changes, then redirects to update g... | def update_participate_form(request, author):
context = standard_context(request)
# It checks if another user tries to change data of a foreign user
if author != request.user.username:
return redirect('poll:notice-access-is-forbidden')
candidate = get_object_or_404(Candidate, author=author)
... |
def updateStarImage(self, pm):
# there is no need to initialize the star image to 0's because the radius is always 1
centerRow = int(pm.starImage.shape[0]/2)
centerCol = int(pm.starImage.shape[1]/2)
maxBright = 1.
if pm.planBright > maxBright: maxBright = pm.planBright
if... | The main task of the code is to reset or update the visual elements and parameters of an astronomical simulation interface. It updates star/planet/system images using data from `pm`, refreshes runtime information, resets transit curves, and adjusts angle ranges, ensuring the canvas reflects the latest simulation state. | def resetCanvas2(self):
self.updateStarImage(pm)
self.updatePlanetImage(pm)
self.updateSystemImage(pm, 0.)
self.ims.set_data(pm.systemImage)
self.UpdateRunInfo()
self.resetTransitCurve()
self.setAngleRange() |
def update_spawner(self, dt):
self.spawning_counter += dt
if self.spawning_counter >= self.enemy_spawning_delay:
self.enemy_spawning_delay *= BIRD_SPAWNING_DELAY_DECREASE
self.difficulty += DIFFICULTY_INCREASE
modifier = 100 + 10*self.difficulty + self.difficulty**2 +... | This method updates game objects by calling their update method, checks if any objects are out-of-bounds (left/right or top/bottom relative to the ship's position and speed), adds them to a garbage list, performs collision checks, then removes and deletes the out-of-bound objects to maintain game state integrity. | def update(self, dt):
self.update_spawner(dt)
# self.ship.update(dt)
garbage = []
for o in self.objects:
o.update(dt)
if (o.pos[0] < -0.1 * WINDOW_HEIGHT) or (o.pos[0] > 1.1 * WINDOW_WIDTH):
garbage.append(o)
elif (o.pos[1] < self.ship.... |
def find_substring(root, prefix):
node = root
for c in prefix:
if c not in node.sons:
return None, None, None
node = node.sons[c]
return node, node.sources, len(prefix)*2
def find_match_replace(root, prefix, k):
result = []
for i in range(len(prefix), 0, -1):
resu... | The main task of the code is to find and return a list of matching results based on a given prefix by combining exact matches, replacement, addition, and deletion operations. It prioritizes exact matches first, then generates alternative matches using three modification types, sorts all results by scores in descending ... | def find_match(root, prefix):
result = []
_, sources, scores = find_substring(root, prefix)
k = 5
if sources:
result.append((sources, scores))
k -= len(sources)
if k <= 0 :
return result, len(prefix)
result.extend(find_match_replace(root, prefix, k))
result.... |
def cod_payment_method(user_contact):
return generate_bill(user_contact, payment_meth='COD')
def online_payment_method(user_contact):
return generate_bill(user_contact, payment_meth='Online Payment')
def complaint_list_message(from_num):
with sql.connect('/home/Harsh159/chat_dir/test_database/user_data.d... | This function routes user interactions based on message IDs by dispatching to specific functions like payment methods, complaint lists, or main menus, using the provided contact number as a parameter. | def button_message(id_message, from_num=None):
if id_message == "201":
return cod_payment_method(user_contact=from_num)
elif id_message == "301":
return online_payment_method(user_contact=from_num)
elif id_message == "359":
return complaint_list_message(from_num)
elif id_mess... |
def all_products_message(user_contact):
with sql.connect('/home/Harsh159/chat_dir/test_database/user_data.db') as user:
cursor = user.cursor()
cursor.execute('SELECT product_id FROM main_product_list WHERE \
product_categ_id=?', (2,))
caps_data = cursor.fetchall(... | The function `interactive_message` routes user input based on the `message` parameter by calling corresponding handler functions like `all_products_message`, `complaint_list_message`, etc., passing `from_num` as context. It acts as a dispatcher to manage different user interactions, such as shopping, payments, FAQs, or... | def interactive_message(message, from_num):
if message == "Shop Now":
return all_products_message(from_num)
elif message == "Contact Saubhagyam":
return complaint_list_message(from_num)
elif message == "Main Menu":
return main_menu(from_num)
elif message == "FAQ":
ret... |
def cod_payment_method(user_contact):
return generate_bill(user_contact, payment_meth='COD')
def online_payment_method(user_contact):
return generate_bill(user_contact, payment_meth='Online Payment')
def complaint_list_message(from_num):
with sql.connect("/home/saubhagyam/Downloads/my_new_project/test_da... | The main task of the code is to route users to specific functions based on the `id_message` input. It checks the value of `id_message` and returns corresponding functions like payment methods, complaint lists, or a main menu, using `from_num` or `wa_num` as parameters to handle user interactions in a messaging system. | def button_message(id_message, from_num=None):
if id_message == "201":
return cod_payment_method(user_contact=from_num)
elif id_message == "301":
return online_payment_method(user_contact=from_num)
elif id_message == "359":
return complaint_list_message(from_num)
elif id_mess... |
def send_interactive_message(user_contact, message_type, text_body, header=None, header_text=None, file_name=None, link=None, button_messages=None, list_data=None):
data = {
"messaging_product": "whatsapp",
"to": user_contact,
"recipient_type": "individual",
"type": "interactive",
... | The function `interactive_message` handles user interactions by routing messages to specific actions. If the message is "Shop Now," it sends a product list; other commands like "Contact Saubhagyam," "Main Menu," "FAQ," "Make Payment," "COD," "Online Payment," or "Customer Care" trigger corresponding functions to manage... | def interactive_message(message, from_num):
if message == "Shop Now":
new_one = [(101, 'All Products 1', 'In this one we have more products.'), \
(102, 'All Products 2', 'In this one we have new prodcuts.'), \
(103, 'All Products 3', 'In this one we will have more new ... |
def message_data(user_name, message, user_id, user_contact_num):
with sql.connect("/home/Harsh159/chat_dir/user_data.db") as user:
cursor = user.cursor()
cursor.execute("INSERT INTO message_data (user_name, message, user_contact_num, user_id) VALUES (?, ?, ?, ?)",
(user_name, message, user... | The function processes WhatsApp messages by extracting user data, handling interactive (button/list) replies, managing order details via database insertion, and responding to text messages with registration/welcome logic or prompts. It routes interactions based on message type, updates user data, and triggers specific ... | def handle_whatsapp_message(body):
message = body["entry"][0]["changes"][0]["value"]["messages"][0]
user_name = body['entry'][0]['changes'][0]['value']['contacts'][0]['profile']['name']
user_id = body['entry'][0]['id']
user_contact_num = body['entry'][0]['changes'][0]['value']['messages'][0]['from']
... |
def message_data(user_name, message, user_id, time_of_message, user_contact_num, order_id=None, delivery_status=None):
with sql.connect("/home/saubhagyam/Downloads/my_new_project/user_data.db") as user:
cursor = user.cursor()
if delivery_status:
cursor.execute("INSERT INTO message_dat... | The code processes incoming WhatsApp messages by extracting user data (name, ID, contact, time) and message type. It handles interactive messages (list/button replies), orders, and text queries. For buttons, it triggers specific actions (e.g., "Shop Now," "FAQ") via `interactive_message`. For "nfm_reply," it processes ... | def handle_whatsapp_message(body):
message = body["entry"][0]["changes"][0]["value"]["messages"][0]
user_name = body['entry'][0]['changes'][0]['value']['contacts'][0]['profile']['name']
user_id = body['entry'][0]['id']
user_contact_num = body['entry'][0]['changes'][0]['value']['messages'][0]['from']
... |
def apiDataRequest(firstCoin="BTC",secondCoin=False,begin=1525132800000,end=1527811199000): #defaults to may 2018
apiCall = {}
apiCall['inputs'] = True
apiCall['oneCoin'] = True
apiCall['firstCoin'] = None
validFirstCoin = validateCoinTag(firstCoin)
validSecondCoin = validateCoinTag(secondCoin)
... | The function generates a Bokeh plot visualizing cryptocurrency data by fetching API data, organizing it, and creating either a coin comparison plot (if two coins are specified) or a time-series plot (if one coin is specified). It returns an HttpResponse with the rendered Bokeh plot embedded in a template. | def bokeh(request,firstCoin,secondCoin=False,begin = False,end = False):
myAPICall = apiDataRequest(firstCoin = firstCoin,secondCoin = secondCoin, begin=begin,end=end)
myPlot = coinDataOrganize(myAPICall)
if(not myAPICall['oneCoin']):
myDataframe = pandasCoinDataFrame(myPlot)
myBokeh = boke... |
def biggestloser():
"""Returns: stock with the the biggest losses in a given day and
its stock price with format: 'TICKER': 'PRICE'."""
day_losers = si.get_day_losers()
output = str(day_losers.at[0, 'Symbol']) + ': ' + \
str(round(si.get_live_price(day_losers.at[0, 'Symbol']), ROUND_NUMBER... | The code defines a function to parse command-line arguments for displaying stock and cryptocurrency data. It uses argparse to handle flags like --biggestloser, --topcrypto, and custom tickers, then concatenates retrieved data into a formatted string. If no valid arguments are provided, it prompts the user to select a s... | def parse_arguments():
"""Adds arguments from ArgParse and parses them to handle arguments"""
parser = argparse.ArgumentParser(description='Displays stock prices for polybar.',
epilog='Output will always be in the format of: \
Biggest Lo... |
def _possible_combinations(self):
pairs = []
for i in range(self._ndocs):
for j in range(i+1, self._ndocs):
pair = set([i, j])
pairs.append(pair)
return pairs
def _distance(self, i, j):
if self._matrix is None:
self._initialize_disc... | The code generates and returns the top n best combinations of document index pairs from a list, ranked by their calculated distances, ensuring exclusivity among selected pairs. | def get_combinations(self, n=1):
"""Return best combinations as index pairs
Args:
n (int, optional): Number of combinations needed
Returns:
list: List of integer tuples representing indexes of documents
in the `docs` list
"""
... |
def mesh_adaptive_pen(f, g, c, x0, n, count, restart_var = 2):
"""
Uses a Mesh Adaptive Direct Search (MADS) to find optimum.
Referenced Algorithm 8.3 in text
Includes count and quadratic penalties.
"""
x_his = [x0]
x = x0
#if not check_feas(c,x):
#x = random_restart(f, g, c, x0,... | The code implements a customizable optimization algorithm that selects a strategy based on the problem type (`prob`). It uses methods like MADS with penalties, particle swarm, Nesterov momentum, Hooke-Jeeves, and Cross Entropy to minimize a function `f` under constraints `c`, starting from `x0`. The algorithm balances ... | def optimize(f, g, c, x0, n, count, prob):
"""
Args:
f (function): Function to be optimized
g (function): Gradient function for `f`
c (function): Function evaluating constraints
x0 (np.array): Initial position to start from
n (int): Number of evaluations allowed. Remember... |
def pickLeg3(servo1, servo2, servo3):
for i in range(90, 40, -1):
servo_Angle(i, servo1)
servo_Angle(i, servo2)
servo_Angle(i, servo3)
utime.sleep_ms(int(speed))
def servo_Angle(angle, s):
if angle < 0:
angle = 0
if angle > 180:
angle = 180
s.goto(round(se... | The code controls robotic leg movements based on the 'cmd' parameter. For 'right', it rotates right-side legs by adjusting servo angles (90° to 60° and back), then repeats for left-side legs. For 'left', it does the reverse: rotates left-side legs (90° to 120° and back). The function uses `pickLeg3`/`putLeg3` to manage... | def rotate(cmd):
# Rotate one leg from left hand side and other two from right hand side.
# Then do the vice versa.
# We have 90 degrees at nominal position.
# Rotate 20 degrees.
# Left leg
# Pick Up...
if str(cmd) == 'right':
############# Right moving...
#1, 8,,,,,4, 1... |
def pickLeg3(servo1, servo2, servo3):
for i in range(90, 40, -1):
servo_Angle(i, servo1)
servo_Angle(i, servo2)
servo_Angle(i, servo3)
utime.sleep_ms(int(speed))
def servo_Angle(angle, s):
if angle < 0:
angle = 0
if angle > 180:
angle = 180
s.goto(round(se... | The code controls a robotic movement by adjusting multiple servos' angles in two phases: first, it moves forward by sequentially changing the angles of specified servos (s5, s9, s1, etc.) over a decreasing range, then returns to the original position by reversing the angles over an increasing range. Functions `pickLeg3... | def front():
############# Forward moving...
# Go forward
pickLeg3(s5, s9, s1)
for i in range(90, 59, -1):
servo_Angle(i, s6)
servo_Angle(120-(90-i), s12) # -> bring from 130 to 90
servo_Angle(90+(90-i), s2)
servo_Angle(60+(90-i), s8) # -> bring from 50 to 90
... |
def template():
html_template = """
<!DOCTYPE html>
<html>
<body>
<h1>Spidey Panel</h1>
<button id="startButton" onclick="sendCommand('start')">Start</button>
<button id="leftButton" onclick="sendCommand('left')">Left</button>
<button id="rightButton" onclick="sendCommand('right'... | The code sets up a Wi-Fi access point and an HTTP server to control a device's movement via web commands. It processes incoming HTTP requests to handle directional commands (left/right/start/stop), direction adjustments (front/stop), and speed control. Global variables track command, direction, and speed values, which ... | def main():
global command, check
global direction_value
global speed_value
gc.collect()
# connection password and ssid.
ssid = 'Spidey'
password = '12345678'
# Creating Soft Access Point
ap = network.WLAN(network.AP_IF)
ap.config(essid=ssid, password=passw... |
def loadSets(loadFile, selectedInstance):
# os.chdir("../../ass1_data/part2/golf")
# print(os.listdir(os.curdir))
with open(loadFile) as file:
line = file.readline().replace("\n", "")
if not len(attributes):
attributes.extend(line.split(" "))
attributes.pop(0)
... | This function performs 10-fold cross-validation on a dataset. It iteratively loads training and test subsets, builds a decision tree model, evaluates its accuracy on the test set, and stores results. After 10 iterations, it calculates and prints the average accuracy across all folds to assess the model's performance. | def doTenFold():
tenFoldList = []
for i in range(10):
attributes.clear()
trainingInstances.clear()
testInstances.clear()
decisions.clear()
loadSets("hepatitis-training-run-"+str(i), trainingInstances)
loadSets("hepatitis-test-run-"+str(i), testInstances)
r... |
def doTenFold():
tenFoldList = []
for i in range(10):
attributes.clear()
trainingInstances.clear()
testInstances.clear()
decisions.clear()
loadSets("hepatitis-training-run-"+str(i), trainingInstances)
loadSets("hepatitis-test-run-"+str(i), testInstances)
r... | The main task of the code is to perform decision tree classification on a dataset. It loads training and test instances, constructs a decision tree, evaluates baseline accuracy, and tests the tree's performance. The code handles both 10-fold cross-validation (if no arguments are provided) and manual testing with specif... | def main():
os.chdir("../../ass1_data/part2")
if(len(sys.argv)==1):
doTenFold()
else:
loadSets(sys.argv[1], trainingInstances)
loadSets(sys.argv[2], testInstances)
root = buildTree(trainingInstances, attributes)
displayTree(root, "")
print("Baseline: "+str(fin... |
def load_brain(self, filename: str) -> None:
"""Attempt to load a previously-saved 'brain' from the
specified filename.
NOTE: the current contents of the 'brain' will be discarded!
"""
if self._verbose_mode:
print("Loading brain from %s..." % filename,)
start... | The `bootstrap` method initializes a Bot by loading a brain file (if provided), AIML files (from `learn`), and executing commands. It handles file paths, converts strings to lists, loads resources, and triggers responses. If `brain_file` exists, it loads the brain; otherwise, defaults to a predefined path. Commands are... | def bootstrap(self, brain_file: str = None, learn=None, commands=None) -> None:
"""Prepare a Bot object for use.
If a brainFile argument is provided, the Bot attempts to
load the brain at the specified filename.
If learnFiles is provided, the Bot attempts to load the
specified ... |
def add_session(self, session_id: str) -> None:
"""Create a new session with the specified ID string."""
# Create the session.
if session_id in self._sessions:
session_data = self._sessions[session_id]
else:
session_data = self._sessions[session_id] = {}
#... | The code processes input text to generate a bot's response by splitting the input into sentences, maintaining conversation history for each session, and concatenating individual responses. It ensures thread safety using a lock, manages session history limits, and returns the combined response while handling concurrency... | def respond(self, text: str, session_id: str = None) -> str:
"""Return the Bot's response to the input string."""
if not text:
return ""
if session_id is None:
session_id = DEFAULT_SESSION_ID
# prevent other threads from stomping all over us.
self._respo... |
def add_session(self, session_id: str) -> None:
"""Create a new session with the specified ID string."""
# Create the session.
if session_id in self._sessions:
session_data = self._sessions[session_id]
else:
session_data = self._sessions[session_id] = {}
#... | This code initializes a chatbot's core components, including the brain (PatternManager), session management, bot predicates (like name), word substitutors for natural language processing, and thread safety mechanisms. It sets default values, prepares session handling, and triggers the bootstrap process to load the brai... | def __init__(self, brain_file: str = None, learn=None, commands=None, verbose: bool = True) -> None:
self._verbose_mode = verbose
self._brain = PatternManager()
self._respond_lock = threading.RLock()
self._text_encoding = DEFAULT_ENCODING
# set up the sessions
se... |
def tobool(val):
return 'true' if val else 'false'
def text_response(self, data='OK', code=200):
if data is None:
data = 'Bad Request'
code = 400
data = (str(data).rstrip() + '\n').encode()
self.send_response(code)
self.send_header('Cont... | This code handles HTTP GET requests by routing to different functions based on the URL path, retrieving radio-related data such as sample rate, frequency, gain, and settings, and managing streaming or status checks. It returns formatted responses or 404 errors for invalid paths. | def do_GET(self):
path = self.path.split('/')[1:]
if self.path == '/quit':
data = tobool(payload['quit'].is_set())
self.text_response(data)
elif self.path == '/rate':
self.text_response(get_sample_rate(radio))
elif self.path ==... |
def radius_ij(person_i_radius, person_j_radius):
return person_i_radius + person_j_radius
def distance_ij(person_i_x, person_i_y, person_j_x, person_j_y):
return math.sqrt((person_i_x - person_j_x) ** 2 + (person_i_y - person_j_y) ** 2)
def normal_ij(person_i_x, person_i_y, person_j_x, person_j_y):
distance... | This function calculates the repulsive force components (f_x, f_y) between two agents (i and j) based on their positions, radii, and velocities. It combines exponential repulsion, pressure resistance, and direction change terms, using normal and tangent vectors. The force depends on whether the agents overlap (r - d > ... | def f_ij(person_i_x, person_i_y, person_j_x, person_j_y, person_i_r, person_j_r, person_i_v_x, person_i_v_y, person_j_v_x, person_j_v_y):
r = radius_ij(person_i_r, person_j_r)
d = distance_ij(person_i_x, person_i_y, person_j_x, person_j_y)
A = DEFAULT_REPULSION_RATE_A
B = DEFAULT_REPULSION_RATE_B
n... |
def Create_Sequence(hand, root):
"""
Creates list of sequence objects of all possible trains that can be created from hand based off root domino,
Then selects the sequences with the longest length/total_value,
Returns None if no matches are possible,
"""
#set up, creating sequence object, f... | The function determines the current player's move in a game using a basic strategy. It checks for playable sequences from the player's tiles, identifies spare tiles if no sequence exists, tracks interruptions, and decides to either interrupt, play a sequence, or play the highest spare tile. It returns whether a gate is... | def Make_Move(players, trains, current_player):
"""
Makes move using basic strategy,
Returns a bool for closed_gate and which train was played on
"""
Gate_Closed = False
sequence = Create_Sequence(players[current_player].tiles, trains[current_player].store[-1])
hand = players[current_player]... |
def _gaussian_noise(self, var, mean=0, std=0.01):
noise = np.random.normal(mean, std, var.shape)
return var+noise
def get_obs(self):
obs = {}
obs['mlp'] = self._get_mlp_obs()
if self.grasp_attrs_dict['policy'] == 'mlp':
return obs
elif self.grasp_attrs_dict['p... | This code processes an action in a reinforcement learning environment by applying noise, clipping, and scaling. It simulates the action, computes observations, and evaluates rewards based on object-hand proximity (distance) and contact status (grasp success). Rewards are calculated for proximity, contact alignment, and... | def step(self, a):
if self.grasp_attrs_dict['noise']: # actuation noise
a = self._gaussian_noise(a, mean=0, std=0.01)
a = np.clip(a, -1.0, 1.0)
try:
a = self.act_mid + a * self.act_rng # mean center and scale
except:
a = a # only for the initializat... |
def get_multicontact_verts(self, verbose=False):
body_xpos = self.data.body_xpos[self.obj_bid]
body_xquat = self.data.body_xquat[self.obj_bid].ravel()
body_xquat = qt.as_quat_array(body_xquat)
contact_verts = []
for geom_mesh_idx, contact_idx in zip(self.fps_geom_indices, self.fp... | The code debugs a simulation by printing object positions, orientations, and mesh data, visualizing contact points and hand positions with markers, and calculating chamfer distances between contact vertices and hand positions for analysis. It periodically resets the model, renders the scene, and outputs metrics like ve... | def debug(self):
obj_pos = self.data.body_xpos[self.obj_bid].ravel()
obj_com = self.data.subtree_com[self.obj_bid].ravel()
body_xpos = self.data.body_xpos[self.obj_bid]
body_xquat = self.data.body_xquat[self.obj_bid].ravel()
palm_pos = self.data.site_xpos[self.S_grasp_sid].ravel(... |
def remove_nas(
df,
cols_to_remove_nas=[
"Issue time",
"Issue Date",
"Latitude",
"Longitude",
"Location",
],
):
"""
Drops na rows for the columns cols_to_remove_nas
"""
for col in cols_to_remove_nas:
df = df.loc[df[col].isna() == False]
... | This function preprocesses a dataset by removing rows with missing values, converting and imputing coordinates, merging with fixed location data, dropping duplicates, renaming columns, filtering invalid entries, and handling missing values to prepare the data for analysis or modeling. | def full_preprocessing(raw_df, verbose=True):
if verbose:
logging.info("Removing the ones with NA-vals in important columns")
df = remove_nas(raw_df)
if verbose:
logging.info("Converting coordinates")
df = convert_coordinates(df)
df = df.merge(fix_locations(df), on="Ticket number")
... |
def fill_nas(df):
df = df.where(pd.notnull(df), None)
return df
def full_preprocessing(raw_df, verbose=True):
if verbose:
logging.info("Removing the ones with NA-vals in important columns")
df = remove_nas(raw_df)
if verbose:
logging.info("Converting coordinates")
df = convert_co... | The main task of the code is to preprocess parking ticket data in batches by renaming columns, handling missing values, and inserting the transformed data into a PostgreSQL database table. It reads raw data in chunks, applies preprocessing, maps column names, and performs batch inserts using psycopg2, ensuring efficien... | def batch_preprocessing(conn=None):
"""
Preprocesses all the data in batches.
"""
colmapping = {
"TICKETNUMBER".lower(): "Ticket number",
"ISSUEDATE".lower(): "Issue Date",
"ISSUETIME".lower(): "Issue time",
"METERID".lower(): "Meter Id",
"MARKEDTIME".lower():... |
def _check_api_info(self):
try:
if not self.API_URL:
for url in self.API_URLS:
try:
response = self._handle_api_error(requests.get('{}info'.format(url))).json()
self.API_URL = url
break
... | The main task of the code is to initiate and monitor an assessment process via API, handling status checks, caching, and result retrieval. It triggers assessments, polls for completion, manages errors, and returns results based on parameters like 'return_all' and 'detail', while supporting resume functionality and para... | def analyze(self, host=None, publish='off', start_new='on',
from_cache='off', max_age=5, return_all='done',
ignore_mismatch='on', resume=False, detail=False):
"""Start the assessment process.
This is basically a wrapper function
for all the API communication whic... |
def get_file_size(file):
file.seek(0, os.SEEK_END)
file_size = file.tell()
file.seek(0)
return file_size
def displayPDF(file):
with open(file, "rb") as f:
base64_pdf = base64.b64encode(f.read()).decode('utf-8')
pdf_display = F'<iframe src="data:application/pdf;base64,{base64_pdf}" width... | The code creates a Streamlit web app with a dark-themed UI, allowing users to upload PDF documents. It processes the uploaded files to generate embeddings, displays a chat interface for querying the document content, and animates the app's title with a gradient and bounce effect. The app handles file storage, embedding... | def main():
st.markdown(
"""
<style>
body {
background-color: #262626;
color: #fff;
}
</style>
""",
unsafe_allow_html=True,
)
gradient_style = (
"background: linear-gradient(to right, #D8B5FF , #1EAE98);"
"text-a... |
def _get_spine_speed(self, vehicle_pos, vehicle_dir, spine_seg):
spine_beg = spine_seg.coords[0]
future_pos = Point(vehicle_pos.x + vehicle_dir[0],
vehicle_pos.y + vehicle_dir[1],
vehicle_pos.z + vehicle_dir[2])
spine_end = self.spine.project... | The code constructs an observation vector for a vehicle by aggregating sensor data, track geometry parameters, and vehicle dynamics. It calculates distances to track edges, vehicle angles, spine speed, and projects the vehicle's position onto the track. The observation includes electrical sensor values (RPM, throttle, ... | def _make_observation(self, sensors):
electrics = sensors['electrics']['values']
vehicle_dir = self.vehicle.state['dir']
vehicle_pos = self.vehicle.state['pos']
vehicle_pos = Point(*vehicle_pos)
spine_beg = self.spine.project(vehicle_pos)
spine_end = spine_beg
s... |
def _make_commands(self, action):
brake = 0
throttle = action[1]
steering = action[0]
if throttle < 0:
brake = -throttle
throttle = 0
self.vehicle.control(steering=steering, throttle=throttle, brake=brake)
def advance(self):
self.bng.step(self.ste... | This code processes an action by clipping and converting it, updates the environment state, computes a reward, and returns the new observation, score, and done status. It increments the episode step count, applies the action to the environment, captures sensor data, calculates the reward, and formats action/reward valu... | def step(self, action):
action = [*np.clip(action, -1, 1), action[0], action[1]]
action = [float(v) for v in action]
self.episode_steps += 1
self._make_commands(action)
self.advance()
new_observation, sensors = self.observe()
if self.observation is not None:
... |
def suppress_orig(vA, vA1, vr, vrj):
"""
total 13 mul's + 2 div's
"""
vp = vr - vrj
r, q = vr
p, s = vp
Ap = np.array([[s, -p], [-p * q, p * r + s]]) # 2 mul's
e = Ap[0][0] * Ap[1][1] - Ap[0][1] * Ap[1][0] # 2 mul's
va = Ap @ vA # 4 mul's
vA = va # 2 mul's
a, b = va
v... | The code performs polynomial root-finding using numerical methods. It initializes coefficients and initial guesses, applies suppression and Newton-Raphson checks, evaluates polynomials via Horner's method, and tests Bairstow's algorithm for quadratic factors. The goal is to compute roots, assess convergence (niter, fou... | def main():
vA = np.array([0.1, 1.2])
vA1 = np.array([2.3, 3.4])
vr = np.array([4.5, 5.6])
vrj = np.array([6.7, 7.8])
vAorig, vA1orig = suppress_orig(vA, vA1, vr, vrj)
print(check_newton(vAorig, vA1orig, vr))
vA1 = suppress(vA, vA1, vr, vrj)
print(check_newton(vA, vA1, vr))
h = [5, 2... |
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
if terminal(board):
return EMPTY
actionList = []
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == EMPTY:
actionList.append((i, ... | The function returns a new board state resulting from applying the specified action to the original board, ensuring the action is valid. It creates a deep copy of the board to avoid modifying the original, then places the current player's symbol at the action's coordinates. | def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
if action not in actions(board):
raise Exception
copyBoard = deepCopyBoard(board)
copyBoard[action[0]][action[1]] = player(board)
return copyBoard |
def time_format(string):
if "All day" in string:
return time_range(0, 23)
elif "," in string:
ranges = string.split(',')
result_set = set()
for t_r in ranges:
result_set = result_set.union(time_formatting(t_r))
return result_set
else:
return time_f... | This function converts raw critter data into a structured Excel file. It processes time fields, creates a DataFrame using type-specific formatting, and exports it as an XLSX file. | def raw_data_to_tidy_excel(critter_data, critter_type, file_name):
critter_copy = []
for critter in critter_data:
if type(critter['time']) == str:
c = critter
c['time'] = time_format(critter['time'])
critter_copy.append(c)
else:
critter_copy.appen... |
def roll(self):
roll = random.randint(1,6)
self.current_player().move(roll)
# Knock pieces off the board if we landed on them
self.knock_off()
self.board.roll = roll
self.current_action = 2
def wait(self):
self.current_action = 2
def next_player(self):
... | The main task of the code is to determine and execute the next action based on the value of `self.current_action`. If `current_action` is 0, it triggers a roll; if 1, it waits; otherwise, it passes to the next player. This function acts as a decision dispatcher for sequential action control in a game or process. | def next_action(self):
if self.current_action == 0:
self.roll()
elif self.current_action == 1:
self.wait()
else:
self.next_player() |
def in_game(self):
return self.is_playing
def current_player(self):
return self.players[self.current_player_id]
def next_action(self):
if self.current_action == 0:
self.roll()
elif self.current_action == 1:
self.wait()
else:
self.next_player() | This code runs a game loop that updates the game state, handles user input (mouse clicks, key presses), and triggers the next action. It also supports demo mode with automated actions and exits on quit events. | def play(self):
while self.in_game():
self.board.current_player(self.current_player())
self.board.update()
for event in pygame.event.get():
if event.type in [pygame.MOUSEBUTTONDOWN, pygame.KEYDOWN]:
self.next_action()
elif... |
def setup_tables(self):
for quarter in QUARTERS_TO_SCRAPE:
self.cursor.execute("DROP TABLE IF EXISTS {}".format(quarter))
self.cursor.execute("CREATE TABLE {}"
"(DEPARTMENT TEXT, COURSE_NUM TEXT, SECTION_ID TEXT, COURSE_ID TEXT,"
... | This code defines a method to clean a database by initializing tables, processing input data to remove or update entries, and closing the connection. It prints status messages before and after the process. | def clean(self, data: Dict[str, List[ClassRow]]):
print('Begin cleaning database.')
self.setup_tables()
self._clean(data)
self.close()
print('Finished cleaning database.') |
def move():
pass
def peek_next():
peek()
global current_x, current_y, current_direction
next_x, next_y = current_x, current_y
if current_direction == 'up':
next_y -= 1
elif current_direction == 'down':
next_y += 1
elif current_direction == 'left':
next_x -= 1
elif... | The main task of the code is to move a robot forward in its current direction, update its coordinates (current_x, current_y) based on the direction, and call a turning function if an obstacle is detected ahead. It uses a sleep delay to control movement speed and relies on global variables to track position and directio... | def move_forward():
move()
time.sleep(0.2)
global current_x, current_y
if peek_next():
if current_direction == 'up':
current_y -= 1
elif current_direction == 'down':
current_y += 1
elif current_direction == 'left':
current_x -= 1
elif ... |
def move():
pass
def peek_next():
peek()
global current_x, current_y, current_direction
next_x, next_y = current_x, current_y
if current_direction == 'up':
next_y -= 1
elif current_direction == 'down':
next_y += 1
elif current_direction == 'left':
next_x -= 1
elif... | The code defines a function `move_forward()` that moves a robot forward, pauses, and updates its global coordinates (`current_x`, `current_y`) based on its direction if the next step is clear. If not, it triggers a turn. The function handles directional movement logic and basic obstacle avoidance by checking the next s... | def move_forward():
move()
time.sleep(0.2)
global current_x, current_y
if peek_next():
if current_direction == 'up':
current_y -= 1
elif current_direction == 'down':
current_y += 1
elif current_direction == 'left':
current_x -= 1
elif ... |
def move():
pass
def peek_next():
peek()
global current_x, current_y, current_direction
next_x, next_y = current_x, current_y
if current_direction == 'up':
next_y -= 1
elif current_direction == 'down':
next_y += 1
elif current_direction == 'left':
next_x -= 1
elif... | This function moves a robot forward by updating its position based on the current direction if the next step is clear. If not, it turns. It uses global variables to track coordinates and includes a delay for movement realism. | def move_forward():
move()
time.sleep(0.2)
global current_x, current_y
if peek_next():
if current_direction == 'up':
current_y -= 1
elif current_direction == 'down':
current_y += 1
elif current_direction == 'left':
current_x -= 1
elif ... |
def is_at_goal():
at_goal()
return (current_x, current_y) == (3, 16)
def turn_clockwise():
global current_direction
if current_direction == 'up':
current_direction = 'right'
elif current_direction == 'right':
current_direction = 'down'
elif current_direction == 'down':
cu... | The main task of the code is to navigate a maze by repeatedly checking the current cell's required turns, rotating clockwise as needed, and moving forward if the next cell is accessible. If not, it rotates until a path is clear. The process continues until the goal is reached, with the agent's position and direction pr... | def navigate_maze():
time.sleep(0.2)
while not is_at_goal():
cell = (current_x, current_y)
if cell in turns_at_cell:
for _ in range(turns_at_cell[cell]):
turn_clockwise()
time.sleep(0.2)
if peek_next():
move_forward()
else:
... |
def is_at_goal():
at_goal()
return (current_x, current_y) == (2, 1)
def turn_clockwise():
global current_direction
if current_direction == 'up':
current_direction = 'right'
elif current_direction == 'right':
current_direction = 'down'
elif current_direction == 'down':
cur... | The code navigates a maze by checking each cell's possible turns, turning clockwise as needed, and moving forward when the next cell is accessible. It repeatedly checks the current position, adjusts direction, and progresses until reaching the goal, logging each move and final success. | def navigate_maze():
time.sleep(0.2)
while not is_at_goal():
cell = (current_x, current_y)
if cell in turns_at_cell:
for _ in range(turns_at_cell[cell]):
turn_clockwise()
time.sleep(0.2)
if peek_next():
move_forward()
else:
... |
def is_at_goal():
at_goal()
return (current_x, current_y) == (1, 2)
def peek_next():
peek()
global current_x, current_y, current_direction
next_x, next_y = current_x, current_y
if current_direction == 'up':
next_y -= 1
elif current_direction == 'down':
next_y += 1
elif cu... | The code navigates a maze by repeatedly checking if the next step is clear. If so, it moves forward; if not, it turns until a clear path is found, then moves. It prints the robot's position and direction after each move, continuing until the goal is reached. The main task is to guide a robot through a maze by avoiding ... | def navigate_maze():
while not is_at_goal():
if peek_next():
move_forward()
else:
while not peek_next():
turner()
move_forward()
print("Moved to:", current_x, "X,", current_y, "Y -", "Direction:", current_direction)
print("Goal reache... |
def error(x, w, y, bias):
return (prediction(x, w, bias) - y)
def loss_func(x, w, y, bias):
first = y * np.log(prediction(x, w, bias))
second = (1- y) * np.log(1- prediction(x, w, bias))
res = - first - second
return res
def prediction(x, w, bias):
return sigmoid(np.dot(x,w) + bias)
def displa... | The function trains a linear model using gradient descent to minimize error between predicted and actual targets. It initializes weights and bias, iterates over epochs, updates parameters based on error gradients, tracks loss and accuracy, and visualizes the decision boundary and loss curve. The model's final weights, ... | def train(features, targets, epocs, learning_rate):
errors = []
bias = 0
n_data, n_weights = features.shape
# weights = np.random.normal(scale=1/n_data**0.5, size=n_weights)
# use the below hard code one, so we line up with the online course
weights= [-0.53076476, 0.93080519]
for i in range(epo... |
def remainingCards(hand):
deck = {}
for rank in range(13):
deck[rank + 1] = 4
for card in hand:
deck[card.getRank()] -= 1
return deck
def wetScore(cards, remainingknowns):
score = 0
fn = fnSuits(cards)
if fn:
blockers = 0
for card in cards + remainingknown... | The code calculates the expected total score for a player's kept cards and crib cards in a card game, considering both current hand values (flushes, nobs) and probabilistic outcomes of remaining deck cards. It adjusts crib scores based on dealer status, computes probabilities for possible card combinations, and combine... | def score(kept, tocrib, isDealer):
ranks = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
#dict reprsenting the remaining frequency of each suit in the deck once the starting hand has been dealt
remaining = remainingCards(kept + tocrib)
#determines whether cards sent to the crib count for or against the p... |
def toCardList(tuples):
cards = []
for card in tuples:
cards.append(Card(card[0], card[1]))
return cards
def combinations(set, length, norep, prev = []):
combos = []
if len(prev) == length:
return [prev]
for index, rank in enumerate(set):
cprev = prev.copy()
cprev... | The function `scoreList` evaluates all possible four-card combinations from a given hand (`handList`), calculates their scores based on the dealer status (`isDealer`), and returns sorted results. It generates combinations, determines kept cards and crib cards for each, computes scores using a helper function, and retur... | def scoreList(handList, isDealer):
#Sample input:
#handList = [(2, 0), (2, 2), (4, 2), (4, 3), (10, 3), (4, 3)]
#isDealer = True
startingHand = toCardList(handList)
scores = []
#Generate all possible four card combinations from starting hand
#Iterate over these combinations:
for combo ... |
def LoadDtp(filename):
#print("{}".format(filename))
TimePoints = set()
Constraints = []
W = 1
with open(filename,"r") as tnfile:
f = StringIO(tnfile.read())
[N, M] = f.readline().strip().split()
N = int(N)
M = int(M)
for i in range(0,N):
[X, T] = f.readline().stri... | (The main task of the code is to solve a constraint problem using a specified encoding method and solver. It loads problem data, generates a MiniZinc model based on the encoder type, executes the solver with a timeout, captures the result, and returns the solution status along with encoding and solving times. Debugging... | def SolveCP(instance, encoder, solver, timeout=None, debug=False):
start = time.time()
TimePoints, Constraints, H = LoadDtp(instance)
mzn = None
if encoder.startswith("naive"):
mzn = MiniZincNaiveEncoder(TimePoints, Constraints, H)
elif encoder.startswith("switch") and not encoder.startswit... |
def LoadDtp(filename):
#print("{}".format(filename))
TimePoints = set()
Constraints = []
W = 1
with open(filename,"r") as tnfile:
f = StringIO(tnfile.read())
[N, M] = f.readline().strip().split()
N = int(N)
M = int(M)
for i in range(0,N):
[X, T] = f.readline().stri... | The function `SolveSMT` encodes a temporal planning instance using a specified encoder (naive, switch, switch-tcsp, or hole), generates an SMT-LIB script, and solves it with a given SMT solver. It returns the solution (0/1/E/?), encoding time, and solving time. Debug mode saves the SMT file. The process involves parsin... | def SolveSMT(instance, encoder, solver, timeout=None, debug=False):
start = time.time()
TimePoints, Constraints, H = LoadDtp(instance)
if encoder.startswith("naive"):
smtlib = SmtNaiveEncoder(TimePoints, Constraints, H)
elif encoder.startswith("switch") and not encoder.startswith("switch-tcsp"... |
def LoadDtp(filename):
#print("{}".format(filename))
TimePoints = set()
Constraints = []
W = 1
with open(filename,"r") as tnfile:
f = StringIO(tnfile.read())
[N, M] = f.readline().strip().split()
N = int(N)
M = int(M)
for i in range(0,N):
[X, T] = f.readline().stri... | This function solves a Mixed Integer Linear Programming (MILP) problem by encoding temporal constraints into an LP file using a specified encoder, then invoking a solver to determine feasibility. It handles timeout errors, computes encoding and solving durations, and returns the solution status along with timing metric... | def SolveMILP(instance, encoder, solver, timeout=None, debug=False):
lp_file = "{}/__{}__.lp".format(TmpDir, os.path.basename(instance))
if os.path.exists(lp_file):
os.remove(lp_file)
start = time.time()
TimePoints, Constraints, H = LoadDtp(instance)
FeasTol = 1/H
for i in range(6,10):... |
def get_device():
device = args.device
return device
def get_evidence(y):
if args.unc_act == 'relu':
return F.relu(y)
elif args.unc_act == 'softplus':
return F.softplus(y)
elif args.unc_act == 'exp':
return torch.exp(torch.clamp(y, -10, 10))
# return torch.exp(y)
... | This function computes the Evidence Deep Learning (EDL) log loss for a model's output against a target, incorporating an annealing schedule and optional vacuity regularization. It calculates evidence from the output, derives alpha values, computes the EDL loss using logarithmic transformation, and applies regularizatio... | def edl_log_loss(output, target, epoch_num, num_classes, annealing_step, device=None):
if not device:
device = get_device()
evidence = get_evidence(output)
# print(torch.max(evidence))
alpha = evidence + 1
edl_loss_val, vacuity = edl_loss(torch.log, target, alpha, epoch_num, num_classes, ann... |
def get_device():
device = args.device
return device
def get_evidence(y):
if args.unc_act == 'relu':
return F.relu(y)
elif args.unc_act == 'softplus':
return F.softplus(y)
elif args.unc_act == 'exp':
return torch.exp(torch.clamp(y, -10, 10))
# return torch.exp(y)
... | The function computes the Evidence-Directed Loss (EDL) using the digamma function for uncertain predictions, incorporating a regularization term (vacuity) to penalize confident incorrect predictions. It calculates the loss based on evidence derived from model outputs, adjusts with epoch-specific annealing, and optional... | def edl_digamma_loss(
output, target, epoch_num, num_classes, annealing_step, device=None
):
if not device:
device = get_device()
evidence = get_evidence(output)
alpha = evidence + 1
edl_loss_val, vacuity = edl_loss(torch.digamma, target, alpha, epoch_num, num_classes, annealing_step, device... |
def get_device():
device = args.device
return device
def get_evidence(y):
if args.unc_act == 'relu':
return F.relu(y)
elif args.unc_act == 'softplus':
return F.softplus(y)
elif args.unc_act == 'exp':
return torch.exp(torch.clamp(y, -10, 10))
# return torch.exp(y)
... | The code computes a loss function combining mean squared error (MSE) with Dirichlet distribution-based uncertainty estimation. It calculates evidence from model outputs, derives alpha parameters, and computes MSE loss adjusted by an annealing schedule. A regularization term (vacuity) is optionally subtracted to penaliz... | def edl_mse_loss(output, target, epoch_num, num_classes, annealing_step, device=None):
if not device:
device = get_device()
evidence = get_evidence(output)
alpha = evidence + 1
mse_loss_val, vacuity = mse_loss(target, alpha, epoch_num, num_classes, annealing_step, device=device)
loss = torch... |
def sort_deployments(deployments: dict) -> dict:
deployments.sort(key = lambda x:x["createdAt"], reverse=True)
return deployments
def check_edge_cases(deployments: dict, environment: str, service: str) -> dict:
if (len(deployments) == 1):
if (deployments[0]["rolloutState"] == "COMPLETED"):
if ((environm... | This script tracks AWS ECS service deployments, validates service/environment parameters, checks deployment status, and reverts to a healthy task definition if a rollout fails. It uses argparse for input, AWS role switching, and ECS API calls to manage service scaling and deployment tracking in non-production environme... | def main():
parser = argparse.ArgumentParser(description="AWS ECS Track Deployment Script")
parser.add_argument("--service", type=str, required=True, help="The name of the service we are interacting with")
parser.add_argument("--environment", type=str, required=True, help="The name of the environment we are inte... |
def _process_with_timestamps(self) -> None:
with open(self.data_file, encoding="utf-8") as f:
for line in tqdm(f):
audio_path, transcript_path = line.strip().split()
audio_path = Path(audio_path)
speech_id = Path(audio_path).stem
... | The run method processes data using either timestamped or non-timestamped methods, then applies silence subsampling if the subsampling factor exceeds 1, handling audio processing workflows with conditional logic based on configuration parameters. | def run(self) -> None:
if self.with_timestamps:
self._process_with_timestamps()
else:
self._process_without_timestamps()
if self.subsampling_factor_for_silence > 1:
self._subsample_silence() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.