dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def wipe_window(window):
""" Removes all elements from the window
PARAMETERS:
window -- the current working window
"""
widget_list = all_children(window)
for item in widget_list:
item.grid_forget()
def create_book_search_results(title):
""" Function to display the results of ... | This function creates a GUI window for book searches, featuring an input field, listbox for dynamic suggestions, and a search button. It binds key releases to update suggestions and double-clicks to handle selections. The search button triggers a results function with sanitized input. | def create_book_search_window():
""" This creates a window for the user to search for a book
There is a button to execute the search"""
wipe_window(window)
book_search_label = Label(window, text="Enter the book to search for", anchor = 'w')
book_search_label.grid(row=0, column=0)
# Creates... |
def wipe_window(window):
""" Removes all elements from the window
PARAMETERS:
window -- the current working window
"""
widget_list = all_children(window)
for item in widget_list:
item.grid_forget()
def create_checkout_book_results(member_id, book_ids):
""" Used to display the... | This function creates a GUI window for checking out books by providing input fields for book IDs (comma-separated) and member ID, along with a "Checkout" button. It clears the window, adds labels and entry widgets for user input, and links the button to a function that processes the inputs to initiate the checkout proc... | def create_checkout_book_window():
""" This creates a window to for a user to checkout the book required"""
wipe_window(window)
# Wiping the window as required
checkout_book_label = Label(window, text="Enter Book ID's (seperated by comma)", anchor='w')
checkout_book_label.grid(row=0, column=0)
... |
def wipe_window(window):
""" Removes all elements from the window
PARAMETERS:
window -- the current working window
"""
widget_list = all_children(window)
for item in widget_list:
item.grid_forget()
def create_return_book_results(book_ids):
""" Used to display the results of w... | The main task of the code is to create a GUI window for returning books, displaying a label and input field for book IDs, and triggering a return process via a button that passes user input to a processing function. | def create_return_book_window():
""" Used to create the return books window and get associated info and pass
it to the return books module"""
wipe_window(window)
# Wiping the window as required
return_book_label = Label(window, text="Enter Book ID's", anchor='w')
return_book_label.grid(row... |
def initialize_model_with_example(example, hparam_set, add_hparams, model_name, ckpt_dir):
"""Returns an initialized model and hparams using our trained t2t data."""
tf.reset_default_graph()
# create hparams and get glyphazzn problem definition
# we don't need to add data_dir=data_dir
hparams ... | This function decodes input examples for each class using a trained model, generating SVG or bitmap outputs. It initializes the model, processes features, tiles class-specific bottlenecks, runs inference, and renders results. The output is a list of decoded glyphs/images for all classes, conditioned on the input exampl... | def infer(example, hparam_set, add_hparams, model_name, ckpt_dir, out='svg', bitmap_depth=8, bitmap_contrast=1, bitmap_fill=False):
"""Decodes one example of each class, conditioned on the example."""
# initialize with t2t data
# model, hparams = initialize_model_with_t2t(hparam_set, add_hparams, model_nam... |
def infer(example, hparam_set, add_hparams, model_name, ckpt_dir, out='svg', bitmap_depth=8, bitmap_contrast=1, bitmap_fill=False):
"""Decodes one example of each class, conditioned on the example."""
# initialize with t2t data
# model, hparams = initialize_model_with_t2t(hparam_set, add_hparams, model_nam... | This function processes an SVG input to generate inferred SVG glyphs using a specified model. It retrieves the SVG from HTTP requests, validates input, configures model paths, executes inference with 'generate_t2t_example', processes results to normalize coordinates, composes SVG elements, and returns outputs as JSON o... | def infer_svg_from_svg(modelname, modelsuffix, glyph):
# sample:
# http://127.0.0.1:5959/api/infer/svg/models-google/external/U?json=False&svg=%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20width%3D%2250px%22%20height%3D%2250px%22%20... |
def infer_from_file(example_file, hparam_set, add_hparams, model_name, ckpt_dir, out='svg', bitmap_depth=8, bitmap_contrast=1, bitmap_fill=False):
""" Load, decode and infer our example """
# https://www.tensorflow.org/tutorials/load_data/tfrecord
raw_dataset = tf.data.TFRecordDataset([ os.fspath(examp... | This function processes a font glyph by auto-tracing its bitmap using a specified model, generating SVG path data. It handles input parameters, performs image inference, converts bitmaps to SVGs via FontForge, extracts path coordinates, and returns the result as JSON or plain text. The process includes temporary file h... | def infer_autotrace_from_font(modelname, modelsuffix, fontname, glyph):
# sample:
# http://127.0.0.1:5959/api/infer/bitmap/models-google/external/Unica/A?json=False
use_json = request.args.get('json', default='true').lower() == 'true'
bitmap_depth = 1 # bitmap_depth is always 1
bitmap_cont... |
def infer_from_file(example_file, hparam_set, add_hparams, model_name, ckpt_dir, out='svg', bitmap_depth=8, bitmap_contrast=1, bitmap_fill=False):
""" Load, decode and infer our example """
# https://www.tensorflow.org/tutorials/load_data/tfrecord
raw_dataset = tf.data.TFRecordDataset([ os.fspath(examp... | The code generates SVG representations of a specified glyph from a font using a machine learning model. It processes input paths, configures model parameters, infers SVG data, normalizes glyph dimensions, composes SVGs, and returns results as plain text or JSON based on the request. | def infer_svg_from_font(modelname, modelsuffix, fontname, glyph):
# sample:
# http://127.0.0.1:5959/api/infer/svg/models-google/external/Unica/A?json=False
use_json = request.args.get('json', default='true').lower() == 'true'
modelbasepath = basepath/modelname
modelsuffix = '' if modelsuf... |
def NormSpecClust(X, n, k, eps, Random, max_iter):
# Algorithm 3 The Normalized Spectral Clustering Algorithm'
# returns an array where the i'th variable corresponds to X[i]'s cluster
# also returns the value k (needed if Random is set to 'True' and the value is recalculated)
L_norm = calcLnorm(X) #... | The main task of the code is to perform spectral and K-means clustering on synthetic data, generating output files and visualizations. It parses command-line arguments for cluster count (K), data points (N), and randomness. The code creates 2D/3D data, applies NormSpecClust and K-means clustering, saves results in txt ... | def main():
"""
The main function of the program,
assigns clusters to points using k_means_pp and NormSpecClust functions
generates output txt files using 'generate_output_files' function
generates pdf file using 'visualize' function.
"""
my_parser = argparse.ArgumentParser(description='k-mean ... |
def __bfs__(root):
# start the timer
start_time = time.time()
# create a set for the explored and a queue containing the frontier states
global nodesExpanded, maxDepth, isFound, runTime
__reset__()
explored = set()
frontier = Queue()
frontier.put(root)
expanded = set()
expanded.a... | The code's main task is to solve a game or puzzle using a specified algorithm (BFS, DFS, or A* with Manhattan/Euclidean heuristics) on a given game state. It selects the appropriate search algorithm, executes it, and returns the solution if found. If no solution is found, it returns `None`. The function acts as a dispa... | def solve(gameState, algorithm):
answer = None
if algorithm == 'BFS':
answer = __bfs__(gameState)
elif algorithm == 'DFS':
answer = __dfs__(gameState)
elif algorithm == 'A* Manhattan':
answer = __aStar__(gameState)
elif algorithm == 'A* Euclid':
answer = __aStar__(gam... |
def as_mesh(scene_or_mesh):
if isinstance(scene_or_mesh, trimesh.Scene):
mesh = trimesh.util.concatenate([
trimesh.Trimesh(vertices=m.vertices, faces=m.faces)
for m in scene_or_mesh.geometry.values()])
else:
mesh = scene_or_mesh
return mesh
def example_deformations(re... | The code loads and processes 3D mesh data from two directories (face1 and face2), computes deformations between reference and posed meshes, applies KMeans clustering to identify patches, encodes/decodes mesh coordinates, and returns a modified mesh with interpolated vertex positions. It involves mesh deformation analys... | def load_meshes(projind,path1="face1", path2="face2",n_poses=10):
'''
Load each mesh and store in an array
'''
global num_patches
meshes = []
rest = as_mesh(trimesh.load_mesh(os.path.join(path1,f"{path1}-reference.obj")))
rest.merge_vertices(merge_tex=True, merge_norm=True)
for i in rang... |
def example_deformations(rest, poses):
'''
Computes deformation gradients between a rest pose and
several input poses. Used to learn similar deformation gradients
for creating patches.
'''
Ds = np.zeros((len(poses), rest.faces.shape[0], 3, 3))
for ind, pose in enumerate(poses):
Di = ... | The code generates an animation by deforming a 3D mesh between poses using deformation analysis, clustering, and interpolation. It loads reference and pose meshes, computes deformation matrices, clusters patches via KMeans, encodes/decodes mesh coordinates, and interpolates vertices to create a blended mesh between pos... | def make_animation():
global num_patches
meshes = []
rest = trimesh.load_mesh("/Users/lucafonstad/Downloads/final-project 3/head-poses/head-reference.obj")
rest.merge_vertices(merge_tex=True, merge_norm=True)
print(len(rest.vertices))
pose = trimesh.load_mesh("/Users/lucafonstad/Downloads/f... |
def as_mesh(scene_or_mesh):
if isinstance(scene_or_mesh, trimesh.Scene):
mesh = trimesh.util.concatenate([
trimesh.Trimesh(vertices=m.vertices, faces=m.faces)
for m in scene_or_mesh.geometry.values()])
else:
mesh = scene_or_mesh
return mesh
def example_deformations(re... | The code interpolates between 3D mesh poses by loading reference and deformed meshes, computing deformation fields, clustering patches via KMeans, encoding mesh coordinates, and interpolating between encoded states using patch adjacencies to generate smooth transitions between poses. | def run_interpolation():
'''
Input meshes and interpolate between them!
'''
global num_patches
meshes = []
rest = as_mesh(trimesh.load_mesh("lion/lion-reference.obj"))
rest.merge_vertices(merge_tex=True, merge_norm=True)
print(len(rest.vertices))
pose = as_mesh(trimesh.load_mesh... |
def _get_instance(self, tile_file):
if self.unzip:
with zipfile.ZipFile(tile_file, 'r') as zip_ref:
zip_ref.extractall(os.path.dirname(tile_file))
tile_file = tile_file.split('.')[0] + ".pickle"
with open(tile_file, 'rb') as handle:
... | The code processes tile files for instance registration by filtering instances using detection and segmentation thresholds, performing contour analysis on masks, converting local masks to global coordinates, and registering instances either directly or via a method. It tracks processing time and memory usage, saves rem... | def start_registration(self, continue_regitration=False):
updated_tile_files = []
timestamps = []
memories = []
self.instances = []
self.tiles = {}
print("Instance registration: ")
if continue_regitration:
twin_file = self.save_shapefile[:-4] + "_twins... |
def value(self):
if self.way == 'c':
return self.S * np.exp(-self.q * self.T) * norm.cdf(self.d1(), 0, 1) - self.K * np.exp(-self.r * self.T) * norm.cdf(self.d2(), 0, 1)
elif self.way == 'p':
return self.K * np.exp(-self.r * self.T) * norm.cdf(-self.d2(), 0, 1) - self.S * np.exp(... | The main task of the code is to generate a formatted string containing six financial derivative metrics: value, delta, gamma, vega, rho, and theta. The method calls six instance methods (value(), delta(), etc.) on 'self' to compute these values and concatenates them into a single string with labels. This provides a con... | def compute_all(self):
return f"value: {self.value()}, delta: {self.delta()}, gamma: {self.gamma()}, vega: {self.vega()}, rho: {self.rho()}, theta: {self.theta()}" |
def gini(data, label_field):
"""Calculate chance of guessing the wrong label"""
data_len = len(data)
label_count = count_label(data, label_field)
impurity = 1
for label in label_count:
probability = label_count[label] / data_len
impurity -= probability**2
return impurity
def question(field, val)... | This function identifies the optimal question (feature-value split) to partition data by maximizing information gain, using Gini impurity as a measure of uncertainty. It iterates through all possible features and their unique values, evaluates each potential split's information gain, and returns the split with the high... | def calculate_best_partition(data, label_field, log=False, log_spacing=50, log_pad=''):
"""Find best question to ask"""
best_gain = 0
best_q = None
uncertainty = gini(data, label_field)
# All possible fields
fields = [ x for x in data[0] if x != label_field ]
# Calculate amount of iterations
unique =... |
def calculate_best_partition(data, label_field, log=False, log_spacing=50, log_pad=''):
"""Find best question to ask"""
best_gain = 0
best_q = None
uncertainty = gini(data, label_field)
# All possible fields
fields = [ x for x in data[0] if x != label_field ]
# Calculate amount of iterations
unique =... | This function recursively builds a decision tree by selecting the best partitioning question, splitting the data into true/false branches, and returning a tree structure with questions and child nodes. It uses log parameters for debugging and handles terminal nodes by counting labels when no further splits improve gain... | def build_tree(data, label_field, log=False, level=0):
pad = "{pad}{level} ".format(pad=' '*level, level=level)
gain, q = calculate_best_partition(data, label_field, log=log, log_pad=pad)
if log: print(pad+"Question done")
if gain == 0:
if log: print(pad+"End node")
# return data
return count_labe... |
def _setup_tokenizer(self):
self.dataset_manager.tokenizer = create_tokenizer(
self.model_args,
**self.dataset_manager.get_tokenizer_config_kwargs(),
)
def _init_notifiers(self, num_runs=1):
# notifier_name should not start with a numeric char
if isinstance(self.i... | The main task of the code is to execute a setup process involving dataset loading, model training/evaluation, and handling multiple random restarts. It initializes tokenizers, processes datasets, runs trials with specified seeds, aggregates results, and optionally generates evaluation statistics. The function returns a... | def run(self, first_run_index=0):
"""
Run this setup. Dataset, model, and training or evaluation are expected to be set.
Args:
first_run_index (int, optional): The start index in the sequence of random restarts. Defaults to 0.
Returns:
dict: A dictionary of run ... |
def _setup_tokenizer(self):
self.dataset_manager.tokenizer = create_tokenizer(
self.model_args,
**self.dataset_manager.get_tokenizer_config_kwargs(),
)
def _init_notifiers(self, num_runs=1):
# notifier_name should not start with a numeric char
if isinstance(self.i... | The main task of the code is to resume a machine learning setup by loading a prior run state from a file, continuing trials with stored restarts, initializing notifiers, and returning aggregated results including random seeds and evaluations. It processes trials starting from the last executed index, optionally adding ... | def resume(self, file, add_restarts=None):
"""
Resume running this setup from a given run state.
Args:
file (str): The run state file to load.
Returns:
dict: A dictionary of run results containing the used random seeds and (optionally) evaluation results.
... |
def get_rank_dictionary(self):
rank_dictionary = {}
for i in self.hand:
if i.get_rank_name() not in rank_dictionary:
rank_dictionary[i.get_rank_name()] = 1
else:
rank_dictionary[i.get_rank_name()] += 1
return rank_dictionary
def get_hand_type(self):
if self.hand == []:
... | This code evaluates a poker hand's type and determines its strength by sorting the hand, identifying its category (e.g., straight, flush, pairs), and invoking specific evaluation methods for each type. It uses a "dirty" flag to avoid redundant evaluations, then updates the hand's rank and classification based on the de... | def evaluate_hand(self):
if not self.dirty:
return
self.hand.sort()
self.rank_dictionary = self.get_rank_dictionary()
self.hand_type = self.get_hand_type()
if self.hand_type == "Straight flush" or self.hand_type == "Straight":
self.__evaluate_straight()
elif self.hand_typ... |
def evaluate_hand(self):
if not self.dirty:
return
self.hand.sort()
self.rank_dictionary = self.get_rank_dictionary()
self.hand_type = self.get_hand_type()
if self.hand_type == "Straight flush" or self.hand_type == "Straight":
self.__evaluate_straight()
elif self.hand_typ... | This code defines the less-than operator for comparing two hands. It evaluates both hands, compares their types, and returns whether the current hand's type strength is less than the other's. If types match, it delegates to a helper method for same-type comparison. | def __lt__(self, other):
self.evaluate_hand()
other.evaluate_hand()
if self.hand_type != other.hand_type:
return self.hand_type_to_strength() < other.hand_type_to_strength()
else:
return self.__is_same_type_lt(other) |
def greet(intent_request):
session_attributes = get_session_attributes(intent_request)
text = "Hello there! What can I help you with today?"
message = {
'contentType': 'PlainText',
'content': text
}
fulfillment_state = "Fulfilled"
return close(intent_request, session_attributes, ... | The code defines a `dispatch` function that routes user intents to corresponding handlers. It extracts the intent name from the request and calls `greet`, `thank`, or `suggest` functions based on the intent. If the intent is unsupported, it raises an exception. The main task is to dispatch user intents to appropriate p... | def dispatch(intent_request):
"""
Called when the user specifies an intent for this bot.
"""
intent_name = intent_request['sessionState']['intent']['name']
# Dispatch to your bot's intent handlers
if intent_name == 'GreetingIntent':
return greet(intent_request)
elif intent_name == '... |
def apply_level(self, level):
self.apply_class(self.classes[level])
self.apply_feats(self.feats[level])
def calc_modifiers(stats):
return {k: (v - 10) // 2 for k, v in stats.items()}
def get_proficiency(level):
return ((level - 1) // 4) + 2
def calc_spell_slots(class_levels):
spell_level = 0... | This function initializes a character's attributes based on their level, setting up stats, attacks, spells, and modifiers. It calculates HP, proficiency, spell slots, and configures melee/ranged attacks, including special abilities like PAM. The character is returned with all computed properties for gameplay use. | def sample_at_level(self, level, name=""):
self.attackmodifiers = []
self.mirrorimages = []
self.binary_feats = defaultdict(lambda: 0)
self.spells = []
self.class_levels = defaultdict(lambda: 0)
self.attacks = 1
self.max_hps = 0
self.stats = self.starting... |
def feed_forward(self, data):
L = self.L
self.A[0] = data.dot(self.layers[0].weights)
self.X[0] = self.layers[0].activation_function(self.A[0])
for l in range(1, L):
self.A[l] = self.X[l-1].dot(self.layers[l].weights)
if (l < L-1):
self.X[l] = self... | The code implements gradient descent optimization for training a neural network. It iteratively performs forward propagation, backpropagation, and weight updates using a specified learning rate. The process runs for a given number of iterations (nIter), periodically evaluating training/test precision, calculating error... | def gradient_descent(self, learning_rate, nIter, data_train,
label_train, data_test, label_test):
cont = 0
self.feed_forward(data_train)
while (cont < nIter):
print("Iteracion: ", cont)
cont += 1
self.back_propagate()
self.... |
def obtain_y(X, weights_capa1):
return relu_mod_v(X.dot(weights_capa1))
def obtain_z(Y, weights_capa2):
return sigmoid_v(Y.dot(weights_capa2))
def obtain_Ekt(label_v, Z):
return Z - label_v
def print_precision(weights_capa1, weights_capa2):
aciertos = 0
for k0 in range(len(fotos_test)):
if (... | The main task of the code is to train a two-layer neural network using gradient descent. It initializes weights with He initialization, computes forward passes (Y, Z), calculates errors (Ekt), and iteratively updates weights (weights_capa1, weights_capa2) to minimize the error. The loop prints training progress, includ... | def main():
np.random.seed(2)
weights_capa1 = np.sqrt(2 / N0) * np.random.rand(N0, N1) # [i, j]
weights_capa2 = np.sqrt(2 / N1) * np.random.rand(N1, 10) # [j, t]
Y = obtain_y(X, weights_capa1)
Y[:, -1] = 1
Z = obtain_z(Y, weights_capa2)
Ekt = obtain_Ekt(label_v, Z)
eps = 1e-4
n_ite... |
def _create_title(self):
title = self.title()
bg_image = asset_manager.get(self.background_image())
title_style = {
'background-image': f'url("{bg_image}")',
'background-size': 'cover',
'color': 'white',
'padding': '1rem'
} if bg_image else... | The main task of the code is to generate an HTML Div container that combines three components: a title, tabs, and a tabs content container. The method `_create` assembles these elements into a structured layout, likely for a Dash/Plotly web interface, by calling three internal methods to build the UI hierarchy. | def _create(self):
return html.Div([self._create_title(),
self._create_tabs(),
self._create_tabs_container()]) |
def createCategoriesLayout(self) :
# Create tab, form and scroll layouts.
tabLayout = cmds.tabLayout(innerMarginWidth=5, innerMarginHeight=15, borderStyle="full")
formLayout = cmds.formLayout(numberOfDivisions=100)
scrollLayout = cmds.scrollLayout(backgroundColor=self.backgroundColor,
... | The code creates a material browser UI window in Maya, removing any existing instance. It sets up a vertical 3-pane layout for categories, materials, and selected items, adjusts pane sizes, initializes UI sections, selects the first category/material, and displays the window. The layout is then initialized for interact... | def createLayout(self) :
# Delete any existing window.
if (cmds.window("RPRMaterialBrowserWindow", exists = True)) :
cmds.deleteUI("RPRMaterialBrowserWindow")
# Create a new window.
self.window = cmds.window("RPRMaterialBrowserWindow",
widt... |
def checkWin(start,goal,size):
for i in start[0]:
if i == 'b':
if goal == 'b':
return size
else:
return -size
length = len(start)
for i in start[length-1]:
if i == 'w':
if goal == 'w':
return size
... | This function evaluates the score of a game state using a minimax algorithm with alpha-beta pruning. It checks for terminal states, alternates between MIN/MAX modes based on the layer depth, generates new states, and recursively evaluates scores. The result is the optimal value for the current player, considering the s... | def scoreVal(start,size,goal,searchAhead,layer):
a = checkWin(start,goal,size)
if a != False:
return a
result_val = 0
if layer % 2 == 1:
mode = "MIN"
else:
mode = "MAX"
new_states = generateNew(start,size,goal,mode)
if layer >= (searchAhead-1):
if new_states =... |
def hexagame(start):
arr = []
for i in range(len(start)):
arr.append(list(start[i]))
return arr
def checkWin(start,goal,size):
for i in start[0]:
if i == 'b':
if goal == 'b':
return size
else:
return -size
length = len(start)
... | This code implements a minimax-based algorithm for the Hexapawn game, evaluating possible moves up to a specified search depth. It starts with an initial game state, checks for immediate wins, generates next moves for the MAX player, scores each move recursively, sorts them, and returns the optimal move as a formatted ... | def hexapawn(input,size,goal,searchAhead):
start = hexagame(input)
a = checkWin(start,goal,size)
if a is True:
return start
layer = 1
nextMoves = generateNew(start,size,goal,"MAX")
if nextMoves == []:
return start
values = []
for s in nextMoves:
val = scoreVa... |
def readData() -> DataFrame:
"""
Reads the csv data and the world data and returns them as a DataFrame
"""
df = pd.read_csv('requests_per_country.csv', encoding='utf-8',
engine='python', on_bad_lines='warn', na_filter=False)
world = gpd.read_file(gpd.datasets.get_path('naturale... | The code generates an interactive choropleth map visualizing Wikipedia request data per country over time. It reads and cleans dataset, segments data by date, creates slider controls for temporal navigation, configures a global map layout with natural earth projection, and exports the visualization as an HTML file for ... | def main():
# reads tha data in
df, world = readData()
# cleans the data and filters off bad countries
df = cleanData(df, world)
dataSlider = getAllDatesData(df)
# put data for each date in its own segment.
steps = getSliderSteps(dataSlider)
sliders = [dict(active=0, pad={"t": 1}, steps=... |
def parse_arguments():
parser = argparse.ArgumentParser(
description='Secret Santa Mailer')
parser.add_argument('--official',
dest='official',
action='store_true',
help='Officially send out all the secret santa emails')
parser.add_argument('--send-test-email',
... | The code's main task is to configure and execute a Secret Santa gift exchange system. It reads email and SMTP settings from a config file, creates gift-giver pairs while avoiding incompatibilities, and sends assignment emails. It supports testing via a dry run or sending actual emails based on command-line arguments, u... | def main():
args = parse_arguments()
config = read_config('config.py')
mailer = Mailer(
from_name=config['email_template']['from_name'],
from_email=config['email_template']['from_email'],
subject=config['email_template']['subject'],
body=config['email_template']['body'],
... |
def ensure_result(obj, *objs):
"""Convert Job or Results to Results.
Can pass either a single Job or Result argument, multiple Job or Result arguments, or an iterable of Job
or Results. Jobs will be waited on to retrieve their results.
Returns:
If a single argument is passed, a single Result i... | The main task of the code is to convert Qiskit Result objects (or Jobs) into a pandas DataFrame or Series, handling multiple results by concatenating them. It processes metadata, subcircuits, and filters extraneous data, returning a structured data format for analysis. | def resultdf(
result: Union[ResultLike, Iterable[ResultLike]],
*results: ResultLike, # type: ignore
subcircuits: Optional[bool] = None,
metadata=True,
drop_extraneous=True,
**kwargs,
) -> Union[pd.Series, pd.DataFrame]:
"""Convert a qiskit Result (or many Results) in... |
def noise_reduction(y: np.ndarray, sr: int) -> np.ndarray:
"""
Reduces noise in the user's audio recording.
Reasoning:
User recordings might have ambient noises. Reducing noise can lead to
better evaluation results.
"""
return nr.reduce_noise(y=y, sr=sr)
def calculate_pitch(y: np.ndarray, ... | The function evaluates user audio performance against an app's audio by calculating accuracy (pitch comparison), timing (onset alignment), and fluency, then averaging these scores. It resamples audio to 44.1kHz, reduces user noise, extracts pitches, detects onsets, and computes weighted metrics for overall performance ... | def basic_feat_sim(path_to_user_audio: str, path_to_app_audio: str) -> float:
"""
Main evaluation function that computes a score for user's performance based on app's audio.
"""
user_y, user_sr = librosa.load(path_to_user_audio, sr=None)
app_y, app_sr = librosa.load(path_to_app_audio, sr=None)
... |
def transfer_matrix(A, O=None, optimize=False, flattened_output=False):
'''Compute the transfer matrix of a given tensor
Input:
A - tensor
This is either a rank-3 tensor A[i,j,k], where i is the physical index and j and k are the virtual indices,
or a higher-rank tensor A[...,i,j,k... | The main task of the code is to compute correlation functions from input tensors. It calculates 1-point and connected 2-point correlation functions using transfer matrices, eigenvectors, and insertion operators. The output is an array of correlations for each sample, combining results from all tensor indices and distan... | def convert_tensors_to_correlations(self, A):
'''Convert tensors to correlations
Input:
self
A - tensors, ndarray of shape (n_samples, d, chi, chi)
Output:
cor - correlations, ndarray of shape (n_samples, N_correlations)
... |
def extract_paragrah_layouts(pdf_path, dpi=DPI, model=None):
if model is None:
model = load_model()
pdf_layouts, pdf_images = lp.load_pdf(pdf_path, load_images=True, dpi=DPI)
paragraph_layouts = []
for page_layout, page_image in zip(pdf_layouts, pdf_images):
model_layout = model.detect(... | The function translates text in a PDF document by extracting paragraph layouts, translating the text (via local processing or an API with an auth key), and merging the translated content back into the original PDF. Optional JSON files storing layouts are saved if `keep_auxiliary` is True. | def parse_translate_merge(
input_pdf,
local=False,
auth_key=None,
keep_auxiliary=False,
):
input_path = Path(input_pdf)
layouts = extract_paragrah_layouts(input_pdf)
if keep_auxiliary:
save_layout_json(
layouts,
input_path.with_name(f"{input_path.stem}_layout_... |
def fillSadhanaCard():
openAnyChrome('Shubham')
sleep(1)
chrNewTab('https://docs.google.com/spreadsheets/d/1E-PXwdOztF2fu6tiU-k8QXbSkhJMZ9fJQoQmMPRknek/edit#gid=308003546')
def chrNewTab(link):
pg.hotkey("command", "t")
pyperclip.copy(link)
paste()
pg.press("enter")
def spectackleDisUnable()... | The main task of the code is to automate filling a Sadhana card form, open a new Chrome tab to Gmail inbox, wait briefly, and then disable or handle a spectacle display issue, likely for a structured daily routine or task automation workflow. | def mailSadhanaCard():
fillSadhanaCard()
chrNewTab('https://mail.google.com/mail/u/0/#inbox')
sleep(1)
spectackleDisUnable() |
def case1_sample_keep_species_in_db(args):
db_fasta_abspath = os.path.abspath(args.input_fasta)
train_fasta_abspath = os.path.abspath(args.output_dir+"/train.fasta")
df = pd.read_csv(args.input_taxfile, sep="\t", index_col=0)
df.index.name="seqid"
sys.stderr.write(f"Read {df.shape[0]} records from {... | The main task of the code is to route processing based on the input case argument, executing different taxonomic data-handling strategies: retaining species, removing duplicates, or pruning higher taxonomic ranks (genus, family) while preserving lower levels. It acts as a dispatcher for five distinct data-processing wo... | def main(args):
if args.case == "1":
case1_sample_keep_species_in_db(args)
elif args.case == "2":
case2_sample_keep_species_remove_identical(args)
elif args.case == "3":
case3_remove_species_keep_genus(args)
elif args.case == "4":
case4_remove_genus_keep_family(args)
... |
def Support(params):
b = params[2]
rc = params[4]
rt = params[5]
rtb = params[6]
if rc <= 0.0 : return False
if rt <= rc : return False
if b <= 0.0 : return False
if rtb <= 0 : return False
if rtb <= b : return False
return True
def LikeRadious(r,params):
return np.piece... | The code computes the log-likelihood of a model describing the distribution of data points (likely astronomical sources) based on parameters defining their radial and angular distribution. It checks parameter validity, calculates transformed coordinates, computes expected radii and angles using modified parameters, eva... | def LogLike(self,params,ndim,nparams):
#----- Checks if parameters' values are in the ranges
if not Support(params):
return -1e50
#============== Obtains radii and pa ===================
a0, d0, b, delta, a, rta, rtb = params[0],params[1],params[2],params[3],params[4], para... |
def Support(rc):
if rc <= 0 : return -np.inf
def logPriors(rc,hyper):
lp_rc = halfcauchy.logpdf(rc,loc=0,scale=hyper[0])
return lp_rc
def logLikeStar(r,p,rc,Rmax):
return np.log(p*LikeCluster(r,rc,Rmax)) | This function computes the log-posterior probability of a parameter `rc` given data and hyperparameters. It checks if `rc` is within valid bounds, calculates the prior probability using `logPriors`, and computes the likelihood for each data point using `logLikeStar`. The total log-posterior is the sum of the log-likeli... | def LogPosterior(params,r,pro,Rmax,hyper):
rc = params[0]
#----- Checks if parameters' values are in the ranges
supp = Support(rc)
if supp == -np.inf :
return -np.inf
# ----- Computes Priors ---------
lprior = logPriors(rc,hyper)
# ----- Computes Likelihoods ---------
llike =... |
def FK_spatial(self, ef_loc, joint_loc, joint_axes, joint_type, joint_angles,
display=False, frame="space", frame_number=0):
n_joints = len(joint_type)
screw_axes = np.zeros([6,n_joints], dtype=float)
# First we want to calculate the screw axes:
for i in range(n_joints):
... | This function performs inverse kinematics (IK) for a robotic arm by iteratively adjusting joint angles to reach a target end-effector pose. It calculates the error between the current and desired positions/orientations, computes the Jacobian matrix, and updates joint angles using the pseudo-inverse of the Jacobian. The... | def J_inverse_kinematics(self, ef_loc, joint_loc, joint_loc_b, joint_axes,
joint_type, T_sd, angle_guess, max_iter=20, epsW=0.001, epsV=0.0001, display=False):
angles_matrix = []
angles_matrix.append(angle_guess)
i = 0
while i < max_iter:
current_angles = angles_ma... |
def FK_spatial(self, ef_loc, joint_loc, joint_axes, joint_type, joint_angles,
display=False, frame="space", frame_number=0):
n_joints = len(joint_type)
screw_axes = np.zeros([6,n_joints], dtype=float)
# First we want to calculate the screw axes:
for i in range(n_joints):
if joint_type[i] == 0:
v_i... | This function performs inverse kinematics using an iterative numerical method to compute joint angles that position the end-effector at a desired location. It calculates forward kinematics, computes orientation/position errors, constructs the body Jacobian, and updates joint angles via pseudo-inverse of the Jacobian un... | def J_inverse_kinematics(self, ef_loc, joint_loc, joint_loc_b, joint_axes,
joint_type, T_sd, angle_guess, max_iter=20, epsW=0.001, epsV=0.0001, display=False):
angles_matrix = []
angles_matrix.append(angle_guess)
i = 0
while i < max_iter:
current_angles = angles_matrix[i]
print(angle_guess)
if ... |
def makeTetrahedronWellMatrix (n, inW, outW):
well_matrix = np.empty((n, n, n))
tetr = tetrahedron(n - 20, (0, 0, 0))
#00100
#01110
#00100
for i in range(0, n):
for j in range(0, n):
for k in range(0, n):
if PointInTetrahedron(tetr, (i, j, k)):
... | The code computes the eigenvalues and eigenvectors of a 3D potential using a tetrahedral mesh, extracts the squared magnitude of a specific eigenvector, converts it into a 3D point cloud, and visualizes the result using Open3D. The main task is to generate and visualize the spatial distribution of a selected eigenstate... | def run():
print('start')
level_to_show = 11
Elevels = 25
N = 50
#mesh = makeSphereWellMatrix(N, 1, 0)
mesh = makeTetrahedronWellMatrix(N, 1, 0)
e_values, e_vec = general_potential_3d(mesh, N, Elevels)
if 1:
np.save('data_E_vectors_Tetrahedron' + str(N) +'x'+ str(N)... |
def _update_snake_bits_positions(self):
"""Updates the position of all snake bits."""
self._update_bits_coords()
self._update_rect_bits()
def _store_snake_head_pos(self):
"""Stores the position of the snake's head after all bits have been updated."""
self.pozitii['x'][0] = self.s... | The main task of the code is to update the snake's position and state on the screen. It updates the snake's head, adjusts the positions of its body segments, stores the head's position, updates the entire snake, and checks for collisions involving the head. This ensures smooth movement and collision detection in a snak... | def _update_snake(self):
"""Updates the snake on the screen"""
self.snake_head.update()
self._update_snake_bits_positions()
self._store_snake_head_pos()
self.snake.update()
self._check_snake_head_collisions() |
def deserialize_bitset(network: Network, alignment: dict, field: Field):
return f"{casts(network, field)}(int({bitset_unpack(alignment, field)}))"
def deserialize_without_shift(network: Network, alignment: dict, field: Field):
return f'{casts(network, field)}(unpack("{unpack_schema(alignment, field.name)}", dat... | This function deserializes a message's fields into a dictionary by applying different deserialization methods based on field type and shift value. It processes each field using either deserialize_bitset, deserialize_without_shift, or deserialize_with_shift, determined by the field's type and shift attribute, and return... | def deserialize(network: Network, message: Message):
result = {}
for field in message.fields:
alignment = message.alignment
if isinstance(field.type, BitSet):
result[field.name] = deserialize_bitset(network, alignment, field)
elif field.shift == 0:
result[field.n... |
def isHangar(self): # Find if in Hangar 1
x = findInAnAreaPos('Scripts/Images/Hangar/Hangar_UNDOCK.png')
self.positionUndock = x
if x[0] != -1:
self.isInHangar = True
self.inField = False
self.inSpace = False
del x
return self.isIn... | The code checks the ship's position, inventories, and environment (Hangar/Space/Field), initiating actions like selling items in the Hangar, warping to an asteroid belt in Space, or docking at a station in the Field based on inventory status and location. It also recursively rechecks position after actions. | def checkPosition(self):
print('Sleeping 10 second')
py.sleep(10)
print('Checking Position')
self.inventory.checkInventory()
print('Inventory Checked: Inventory open is {0} and Inventory'
' Full is {1}'.format(self.inventory.isOpen, self.inventory.isFull))
s... |
def _get_content(message: m.Message) -> bytes | None:
"""Get the content of the file from the message.
Args:
message: The message containing the file content.
Returns:
The content of the file.
"""
content = message.data.get("content")
if content is not None:
casted_conten... | The code processes a file message by extracting content and path, checking for non-empty content, determining the file type, skipping blacklisted types, scanning supported OSV files for vulnerabilities, parsing results, and emitting vulnerabilities if found. | def _process_asset(self, message: m.Message) -> None:
"""Process message of type v3.asset.file."""
content = _get_content(message)
path = _get_path(message)
if content is None or content == b"":
logger.warning("Message file content is empty.")
return
file_... |
def interpretDeclare(self, node):
for child in node.getChildren():
if node.getNodeType() is NodeType.TERM:
self.interpretTerm(child)
def interpretAssignment(self, node):
for child in node.getChildren():
if node.getNodeType() is NodeType.TERM:
self.... | The main task of the code is to interpret a parsed SCL file by processing its syntax tree. It iterates through the root node's children, invoking specific methods like `interpretDeclare`, `interpretAssignment`, `interpretIf`, and `interpretWhile` based on node types. PRINT_METHOD nodes are currently unhandled. The func... | def interpret(self):
print("Parsing SCL File", "\n")
parseTree = super().parse()
print("\nFinished Parsing File")
print("="*50, "\n")
# Iterate through all of <program> node's direct children
for node in parseTree.getRoot().getChildren():
if Node.getNodeType(... |
def modPrint(self, txt):
print(str(txt))
self.printLines.append(str(txt))
def parseFactor(self, node):
factorNode = Node(node, self.scanLines[self.currentLineNum], NodeType.FACTOR)
node.addChildNode(factorNode)
self.modPrint(" " + "\t" * node.getDepth() + "Parsing " + str(factorN... | The main task of the code is to parse a "term" node by processing an initial factor, then repeatedly parsing additional factors connected by multiplicative operators (* or /) while validating syntax structure, adding child nodes to the term, and handling errors for missing factors or invalid tokens. | def parseTerm(self, node):
termNode = Node(node, self.scanLines[self.currentLineNum], NodeType.TERM)
node.addChildNode(termNode)
self.modPrint(" " + "\t" * node.getDepth() + "Parsing " + str(termNode.getNodeType().value))
self.parseFactor(termNode)
if len(termNode.getChildren())... |
def modPrint(self, txt):
print(str(txt))
self.printLines.append(str(txt))
def parseTerm(self, node):
termNode = Node(node, self.scanLines[self.currentLineNum], NodeType.TERM)
node.addChildNode(termNode)
self.modPrint(" " + "\t" * node.getDepth() + "Parsing " + str(termNode.getNod... | This code parses an expression node by creating an EXPR node, parsing a term, and optionally additional terms based on the current token's value. It validates the structure, handles errors, and updates the node hierarchy, returning True on success or False with error messages on failure. | def parseExpr(self, node):
exprNode = Node(node, self.scanLines[self.currentLineNum], NodeType.EXPR)
node.addChildNode(exprNode)
self.modPrint(" " + "\t" * node.getDepth() + "Parsing " + str(exprNode.getNodeType().value))
self.parseTerm(exprNode)
if len(exprNode.getChildren()) =... |
def modPrint(self, txt):
print(str(txt))
self.printLines.append(str(txt))
def nextToken(self):
self.currentToken = self.nextLexeme().getToken()
def parseExpr(self, node):
exprNode = Node(node, self.scanLines[self.currentLineNum], NodeType.EXPR)
node.addChildNode(exprNode)
... | This function parses a variable declaration node by validating the syntax structure, including type identification, assignment operator, expression parsing, and semicolon termination. It creates a DECLARE node, checks token sequences for correctness, handles errors by removing invalid nodes, and logs parsing progress. ... | def parseDeclare(self, node):
declareNode = Node(node, self.scanLines[self.currentLineNum], NodeType.DECLARE)
node.addChildNode(declareNode)
self.modPrint(" " + "\t" * node.getDepth() + "Parsing " + str(declareNode.getNodeType().value))
typeNumCode = self.currentToken.getNumCode()
... |
def modPrint(self, txt):
print(str(txt))
self.printLines.append(str(txt))
def nextToken(self):
self.currentToken = self.nextLexeme().getToken()
def parseExpr(self, node):
exprNode = Node(node, self.scanLines[self.currentLineNum], NodeType.EXPR)
node.addChildNode(exprNode)
... | The main task of the code is to parse an assignment statement by validating its structure: checking for an identifier, assignment operator (=), expression, and semicolon. If any component is invalid, it generates errors, removes the malformed child node, and returns False. It constructs a DECLARE node for the assignmen... | def parseAssignment(self, node):
assignNode = Node(node, self.scanLines[self.currentLineNum], NodeType.DECLARE)
node.addChildNode(assignNode)
self.modPrint(" " + "\t" * node.getDepth() + "Parsing " + str(assignNode.getNodeType().value))
if 2 <= self.currentToken.getNumCode() <= 9:
... |
def modPrint(self, txt):
print(str(txt))
self.printLines.append(str(txt))
def nextToken(self):
self.currentToken = self.nextLexeme().getToken()
def parseExpr(self, node):
exprNode = Node(node, self.scanLines[self.currentLineNum], NodeType.EXPR)
node.addChildNode(exprNode)
... | The code parses a while statement by validating its syntax structure, checking for required tokens (WHILE, DO, numeric arguments, operators), and handling errors by removing invalid nodes and reporting missing components. It constructs a PRINT_METHOD node, ensures correct token order, and uses parseExpr for expressions... | def parseWhileStmt(self, node):
whileNode = Node(node, self.scanLines[self.currentLineNum], NodeType.PRINT_METHOD)
node.addChildNode(whileNode)
self.modPrint(" " + "\t" * node.getDepth() + "Parsing " + str(whileNode.getNodeType().value))
if self.currentToken is Token.WHILE_KEYWORD:
... |
def modPrint(self, txt):
print(str(txt))
self.printLines.append(str(txt))
def nextLexeme(self):
# If lexeme number is more than the index length -1 then increment line by 1 and reset lexeme number
if self.lexemeNumber >= len(self.scanLines[self.currentLineNum].getLexemes()):
... | This code parses a program by constructing a syntax tree. It processes tokens sequentially, creating nodes for declarations, assignments, control structures (if/while), and print statements. The parser loops through input lines, branching based on token types, and builds a hierarchical tree structure rooted at a PROGRA... | def parse(self):
root = Node(None, None, NodeType.PROGRAM)
self.modPrint("Parsing " + str(root.getNodeType().value))
lexeme = self.nextLexeme()
self.currentToken = lexeme.getToken()
while self.currentLineNum < len(self.scanLines) - 1:
if 29 <= self.currentToken.getNu... |
def find_switches_with_filters(self,
db_session,
fuzzy_match=False,
expand=True,
id=None,
model=None,
network_... | The main task of the code is to search for network switches in a database based on input criteria (model, network module, platform), identify equivalent switches via mappings, and return a structured result indicating match status, modular status, and equivalent switches. It handles edge cases like no matches, multiple... | def find_equivalent_switch(self, fields):
try:
model = fields.get("Model", None)
network_module = fields.get("Network_Module", None)
platform = fields.get("Platform", None)
data = {}
data["matched"] = False
data["modular"] = False
... |
def random_turn(player_score, opponent_score):
if not len(trot[player_score][opponent_score]):
return -1
elif sum(trot[player_score][opponent_score].values()) < 200:
return -1
random_value = random.randint(1, sum(trot[player_score][opponent_score].values()))
selected_turn = -1
w... | The code simulates a game between a player and an opponent over multiple rounds, calculating the player's average win rate. It tracks scores, determines turns, and evaluates outcomes using strategies defined in player_actions and opponent_actions. The function incorporates extra turns, noisy moves, and win-rate calcula... | def train_model_against_opponent(first_move=0, player_actions=4, opponent_actions=4, player_score_start=0, opponent_score_start=0, player_max_score=50, opponent_max_score=50, test_rounds=100000):
total_winrate = 0
for _ in range(test_rounds):
result_winrate = 0
playerScore = player_score_start
... |
def random_turn(player_score, opponent_score):
if not len(trot[player_score][opponent_score]):
return -1
elif sum(trot[player_score][opponent_score].values()) < 200:
return -1
random_value = random.randint(1, sum(trot[player_score][opponent_score].values()))
selected_turn = -1
w... | This function evaluates the win rate of a player's initial move against an opponent using optimal or random strategies in a simulated game. It runs 100,000 rounds, tracking scores, determining turn order, and calculating win rates based on game outcomes. The result is the average win rate of the player's starting move ... | def train_model_against_self(first_move, actions, player_score_start=0, opponent_score_start=0, test_rounds=100000):
total_winrate = 0
for _ in range(test_rounds):
result_winrate = 0
playerScore = player_score_start
opponentScore = opponent_score_start
current_turn = random_turn(... |
def parseGraphNodeName(self, name):
nodeMark = name.lower()[0]
nodeIdx = int(name[1:])
return nodeMark, nodeIdx
def parseConsumerNode(self, node):
label = node['label']
fetchFrom = self.parseConsumerLabel(label)
if fetchFrom:
node['fetch_from'] = fetchFrom
... | This function parses a graph node by determining its type (e.g., 'c' for consumer, 'p' for producer), applying a corresponding template, and setting attributes like name, index, label, and graph node reference. It handles specific node type processing and returns the constructed node object or None if the node type is ... | def parseGraphNode(self, graphNode, graph):
nodeMark, nodeIdx = self.parseGraphNodeName(graphNode)
allLabels = nx.get_node_attributes(graph, 'label')
nodeLabel = allLabels[graphNode] if graphNode in allLabels else 'none'
try:
node = copy.deepcopy(NODE_TEMPLATES[nodeMark])
... |
def parseGraphNode(self, graphNode, graph):
nodeMark, nodeIdx = self.parseGraphNodeName(graphNode)
allLabels = nx.get_node_attributes(graph, 'label')
nodeLabel = allLabels[graphNode] if graphNode in allLabels else 'none'
try:
node = copy.deepcopy(NODE_TEMPLATES[nodeMark])
... | This function parses a graph's nodes into structured objects, categorizes them as producers/consumers, links consumer 'fetch_from' references to producer objects by name, establishes routing via shortest paths, adds network shaping parameters, and returns the processed node dictionary. | def parseTopologyGraph(self, graph):
nodes = {}
for graphNode in graph.nodes():
node = self.parseGraphNode(graphNode, graph)
if node:
nodes[graphNode] = node
producerNodes = [x for x in nodes.values() if x['type'] == 'producer']
consumerNodes = [x ... |
def mirror_modules(self):
for imod in (0, 1):
self.x0[imod] = (self.shiftMirrorX[imod] - self.x0[imod]) if self.__mirrorX_after[imod] else self.x0[imod]
self.y0[imod] = (self.shiftMirrorY[imod] - self.y0[imod]) if self.__mirrorY_after[imod] else self.y0[imod]
self.__mirrorX_a... | The main task of the code is to perform a comprehensive analysis by sequentially executing four key steps: mirroring modules, computing initial angles, aligning components, and calculating all projections. This method orchestrates these operations to process and analyze data structures, likely in a geometric or signal ... | def full_analysis(self):
self.mirror_modules()
self.compute_angles_0()
self.align()
self.compute_all_projections() |
def add_consonant():
shuffle(consonants)
letters.append(consonants[0])
def add_vowel():
shuffle(vowels)
letters.append(vowels[0])
def add_random():
options = randint(0,2)
if options in [0,1] :
add_consonant()
else:
add_vowel()
def get_words(letters, length):
global wordli... | The main task of the code is to allow users to generate letters through menu-driven options (normal input, random letters, or manual entry), then search for the longest possible valid word using those letters by iterating from 9 to 1 letters. It returns a list of found words. | def letter_game(wordlist):
# show the menu to the player
while True:
print("Welcome to the word game!")
print("1. Normal")
print("2. Random")
print("3. Solve")
print("4. Exit")
selection = input("pick 1, 2 or 3: ")
try:
if int(selection) in rang... |
def get_alphabet_firstn(n):
"""
get_alphabet_firstn(n)
Returns the firtst n letters of the alphabet
Parameters
----------
n: string
number of letters
Returns
-------
list
Example
-------
get_alphabet_firstn(3) # returns ['a','b','c']
"""
return list(... | The code generates roots for a voting system by creating candidate names, possible voter preferences, and normalized vectors based on the specified method (direct, indirect, or semidirect). It then derives roots from these vectors and returns them, likely for analyzing electoral outcomes or preference aggregation. | def generate_roots(number_of_voters, number_of_candidates, method="semidirect"):
candidates = get_alphabet_firstn(number_of_candidates)
possible_prefs = all_possible_prefs(candidates)
if method == "direct":
normalized_vectors = generate_normalized_direct(number_of_voters, number_of_candidates)
... |
def GeodesicDistance(self, lat1, long1, lat2, long2):
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
... | This function calculates and visualizes a non-direct flight path between departure and arrival points with user-defined waypoints. It computes geodesic distances, headings, detour ratios, and generates reachable ground footprints for an aircraft's flight profile, including contingency site analysis and flight path plot... | def DrawNonDirectRoutingTrip(self, DepType, ArrType, idxDep, idxArr, Aircraft, CruiseAltitudeInFeet, WayPoints, Save=False):
# FOR DEPARTURES
if DepType == "Regional":
latDep_deg = self.lat_regional_deg[idxDep]
lonDep_deg = self.lon_regional_deg[idxDep]
latDe... |
def straight_flush(hand):
"Return straight flush"
ranks = card_ranks(hand)
if straight(hand)!=False:
if flush(hand)!=False:
return "straight flush with high card"+ " " + aDict[str(ranks[0])],8
return False
def flush(hand):
"Returns flush, if all the cards have the same suit."
... | The function `best_hand` determines the highest-ranking poker hand from a given set of cards. It evaluates hands in descending order of priority: straight flush, full house, flush, straight, and others. If none of these are detected, it defaults to the best hand based on card values (e.g., pairs, triples). The function... | def best_hand(hand):
#we use the fact that function kinds(hand) returns the best hand
if straight_flush(hand)==False and flush(hand)==False and straight(hand)==False and full_house(hand)==False:
if kinds(hand)!=False:
return kinds(hand)
if full_house(hand)!=False:
return full_hou... |
def sorted_chromosomes(self):
ordered_dict = tuple((chromosome, self._fitness_dict[chromosome])
for chromosome, fitness in
sorted(self._fitness_dict.items(), key=itemgetter(1), reverse=True))
# keyvalue_pairs = list(ordered_dict.items())
... | The method generates the next generation in a genetic algorithm by selecting half the population, performing crossover to create new genes, applying mutation, and optionally including parent genes. It combines these to form the next generation, ensuring diversity and inheritance of traits. | def evolve_next_generation(self):
selected = self._selector.select(self.sorted_chromosomes(), k=self._initial_population_size / 2)
new_genes = self._crossover(selected)
mutated_genes = [self._mutator.mutate(genes) for genes in new_genes]
next_generation = mutated_genes
if self._i... |
def compute_best_move_square(square, avail_dirs=NEIGH_DIRECTIONS):
"""
Get best position for a square without taking into consideration other square from his territory
@param square: Current square
@param avail_dirs: Directions that need to be computed in actual conditions
@return: ... | The function computes optimal collective moves for owned squares by processing a stack of potential moves, handling self-destructive moves (combined_strength > MAX_STRENGTH), tracking visited targets in a grid, and compiling valid moves into a list for the engine. It iterates through squares, checks directions, avoids ... | def get_best_collective_moves():
"""
Computes the best collective moves by processing a stack of individual moves,
taking care of the self-destructive moves (e.g: moves which have combined_strength > MAX_STRENGTH)
@return: List of moves which is send to the engine to make the moves for each square
"... |
def copy_fields(self, source, target):
if IDexterityContent.providedBy(source):
self.copy_fields_dexterity(source, target)
def copy_seo_properties(self, source, target):
# TODO: extract this to an adapter of ITranslateThings
# Copy SEO properties added by quintagroup.seoptimizer
... | The code copies content from an item to its translations in specified languages. It skips items of certain portal types, creates translations if they don't exist, and duplicates fields, SEO data, properties, and other attributes from the original item to each translation, then reindexes the translated objects. | def copy_contents_of(self, item, target_languages):
if item.portal_type in SKIPPED_PORTAL_TYPES:
log.info("Item skipped: {0}".format("/".join(item.getPhysicalPath())))
else:
for language in target_languages:
manager = ITranslationManager(item)
if n... |
def is_prime(number:int) -> bool:
end=int(math.sqrt(number))+1
for i in range(2,end): # loop up to and including the square root of the number and if no divisors yet, it is prime
if number%i==0:
return False
return True
def are_relatively_prime(num1:int,num2:int) -> bool:
# if is_pri... | The main task of the code is to test multiple functions related to prime numbers: checking if a number is prime, determining if two numbers are relatively prime, generating prime lists, and decomposing numbers into prime factors. It prints results for various inputs to validate the correctness of these functions. | def main():
print(is_prime(8))
print(is_prime(2))
print(is_prime(3))
print(is_prime(11))
print(is_prime(103))
print('\n\n\n')
print(are_relatively_prime(1,2))
print(are_relatively_prime(2,2))
print(are_relatively_prime(1,3))
print(are_relatively_prime(10,4))
print('\n\n\n')
... |
def evaluate(
self, det_type: str, unique_metrics: Set[str], multiprocessing: bool = False
):
logger.info(f"Running per image evaluation for {det_type}.")
start_time = time.time()
class_ids = self.params[det_type].class_ids
self._prepare(det_type)
self.ious[det_typ... | The code processes evaluation metrics by generating unique identifiers for each detection type from the input `metric_filter`, then evaluates, accumulates, and summarizes these metrics. It iterates over `self.eval_type`, constructs metric keys using formatted strings, and applies three methods to handle each detection ... | def run(self, metric_filter):
unique_metrics = {}
for det_type in self.eval_type:
unique_metrics = set(
[
f"ar{x['ar']}-bg{x['bg']}-lt{x['lt']}-df{x['df']}"
for x in metric_filter[det_type]
]
)
se... |
def detect_ball(self, image):
""" Detect one or more balls in image.
Arguments:
image: RGB image in which to detect balls
Returns:
list of tuples (x, y, radius)
"""
gray_im = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
blurred_im = cv.Gau... | The code processes an image to detect balls, estimate their 3D positions using detected 2D coordinates, and visualize them by drawing balls and bounding cubes on the image. It returns a list of 3D (X,Y,Z) coordinates for each detected ball. | def process_frame(self, image):
""" Detect balls in frame, estimate 3D positions, and draw on image
Arguments:
image: image to be processed
Returns:
list of (X,Y,Z) 3D points of detected balls
"""
circle_cords = self.detect_ball(image)
... |
def usage():
print("Usage: bitmap2cpp [-a|--alpha] -o output input...")
print("")
print("-a, --alpha : Enable alpha channel")
print("-o : Filename of C++ source file to be generated")
print("INPUT : PNG input files")
def process(input_file, rect=None, index=None, flag_alph... | The main task of the code is to parse command-line arguments, process input text using the `process` function with an optional alpha flag, and either save the result to a specified output file or print it to stdout, handling user options like help, alpha mode, and output destination. | def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "hao:", ["alpha", "help", "output="])
except getopt.GetoptError:
usage()
sys.exit(2)
output = None
alpha = False
for o, a in opts:
if o in ("-a", "--alpha"):
alpha = True
if o in ("-h", "-... |
def loadManga(e):
global currentPage
if currentPage:
page.remove(currentPage)
page.add(mangaSearchPage)
currentPage = mangaSearchPage
global results
results = recentManager.data['Manga']
results = recentManager.revDict(results)
placeRes... | The function `changeToolBar` handles navigation between different UI pages based on the selected index from a toolbar. It removes the current page and adds a new one (download, main, search, or menu) while updating the UI. For the main page, it processes recent data, reverses a dictionary, and places results. The core ... | def changeToolBar(e):
global currentPage
i = e.control.selected_index
if i == 0:
if currentPage:
page.remove(currentPage)
page.add(downloadPage)
currentPage = downloadPage
page.update()
if i == 1:
lo... |
def separate_queries(queries):
queries = comment_remover(queries)
return [query.strip() + " ;" for query in queries.split(";") if query.strip()]
def query_type_check(queries):
"""
Gets an list of queries and returns a list of query which are create table queries
"""
create_queries = []
for q... | The code reads a script file, splits it into individual SQL queries, validates their types, parses each query into a table structure using a default test case configuration, and returns a list of parsed tables. | def read_script(file_path, default_query_chk=default_test_cases):
tables = []
with open(file_path, "r") as f:
main_query = f.read()
queries = separate_queries(main_query)
queries = query_type_check(queries)
for query in queries:
table = parse_create_query(query, defau... |
def highest_MFE_start(AminoAcid_Seq, tuple_inherited):
ex_sys, des_GC, codons_dict, CC_dict, CC_evaluation_dict, CoBias_dict, lst_parameters, seq_fold = tuple_inherited
aaSeq = AminoAcid_Seq[:20] ; lenAASeq = len(aaSeq) ; candidates = {}
for Round in range(10):
ATruns_Off = 0 ; PyrRuns_Off = 0; rSit... | The function `back_translate` generates 10 DNA sequence candidates from an amino acid sequence by backtranslation, optimizing for desired GC content, codon usage, and avoiding motifs like restriction sites, homopolymers, and A/T/pyrimidine stretches. It uses codon context, autocorrelation bias, and iterative adjustment... | def back_translate(geneName, AminoAcid_Seq, Max_threshold, tuple_inherited):
#unpack values from tuple
ex_sys, des_GC, codons_dict, CC_dict, CC_evaluation_dict, CoBias_dict, lst_parameters, seq_fold = tuple_inherited
#Defining all the parameters that are needed for the backtranslation
candidates_dict = ... |
def adddnsroutes():
for dnsprovider in dnsproviderlist:
addroute(dnsprovider)
def getdnsip(host):
dnsrequest = dns.resolver.Resolver()
dnsrequest.timeout = 4
dnsrequest.lifetime = 8
dnslist = []
#first we try with the default windows dns settings
dnslist = rundnsquery(dnsrequest,host)
if (dnslist): retur... | The function attempts to send a message via alternative routes by adding backup DNS and gateway routes, using DNS records for 'rest.textmagic.com' to configure routes, handling exceptions during message sending, and cleaning up routes afterward. It returns a boolean indicating success or failure. | def send_message_alt_route():
#This lets us know if we were able to send the message
messagesent=True
#We need the backup route to the DNS servers since the primary failed
adddnsroutes()
#We now get the dns results for textmagic
dnslist=getdnsip('rest.textmagic.com')
#We add a route out to the backup gat... |
def create_grad_vectors(width,height,cell_width,cell_height):
num_rows = round_up(height/cell_height)
num_cols = round_up(width/cell_width)
grid = np.empty((num_rows+1,num_cols+1),dtype=list)
for r in range(num_rows+1):
for c in range(num_cols+1):
grad_vector = get_unit_vector([random.uniform(-1,1),random.uni... | The code generates a 2D Perlin noise array of specified dimensions by interpolating gradient vectors at grid points. It calculates relative positions within cells, computes dot products with surrounding gradients, applies 2D interpolation, scales values, and tracks min/max heights for normalization. The output includes... | def perlin_array(width,height,cell_width,cell_height,scale=1):
max_height = 0
min_height = 0
grid = create_grad_vectors(width,height,cell_width,cell_height)
noise_array = np.zeros((height,width))
for y in range(height):
for x in range(width):
rel_x = (x-(x//cell_width)*cell_width)/cell_width
rel_y = (y-(y/... |
def image_from_binary(binary):
"""Get a ROM image from the given ELF binary."""
temp = get_temp_dir()
binary_copy = temp / binary.name
shutil.copy(binary, binary_copy)
image = temp / (binary.name + '.n64')
run([
'bazel', 'run', '-c', 'opt', '//tools/makemask', '--',
'-program', b... | The function `get_image` determines the path to an N64 image by prioritizing direct input paths (`-image`, `-binary`), then resolving artifacts/revsions, and finally using Bazel to build and extract the image from a target. It handles build events, validates output, and converts non-.n64 outputs to image format if need... | def get_image(args):
"""Return a path to the image to run."""
# From -image:
if args.image is not None:
return pathlib.Path(args.image)
# From -binary:
if args.binary is not None:
return image_from_binary(pathlib.Path(args.binary))
# From -artifact or -revision:
artifact = ... |
def list_artifacts():
dir = pathlib.Path.home() / 'Documents/Artifacts'
find_revision = re.compile(r'\.r(\d+)\.')
for item in dir.iterdir():
m = find_revision.search(item.name)
if m is not None:
item_rev = int(m.group(1), 10)
yield item_rev, item
def get_image(args):
... | (The main task of the code is to parse command-line arguments for running a game via emulator or hardware flashcart, handling options like emulator selection, compilation mode, region (NTSC/PAL), and input sources (artifact, ROM image, etc.). It lists available artifacts if requested, prepares the ROM image, and execut... | def main(argv):
emulators = {
'cen64': cen64,
'mame': mame,
'mupen': mupen64,
'mupen64': mupen64,
}
p = argparse.ArgumentParser(
prog='run.py',
description='Run game',
allow_abbrev=False,
)
p.add_argument('-verbose', '-v', action='store_true',
... |
def move_cursor(self, token: Token, next_token: Token | None) -> None:
if not next_token:
return
match (token, next_token):
case [OpeningTag(is_self_closing=False), ClosingTag()]:
self.depth = self.depth
case [OpeningTag(is_self_closing=False), _]:
... | The code compiles a sequence of tokens into a formatted string. It processes each token using class-specific visit methods, manages token navigation, and constructs the output code. It ensures proper line endings by appending a newline if missing, then returns the concatenated result. The core task is transforming toke... | def compile(self, tokens: deque[Token]) -> str:
self.tokens = tokens
self.depth: int = 0
self.token: Token | None = tokens.popleft()
self.code: deque[str] = deque()
while self.token:
getattr(self, f"visit_{self.token.__class__.__name__}")(self.token)
sel... |
def _convDown(x, num_filters, filters, conv_layer_counter, use_bn):
return _convLayer(
x,
num_filters,
filters, (2, 2),
conv_layer_counter,
use_bn,
True,
padding='valid')
def _residual(x, num_filters, filters, conv_layer_counter, use_bn):
c1, conv_layer_co... | This function constructs a deep neural network model using Keras, designed for image feature extraction. It defines a network with convolutional layers, residual blocks, and downsampling stages to process input images, ultimately producing a 128-dimensional embedding. The model adapts to channel ordering and returns a ... | def build_dlib_model(image_h=150, image_w=150, use_bn=False):
if K.image_data_format() == 'channels_last':
batch_input_shape = (1, image_h, image_w, 3)
input_shape = (image_h, image_w, 3)
else:
batch_input_shape = (1, 3, image_h, image_w)
input_shape = (3, image_h, image_w)
... |
def log_hpr(hpr):
logging.info("\r--------------------------------------\n")
for key, hyperparameter_range in hpr.items():
start = hyperparameter_range[0]
stop = hyperparameter_range[-1]
if isinstance(start, (int, float)) and isinstance(stop, (int, float)):
... | This code performs hyperparameter tuning via grid search. It validates hyperparameter keys, iterates through all combinations of ranges, trains models, evaluates scores, and retains the best hyperparameters yielding the highest average score over the last 100 episodes. | def tune(self):
for hp_key, hpr_key in zip(self.hp.keys(), self.hpr.keys()):
if not hp_key == hpr_key:
logging.error("\rINVALID HYPERPARAMETERS FOR TUNING\n")
exit()
self.log_hpr(self.hpr)
best_score = 0
best_episode_counter = None
be... |
def train(self, episodes=None, steps_per_episode=None, filename=None):
# parameters
episodes = self.hp["episodes"] if episodes is None else episodes
steps_per_episode = self.hp["steps_per_episode"] if steps_per_episode is None else steps_per_episode
# verify environment is created and r... | The main task of the code is to initialize the agent's environment and execute different operations based on the specified mode. In "train" mode, it trains the agent, saves the state, and plots scores; in "tune" mode, it adjusts parameters; in "show" mode, it displays results. The function logs the selected mode and de... | def setup(self, mode, world):
self.world = world
if mode == "train":
logging.info("\rMODE: training\n")
absolute_scores, average_scores = self.train(filename="agent_state.pth")
self.plot(scores=absolute_scores, filename="scores_absolute.png")
self.plot(sco... |
def show_create_file_option():
select_file.destroy()
select_folder.destroy()
global File_name_type
File_name_type = Label(app, text="Write The Name Of The File In The Box below And press The Button ")
File_name_type.pack()
global file_name
file_name = Entry(width=40)
file_name.pack()
... | The code checks if both a folder and file are selected to show a create file option, or displays errors if only one is selected, ensuring valid user input for file operations. | def check_file_folder():
if Folder_selected == True & File_selected == True:
show_create_file_option()
elif Folder_selected == False & File_selected == True:
show_empty_folder_error()
elif Folder_selected == True & File_selected == False:
show_empty_file_error() |
def align_reference_prediction(ref: dict, pred: dict, drop_missing: bool = True) -> Tuple[pd.DataFrame, List]:
# merge reference a prediction dicts and cast to Pandas.DataFrame
aln_pred = pd.DataFrame({**ref, **pred})
predname = aln_pred.columns.get_level_values(0)[-1]
logging.debug("aligned reference ... | The main task of the code is to benchmark and evaluate multiple prediction models against a reference dataset by aligning predictions with the reference, computing metrics like ROC curves, PR curves, and confusion matrices, and saving results in CSV files. It supports dataset-level, target-level, and bootstrap analysis... | def bvaluation(reference: str, predictions: list, outpath=".", dataset=True, target=False, bootstrap=False,
run_tag="analysis", threshold_file=None, normalize=False):
outpath = Path(outpath)
outpath.mkdir(parents=True, exist_ok=True)
reference = Path(reference)
refname = reference.stem
... |
def KBtocnf():
global KBclauses
def collect(subargs):
for arg in subargs:
if arg.operator == operator: collect(arg.arguments)
else: result.append(arg)
for kbi in KB:
operator='&'
result = []
collect([cnfconvert(expressionize(kbi))])
KBclaus... | The code implements an agent navigating a grid-based environment, updating a knowledge base (KB) with perceptions (breeze/stench) and using CNF conversion for logical reasoning. It tracks visited rooms, selects unvisited or least-cost paths, and records navigation steps. The agent avoids unsafe areas, applies heuristic... | def main():
path=[]
rooms=[]
global KBclauses
KBtocnf()
ag = Agent()
visited={}
validMoves = [[0,1],[0,-1],[-1,0],[1,0]]
while(ag.PerceiveCurrentLocation()!=[None,None]):
rooms.append(ag.FindCurrentLocation())
print('curLoc',ag.FindCurrentLocation())
if tuple(ag.F... |
def pickrand(population, fitness):
poplist=list(population)
maxfit=fitness(poplist[0])
for elem in poplist:
ftemp=fitness(elem)
maxfit=max(maxfit,ftemp)
weights=[]
for elem in poplist:
weights.append(fitness(elem)/maxfit)
return random.choices(poplist,weights,k=2)
def... | This code implements a genetic algorithm to evolve a population of solutions (likely for optimization problems like TSP). It iteratively selects parents, reproduces offspring with mutation, and replaces the population until convergence. The goal is to minimize route length, with each generation printing progress and th... | def genalgo(population,fitness):
generation=0
doneflag=False
while(True) and not doneflag:
generation+=1
print(generation)
newpop = set({})
n = len(population)
# for _ in range(n):
while len(newpop)<100:
x,y = pickrand(population,fitness)
... |
def generate_deck(self):
# Create a standard deck of 52 cards
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
deck = [{'rank': rank, 'suit': suit} for rank in ranks for suit in suits]
random.shuffle(deck... | The code initializes a card game by setting up the number of players, generating a deck of cards, creating player instances, and initializing the dealer's hand. It calls a reset method to prepare the game for play, likely shuffling the deck and resetting player and dealer hands. | def __init__(self, num_players):
self.num_players = num_players
self.deck = self.generate_deck()
self.players = [self.initialize_player() for _ in range(num_players)]
self.dealer_hand = []
self.reset_game() |
def initialize_population():
return [[random.choice(DECISIONS) for _ in range(len(POSSIBLE_UPCARDS) * len(POSSIBLE_HANDS))] for _ in range(POPULATION_SIZE)]
def calculate_fitness(chromosome):
num_hands = 100
initial_bankroll = 1000 # Adjust this based on your needs
bet_amount = 10 # Adjust this based ... | The code implements a genetic algorithm to evolve a population of chromosomes over multiple generations. It initializes a population, evaluates fitness, selects parents via tournament selection, generates new offspring through crossover and mutation, and replaces the population iteratively. The process repeats for a se... | def genetic_algorithm():
# Main genetic algorithm
population = initialize_population()
for generation in range(NUM_GENERATIONS):
# Evaluate fitness of each individual in the population
fitness_scores = [calculate_fitness(chromosome) for chromosome in population]
# Select parents us... |
def _init_rt_status(self, rt_files):
pkls = glob.iglob('routines/*.pkl')
[os.remove(pkl) for pkl in pkls]
status = glob.iglob('routines/rt_status.txt')
[os.remove(statu) for statu in status]
rt_names = [rt_file.replace('.txt', '').replace('routines/', '') for rt_file in rt_files]... | This code initializes an object to manage runtime routines by loading, categorizing, and updating routine files. It processes `.txt` files in the 'routines' directory, checks for outdated files, loads them into DataFrames or pickled objects, categorizes routines by type, and updates internal status tracking. The code a... | def __init__(self, starting_rt='TwinkleAll_high_rt', compile_routines=False):
rt_files = sorted(glob.iglob('routines/*_rt.txt'), key=os.path.getmtime, reverse=True)
if compile_routines:
self._init_rt_status(rt_files) # Uncomment to refresh routines #TODO do init of all rts in rt_status her... |
def calculate_BIC_one_hap(inFileName, genomeFileLoc):
# read polymorphic sites and filter
data = read_polymorphicsSite(inFileName)
count_before = len(data)
data = filter(data)
count_after = len(data)
tmp = [count_before, count_after,
round(count_after * 1.0 / count_before, 5)]
pr... | The code predicts the optimal number of haplotypes using the EM algorithm by evaluating BIC values for 1 to 9 haplotypes. It checks for a single haplotype, runs EM iteratively, and stops when likelihoods stabilize or BIC criteria are met, returning the determined haplotype count and SNP data. | def automatica_predict_EM(parameter):
print(parameter)
inFileName = parameter[0]
genomeFileLoc = parameter[1]
resLoc = parameter[2]
# print parameter
previous_numHaps = -1
likelihood_log = {}
if not os.path.exists(resLoc):
os.mkdir(resLoc)
# calculate BIC when i=1
BIC_... |
def abs_hum(self, temperature, rh_humidity):
"""
compute absolute humidity from relative based on temperature
"""
pws = self.__get_pws_water(temperature)
pw = pws * rh_humidity
res = 2.16679 * pw / (273.15 + temperature)
return res
def ah_bilance(self, t_... | This code calculates the relative humidity and room temperature after considering air flow, enthalpy balance, and user error. It uses input parameters for inside/outside temperature/humidity, air flow, and error to compute adjusted values for environmental control systems. | def process(self, to, ho, ti, hi, air_flow, err_usr):
"""
@PAM temp_outside, hum_outside, temp_inside, hum_inside, air_flow, err_of usr
@RETURN float of relative humidity, float of temperature
"""
self.temp_in = ti
self.hum_in = hi
self.temp_out = to
self.... |
def finetune(self):
"""
Finetune the model with the first dataset using the transformer trainer
And save the finetuned model
:return: None
"""
print("Finetuning")
train_ds = list(self.train_dataset.values())[0]
eval_ds = list(self.eval_dataset.values())[0]... | The main task of the code is to fine-tune a model on the first dataset and subsequently train LoRA adapters on additional datasets using a custom trainer. It processes datasets sequentially, skips already trained ones, saves the model and adapters after each training step, and ensures LoRAs are added and re-trained ite... | def train(self, trainer=None):
"""
Custom train function for MLTrainer
Starting by processing the datasets, then finetuning with the first dataset
and save the finetuned model if needed
Be ware the finetuning method don't use the custom trainer
And then create the Loras a... |
def has_balance_to_buy(self):
logging.info('checking if we have some balance to buy')
q = self.exchange.get_balance(self.base_currency)
# balance_adjustment to avoid INSUFFICIENT FUNDS MESSAGE
balance_adjustment = 0.0005
self.balance = q['result']['Available'] - balance_adjustmen... | The code's main task is to execute trading operations by first checking if there's sufficient balance to buy an asset, then purchasing it if possible. It subsequently checks for existing orders and sells them if present. Finally, it logs a pause duration and sleeps for a specified time to manage trading intervals or co... | def do_trade(self):
if self.has_balance_to_buy():
self.buy(self.get_market_to_buy())
if len(self.orders) > 0:
self.sell()
logging.info(f'Sleeping for {self.sleep_time} seconds')
sleep(self.sleep_time) |
def heuristic(board):
'''
This function will calculate the heuristic value of the given board
'''
def diagonal_conflict(chessboard):
'''This function count the number of diagonal conflicts in the chessboard'''
count = 0
for i in range(len(chessboard)):
for j in range(... | The main task of the code is to demonstrate a hill climbing algorithm on a randomly generated n×n board (n=10). It initializes a board with random values, calculates its heuristic and heuristic matrix, then applies the hillclimbing function to find optimal moves. The code prints the initial board state, heuristic value... | def main():
'''
This is the main function
'''
#generate a random board
n = 10
board = np.zeros((n, n))
board[np.random.choice(n, n, replace=False), np.arange(n)] = np.random.randint(1, 9,n)
print("The initial board is:")
print(board)
print("The heuristic of the initial board is:"... |
def get_current_cost(chessboard, model):
values = [] # df values
# cols = [] # df col titles
board = chessboard
# attribute 1 - heaviest queen weight
heaviestQueenWeight = np.amax(board)
values.append(heaviestQueenWeight)
# cols.append('heaviest queen weight')
# attribute 2 - heaviest qu... | The code implements the A\* algorithm to solve a chessboard puzzle by finding the optimal sequence of moves to minimize conflicts. It manages a priority queue (`fringe_chess`) of potential states, selects the lowest-cost node, generates new states via vertical piece swaps, and evaluates their cost using a heuristic (mo... | def run_Astar(chessboard, fringe_chess,found_list,start_time, model):
model = model
current_time = time.time() - start_time
#print('current time', current_time)
if current_time >= 180:
return "Timed out", False, -1
a = True
while a == True:
chosen_chess = np.argmin(fringe_chess... |
def generate_random_board(n):
'''This function will generate a random board of size n'''
board = np.zeros((n, n))
board[np.random.choice(n, n, replace=False), np.arange(n)] = np.random.randint(1, 9,n)
return board
def get_current_cost(chessboard):
return spot_conflict(chessboard)
def run_Astar(chess... | This function conducts multiple iterations of the n-queen problem experiment using A* search. It initializes a random board, runs the A* algorithm, records valid solutions (boards and their costs) in a DataFrame, and returns the updated DataFrame after `niters` trials. | def experiment(n, df, niters,seed = 1):
'''
this function will run the experiment niters times of the n-queen problem
'''
np.random.seed(seed)
for i in range(niters):
print('n:', n, 'niter:', i+1)
start_time = time.time()
found_list = [0]
board = generate_random_... |
def generate_random_board(n):
'''This function will generate a random board of size n'''
board = np.zeros((n, n))
board[np.random.choice(n, n, replace=False), np.arange(n)] = np.random.randint(1, 9,n)
return board
def get_current_cost(chessboard, model):
values = [] # df values
# cols = [] # df ... | The function `experiment` runs the n-queen problem experiment `niters` times using a specified model. For each run, it generates a random chessboard, applies the A* algorithm to solve it, and records runtime and solution quality (conflict reduction ratio). It aggregates metrics like average runtime, success rate (conve... | def experiment(n, model, niters,seed = 1):
'''
this function will run the experiment niters times of the n-queen problem
'''
model = model
np.random.seed(seed)
count = 0
runtime = []
solution_scores = 0
solution_scores_list = []
count_solutions = 0
found_list = [0]
for i... |
def get_loss(self):
"""
Calculates the loss of the current generated midi sample.
:return: The loss of the current generated midi sample.
"""
inputs = self.observation(self.midi_sample, as_tensor=True)
targets = self.observation(self.target_midi_sample, as_tensor=True)
... | The code calculates a reward for a generated MIDI sample by starting with the negative loss compared to a target sample, then applying penalties for note repetition, pattern frequency, and presence of less common notes. The reward is adjusted by multiplying these penalties and dividing the final value by 2.0 to balance... | def get_reward(self):
"""
The reward is the loss between the generated midi sample and the target midi sample.
Since the reward needs to get higher the closer the generated midi sample is to the target midi sample,
the reward is negative.
Additionally the reward gets multiplied b... |
def add_action_to_sample(self, action):
for i in range(self.token_dim):
if action % self.token_dim == i:
self.midi_sample[i].append(action // self.token_dim)
def update_sample(self, reset=False):
if reset:
self.midi_sample = {i: [] for i in range(self.token_dim)}
... | The main task of the code is to append a given MIDI token to the sequence, check if the sequence has reached its maximum length (ending the episode), compute a reward if learning is enabled, and return the updated observation, reward, done status, and auxiliary information for reinforcement learning training. | def step(self, action):
"""
:param action: The next mumidi token to add to the generated midi sample.
:return: (observation, reward, done, info)
"""
# check modulo of action to find out which dimension in the midi sample to update
self.add_action_to_sample(action)
... |
def new_line():
print('.')
def three_lines():
new_line()
new_line()
new_line()
def nine_lines():
three_lines()
three_lines()
three_lines() | The main task of the code is to simulate clearing a screen by printing multiple newline characters and specific line-counting functions, with a print statement indicating 15 lines executed successfully to help track progress. It uses repeated new_line() calls, three_lines(), nine_lines(), and a final new_line() to achi... | def clear_screen():
new_line()
new_line()
new_line()
three_lines()
print ( '15 Lines are executed succefully') #here I added this print statement because, I think it will be easy to count dots,
nine_lines()
new_line() |
def is_valid_move(self, pc: PlayerColor, pos: Position) -> bool:
result = self.is_empty(pos) and self.does_move_flip_any_field(pc, pos)
return result
def _find_positions_flipped_by_move(
self, pc: PlayerColor, pos: Position
) -> set[Position]:
"""
Find all positions that woul... | The code executes a player's move in a game by validating the position, placing the player's piece, flipping adjacent opponent pieces, and raising an error for invalid moves. | def play_move(self, pc: PlayerColor, pos: Position) -> None:
if self.is_valid_move(pc, pos):
self[pos] = Field.for_player_color(pc)
flipped_positions = self._find_positions_flipped_by_move(pc, pos)
self._flip_positions(pc, flipped_positions)
else:
raise Va... |
def update_time_counter(self):
#self.timeCount.setStyleSheet('color: black;'+'font-weight: normal;'+'font-size: 18px;')
global counter
counter = 30
def clear_widgets(self):
""" Clearing the widgets applying LIFO principle (stacks) """
for widget in self.widgets:
if l... | The main task of the code is to initiate a quiz by fetching questions based on selected category, difficulty, and amount. If no questions are available, it displays an error message prompting the user to choose another category. Otherwise, it clears the interface and proceeds to the trivia frame for the quiz. | def startQuiz(self):
self.update_time_counter()
self.questions = fetch_questions_local(
self.selectedCategory,
self.amount,
self.selectedDifficulty
)
if not self.questions:
msgBox = QtWidgets.QMessageBox()
msgBox.setWindowTitle... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.