dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def bootstrapped_feature_select_all_hyperparameters(self, X_train, y_train):
data_dir_path = pathlib.Path(__file__).parent / '../data'
filename = data_dir_path / f'intercept{self.is_fit_intercept}_center{self.is_center_data}_borepli{self.bootstrap_replicates_lst}_{self.n_lambdas}lams_{self.n_alphas}alph... | The function 'get_price' evaluates a model by performing bootstrapped feature selection, running a single iteration of model training and validation, and generating test set predictions. It returns test features, predicted values, and actual values after computing metrics like MSE and tracking error. The method uses hy... | def get_price(self, bootstrap_replicates: Union[int, None],
soft_J_percentage: float = None):
X_train, y_train, X_val, y_val, X_test, y_test = self.train_test_val_split
self.bootstrapped_feature_select_all_hyperparameters(X_train, y_train)
size_J, mse, daily_tracking_error, J =... |
def _clean(target_dir):
report_exts = ('.html', '.xml')
target_files = os.listdir(target_dir)
for file_name in target_files:
if file_name.endswith(report_exts):
print('Removing file: ', os.path.join(target_dir, file_name))
os.remove(os.path.join(target_dir, file_name))
c... | The code defines a CLI interface for the QAT (Quick API Test) library, parsing command-line arguments to execute actions like 'clean', 'init', or 'run'. It handles configurations, input files, logging, reporting, and directory settings, enabling users to manage test suites, generate reports, and control test execution ... | def main():
parser = argparse.ArgumentParser(description='QAT (Quick API Test) Library CLI Interface')
parser.add_argument('--version', action="version",
version=VERSION,
help='QAT library version')
parser.add_argument('action', metavar='action', type=str,
... |
def ingest_data(self) -> pd.DataFrame:
"""Concatenate multiple files into a single dataframe
Arguments:
filepaths: list of filepaths
Returns:
df: concatenated dataframe
"""
frames = [pd.read_csv(file_path, compression = 'zip', low_memory = False, ... | The main task of the code is to ingest, clean, and save data, returning a cleaned DataFrame. The `wrangle_data` method calls `ingest_data` to load data, applies `clean_data` to process it, stores the result in `self.df`, saves the data using `save_data`, and finally returns the cleaned DataFrame for further use. | def wrangle_data(self) -> pd.DataFrame:
"""Wrapper function to ingest and clean the data.
Returns:
self.df: Cleaned dataframe.
"""
df = self.ingest_data()
self.df = self.clean_data(df)
self.save_data()
return self.df |
def psnr(img_batch, ref_batch, batched=False, factor=1.0):
"""Standard PSNR."""
def get_psnr(img_in, img_ref):
mse = ((img_in - img_ref)**2).mean()
if mse > 0 and torch.isfinite(mse):
return (10 * torch.log10(factor**2 / mse))
elif not torch.isfinite(mse):
return ... | The main task of the code is to compute image quality metrics (PSNR, SSIM, LPIPS) between reconstructed images and ground truth images, then aggregate them in batches based on specified parameters (average, max, or min). It sorts image files, converts them to tensors, calculates metrics per image pair, and outputs batc... | def run(args):
key = lambda x: int(x.split('/')[-1].split('.')[0])
key_gt = lambda x: int(x.split('/')[-1].split('.')[0].split('_')[0])
tt = tf.ToTensor()
recon_file_name = sorted(glob.glob(os.path.join(args.result_path, args.model_hash, "*[0-9].png")), key=key)
gt_file_name = sorted(glob.glob(os.pa... |
def plot_hourglass_from_func(
func,
year,
month,
freq="5min",
tz="Chile/Continental",
site=EarthLocation.of_site("Cerro Pachon"),
max_sun_alt=-8 * u.deg,
color_limits=None,
cmap=plt.get_cmap("viridis"),
ax=None,
):
"""Return visits centered near a pointing
Parameters
... | The main task of the code is to generate multiple visualizations (plots) analyzing observational cadence data from an astronomical database. It creates a moon altitude plot, RA (right ascension) distribution plots, HA (hour angle) plots, effective temperature (teff) plots, and a block-based cadence plot. Each plot uses... | def main():
"""Make the sample cadence figure."""
plotprep.config_logging()
plotprep.config_matplotlib()
logger.info("Making moon plot")
fig, ax = plt.subplots()
plot_hourglass_from_func(moon_alt, YEAR, MONTH, ax=ax)
logger.info("Saving moon plot")
fig.savefig(MOON_PLOT_FNAME, dpi=600, ... |
def find(compute_api, wished_server):
compute_api.module.debug("Getting inside find")
# Pagination is not handle for this demo
url = 'servers?per_page=50'
response = compute_api.get(url)
if not response.ok:
msg = 'Error during server search: (%s) %s' % (response.status_code,
... | The main task of the code is to ensure a server meets desired configurations by checking its existence, creating it if absent, modifying attributes if needed, and waiting for state transitions/installation. It returns whether changes were made and the target server, with check-mode support for simulation. | def ready_strategy(compute_api, wished_server):
compute_api.module.debug("Starting ready strategy")
changed = False
query_results = find(compute_api=compute_api, wished_server=wished_server)
if not query_results:
changed = True
if compute_api.module.check_mode:
return change... |
def check_env_is_activated():
ouput = run_command('conda env list').split("\n")[2:]
env_names = list(filter(lambda x: "*" in x, ouput))
print(f"Enviroment detected: {env_names[0]}")
if CONDA_ENV_NAME not in env_names[0]:
print(
f"Please activate conda environment by running: `conda ... | The main task of the code is to check if the environment is activated, verify if the run file has changed, update the run file if necessary, update dependencies, set up an exercise, and retrieve the project ID. It ensures the correct execution environment is maintained and triggers updates or re-runs when changes are d... | def main():
if check_env_is_activated():
if check_if_run_changed():
download_file(SELF_ORIGIN_PATH, 'run_py_new.py')
print_red("Run File is Changed. Please Re-RUN the file.")
os.rename('run.py', 'old_run.py')
os.rename('run_py_new.py', 'run.py')
os... |
def drawDiamonds():
for diamond1 in game.diamonds:
diamond1.offset = game.onScreenX
#Handle the event of collecting a diamond
if player1.goingRight or player1.direction == 1:
if abs(diamond1.x - player1.x) <= 50 or abs(diamond1.x - player1.x - 90) <=50:
if diamo... | The code draws the game scene by rendering the background, door, signs, items, player, lives, and diamonds. It handles gravity mechanics for different levels, processes player jumps, checks for game over conditions, and updates the display with all game elements including platforms, enemies, spikes, and diamond counts. | def drawWind():
#draw the Background
game.level.draw(game.win)
#Place the level-ending dooor
game.door1.offset = game.onScreenX
game.door1.draw(game.win)
#place all the signs
for sign in game.signs:
sign.offset = game.onScreenX
sign.draw(game.win)
for item in ga... |
def getMail(s):
s.send(b"@rxmsg")
data = getData(s)
i = 3
#parse the reply from server using the keywords msg and file
#append usernames and messages or usernames and filenames to tuples
#save any files received
messages = []
files = []
while i < len(data):
if data[i]... | The main task of the code is to render the game scene by drawing backgrounds, player characters, platforms, diamonds, and enemies, while handling multiplayer communication to synchronize player positions and game states. It processes incoming messages to update the remote player's status, manages gravity mechanics for ... | def drawWind():
global s,friend, SecondPlayeronScreenX, otherPlayerLevel
#draw the Background
game.level.draw(game.win)
#Place the level-ending dooor
game.door1.offset = game.onScreenX
game.door1.draw(game.win)
#place all the signs
for sign in game.signs:
sign.offset = game... |
def checkButtons(keys):
#These are the directional buttons (Left and Right)
if keys[pygame.K_LEFT]:
player1.goingLeft = True
player1.goingRight = False
player1.direction = 0
if not player1.x < 50:
#Ensure that the player isn't blocked by a ... | The main task of the code is to run a game loop that handles player input, updates game state, manages camera scrolling, controls enemy behavior, transitions between levels when the player reaches doors, and resets the game upon player death or menu selection. It maintains game run status, processes events, and renders... | def gameLoop(game,player1):
game = game
player1 = player1
screenWidth = game.screenWidth
screenHeight = game.screenHeight
pygame.display.set_mode((screenWidth,screenHeight))
## GameRun stores the current status of the game
##(whether it is on or has been quited)
while game.gameRun:
... |
def sendMessage(s, friend, message):
#caclulate total size of the command string
#and send the send message command to server
size = 16 + len(friend) + len(message)
length = len(str(size))
command = "@" + "0" * (5 - length) + str(size)
command += "@sendmsg@" + friend + "@" + message
s.... | The code defines a game loop that handles user input, updates game state, manages camera movement, enemy behavior, level transitions, and game over conditions. It processes events, updates player/enemy positions, checks for level progression, and displays appropriate messages when the player quits, wins, or loses. The ... | def gameLoop(game,player1):
global s,friend
game = game
player1 = player1
screenWidth = game.screenWidth
screenHeight = game.screenHeight
pygame.display.set_mode((screenWidth,screenHeight))
## GameRun stores the current status of the game
## (whether it is on or has been quited)
... |
def getMail(s):
s.send(b"@rxmsg")
data = getData(s)
i = 3
#parse the reply from server using the keywords msg and file
#append usernames and messages or usernames and filenames to tuples
#save any files received
messages = []
files = []
while i < len(data):
if data[i]... | The code processes incoming game-related messages from a socket, managing friend requests by adding/removing friends from a list, and initiating a Pygame-based game session when a request is accepted. It checks for "Game Request," "Request Cancelled," and "Game Accepted" messages, updating the UI and starting the game ... | def checkRequests(self,socket):
mail = getMail(socket)
messages = mail[0]
#check all the messages and display them on chat windows
#create chat window if not already present
if messages:
for i in messages:
friend1 = i[0]
message = i[1... |
def closeWnd(self,root,Requests,socket):
for friend in self.pendingRequest:
sendMessage(socket,friend,"Request Cancelled")
self.root.destroy()
def sendGameRequest(self,socket,username,friend=0):
if friend == 0 and self.list2.curselection() != ():
friend = self.l... | The code initializes a GUI for a multiplayer client, setting up a window with friend lists, pending requests, and buttons to send/accept game requests. It configures the interface, binds window closure to a cleanup function, and initializes data structures to track requests. The GUI updates lists and checks for incomin... | def __init__(self,root,socket,username):
self.username = username
root.title("Multiplayer Client")
root.minsize(height=230, width=570)
self.mainframe = Frame(root)
self.emptylabel = Label(self.mainframe)
self.emptylabel2 = Label(self.mainframe)
self.pendingReques... |
def get_keywords(self, question: str) -> list:
"""Get keywords from a question by removing stopwords and punctuation."""
language = self.detect_language(question)
stopwords_language = set(stopwords.words(language))
custom_stopwords = {"?", "!", ".", ","}
stopwords_language.update... | The code's main task is to search documents for a question by extracting keywords, processing documents, detecting language, identifying top matching documents, and returning a list of up to three top documents with their names, file locations, and scores. | def search_documents(self, question: str) -> list:
"""Search the documents for a question and return a list of top documents with their locations and scores."""
# Get the keywords from the question
keywords = self.get_keywords(question)
# Process the documents and create Document objec... |
def get_bitpacks(path):
bitpacks = {}
with open(path, "r") as file:
modrs = file.read()
matches = re.finditer(
r"^\s+?(\d+?)u32 => (\[(?:\d+?(?:, )?)+\]),", modrs, re.MULTILINE
)
for match in matches:
assert len(match.groups()) == 2
crn = int(m... | This function tests whether the bitpack-based conflict detection method produces the same results as a naive conflict detection method for all pairs of course sections in each term's data. It loads course data, generates bitpack representations, and compares conflict outcomes between every section pair using assertions... | def test_conflict_bitpacks():
for term in os.listdir("data"):
bitpacks = get_bitpacks(f"data/{term}/mod.rs")
sections = []
with open(f"data/{term}/courses.json") as f:
for school in json.load(f):
for course in school["courses"]:
for section in ... |
def create_buttons(container):
button_frame = tk.Frame(container, bg="Black", borderwidth = 1, border=1, relief=tk.GROOVE )
button_frame.columnconfigure(0, weight=1)
button_frame.columnconfigure(1, weight=1)
button_frame.columnconfigure(2, weight=1)
button_frame.rowconfigure(0, weight=1)
button... | The function `create_main_window` constructs a GUI layout using Tkinter by placing a buttons frame, a fraction label frame, and a status label within a root window. It positions these elements at specific coordinates and dimensions to organize the interface, though a placeholder `print(liftDelta)` suggests incomplete o... | def create_main_window(root):
print(liftDelta)
statusText=tk.StringVar()
# root.resizable(0, 0)
button_frame=create_buttons(root)
button_frame.place(x=0, y=0, height=400, width=500)
fraction_frame=create_fraction_label(root)
fraction_frame.place(x=500, y=0, height=400, width=300)
stat... |
def _simplify_punctuation(text):
# from https://github.com/shivam5992/textstat/issues/77
text = re.sub(r"[,:;()\-]", " ", text) # Override commas, colons, etc to spaces/
text = re.sub(r"[\.!?]", ".", text) # Change all terminators like ! and ? to "."
text = re.sub(r"^\s+", "", text) # Remove white s... | The code preprocesses input text by calculating linguistic and readability features using libraries like textstat, generating a dictionary of metrics such as Flesch scores, SMOG index, difficult words, parse tree depth, and POS tags. It simplifies punctuation first, then aggregates features for text analysis tasks like... | def preprocess_text(text):
"""Takes a text, generate features, and returns as dict
Args:
text (str): the text to be preprocessed.
Returns:
dict: a dictionary of feature names with associated values
"""
text = _simplify_punctuation(text)
features = {
"flesch_reading_ea... |
def get_split(self ,dataset):
max = np.array(dataset).max()
class_values = list(set(row[-1] for row in dataset))
b_index, b_value, b_score, b_groups = max+100, max+100, max+100, None
for index in range(len(dataset[0])-1):
for row in dataset:
groups = self.test... | The code constructs a decision tree by recursively splitting data nodes up to a specified maximum depth. It initializes the root node, processes splits, and optionally visualizes the tree if `show_tree` is True. The function returns the root of the built tree structure. | def build_tree(self,show_tree: bool):
root = self.get_split(self.data)
self.split(root, self.max_depth, 1, 1)
self.root = root
if(show_tree):
self.print_tree(self.root)
return root |
def getCSL(self):
CSL = self.inputCSL.get(1.0, Tkinter.END)
CSL = CSL.lower()
while CSL.find('\n') > -1:
CSL = CSL[:CSL.find('\n')] + CSL[CSL.find('\n') + 1:]
while CSL.find('\r') > -1:
CSL = CSL[:CSL.find('\r')] + CSL[CSL.find('\r') + 1:]
while CSL.find('... | The main task of the code is to handle a button click event that processes a chemical substance list (CSL) by checking against a dictionary of aliases and product data. It clears output fields, checks if the dictionary is empty, and updates UI elements with either a warning message or the processed CSL and unknown ingr... | def OnButtonClickCSL(self):
CSL = self.getCSL()
unknownIngredients = self.processList(CSL, self.alias, self.products)
self.outputCSL.delete(1.0, Tkinter.END)
self.outputUnknowns.delete(1.0, Tkinter.END)
if len(self.alias) == 0:
self.labelVariable.set(u"Dictionary Empt... |
def load_file(self, file_path, timeout, all_tactics=True):
input_dict = {
"path": file_path,
"allTactics": all_tactics
}
input = json.dumps(input_dict)
output = self.send_and_recv(input, timeout)
repl_io = Lean4ReplIO(input, output)
return repl_io
... | The function processes input code by checking if it starts with a load command. If so, it loads the specified file and returns the result along with post-state handling. Otherwise, it returns None and executes a simple magic command with the given timeout. | def run_magic(self, code, timeout):
# if code starts with --%load, load the file
matched_load = re.match(r'^--%\s*load\s+(?P<path>[^\n]*)', code)
if matched_load:
path = matched_load.group('path')
repl_io = self.load_file(path, timeout)
return repl_io, self.ha... |
def comment_out_magic(self, code):
# replace string matching regrex ^% with --%
return re.sub(r'^%', '--%', code)
def run_magic(self, code, timeout):
# if code starts with --%load, load the file
matched_load = re.match(r'^--%\s*load\s+(?P<path>[^\n]*)', code)
if matched_load:
... | This function executes provided code in a Lean4 environment, handling both regular commands and proof tactics. It constructs input dictionaries based on the environment and proof states, sends them for processing, and returns results or errors. Exceptions like timeouts or interrupts trigger specific error responses wit... | def run_command(self, code, timeout=-1):
try:
code = self.comment_out_magic(code)
repl_io, state = self.run_magic(code, timeout)
# For heavy magic, ignore the rest of code
if repl_io is not None:
return repl_io
env = state.env
... |
def is_correct_extension(path: str, file_extension: str) -> bool:
"""
Returns True if the file at path matches the filter: file_extension.
Returns False otherwise.
"""
if file_extension == "*":
return True
# if file_extension.startswith("not"):
# no_type = file_extension[4:]
... | This function recursively moves all files with a specified extension from a directory to a bucket, applying their permissions. It checks each file's extension, handles exceptions, and processes files without including the directory itself. | def move_all_files_and_permissions(directory_path: str, bucket_name: str, file_extension: str):
"""
Moves all files in directory_path to bucket_name and applies all permissions
(recursively).
Calls [is_correct_extension(), move_file_and_permissions(), move_all_files_and_permissions()] in order.
- ... |
def bucket_exists(bucket_name: str) -> bool:
"""
Returns True if bucket_name leads to an existing bucket in AWS S3 and False otherwise.
- if the user does not have the permission to access the bucket, the program will return False (subject to change)
- any errors will result in the program to return Fa... | The function `move_local_to_s3` transfers files and folders from a specified local directory to an AWS S3 bucket, ensuring the bucket exists and matches permissions. It validates paths, applies file filters, and uses helper functions to move data while logging errors and success. The local directory must reside within ... | def move_local_to_s3(sub_directory_path: str, bucket_name: str):
"""
Moves all files and folders in sub_directory_path to the AWS S3 bucket bucket_name.
Calls [bucket_exists(), is_correct_extension(), move_file_and_permissions(), move_all_files_and_permissions()]
in order (only this function will be ca... |
def handle_server_package(self, package):
if package['type'] == 'message':
print('{} >> {}'.format(
package['sender_username'], package['data']))
else:
print(package['data'])
def parse_package(self, package):
"""Parse a package"""
return loads(pack... | This code monitors for input from a server socket and standard input. It processes incoming server data, handles user commands (if input starts with '/'), and sends messages to a connected room if applicable. | def monitor(self):
readable_changes, _, _ = select([self.socket, stdin], [], [])
for change in readable_changes:
if change == self.socket:
self.handle_server_package(self.parse_package(self.receive()))
elif change == stdin:
message = stdin.readline... |
def connection_spec_to_graph(connections, used_connections, node_labels, org_num=0):
g = nx.MultiDiGraph(max_k=connections.shape[1])
nodes = [(x, {"ordering": y, "org_num": org_num}) for y, x in enumerate(node_labels)]
g.add_nodes_from(nodes)
edges = []
active_connections = np.argwhere(used_connecti... | This function performs a crossover operation between two network graphs, combining their connections while preserving special nodes. It generates subgraphs, merges them into a total graph, and returns the merged connection specifications along with node mapping details for both original graphs. | def network_crossover_random(connections_1, used_connections_1, connections_2, used_connections_2,
special_nodes, size_first):
N = connections_1.shape[-2]
node_labels_1 = np.arange(start=0, stop=N, step=1)
node_labels_2 = np.arange(start=N, stop=2*N, step=1)
node_labels_2[sp... |
def create_schema(schema_name):
query = f'CREATE SCHEMA IF NOT EXISTS {schema_name};'
return execute_query(query)
def create_table(table_name, schema_name, columns_dict):
columns = []
for column, data_type in columns_dict.items():
columns.append(f'{column} {data_type}')
columns = ','.join(co... | The main task of the code is to set up a database schema, create multiple tables (married, unmarried, and main) within the schema, read data from a file, and insert the data into the database. The function prints intermediate outputs like schema/table creation status, row count, and insertion results. It uses predefine... | def setup_project():
print(create_schema(constants.SCHEMA_NAME))
print(create_table(constants.TABLE_NAME_MARRIED, constants.SCHEMA_NAME, COLUMNS_DICT))
print(create_table(constants.TABLE_NAME_UNMARRIED, constants.SCHEMA_NAME, COLUMNS_DICT))
print(create_main_table(constants.TABLE_NAME, constants.SCHEMA_... |
def get_cp(self, factor=1.0):
"""
This method returns ``None`` if not a .cv file. Otherwise:
Returns the :math:`C_p`-values (capacitance of an equivalent
parallel circuit) from the data. These are directly provided by
the Agilent LRC meter (assuming the default setting to
... | This method computes complex admittance Y = G_p + iωC_p from Agilent LRC meter data in .cv files, returning a 2D complex numpy array scaled by a factor. It checks file type, retrieves conductance (G_p), capacitance (C_p), and frequencies, then calculates Y for each voltage-frequency pair using ω = 2πf. The result is mu... | def get_Y(self, factor=1.0):
"""
This method returns ``None`` if not a .cv file. Otherwise:
Returns the complex admittance :math:`Y = G_p + i \; \omega \cdot C_p`
directly from the values provided by the Agilent LRC meter (assuming
the default setting to :math:`C_p`-mode). For t... |
def get_cp(self, factor=1.0):
"""
This method returns ``None`` if not a .cv file. Otherwise:
Returns the :math:`C_p`-values (capacitance of an equivalent
parallel circuit) from the data. These are directly provided by
the Agilent LRC meter (assuming the default setting to
... | This method calculates and returns the magnitude (|Y|) and phase (φ_Y) of complex admittance Y = G_p + iωC_p from .cv files, scaling |Y| by a factor. It returns two 2D arrays: one for |Y| values (scaled) and one for φ_Y, with dimensions matching voltage and frequency ranges. Returns None for non-.cv files. | def get_Yabs_Phi(self, factor=1.0):
"""
This method returns ``None`` if not a .cv file. Otherwise:
Returns the norm :math:`|Y|` and the phase :math:`\phi_Y` of the
complex admittance :math:`Y = G_p + i \; \omega \cdot C_p` directly
from the values provided by the Agilent LRC met... |
def get_cp(self, factor=1.0):
"""
This method returns ``None`` if not a .cv file. Otherwise:
Returns the :math:`C_p`-values (capacitance of an equivalent
parallel circuit) from the data. These are directly provided by
the Agilent LRC meter (assuming the default setting to
... | This method calculates equivalent series capacitance (C_s) values from C_p and G_p data using the formula Cs = (Gp² + (ωCp)²)/(ω²Cp), where ω = 2πf. It returns a 2D numpy array of scaled C_s values (by a given factor) for each voltage and frequency, or None if the file isn't a .cv file. The output respects previously s... | def get_cs(self, factor=1.0):
"""
This method returns ``None`` if not a .cv file. Otherwise:
Returns the :math:`C_s`-values (capacitance of an equivalent
serial circuit, see picture above). These are calculated using
the :math:`C_p` and :math:`G_p` data together with the
... |
def get_cp(self, factor=1.0):
"""
This method returns ``None`` if not a .cv file. Otherwise:
Returns the :math:`C_p`-values (capacitance of an equivalent
parallel circuit) from the data. These are directly provided by
the Agilent LRC meter (assuming the default setting to
... | This method calculates and returns Rs-values (equivalent series resistance) for each voltage and frequency from a .cv file. It uses Cp, Gp data and frequencies from metadata, applying the formula Rs = Gp / (Gp² + (ωCp)²). The result is a 2D numpy array scaled by an optional factor. Returns None if the file isn't .cv. | def get_rs(self, factor=1.0):
"""
This method returns ``None`` if not a .cv file. Otherwise:
Returns the :math:`R_s`-values (resistance of an equivalent
serial circuit, see picture above). These are calculated using
the :math:`C_p` and :math:`G_p` data together with the frequen... |
def fpart(value):
return abs(value) % RONE
def rpowi(base, exp):
if (exp % 2 != 0):
res = base
else:
res = RONE
exp //= 2
while(exp != 0):
base = rmul(base, base)
if (exp % 2 != 0):
res = rmul(res, base)
exp //= 2
return res
def toInt(value):
... | This function computes the real power of a base raised to an exponent by separating the exponent into integer and fractional parts. It calculates the integer part using a helper function, then applies logarithms and exponentials to handle the fractional part, combining both results for the final output. Special cases l... | def rpow(base, exp):
if (exp == 0):
# Anything to the 0 is 1
return RONE
if (base == 0):
# 0 to anything except 0 is 0
return 0
frac = fpart(exp)
whole = exp - frac
wholePow = rpowi(base, toInt(whole))
if (base < RONE):
newExp = rmul(frac, ln(rdiv(RONE,... |
def getRawWeight(T):
res = alpha[T//3600]
return (Decimal(1-res), Decimal(res))
def calRightProtocolLP(Bin, Bout, Win, Wout, constsSwapAmount):
actual_swap_fee = constsSwapAmount * swapFee
actual_protocol_fee = actual_swap_fee * protocolFee
tempBin = Bin + constsSwapAmount - actual_protocol_fee
... | This function simulates a token-to-XYT swap in a liquidity protocol. It calculates expected LP token changes (alter), updates balances and treasury, computes actual LP tokens (actualLp), and reports the difference between expected and actual values relative to total supply. The process involves weight calculations, bal... | def swapTokenToXyt(T, inAmount):
print("\n==================SWAPPING===================")
global Bin, Bout
Win, Wout = getRawWeight(T)
alter = calRightProtocolLP(Bin, Bout, Win, Wout, inAmount)
print("LP alter:", alter)
updateK(T)
outAmount = calOutWeight(Bin, Bout, Win, Wout, inAmoun... |
def getRawWeight(T):
res = alpha[T//3600]
return (Decimal(1-res), Decimal(res))
def calRightProtocolLP(Bin, Bout, Win, Wout, constsSwapAmount):
actual_swap_fee = constsSwapAmount * swapFee
actual_protocol_fee = actual_swap_fee * protocolFee
tempBin = Bin + constsSwapAmount - actual_protocol_fee
... | This function simulates a token swap operation in a DeFi context, calculating liquidity provider (LP) token adjustments, updating pool balances, and verifying discrepancies between calculated and actual LP values. It prints swap details, LP alterations, output amounts, and the difference between theoretical and actual ... | def swapXytToToken(T, inAmount):
print("\n==================SWAPPING===================")
global Bin, Bout
Win, Wout = getRawWeight(T)
alter = calRightProtocolLP(Bout, Bin, Wout, Win, inAmount)
print("LP alter:", alter)
updateK(T)
outAmount = calOutWeight(Bout, Bin, Wout, Win, inAmount)
... |
def shuffle(self):
idx = [i for i in range(self.x.shape[0])]
np.random.shuffle(idx)
self.x = self.x[idx]
self.y = self.y[idx]
def resetWeightDerivative(self):
self.DW=[]
self.DB=[]
prevInput=self.x.shape[1]
for i in self.HiddenLayerNuron:
self... | The code trains a neural network using gradient descent with batch processing. It shuffles data, performs forward and backward passes, updates weights, and tracks loss/accuracy per epoch. Logging is enabled if specified, with progress details printed. | def train(self):
if(self.runlog):
print('.....................................')
print('Starting Gradient Descent..')
print('.....................................')
for epoch in range(self.epochs):
self.shuffle()
self.resetWeightDeriva... |
def i2c_master_passthrough(self, passthrough):
"""
Enables or disables I2C Master Passthrough
:return: Returns true if the setting write was successful, otherwise False.
:rtype: bool
"""
# Read the _AGB0_REG_INT_PIN_CONFIG, store in local variable "registe... | This function initializes a magnetometer (AK09916) via I2C by configuring the I2C master, resetting it until communication is established, setting the magnetometer to continuous 100Hz mode, and configuring I2C slave parameters. It returns True on success, False if communication fails after multiple attempts. | def startup_magnetometer(self):
"""
Initialize the magnotometer with default values
:return: Returns true of the initializtion was successful, otherwise False.
:rtype: bool
"""
self.i2c_master_passthrough(False) #Do not connect the SDA/SCL pins to AUX_DA/AU... |
def autoAdd(d,u,t):
#adds daily tasks and uncompleted tasks
t = autoDailies(t,d)
t = autoDeadline(t)
counter = 0
#for u, it's a bit different as tasks in u have a datetime stamp already
print(f"You have {len(uncompleted)} uncompleted tasks left from last time")
for task in u:
if task... | The function `buildTomorrow` manages a list of tasks for tomorrow. If the list exists, it displays tasks and asks the user to delete it or continue. If empty, it adds new tasks with timestamps until "stop" is entered, then returns the updated list. | def buildTomorrow(tomorrowList):
print("Building List for Tomorrow")
time.sleep(0.3)
if len(tomorrowList) > 0:
print("You already have a list for tomorrow")
print(f"Here are your {len(tomorrowList)} tasks.")
for task in tomorrowList:
print(f"{tomorrowList.index(task) + 1}... |
def quickList(uncompleted): # builds list from scratch and then completes it by combining two functions.
completedList, uncompleted, deadline = doList(buildList(uncompleted), uncompleted)
print(f"You have {len(uncompleted)} tasks left")
return completedList, uncompleted, deadline
def syncUncompleted(uncompl... | The code presents a menu-driven interface for managing daily and long-term tasks, allowing users to create lists, review tasks, add new tasks, move tasks between lists, and report completions. It validates user input, updates task lists (dailies, uncompleted, deadline), and syncs data. The main task is to provide an in... | def menu(dailies,tomorrowList, uncompleted,deadline):
menuList = ["Create new list.","Create list for tomorrow.","Load list made yesterday","Review current daily tasks","Add new daily tasks","See Uncompleted Tasks","Move Current Task to Long-Term Tasks","Create new tasks and add to Long-Term Task","Report completio... |
def load_fmnist(labels):
X_train, y_train, X_test, y_test = dataget.image.fashion_mnist().get()
ind = [i for i in range(len(y_train)) if y_train[i] in labels]
X_train, y_train = X_train[ind], y_train[ind]
n = len(ind)
X_train = X_train.reshape(n, -1).astype(np.float32)/255.0
y_train = y_train.re... | The function `load_dataset` dynamically loads and returns training and test data based on the specified dataset name and parameters. It handles specialized datasets like "FMNIST2" and "CIFAR2" with label/ratio customization, routes names starting with "f" or containing "pointer" to a dedicated loader, and defaults to a... | def load_dataset(dataset_name, **kwargs):
if dataset_name == "FMNIST2":
labels = kwargs.get("labels", [2, 9])
return load_fmnist(labels)
elif dataset_name == "CIFAR2":
labels = kwargs.get("labels", [3, 0])
ratio = kwargs.get("ratio", 1)
return load_cifar2(labels, ratio)
... |
def gen_hardware_events():
hardware_configs = ["cpu-cycles",
"instructions",
"cache-references",
"cache-misses",
"branch-instructions",
"branch-misses",
"bus-cycles",
... | The main task of the code is to generate a combined string containing hardware events, software events, hardware cache events, and ARM raw events, prefixed with an auto-generated comment. It concatenates outputs from four helper functions and returns the aggregated result. | def gen_events():
generated_str = "// This file is auto-generated by generate-event_table.py.\n\n"
generated_str += gen_hardware_events() + '\n'
generated_str += gen_software_events() + '\n'
generated_str += gen_hw_cache_events() + '\n'
generated_str += gen_arm_raw_events() + '\n'
return generated_str |
def set_isa(self, metadata: str) -> None:
"""Sets the instruction set architecture.
Args:
metadata (str): The input CFG file metadata.
Raises:
exceptions.ArchitectureError: An error occurred when the input CFG
file ISA is incompatible with the target arc... | This code parses lines from a CFG file using a state machine to process method names, CFG blocks, flags, HIR instructions, and disassembly data, transitioning between states to handle different parsing stages while raising errors for invalid input and updating internal state and annotations accordingly. | def parse_line(self, line: str) -> None:
"""Parses a line from the input CFG file.
Args:
line (str): A line to parse.
Raises:
exceptions.ParseError: An error occurred during parsing.
"""
if self.state == State.START:
if line == EOF_MARKER:
... |
def qkp_objective_function(self, selections):
confidence_weight = np.sum(self.confidences*selections)
dissimilarity_weight = np.sum(self.dissimilarity_matrix*np.outer(selections, selections))
return confidence_weight * dissimilarity_weight
def candidate_to_string(self, candidate: np.ndarray):
return "".jo... | This code implements a tabu search algorithm to optimize the quadratic knapsack problem (QKP). It iteratively generates neighboring solutions, evaluates them using a custom objective function, maintains a tabu list to avoid revisiting recent solutions, and updates the best solution when a higher-quality candidate is fo... | def run(self, initial_solution: np.ndarray):
"""Running the tabu search."""
best_solution = initial_solution
best_candidate = initial_solution
best_eval = self.qkp_objective_function(best_candidate)
tabu_list = [initial_solution]
eval_map = {self.candidate_to_string(initial_solution):self.qkp_objective_fu... |
def RetrieveData():
pass
def NumberFunction( Min, Max, Message):
Verify = False
while Verify == False:
Input = input(Message)
#is try statement checks the users input is a valid integer
try:
Input = int(Input)
Verify = True
except:
print("T... | The main task of the code is to provide a menu-driven contact management system. It retrieves contact data, displays options for viewing, creating, deleting, editing, searching contacts, or closing the app, validates user input, and executes corresponding functions based on the selected option. | def Main():
RetrieveData()
print("CONTACTS")
print("---------------------")
print("1. View All Contacts ")
print("2. Create Contacts")
print("3. Delete Contacts")
print("4. Edit Contacts")
print("5. Search Contacts")
print("6. Close application ")
Userinput = NumberFunction(1,6,... |
def karaman(pkidb_ligands=False, fda_approved=False, kinmap_kinases=False, data_path=KARAMAN_PATH):
"""
Load Karaman profiling dataset [1] from KinMap [2].
Optionally: Keep only (a) all PKIDB ligands or (b) all FDA-approved PKIDB ligands (while
renaming all ligands to their names in PKIDB).
[1] htt... | The function `load` provides a unified interface to retrieve kinase profiling datasets (e.g., 'karaman', 'davis') as pandas DataFrames. It applies filters for PKIDB ligands, FDA approval, and KinMap kinase mappings, returning structured data with kinases as rows and ligands as columns. Your return | def load(dataset_name, pkidb_ligands=False, fda_approved=False, kinmap_kinases=False):
"""
Utility function to load different profiling datasets via the same API.
Parameters
----------
dataset_name : str
Dataset name: 'karaman' or 'davis'
pkidb_ligands : bool
Keep only PKIDB lig... |
def drawResponseArrays(myWin,bgColor,horizVert,xOffset,possibleResps,bothSides,leftRightCentral):
'''If bothSides, draw array on both sides, with one side dimmed
If leftRight=0, collect response from left side, and draw other side dim. Otherwise if =1, from right side.
possibleResps is usually an array of a... | The function `collectOneLineupResponse` gathers a participant's response by allowing them to click on a visual lineup of options (vertical or horizontal), positioned left, right, or central. It displays indicators, handles mouse/keyboard inputs, validates clicks, plays sounds for correct/incorrect selections, and retur... | def collectOneLineupResponse(myWin,bgColor,myMouse,drawBothSides,leftRightCentral,OKtextStim,OKrespZone,possibleResps,xOffset,clickSound,badClickSound):
if leftRightCentral == 0: #left
constCoord = -1*xOffset
horizVert = 1 #vertical
elif leftRightCentral == 1: #right
constCoord = xOffset
... |
def alpha_lv(self, Tc):
TK = Tc + 273.15
if self.name == "18O":
ln_a = 0.35041 * (1e6 / TK ** 3) - 1.6664 * (1e3 / TK ** 2) + 6.7123 / TK - 0.007685
elif self.name == "2H":
ln_a = 1.1588 * (TK ** 3 / 1e9) - 1.6201 * (TK ** 2 / 1e6) + 0.79484 * (TK/1e3) + 2.9992 * (1e6 / T... | This function computes the delta_e value by combining the product of alpha_lv(Tc) and delta_w with adjustments from RH, delta_atm, and eps_tot(Tc, RH), then dividing by a denominator involving RH and eps_k(RH). It likely models a physical or environmental process, such as evaporation or atmospheric interactions, using ... | def delta_e(self, Tc, RH, delta_w, delta_atm):
num = self.alpha_lv(Tc) * delta_w - RH * delta_atm - self.eps_tot(Tc, RH)
den = 1 - RH + self.eps_k(RH) / 1000
return num / den |
def getValidLocation(board):
valid_locations = []
for col in range(7):
if isValidLocation(board, col):
valid_locations.append(col)
return valid_locations
def isTerminalNode(board):
return Is_Winning(board, 1) or Is_Winning(board, 2) or len(getValidLocation(board)) == 0
def Is_Winning... | This function implements the Minimax algorithm for a turn-based game, recursively evaluating all possible moves up to a specified depth. It determines the optimal column to place a coin (for maximizing or minimizing players) by assessing terminal game states (win/loss/draw) and selecting moves that maximize/minimize th... | def MinMax(board, depth, maximizingPlayer):
valid_locations = getValidLocation(board)
is_terminal = isTerminalNode(board)
if depth == 0 or is_terminal:
if is_terminal:
if Is_Winning(board, 2):
return (None, 100000000000000)
elif Is_Winning(board, 1):
... |
def getValidLocation(board):
valid_locations = []
for col in range(7):
if isValidLocation(board, col):
valid_locations.append(col)
return valid_locations
def isTerminalNode(board):
return Is_Winning(board, 1) or Is_Winning(board, 2) or len(getValidLocation(board)) == 0
def Is_Winning... | This function implements the Alpha-Beta pruning algorithm for a game like Connect Four, evaluating optimal moves by recursively exploring the game tree. It determines the best column to place a coin (maximizing/minimizing player) while pruning suboptimal branches using alpha-beta values. The function returns the select... | def Alpha(board, depth, alpha, beta, maximizingPlayer):
valid_locations = getValidLocation(board)
is_terminal = isTerminalNode(board)
if depth == 0 or is_terminal:
if is_terminal:
if Is_Winning(board, 2):
return (None, 1)
elif Is_Winning(board, 1):
... |
def createBoard():
global board
return board
def measure_minimax_performance(board, depth):
start_time = time.time()
MinMax(board, depth, True)
end_time = time.time()
execution_time = end_time - start_time
return execution_time
def measure_alphabeta_performance(board, depth):
start_time ... | The code compares the performance of Minimax and Alpha-Beta pruning algorithms by measuring their execution times and node counts at varying search depths (3, 4, 5). It prints a table showing depth, Minimax time, Alpha-Beta time, and Alpha-Beta nodes, highlighting efficiency gains of Alpha-Beta over Minimax. | def compare_performance():
board = createBoard()
depths = [3, 4, 5] # Different depths to test
print("Depth\tMinimax Time\tAlpha-Beta Time\tAlpha-Beta Nodes")
for depth in depths:
minimax_time= measure_minimax_performance(board, depth)
alphabeta_time= measure_alphabeta_performance(boar... |
def initialPop(nPop,nCities):
pop_list=[-1]*nPop*2
for j in range(nPop):
pop_list[j]=randomSearch(nCities)
return pop_list
def currentBestGen(nPop,pop):
s=[]
for i in range(nPop):
s.append(distanceTour(pop[i]))
return min(s)
def selection(nPop,pop_list):
selectPop=[-1]*2... | The code implements a Genetic Algorithm (GA) to optimize a population of solutions over a specified number of generations. It initializes a population, iteratively selects and applies operations (crossover/mutation) to generate new populations, tracks the best fitness per generation, and returns metrics including gener... | def GA(nPop,nCities,generation):
stime=time.time()
pop_list=initialPop(nPop,nCities)
Gen=[]
Fitness=[]
iteration=0
while iteration<generation:
Gen.append(iteration)
Fitness.append(currentBestGen(nPop,pop_list[0:nPop]))
pop_list=selection(nPop,operators(nPop,pop_list))
... |
def initialPop(nPop,nCities):
pop_list=[-1]*nPop*2
for j in range(nPop):
pop_list[j]=randomSearch(nCities)
return pop_list
def currentBestGen(nPop,pop):
s=[]
for i in range(nPop):
s.append(distanceTour(pop[i]))
return min(s)
def selection(nPop,pop_list):
selectPop=[-1]*2... | The code evaluates the runtime of a genetic algorithm (GA) for solving the Traveling Salesman Problem (TSP) across varying numbers of cities (6–24). It runs the GA three times per city count, measuring the time to converge to a solution, computes average runtimes, and plots them against city counts. An exponential curv... | def findingOptimaltime():
nPop=20
nCities=[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
bestDist=[3168,3637,4817,4828,5273,6326,6334,6820,7375,8132,
8386,8635,8697,9262,9888,9964,10031,10055,10838]
Time=[]
for j in range(3):
for i in range(len(nCities)):
po... |
def led_strip_uit():
for i in range(4):
apa102_send_bytes([0, 0, 0, 0, 0, 0, 0, 0])
for i in range(8):
apa102_send_bytes([1, 1, 1, 1, 1, 1, 1, 1])
for i in range(3):
apa102_send_bytes([0, 0, 0, 0, 0, 0, 0, 0])
for i in range(4):
apa102_send_bytes([1, 1, 1, 1, 1, 1... | This function retrieves a user's total gaming time from an API, visually represents it via a servo motor movement and LED colors, then displays the result in a text field showing the player's name and cumulative playtime in hours. | def toon_gametijd():
led_strip_uit()
totale_gametijd = API.totale_gametijd(steam_id[0])
gametijd = 100 - round(totale_gametijd /10)
for i in range(100, gametijd, -1):
servo_pulse(servo, i)
kleuren(totale_gametijd)
destroy()
display_2.delete(1.0, END)
display_2.insert(END, f'''{AP... |
def load_json_list():
with open('edit_tag_list.json', mode='r', encoding='utf-8') as jsf:
return json.load(jsf)
def load_as_txt(filename: str) -> str:
list_lines: list[str]
with open(filename, mode='r', encoding='utf-8')as file:
list_lines = file.read().split('\n')
return list_lines
def ... | The code modifies HTML content by inserting or replacing specified tags based on JSON configuration. It reads a file, processes text using defined tags, and writes changes back if successful. The function returns True on success, False otherwise. | def file_io(filepath: str, f_insert: bool, f_replace: bool):
d_json = load_json_list()
#wfilename: str = f'{os.path.splitext(filepath)[0]}_edit.html'
l_txt: list[str] = load_as_txt(filepath)
o_tag: list[str] = d_json['outer_tag']
c_tag: str = d_json['marked_tag']
f_sucsess: bool = False
prin... |
def oracle_osstat(self):
sql = """select stat_name, value from v$osstat
where stat_name in ('PHYSICAL_MEMORY_BYTES', 'NUM_CPUS', 'IDLE_TIME', 'BUSY_TIME'
)
"""
res = self.get_query(sql)
cpu_idle = 0
cpu_busy = 0
for stat_name,... | The main task of the code is to aggregate Oracle-related statistics by merging results from multiple methods into a single dictionary. It combines OS statistics, wait events, session counts, load metrics, and memory data using dictionary unpacking, then returns the consolidated dictionary containing all collected Oracl... | def get_oracle_stats(self):
orastat = {}
orastat = {**orastat, **self.oracle_osstat()}
orastat = {**orastat, **self.get_ora_stat()}
orastat = {**orastat, **self.get_wait_events()}
orastat = {**orastat, **self.get_oracle_session_count()}
orastat = {**orastat, **self.get_or... |
def clear():
if platform.system() == 'Windows':
os.system('cls')
else:
os.system('clear')
def print_location():
print('#' * (4 +len(player.position)))
print(f'# {bcolors.HEADER}{player.position.upper()}{bcolors.ENDC} #')
print('#' * (4 +len(player.position)))
def choose_action():
... | This function displays the player's current location and environment description, checks for specific game state conditions (like solved puzzles or repeated visits), prints contextual messages, presents action options, and processes user input to trigger game actions like examining, moving, or exiting. It maintains the... | def prompt():
clear()
print_location()
print('\n' + (cube[player.position][DESCRIPTION]))
if (cube[player.position][REPS]) >= 1:
(cube[player.position][REPS]) == 1
player.solves == player.solves
print(f"{bcolors.BOLD}\nSomething seems different, but nothing's changed here.{bcolor... |
def save_uploadedfile(uploadedfile):
# Determine the local path where the file will be saved
filepath = os.path.join("tempDir", uploadedfile.name)
# If the uploaded file is a STP file, convert it to STL format
if uploadedfile.name.split('.')[-1].lower() == 'stp':
stl_bytes = convert_to_stl(... | The main task of the code is to create a Streamlit-based CAD Matching API that compares uploaded 3D models (STL/STP) against a database by preprocessing files into point clouds, using centroid distances and Hausdorff metrics for matching, ranking results, and displaying top matches with visualizations. It leverages mul... | def main():
# Display a title for the Streamlit app
st.title('CAD Matching API')
# Allow the user to upload a file for comparison
uploaded_file = st.file_uploader("Choose a file for comparison", type=['stl', 'stp'], key='comparison_upload')
# If the user uploads a file
if uploaded_file is ... |
def save_uploadedfile(uploadedfile):
filepath = os.path.join("tempDir", uploadedfile.name)
if uploadedfile.name.split('.')[-1].lower() == 'stp':
stl_bytes = convert_to_stl(uploadedfile)
filepath = filepath.replace('.stp', '.stl')
with open(filepath, "wb") as f:
if uploadedfile.name.... | The main task of the code is to compare a user-uploaded CAD file (STL/STP) against a database of files by preprocessing the input, using centroid-based preselection, and refining matches through point cloud comparison. It displays top matches with scores, product families, and visualizations, leveraging multiprocessing... | def main():
st.title('CAD Matching API')
uploaded_file = st.file_uploader("Choose a file for comparison", type=['stl', 'stp'], key='comparison_upload')
if uploaded_file is not None:
st.text("Saving uploaded file...")
comp_filepath = save_uploadedfile(uploaded_file)
mesh = t... |
def connect_to_db():
conn = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASSWORD
)
return conn
def create_table_if_not_exists(conn, table):
"""Create the table if it doesn't already exist."""
cur = conn.cursor()
... | The code establishes a database connection, ensures a table exists, closes the connection, and processes Azure blobs to upload data to the database. | def main():
# Establish a database connection
conn = connect_to_db()
# Ensure the table exists
create_table_if_not_exists(conn, table)
# Close the initial connection
conn.close()
# Process the blobs and upload to the database
process_and_upload_files_from_azure_blob(container_... |
def move_to_location(self, move):
"""
4*3 board's moves like:
0 1 2
3 4 5
6 7 8
9 10 11
and move 5's location is [1,2]
"""
h = move // self.width
w = move % self.width
return [h, w]
def find_list(self, start, middle, between):
h_dist = (middle[0] - start[0]) / between
w_dist = (middle[1] -... | This function checks if a game has ended after a move by evaluating if the last player has achieved a winning condition (n-in-a-row) in any direction from the move's position. If no winner is found and no moves remain, it declares a tie. It returns a boolean indicating game end status and the winner, with optional prin... | def check_if_end(self, move, is_shown):
winner = -1
if move == -1:
return False, winner
else:
h, w = self.move_to_location(move)
between = self.n_in_row - 1
starts = [
(h - between, w - between),
(h - between, w),
(h - between, w + between),
(h, w - between)
]
last_player = (sel... |
def _generate_transient_cert_cert(self):
"""
Use `openssl` command to generate a new transient client certificate
with 24 hours of validity.
"""
certdir = os.path.join(self.config_dir, "transient_certs")
name = str(uuid.uuid4())
self._generate_client_cert(certdir,... | This function handles client certificate requests by checking if the server is in restricted mode, informing the user of certificate issues based on status codes, presenting options to generate or load certificates, and executing the chosen action. It raises exceptions for restricted mode or user aborts, ensuring secur... | def _handle_cert_request(self, meta):
# Don't do client cert stuff in restricted mode, as in principle
# it could be used to fill up the disk by creating a whole lot of
# certificates
if self.restricted:
print("The server is requesting a client certificate.")
pri... |
def _deactivate_client_cert(self):
if self.active_is_transient:
for filename in self.client_certs["active"]:
os.remove(filename)
for domain in self.active_cert_domains:
self.client_certs.pop(domain)
self.client_certs["active"] = None
self.a... | This code provides a menu-driven interface for managing client certificates, allowing users to deactivate, generate new certificates, load existing ones, or import external certificates. It displays active certificates, processes user choices, and delegates actions to helper methods like _deactivate_client_cert, _gener... | def do_cert(self, line):
"""Manage client certificates"""
print("Managing client certificates")
if self.client_certs["active"]:
print("Active certificate: {}".format(self.client_certs["active"][0]))
print("1. Deactivate client certificate.")
print("2. Generate new cer... |
def _deactivate_client_cert(self):
if self.active_is_transient:
for filename in self.client_certs["active"]:
os.remove(filename)
for domain in self.active_cert_domains:
self.client_certs.pop(domain)
self.client_certs["active"] = None
self.a... | This function fetches data over the network using the Gemini protocol, handling certificate management, redirects, and response processing. It validates headers, manages client certificates for domain changes, handles user prompts for security decisions, processes redirects with user confirmation, and caches responses.... | def _fetch_over_network(self, gi):
# Be careful with client certificates!
# Are we crossing a domain boundary?
if self.active_cert_domains and gi.host not in self.active_cert_domains:
if self.active_is_transient:
print("Permanently delete currently active transient c... |
def _is_cached(self, url):
if url not in self.cache:
return False
now = time.time()
cached = self.cache_timestamps[url]
if now - cached > _MAX_CACHE_AGE_SECS:
self._debug("Expiring old cached copy of resource.")
self._remove_from_cache(url)
... | This method handles fetching and processing Gemini resources, including protocol checks, caching, network requests, error handling, and content rendering. It manages redirects, uses cached data if available, executes handler programs for non-text/gemini MIME types, and updates the application's state and history. | def _go_to_gi(self, gi, update_hist=True, check_cache=True, handle=True):
"""This method might be considered "the heart of AV-98".
Everything involved in fetching a gemini resource happens here:
sending the request over the network, parsing the response if
its a menu, storing the respons... |
def load_secrets():
global spotify_client_id, spotify_client_secret, genius_client_id, genius_client_secret, genius_token, genius
with open('secrets') as f:
spotify_client_id = f.readline().strip()
spotify_client_secret = f.readline().strip()
genius_client_id = f.readline().strip()
... | The main task of the code is to run a command-loop interface that loads secrets, authenticates with Spotify, and processes user inputs in a state machine. It starts in "FREEINPUT" mode, accepting commands via input(), which are handled by the handle_free_input() function to update the state until the "QUIT" state is re... | def main():
load_secrets()
generate_spotify_token()
current_state = States.FREEINPUT
while current_state != States.QUIT:
if current_state == States.FREEINPUT:
current_state = handle_free_input(input("Enter a command.\n")) |
def check_combinations(self):
min_combo_length = 3
all_indexes = []
# vertical combination checking
for col in range(self.cols):
c = 1
curr_shape = ''
indexes = []
for row in range(self.rows):
shape = self.shapes[(row, col)... | This function processes input events in a game, checking for valid combinations. If a swap was made and no combination is found, it reverts the swap; otherwise, it removes matched elements and decrements moves. If no prior swap exists, it removes all detected combinations and checks for new swaps, updating game state a... | def check_input(self, events):
if self.active:
if self.last_swapped:
if not self.score_allowed:
self.score_allowed = True
if not self.check_combinations():
self.switch_shapes(*self.last_swapped)
else:
... |
def check_combinations(self):
min_combo_length = 3
all_indexes = []
# vertical combination checking
for col in range(self.cols):
c = 1
curr_shape = ''
indexes = []
for row in range(self.rows):
shape = self.shapes[(row, col)... | This code updates a game state by adjusting scores, checking shape positions, handling swaps, managing combinations, updating visual elements like sparkles, and determining game over conditions based on remaining moves or target score. | def update(self, events):
if self.add_score:
self.score += 1
self.add_score -= 1
self.active = True
for _, shape in self.shapes.items():
if shape.x != shape.target_x or shape.y != shape.target_y:
self.active = False
shape.update(e... |
def collect_os_data(self):
if self.os_client is False:
self.os_client = OSHelper()
servers = self.os_client.server_list(self.os_search_pattern)
if len(servers) != 1:
print(f"Wrong server count for {self.os_name}: {len(servers)}")
sys.exit(1)
self.os... | This code initializes a class to manage OpenStack and Terraform resources, setting up data structures for tracking compute instances, ports, and state files. It configures resource filters, port mappings, and client connections, while preparing to collect OpenStack data, parse Terraform states, and check/extract VMs if... | def __init__(
self,
os_name,
tf_name,
tf_ports,
tfstate_path,
target_tfstate_path=False,
check=True,
init_only=True,
):
self.os_name = os_name
self.os_search_pattern = f"^{os_name}$"
self.tf_name = tf_name
self.check = ... |
def check_win(self, player):
# TODO: Check win
if self.check_row_win(player) == True:
return True
if self.check_col_win(player) == True:
return True
if self.check_diag_win(player) == True:
return True
return False
def check_tie(self):
... | The code implements the **minimax algorithm** for a tic-tac-toe game. It recursively evaluates all possible moves for a given player ("O" or "X") at a specified depth, aiming to maximize ("O") or minimize ("X") the game outcome. It checks base cases (win, tie, depth limit) and returns scores (10 for "O" win, -10 for "X... | def minimax(self, player, depth):
opt_row = -1
opt_col = -1
#Base Case
# if self.check_win(player) == True or self.check_tie() == True:
if self.check_win("O") == True:
return (10, None, None)
if self.check_win("X") == True:
return (-10, None, None)... |
def check_win(self, player):
# TODO: Check win
if self.check_row_win(player) == True:
return True
if self.check_col_win(player) == True:
return True
if self.check_diag_win(player) == True:
return True
return False
def check_tie(self):
... | This function implements the minimax algorithm with alpha-beta pruning for a Tic-Tac-Toe AI. It evaluates all possible moves recursively, maximizing for player "O" and minimizing for "X", while pruning suboptimal branches to improve efficiency. The function returns the best move's score and coordinates, considering gam... | def minimax_alpha_beta(self, player, depth, alpha, beta):
opt_row = -1
opt_col = -1
# Base Case
#if self.check_win(player) == True or self.check_tie() == True:
if self.check_win("O") == True:
return (10, None, None)
if self.check_win("X") == True:
... |
def print_instructions(self):
# TODO: Print the instructions to the game
instructions = "Welcome to TicTacToe!\nPlayer 1 is X and Player 2 is O.\nTake turns placing your pieces - the first to 3 wins!"
print(instructions)
def print_board(self):
# TODO: Print the board
counter = 0
... | The code's main task is to run a tic-tac-toe game by alternating turns between players 'X' and 'O', printing the board after each move, checking for win conditions or a tie, and displaying the result when the game ends. It starts by printing instructions and the initial board, then loops until a win or tie occurs, ensu... | def play_game(self):
# TODO: Play game
self.print_instructions()
self.print_board()
while self.check_tie()==False and self.check_win('X')==False and self.check_win('O')==False:
self.take_turn('X')
self.print_board()
if self.check_win('X')==False and s... |
def rsa_pem_from_jwk(self, jwk):
return RSAPublicNumbers(
n=self.decode_value(jwk['n']),
e=self.decode_value(jwk['e'])
).public_key(default_backend()).public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo... | The code retrieves a public key from a given token by first obtaining the Key ID (KID), fetching the corresponding JSON Web Key (JWK), and converting it into an RSA PEM format using the `rsa_pem_from_jwk` method. This process enables secure cryptographic operations using the extracted public key. | def get_public_key(self, token):
return self.rsa_pem_from_jwk(self.get_jwk(self.get_kid(token))) |
def generate_top_eye_lid(self):
self.top_eye_lid=self.generate_eye_lid_curve(direction=1)
def generate_bottom_eye_lid(self):
self.bottom_eye_lid=self.generate_eye_lid_curve(direction=-1)
self.bottom_eye_lid.reverse()
def generate_iris_and_pupil(self):
minX,maxX,minY,maxY=self.bbox
... | The main task of the code is to render 2D eye components, including eyelids, iris, pupil, and brow, using cubic Bézier curves. It generates shapes for the top and bottom eyelids, creates the iris and pupil, calculates bounding boxes, and draws all elements onto an image using the provided `img_draw` object with a speci... | def render_2D(self,path,img_draw):
self.p0,self.p3=path
self.dist=math.dist(self.p0,self.p3)
self.cbcg=CubicBezierCurveGenerator()
self.generate_top_eye_lid()
self.generate_bottom_eye_lid()
self.eyelid=self.top_eye_lid+self.bottom_eye_lid
self.bbox=getBbox(self.ey... |
def reset_shape(self):
# Reset sliders to zero
self.update_poly = False
for label, com_slider in self.shape_controls:
com_slider.reset()
self.update_poly = True
self.update_render()
def reset_pose(self):
self.update_poly = False
for label, com_slider i... | The code resets a model's shape, pose, and transformation parameters to their initial states, preparing the model for a new simulation or task by reinitializing key attributes. | def reset_model(self):
self.reset_shape()
self.reset_pose()
self.reset_trans() |
def type_generator(question, prompt_type, api_key, LLM_engine):
sleep(1)
prompt = prompt_type
prompt = prompt + " Question: " + question + "Type of the question: "
got_result = False
while got_result != True:
try:
openai.api_key = api_key
answer_modi = openai.Completi... | The code evaluates the performance of a question-answering system by generating candidate answers through combinatorial entity ID replacements in expressions. It compares predicted answers against ground truth labels, tracking exact match scores, no-answer cases, and total evaluations. The function uses retrieval-based... | def all_combiner_evaluation(data_batch, selected_quest_compare, selected_quest_compose, selected_quest,
prompt_type, hsearcher, rela_corpus, relationships, temp, que_to_s_dict_train,
question_to_mid_dict, api_key, LLM_engine, name_to_id_dict, bm25_all_fns, all_fns... |
def parse_args():
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('--shot_num', type=int, metavar='N',
default=40, help='the number of shots used in in-context demo')
parser.add_argument('--temperature', type=float, metavar='N',
defau... | The main task of the code is to evaluate a hybrid retrieval model for answering questions using a combination of BM25 and Contriever searchers, along with relationship and entity mappings. It processes training and evaluation data, tokenizes text, builds BM25 indexes, and runs the `all_combiner_evaluation` function to ... | def main():
args = parse_args()
nlp = spacy.load("en_core_web_sm")
bm25_searcher = LuceneSearcher('contriever_fb_relation/index_relation_fb')
query_encoder = AutoQueryEncoder(encoder_dir='facebook/contriever', pooling='mean')
contriever_searcher = FaissSearcher('contriever_fb_relation/freebase_contr... |
def download_data(self, table_name, label_column_names, output_path, format_type, image_id="image_id", filter_sql=[]):
"""
Downloads data from existing table on the database. Executes and commits any filters from filter_sql
before downloading. Download format can be specified by format_type. Im... | The main task of the code is to join image and label tables using a specified column, apply optional SQL filters, and download the combined data in a specified format to designated output directories. It creates a temporary table for the joined data, invokes a download method, then cleans up by dropping the temporary t... | def join_and_download_data(self, images_table_name, labels_table_name, label_column_names, output_path, format_type, image_id="image_id", filter_sql=[]):
"""
Downloads data from the join of two tables (image table and labels table). Executes and commits
any filters from filter_sql onto the table... |
def goAgent(self, agent):
agent.go(self.chessboard)
def checkCandidateList(self, candidate_list, player_now):
movable_chess = set(self.getMovableChess(player_now))
return movable_chess == set(candidate_list)
def go(self, pos, player_now):
chess_to_reverse = []
for d in self.directions:
nx, ny = pos[0] + d[... | The main task of the code is to simulate a two-player game (e.g., Go) between black and white agents, tracking time spent per move, enforcing turn-based gameplay, handling pass moves, determining the winner, and logging performance metrics like average and maximum time usage per player. The loop alternates turns, valid... | def play(self):
player_now = COLOR_BLACK
round_doubled = 0
pass_count = 0
time_total = {}
time_max = {}
while(True):
agent = self.agent_black if player_now == COLOR_BLACK else self.agent_white
player_name = agent.name
if player_name not in time_total:
time_total[player_name] = 0
if pl... |
def S(n):
return T1(n) / Tn(n)
def E(n):
return S(n) / n
def R(n):
return On(n) / O1(n) | The main task of the code is to compute the value of Q(n) by multiplying the results of S(n) and E(n), then dividing by R(n). The function Q(n) thus represents a mathematical relationship where the output depends on the product of two functions (S and E) of n, scaled by the reciprocal of another function (R) of n. | def Q(n):
return S(n) * E(n) / R(n) |
def S(n):
return T1(n) / Tn(n)
def E(n):
return S(n) / n
def R(n):
return On(n) / O1(n) | The code defines a function Q(n) that computes the product of S(n) and E(n), then divides the result by R(n). Its main task is to evaluate the mathematical expression S(n) * E(n) / R(n) for a given input n, relying on the implementations of the helper functions S(n), E(n), and R(n). | def Q(n):
return S(n) * E(n) / R(n) |
def get_efi_img(cfg):
arch = cfg["architecture"]
vm_folder = cfg["vm_folder"]
if arch == "aarch64":
# Fedora location
src = Path("/usr/share/edk2/aarch64/QEMU_EFI.fd")
if not src.exists():
# Arch Linux location
src = Path("/usr/share/edk2-armvirt/aarch64/QEMU... | This function generates QEMU command-line arguments based on a configuration dictionary, specifying architecture, cores, memory, and VM settings. It configures firmware, disk images, KVM acceleration, networking, and other hardware components, with architecture-specific adjustments for AArch64. The output is a list of ... | def default_qemu_arguments(cfg):
arch = cfg["architecture"]
cores = cfg["cores"]
memory = cfg["memory"]
vm_folder = cfg["vm_folder"]
# QEMU binary
qemu = [f"qemu-system-{arch}"]
# No display
qemu += ["-display", "none"]
qemu += ["-serial", "mon:stdio"]
# Firmware
fw_str = ... |
def get_efi_vars(cfg):
arch = cfg["architecture"]
vm_folder = cfg["vm_folder"]
if arch == "aarch64":
efivars = vm_folder.joinpath("efivars.img")
if not efivars.exists():
run_cmd(["truncate", "-s", "64m", efivars])
return efivars
if arch == "x86_64":
src = Pa... | This code sets up a virtual machine by creating a directory structure, generating an EFI variables image, creating a disk image with specified size, downloading an ISO, and configuring QEMU with SCSI devices and CD drive parameters to launch the VM. | def setup_vm(cfg):
vm_folder = cfg["vm_folder"]
size = cfg["size"]
# Create folder
remove(cfg)
vm_folder.mkdir(parents=True, exist_ok=True)
# Create efivars image
get_efi_vars(cfg)
# Create disk image
qemu_img = ["qemu-img", "create", "-f", "qcow2", get_disk_img(vm_folder), size]
... |
def getWebPage(url):
request = requests.get(url)
soup = BeautifulSoup(request.text, 'html.parser')
return soup
def getAllPlayableCharacterTableLinks(soup):
body = soup.find('body')
col3 = body.find('div', class_= "l-3col")
centerCol3 = col3.find('div', class_= "l-3colMain")
mainCenterCol3 = ... | The code scrapes character links from a webpage, optionally stores them in Firestore, and saves character images based on specified settings. | def startScrape(sendToDatabase=True, imageProperties=ImageSettings()):
soup = getWebPage(url)
tableLinks = getAllPlayableCharacterTableLinks(soup)
characaterLinks = getLinks(tableLinks)
if(sendToDatabase):
writeToFireStore(characaterLinks)
if(imageProperties.saveImages):
saveCharacte... |
def loadQ():
with open(dir + '/savedQAggr.pkl', 'rb') as f:
return pickle.load(f)
def readFile(path):
file = open(path)
board = createBoard(file.readline())
player = file.readline()
return (board, player)
def validMoves(board, player):
# Due to the absolutely insane number of prints, don... | The function `useSavedQ()` loads a pre-trained Q-value table, reads a game state from a file, identifies valid moves, selects a move using the Q-values (with a small exploration rate), applies the move to generate a new board state, and outputs the updated board. It demonstrates using a saved policy (Q-table) to make d... | def useSavedQ():
Q = loadQ()
print(len(Q))
# board,player = startingState,'white'
board, player = readFile(dir + "/incomingGame.txt")
pp.pprint(board)
moves = validMoves(board, player)
pp.pprint(moves)
nextMove = pickMove(0.001, moves, board, Q, player)
'''
for keys in Q:
... |
def result(board):
if board[0][0] != "__" or board[10][0] != "__" or board[10][10] != "__" or board[0][10] != "__":
return "white"
kingFound = False
for x in range(11):
for y in range(11):
if board[x][y] == "wK":
kingFound = True
if not kingFound:
retu... | The code trains a Q-learning agent to play a turn-based game (e.g., chess) by iteratively simulating games, updating Q-values for moves based on rewards (e.g., captures) and game outcomes. It uses epsilon-greedy exploration with decay, adjusting Q-values for state-move pairs to maximize rewards. The agent learns optima... | def trainQ(nRepitions, learningRate, epsilonDecayFactor, Q={}):
# pp.pprint(Q)
rho = .01
epsilon = 1
for i in range(nRepitions):
if (i % 100 == 0):
print("Status: " + str(i) + r" / " + str(nRepitions))
currentState = startingState
oldState = startingState
old... |
def movement(self):
if self.canMove:
self.rect.x += self.speed_x
self.collision_rect.x += self.speed_x
self.rect.y += self.speed_y
self.collision_rect.y += self.speed_y
if self.facing == 'up':
self.y_change = -1
self.x_c... | The code's main task is to update an object's movement, handle terrain collisions, and animate it. It disables movement during a delay period and removes the object if it moves outside a predefined range relative to the player's position, ensuring efficient rendering and interaction within the game environment. | def update(self):
self.movement()
self.collideTerrain()
self.animate()
time_now = pygame.time.get_ticks()
if time_now < self.movementDelay:
self.canMove = False
else:
self.canMove = True
if not (self.game.player.rect.centerx-TerrainGenE... |
def collideEnemy(self):
if not self.inCombat:
for sprite in self.game.enemy_group:
collide = pygame.Rect.colliderect(self.collision_rect, sprite.collision_rect)
if collide:
self.game.enemy_group_inCombat.add(sprite)
self.game.en... | The code updates the player's position, handles collisions with enemies and terrain, animates movement, calculates distances to towns, updates town statistics, and resets movement variables in a game loop. | def update(self):
self.collideEnemy()
self.movement()
self.animate()
self.rect.x += self.direction[0] * PLAYER_SPEED
self.collision_rect.x += self.direction[0] * PLAYER_SPEED
self.collideTerrain('x')
self.rect.y += self.direction[1] * PLAYER_SPEED
self.co... |
def pdf_gaussian_signal(gamma,phi):
"""
pdf of interferometric phase assuming both signal and noise follow complex
Gaussian distribution
Parameters
----------
gamma : float
signal-to-clutter ratio (SCR)
phi : float or float array
interferometric phase
Returns
------... | This function calculates the optimal Signal-to-Noise Ratio (SCR) by evaluating the log-likelihood of observed phases (phi) under three statistical models: Gaussian, constant, or 'sarpixel'. It iterates over a range of SCR values, computes the log-likelihood for each model, and selects the SCR maximizing the likelihood.... | def _cal_scr(phi,model='constant'):
rho = np.linspace(0.0,0.99,49)
scrs = rho/(1-rho)
if len(phi.shape) == 1:
phi = np.expand_dims(phi,axis=1)
loglikelihood = np.zeros((len(scrs),phi.shape[1]))
for i in range(len(scrs)):
if model == 'gaussian':
p = pdf_gaussian_signal(scr... |
def check_pawn_action(self, action):
# move up
initial_x, initial_y = self.positionAIPlayer[0], self.positionAIPlayer[1]
if action == 0:
posX = self.positionAIPlayer[0] - 1
if self.positionAIPlayer[0] == 0:
return False
if self.positionAIPlayer... | This code processes an action in a reinforcement learning environment by validating moves, updating game state, checking termination conditions, calculating rewards, and returning the new observation, reward, done status, and info for the agent. | def step(self, action):
done = 0
AI_move = False
self.reward = 0
if action <= 3:
AI_move = self.check_pawn_action(action)
done = self.check_end()
if AI_move != True:
print("Mistake")
self.reward -= 30
else:
... |
def read_schematic(filename, schema):
with open(filename, 'r') as f:
for line in f:
schema.append(line.strip())
def scan_line(schema, line):
global TOTAL_SUM, GEARS
indigit = False
symbolized = False
geared = False
number = 0
gearposes = set()
for column in range(len(... | The code reads a schematic diagram from 'input.txt', processes each line to analyze components, and counts specific elements (likely gears) using the `count_gears()` function. The main task is to parse and analyze a schematic to determine the number of gears or similar components present. | def main():
schema = []
# read_schematic('test.txt', schema)
read_schematic('input.txt', schema)
for i in range(len(schema)):
scan_line(schema, i)
print(count_gears()) |
def forward_propagate(network, row):
inputs = row
for layer in network:
new_inputs = []
for neuron in layer:
activation = activate(neuron['weights'], inputs)
neuron['output'] = transfer(activation)
new_inputs.append(neuron['output'])
inputs = new_inputs
return inputs
def backward_propagate_error(netwo... | This function trains a neural network using backpropagation over multiple epochs. It iterates through training data, computes network outputs, calculates error against expected labels, propagates errors backward, and updates weights with a given learning rate. It accumulates total error per epoch, stores it for trackin... | def train_network(network, train, l_rate, n_epoch, n_outputs):
for epoch in range(n_epoch):
sum_error = 0
for row in train:
outputs = forward_propagate(network, row)
expected = [0 for i in range(n_outputs)]
expected[row[-1]] = 1
sum_error += sum([(expected[i]-outputs[i])**2 for i in range(len(expected)... |
def GetVideoFrames(video, frames):
vidobj = VideoFileClip(video)
# make video object
filename, _ = os.path.splitext(video)
filename += "-video_maker-temp"
if not os.path.isdir(filename):
os.mkdir(filename)
# make folder
if frames is None:
saving_fps = vidobj.fps
else:
... | The code converts a video into ASCII art frames, saving them as a JSON file. It accepts parameters for input video path, frame rate, output name, image width, color mode (RGB/BW), and scale ratio. The video is split into frames, transformed into ASCII, saved, and temporary files are cleaned up. An optional flag plays t... | def main():
parser = argparse.ArgumentParser(description="Video-to-ASCII converter")
parser.add_argument('--file', '-f', dest='Video', required=True, help="Path to file")
parser.add_argument('--fps', dest="frames_per_second", required=False, help="Frames per second to save")
parser.add_argument('--out',... |
def _select_execution_mode(
self,
requested: Optional[RequestedProcessExecutionMode],
processor: BaseProcessor
) -> tuple[ProcessExecutionMode, dict[str, str]]:
"""Select the execution mode to be employed
The execution mode to use depends on a number of factors:
... | The function executes processes via pygeoapi, handling two types: standard processes run locally as Prefect flows and custom Prefect-aware processes leveraging deployment features. It selects execution mode, generates a job ID, executes the appropriate method, and returns job details, output, status, and headers. | def _execute(
self,
process_id: str,
execution_request: ExecuteRequest,
requested_execution_mode: RequestedProcessExecutionMode | None = None,
) -> tuple[str, str, Any, JobStatus, dict[str, str]]:
"""Process execution handler.
This manager is able to execute two type... |
def clean_message(message):
'''(str) -> str
REQ: message contains only 1 line of text.
REQ: len(message) > 0
>>> clean_message('fighting,.,.,.,!!Easy5747291---=nvm...')
'FIGHTINGEASYNVM'
>>> clean_message('........................................')
''
>>> clean_message('... | The function `process_message` encrypts or decrypts a message using a deck of cards as a keystream. It cleans the input message, iterates through each character, generates a keystream value from the deck, and applies encryption/decryption (based on `enc_or_dec`) to each character. The transformed characters are concate... | def process_message(deck_of_crds, message, enc_or_dec):
'''(list of int, str, str) -> str
REQ: len(deck_of_crds) > 0
REQ: len of message > 0
REQ: enc_or_dec == 'e' or 'd'
'''
clnd_message = clean_message(message)
counter =0
x = ""
# Generate different key_stream_values for each ... |
def power_rule(currentNode, currentValue, dStack):
power = currentNode.getRightChild().key
if dStack.isEmpty():
currentNode.key = '*'
currentNode.getLeftChild().key = power
dStack.push(currentNode)
currentNode = currentNode.getRightChild()
currentNode.key = '^'
cu... | This function applies a specified derivative rule to a parent node in a symbolic differentiation process. Depending on the 'rule' parameter, it invokes corresponding functions (power_rule, chain_rule, etc.) to handle differentiation rules like power, chain, product, and simple operations. After applying the rule, it re... | def derivative_rule(parent, rule, dStack):
if rule == 'power':
power_rule(parent, parent.key, dStack)
return parent
elif rule == 'chain':
chain_rule(parent, parent.key, dStack)
return parent
elif rule == 'multi':
multi_rule(parent, parent.key, dStack)
return p... |
def get_key_from_cache(self, *args, **kwargs) -> typing.Optional[str]:
return self.get_fresh_pem_key()
def get_fresh_pem_key(self) -> str:
key = self.get_fresh_key_from_upstream()
return f"-----BEGIN PUBLIC KEY-----\n{key}\n-----END PUBLIC KEY-----"
def set_key(self, key: str, *args, **kwargs) -... | This function retrieves a key from the cache if it exists; otherwise, it generates a new key, stores it in the cache, and returns it. It ensures a key is available by either fetching it or creating and persisting it, handling both cache hits and misses efficiently. | def get_or_set_key(self, *args, **kwargs) -> str:
key = self.get_key_from_cache(*args, **kwargs)
if key:
return key
key = self.get_fresh_pem_key()
self.set_key(key, *args, **kwargs)
return key |
def acq_mask_image(self):
if self.hostname in self.instrument_hosts:
pass
else:
print('Not running on permitted host. No action taken.')
def analyze_mask_image(self, filtersize=7):
'''Loop over all slits in the image and using the affine transformation
determined... | The code builds a plugin GUI for handling CSU mask images, featuring buttons for acquisition, analysis, overlay, and bar control, along with input fields and callbacks for user interactions. It organizes controls into frames with flexible layouts, supports orientation adjustments, and manages settings for bar positions... | def build_gui(self, container):
"""
This method is called when the plugin is invoked. It builds the
GUI used by the plugin into the widget layout passed as
``container``.
This method may be called many times as the plugin is opened and
closed for modal operations. The m... |
def print_board():
print('---------')
for i in range(3):
print(f'| {board[i * 3]} | {board[i * 3 + 1]} | {board[i * 3 + 2]}')
print('---------')
def check_winner(player):
# Check rows
for i in range(0, 9, 3):
if board[i] == board[i + 1] == board[i + 2] == player:
retu... | This code implements a Tic-Tac-Toe game where a human player ('O') alternates turns with an AI ('X'). It handles player input, validates moves, checks for a win or tie after each move, and switches turns until the game concludes with a win or draw. | def play_game():
player = 'O'
while True:
print_board()
if player == 'O':
move = int(input("Player O, choose your move (1-9): ")) - 1
if board[move] == ' ':
board[move] = player
if check_winner(player):
print_board()
... |
def smooth_patch_predict(model, image, patch_size, model_preprocessing, smooth, visualize=True):
"""
Predicts on overlapping patches and combines masks using 2D interpolation.
https://github.com/bnsreenu/python_for_microscopists/tree/master/229_smooth_predictions_by_blending_patches
"""
input_imag... | The main task of the code is to predict a segmentation mask from an input image using a pre-trained model (e.g., UNet, PSPNet). It preprocesses the image, loads a model with specified architecture and weights, applies patch-based prediction (with optional smoothing), visualizes the result, and saves the segmented outpu... | def predict_image(img, im_size, weights, arch='unet', backbone='resnet34', train_transfer='imagenet', smooth=False, save_path=None, visualize=True):
"""
Preprocesses image for prediction, loads model with weights and uses model to predict segmentation mask.
"""
BACKBONE = backbone
TRAIN_TRANSFER = t... |
def gaussian_comp_model(phase_center, comps, nu, name = 'Gauss_pointE.cl'):
"""Function that creates a component list to be used with simobserve.
Args:
phase_center:
List or tuple with RA (in hours) and DEC (in degrees) of the phase
center. Example:
phase_center = (15.8, -35.0)
... | The main task of the code is to simulate ALMA observations with atmospheric phase noise, using either a FITS model image or Gaussian components to construct the sky model. It applies phase noise to simulated visibilities, generates output files, and optionally produces plots comparing baseline distributions and visibil... | def simobserve_phase(fconf, pwv, obstime, model_image = None,
phase_center = None, comps = None, nu_comp = None,
mapsize = "", bandwidth = 8, prms_0 = 1.0, nu_scale = None,
integration = '40s', prms_timescale = 1, verbose = False,
plots... |
def _date_format_or_default(date,granularity,boundary):
if date:
date = datetime.strptime(date, "%d/%m/%Y")
else:
if boundary == "start":
# 1000 records up to now (i.e. today - 1000*<granularity>)
multiplier = 1 if granularity == "day" else 7 if granularity == "week" else 30
date = datetime.now() - timed... | This function retrieves financial data for a specified stock ticker within a given date range, using pre-saved CSV files for efficiency. If existing data is incomplete, it fetches missing segments, combines them, and saves the updated dataset. It supports daily, weekly, or monthly granularity, defaulting to the current... | def get_data(ticker, date_from=None, date_to=None, granularity="day", save=True):
"""
Gets data for ticker between chosen date period (date_from defaults to 1000
records before date_to; date_to defaults to now).
Saving collected data improves efficiency for future executions: data will be
taken from saved records... |
def _set_maze_paths(self):
"""Given maze array, return its adjacency list and all paths"""
maze_adjacency_list = self._maze_to_adjacency_list()
all_paths: typing.List[typing.List[Position]] = self.find_all_paths(maze_adjacency_list, self.maze_start)
all_paths_to_exit: typing.List[typing.... | The code initializes a maze based on input parameters. If a numpy array is provided, it directly uses it as the maze. Otherwise, it generates a random maze of the specified shape, adjusting complexity via `difficult_level`. It ensures the maze meets difficulty criteria (e.g., path length, uniqueness) through iterative ... | def __init__(self, shape: typing.Union[int, typing.Tuple, np.ndarray], difficult_level=0, max_init_try=10000):
"""
:param shape: int, tuple of int, numpy array. When given an int or tuple of int, a random maze of the size is
initialized. When given a numpy array, the maze is initialized from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.