dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def gen_section_struct(int_type, pointer_type, signature, depth, data_size=0, data_subcon=Bytes(lambda this: this.data_size), enrs=False, relocation=False, optional=False):
"""
Generates a Construct scruct for an arbitrary section, with user-defined
signature, data_size (can be lambda), and data subcon.
... | The function generates a Construct struct for nested sections from info dicts, recursively building hierarchical data structures with child sections and EOF markers, using specified integer/pointer types and section parameters like signature, data size, and relocation flags. | def gen_cs3_sections(int_type, pointer_type, sections, depth=0):
"""
Generates a Construct scruct for multiple sections, including children,
from a list of info dicts.
My understanding is that these should be structured in the file like:
[
SECTION_MAIN
SECTION_ENRS
SECTI... |
def candidate_points(self, pegs, enemy_pegs, polygon_candidates, enemy_polygon_candidates):
if len(pegs) == 0:
return (0, None) if 0 not in enemy_pegs else (self.board_length*self.board_width-1,None)
# return [i for i in [0, self.board_width-1, (self.board_length-1)*self.board_width, sel... | The code implements a Monte Carlo algorithm to evaluate potential moves in a peg placement game. It simulates random game rounds, alternating player and enemy moves, to calculate the average score of each candidate move. The method tracks scores and iteration counts, then selects the candidate with the highest score-to... | def monte_carlo(self, pegs, polygon_candidates, enemy_pegs, enemy_polygon_candidates):
temp_polygon_candidates = polygon_candidates.copy()
temp_enemy_polygon_candidates = enemy_polygon_candidates.copy()
temp_pegs = pegs.copy()
temp_enemy_pegs = enemy_pegs.copy()
candidates = sel... |
def hasElement(node, element):
"""Check if exlement existing in a tag."""
if node.getElementsByTagName(element).length > 0:
return True
else:
return False
def getInertia(node):
"""Parse inertia of a link."""
inertia = Inertia()
inertialElement = node.getElementsByTagName('inertia... | This function parses a link element from an XML node by extracting its name and associated inertial, visual, and collision properties. It creates a Link object, populates its attributes based on the node's elements, and sets inertia.mass to None if no inertial/visual/collision elements exist. The path parameter likely ... | def getLink(node, path):
"""Parse a link."""
link = Link()
link.name = node.getAttribute('name')
if hasElement(node, 'inertial'):
link.inertia = getInertia(node)
if hasElement(node, 'visual'):
getVisual(link, node, path)
if hasElement(node, 'collision'):
getCollision(link... |
def InitEndEntity(self):
self.oEntity.PosInit(self.oEntity.tCovidePos, self.oInitPos.tInitCovidPos, self.oEntity.CoronaPosDiff)
self.lPrintValues = (self.CovidImage, self.oEntity.tCovidePos)
def Event(self):
for event in pygame.event.get():
if self.bStartRunning:
self... | The code handles end-of-game logic by checking infection/end conditions, displaying results (game over or score), saving scores to a file, and resetting game entities for a new round. It updates the screen with relevant messages and prepares the environment for potential restarts. | def EndThread(self):
if self.oEntity.bGetInfection or self.bEndRunning:
self.InitEndEntity()
self.oStorage.CreateFile(str(self.oEntity.ScoreValue), self.UserName)
while self.oEntity.bGetInfection or self.bEndRunning or self.bAllScore:
self.Event()
... |
def FileEmpty(self):
if not os.path.exists(self.sDirName + self.sFileName):
return True
return os.stat(self.sDirName + self.sFileName).st_size == 0
def CheckFileForOverwrite(self, UserName, Score):
charValue = self.oStringHelper.IsRemovelNeeded(UserName)
if charValue:
... | The main task of the code is to create or update a file with player scores. It checks if the file exists and whether the new score/player name already exists. If the file isn't empty and the content hasn't changed, it exits early. If changes are needed, it rewrites existing content or appends new data, handling errors ... | def CreateFile(self, _sScore, _sPlayerName):
if not self.FileEmpty():
Exists, ChangedContent = self.CheckFileForOverwrite(_sPlayerName, _sScore)
if Exists and not ChangedContent:
return
elif ChangedContent:
try:
file = open(... |
def Init(self):
self.oEntity.PosInit(self.oEntity.lEnemyPos, self.oInitPos.tInitEnemyPos, self.oEntity.EnemyPosDiff)
self.oEntity.PosInit(self.oEntity.lPlayerPos, self.oInitPos.tInitPlayerPos, self.oEntity.PlayerPosDiff)
self.oEntity.FlagInit()
def GUI(self):
pygame.display.set_caption("... | This function initializes a game by setting up the GUI, starting a thread, and entering a loop that handles game events, updates player/enemy positions, manages vaccine firing, checks for infections, renders entities, updates the score, and refreshes the screen until the game ends. | def MainFunction(self):
self.Init()
self.GUI()
self.StartThread()
self.UserName = self.oInputText.sUserName
self.oStorage.CreateFolder()
while self.bRunning:
self.Event()
self.FillScreen()
self.oEntity.PlayerPos()
self.oEnti... |
def get_user_card_ids(user_uuid):
"""
Get all cardIds associated with a user_uuid from the baseline service
Keyword arguments:
user_uuid: a single user_uuid
"""
user_cards_response = baseline_service.get_user_cards_by_user(user_uuid)
if user_cards_response['upsideCode'] != USER_CARDS_FOUND_... | This function determines if a user is new to a specific site by checking if they had any transactions within 365 days before their enrollment. It retrieves the user's card IDs, filters transactions for the site, and compares them against the enrollment timestamp. If no qualifying transactions exist, the user is marked ... | def get_user_uuid_is_new_at_site(site_uuid, user_uuid, source_terminal_filter=None):
"""
Checks whether user is new based on current data
"""
user_card_ids = get_user_card_ids(user_uuid)
user_crawled_tx = get_crawled_txns(site_uuid, source_terminal_filter=source_terminal_filter,
... |
def get_initialized_pre_post_map(relative_month_range):
pre_post_map = dict((x, {'sales': 0,
'visits': 0}) for x in relative_month_range)
return pre_post_map
def get_crawled_txns_for_site_cards(site_crawled_txns, card_ids):
"""
Filter a crawled transaction dataframe to speci... | The function aggregates sales and visits data for users and their associated shadows across specified months. It initializes statistics maps, processes each user's transactions, and calculates pre/post-period metrics. It separately aggregates user and shadow data, returning both sets of monthly statistics. | def get_stats_by_month(site_uuid,
user_site_enrollment_timestamp,
user_card_to_shadows,
site_crawled_txns,
relative_month_range):
user_stats_by_month = get_initialized_pre_post_map(relative_month_range)
shadow_stats_by_... |
def get_all_user_uuid_from_incremental(site_uuid, source_terminal_filter=None, incremental=None):
"""
Get all useruuid that have a transaction in incremental at a site_uuid
Keyword arguments:
site_uuid -- a site_uuid or list of site_uuids
source_terminal -- the source_terminal of the incremental tr... | This function generates shadow panels for all users of a site by processing incremental user data and filtered transaction records. It retrieves user UUIDs, transaction data, and timestamps, then creates shadow panels for each user using the provided parameters, returning a dictionary of panels with keys combining site... | def generate_all_site_user_shadow_panels(site_uuid,
source_terminal,
incremental=None,
crawled_data_end_date=None):
# 1 Get all user_uuid from incremental
all_site_users = get_all_user_uuid... |
def get_list_if_string(object):
"""
Converts a string to a list
"""
if type(object) == str:
object = [object]
return object
def generate_all_site_user_shadow_panels(site_uuid,
source_terminal,
incremental=None,... | The function generates pre/post data for specified sites by processing user panels. It handles incremental data if provided, aggregates panel information across sites, and constructs final pre/post results using the aggregated data. | def generate_site_pre_post_data(site_uuid, source_terminal, modify_month_minus_1=True, incremental=None):
site_uuid = get_list_if_string(site_uuid)
panel_dict = {}
for site in site_uuid:
if incremental is not None:
site_incremental = incremental.query("siteuuid == @site")
else:
... |
def verify_data_set_length(expected_length_at_least, data_set, func_name):
"""
Verify the data set length by specified data set length
Parameters
----------
data_set : list
list of values. eg: [1,2,3,4,5]
expected_length_at_least : int
the smallest data point. The data se... | The function `correlation_pearson` calculates the Pearson correlation coefficient, measuring the linear relationship between two quantitative datasets. It verifies input validity (minimum length 2, equal lengths), computes means and standard deviations of both datasets, pairs data points, and calculates covariance divi... | def correlation_pearson(data_setx, data_sety):
"""
Calculate measure of the linear relationship between two quantitative variables
Parameters
----------
data_set : list
consist of numeric values. eg: [1,2,3,4,5]
Returns
-------
float
pearsonr
"""
# verify ... |
def binaryStateMeasurementModelEnhancer_Explicit(pz : float, gama : Union[float,np.ndarray])-> Union[float,np.ndarray]:
'''
pz - probability of measurement z occuring given that we measure the thing [0,1]
gama - probability of measuring the correct thing [0,1]
assumption: z measures a binary state
... | This function updates a cell's occupancy probability using inverse sensor models and Bayesian inference. It calculates the likelihood of a measurement given the cell's state, combines it with the prior probability (pkm1), and adjusts using schedule-dependent sensor models. The result is converted from odds to probabili... | def updateCell_inverse(z : str, s : g1d, t : float, pkm1: float, gama = 1) -> float:
#ASSUMING FORWARD SENSOR MODEL IS MODELD
'''
z - meaurement "⬜" or "⬛"
s - schedule of cell
t - world time
pkm1 - posterior probability of cell being occupied in last step
gama - probability of measuring cel... |
def _make_temples(self, wc, gc_dir):
self._check_webcache(wc) # lists temples' name and dedication
with open(wc) as f:
d1 = json.load(f)
for name, ded in d1.items():
self._check_geocache(gc_dir, name)
with open(f'{gc_dir}/{name}.json') as f:
d... | The main task of the code is to initialize a class instance by setting up attributes like 'temples', 'data', and 'index' through private methods (_make_temples, _make_data, _make_index), while also creating shortcuts. It uses parameters 'webcache' and 'geocache_dir' to configure temple and geocache data, preparing the ... | def __init__(self, webcache='lds_cache.json', geocache_dir='google_caches'):
self.temples = []
self._make_temples(webcache, geocache_dir)
self.data = None
self._make_data()
self.index = None
self._make_index()
self._make_shortcuts() |
def create_worker_affinities(self, world: World) -> Dict[WorkerId, int]:
"""
We use the distances from the root/gatekeeper to determine affinities
The gatekeeper get a penalty equal to the distance to the furthest worker
The furthest worker gets a penalty of 0
"""
_, move... | The main task of the code is to schedule and prioritize commands for workers based on execution plans, managing worker costs and updating execution states. It processes pearls with workers, generates prioritized commands using a heap, selects top commands per worker, deducts worker costs, and updates execution plans by... | def step(self, world: World) -> Collection[Command]:
pearl_workers = world.get_pearls_with_workers()
self.logger.debug(
f"step: {len(pearl_workers)} pearls, {len(self.execution_plans)} execution plans"
)
for i, item in enumerate(pearl_workers.items()):
self.logge... |
def print(self,msg):
if self.verbose:
print(msg)
def download_url(url, output_path):
with DownloadProgressBar(unit='B', unit_scale=True,
miniters=1, desc=url.split('/')[-1]) as t:
urllib.request.urlretrieve(url, filename=output_path, reporthook=t.update_to)
d... | This code initializes a dataset loader for satellite data (e.g., NDVI/EVI) from specified regions. It downloads/caches data, applies date filtering, normalizes values, interpolates missing data, encodes temporal features (e.g., DOY), applies smoothing, removes seasonality, and transforms data into sequences for time-se... | def __init__(self, region="africa",
fold="train",
verbose=True,
split_ratio = [.6,.2,.2],
seq_length=100,
overwrite=False,
include_time=False,
filter_date=(None,None),
znormalize=False... |
def print(self,msg):
if self.verbose:
print(msg)
def download_url(url, output_path):
with DownloadProgressBar(unit='B', unit_scale=True,
miniters=1, desc=url.split('/')[-1]) as t:
urllib.request.urlretrieve(url, filename=output_path, reporthook=t.update_to)
d... | This code initializes a dataset class for handling Sentinel-5P data, downloading and caching a CSV file, splitting it into train/valid/test sets, converting data into sequences, and normalizing inputs/outputs for machine learning tasks. It handles data loading, preprocessing, and caching to enable efficient training wi... | def __init__(self,
fold="train",
verbose=True,
split_ratio = [.6,.2,.2],
seq_length=100,
include_time=False,
overwrite=False):
super(Sentinel5Dataset).__init__()
self.dataset_url = "https://syncandshar... |
def to_global(self, Path_N): # convert paths from image to global coordinates
loc = self.est_pose
self.robot_pose = self.current_pose(loc)
# # global robot pose message from Vicon or Odom_filtered_map EKF_map (ROS Robot_Localization package) in cm
X_G_R = self.robot_pose[0]*... | The code implements a path planning and control system for a robot using A* algorithm on a transformed image. It waits for image, pose, and transformed image data, then processes the image to generate a grid map. The A* planner computes an optimal path from the robot's current position to a target location, visualizes ... | def timer_callback(self, event):
if self.im is None:
rospy.logwarn_throttle(2.5, "Controller waiting for labelled image...")
return
if self.est_pose is None: # is None....no position data from Vicon or EKF...ceck appropriate topic
rospy.logwarn_throttle(... |
def dist(self, C, subim, rmin, cmin, S, m):
[rows, cols, chan] = subim.shape
x, y = np.meshgrid(np.arange(cmin, (cmin+cols)), np.arange(rmin, (rmin+rows)))
x = x-C[3]
y = y-C[4]
ds2 = x**2 + y**2
for n in range(0, 3):
subim[:, :, n] = (subim[:, :, n] - C[n... | This code performs image segmentation using a modified SLIC algorithm to generate superpixels, followed by clustering with SPDBSCAN and merging similar regions. It returns a feature matrix of merged clusters and a labeled image for segmentation. | def my_slic(self, image, k, m, seRadius, nItr):
[rows, cols, chan] = image.shape
im = color.rgb2lab(image) #better for tiles vs black mat
S = mt.sqrt(rows * cols / (k * mt.sqrt(3) / 2))
nodeCols = np.around(cols / S - 0.5)
S = cols / (nodeCols + 0.5)
nodeRows... |
def four_point_transform(self, img):
tl = [298, 489]
tr = [503, 489]
br = [791, 739]
bl = [9, 739]
rect = np.array(([tl, tr, br, bl]), dtype="float32")
maxWidth = self.size[0]
maxHeight = self.size[1]
dst = np.array([
[0, 0],
[m... | The code processes a Gazebo image by transforming it, segmenting clusters, and publishing messages with labeled data and cluster attributes. It distinguishes between known and unknown clusters, sending tailored messages to different ROS nodes. If all clusters are known, it publishes to ASTAR.py; otherwise, it sends dat... | def timer_callback(self, event):
if self.start is False:
rospy.logwarn_throttle(2.5, "Send empty message to start program...")
return
elif self.gazebo_image is None:
rospy.logwarn_throttle(2.5, "Waiting for Gazebo image...")
return
# get transfor... |
def _parse_metadata(self) -> None:
"""
Parse and populate the metadata section from the XML content.
Returns:
None
"""
metadata_element = self.soup.find('Metadata')
if metadata_element is None or metadata_element == -1:
print("Metadata section not... | The code initializes a class to process XML data from a given URL, setting up internal data structures (metadata, contents, etc.) and fetching XML content. If `parse_contents` is True, it parses metadata, contents, primary text, and commentaries from the XML. If `parse_sections` is True, it additionally parses sections... | def __init__(
self,
base_url: str,
parse_contents: bool = True,
parse_sections: bool = False
):
# Initialize internal data structures
self.metadata = {}
self.contents = {}
self.primary = {}
self.commentaries = {}
# Init... |
def __find_dual_variables(self) -> None:
"""
Iterates over the assigned indices & calculates
each variable by the form U variable + V variable - C cost
"""
u_vars, v_vars = self.__find_equation_vars()
equations = list()
for i, j in self.assigned_indices:
... | The code implements the transportation algorithm to iteratively improve a solution by identifying non-basic variables with positive indicators, creating and updating loops for reassignment, and recording each iteration's state. It continues until no further improvements are possible, then finalizes the optimal solution... | def improve(self) -> None:
"""
Applies the transportation algorithm when the problem has non basic
indicators greater than 0
"""
self.__find_dual_variables()
self.__find_non_basic_indicators()
i = 0
while self.improvable:
self.__create_loop()... |
def _check_configuration_file_availability():
"""
Check availability of configuration file and load.
"""
if os.path.exists(constants.PATH_TO_SCALER_CONFIG_FILE):
logger.log_action("info", "Configuration file found in the directory!", cloud_log_bool=False)
main.configs = _load_config()
... | The main task of the code is to cross-validate the existence and availability of critical system components and files, including configuration files, forecasting models, Prometheus, and cloud monitoring dashboards. It performs checks via private methods and logs an informational action indicating a wait period. | def load_fundamentals():
"""
Method to cross validate the existence of all needful files.
"""
_check_configuration_file_availability()
_check_forecasting_model_availability()
_check_prometheus_availability()
_check_cloud_monitoring_dashboard_status()
logger.log_action("info", "Waiting ... |
def _publish_pod_replica_count_metrics(pod_count_after_scaling: int, configurations: dict):
"""
Method to publish metrics of the predicted pod replica count to the Google cloud monitoring Dashboard
Parameters
----------
pod_count_after_scaling
Number of pod replicas
configurations
... | The function publishes custom metrics to Google Cloud Monitoring, including pod replica counts, predicted workload requests, and Prometheus server request counts, using configurations from a custom HPA (Horizontal Pod Autoscaler) program to update the cloud dashboard with Kubernetes-related performance data for autosca... | def cloudMetricPublishing(pod_count: int, predicted_workload: int, prometheus_request_count: int, configurations: dict):
"""
Method to publish custom metrics to the Google cloud monitoring dashboard
Parameters
----------
pod_count
Number of pod replicas to be executed for the next iteration... |
def preset_argparser(elastic: bool = False):
parser = argparse.ArgumentParser()
parser = add_preset_arguments(parser, elastic)
return parser
def add_preset_arguments(parser: argparse.ArgumentParser, elastic: bool = True):
parser.add_argument("--conf", type=str, required=True)
parser.add_argument("... | The function parses command-line arguments, loads and validates a configuration using a Pydantic model, applies overrides, and optionally displays the configuration. It initializes an argument parser with elastic-specific parameters if required, returning the validated configuration and parsed arguments (if parser was ... | def load_arg_config(
config_model, show: bool = False, elastic: bool = False, parser=None
):
"""
Loads configuration based on command-line arguments and applies overrides.
This function initializes the argument parser with or without elastic specific arguments based on the `elastic` flag.
It then p... |
def zeroSlider(): #Sets the current PiCam slider position as 'home'
global sliderPosition
sliderPosition = 0
print("The current position of the PiCam is now the home position")
def runStackRoutine(): #With current settings,
global objectName
global stackNumber
global path
newPath = obj... | The code's main task is to execute a full camera routine involving multiple stacks of shots. It initializes settings, prints the routine details, loops through specified stacks, runs each stack's routine, rotates clockwise, and returns home. The function coordinates camera operations and mechanical movements for struct... | def runFullRoutine():
zeroSlider()
global camera
global numberStacks
global numberShots
print("PiCam Full Routine Started!")
print(str(numberStacks)+" stacks of " + str(numberShots) + " shots")
for x in range(0,numberStacks):
runStackRoutine()
driveCW()
goHome() |
def setHome(): # Sets the current PiCam slider position as 'home'
global sliderPosition
sliderPosition = 0
ui.location_value_lbl.setText(str(sliderPosition))
print("The current position of the PiCam is now the home position")
def runStackRoutine(): # With current settings
global projectName
glo... | The code executes a full imaging routine by capturing multiple stacks of shots, moving the camera directionally (clockwise/counter-clockwise) after each stack, and returning to the home position. It initializes settings, processes each stack, adjusts camera direction, and finalizes by returning to the starting point. | def runFullRoutine():
setHome()
global direction
global camera
global numberStacks
global numberShots
print("PiCam Full Routine Started!")
print(str(numberStacks)+" stacks of " + str(numberShots) + " shots")
for x in range(0,numberStacks):
runStackRoutine()
if direction =... |
def get_target(target):
"""Get a target by name, or return the default target object.
We can't use default args in function defs because the default is
set at runtime based on config"""
if target == None:
logger.debug("get_target: using target #0")
if len(config["targets"]) == 0:
... | The function preprocesses markdown content by reading it from a local or remote source, applying templates and filters if enabled, and returning the processed text. It handles both direct file reads and preprocessing via a templating environment, with options to bypass errors, apply filters, and use configuration setti... | def preprocess_markdown(page, target=None, categories=[], page_filters=[],
mode="html", current_time="TIME_UNKNOWN",
bypass_errors=False, skip_preprocessor="NOT SPECIFIED"):
"""Read a markdown file, local or remote, and preprocess it, returning the
preprocessed te... |
def get_target(target):
"""Get a target by name, or return the default target object.
We can't use default args in function defs because the default is
set at runtime based on config"""
if target == None:
logger.debug("get_target: using target #0")
if len(config["targets"]) == 0:
... | The function `parse_markdown` converts a page's markdown content into HTML by preprocessing, applying filters (both HTML-string and BeautifulSoup-based), handling errors, and returning the final filtered HTML. It uses markdown extensions, processes filters sequentially, and ensures robust parsing with logging. | def parse_markdown(page, target=None, pages=None, categories=[], mode="html",
current_time="", bypass_errors=False):
"""Takes a page object (must contain "md" attribute) and returns parsed
and filtered HTML."""
target = get_target(target)
logger.info("Preparing page %s" % page["name... |
def getNodeWithMostPeople(self, node):
"""
method to get the node with the most people in it.
Parameters
----------
node -> node in which we go through the branch lenghts.
Returns
-------
keyWithMostPeople : dictionnary key t... | This method recursively creates branches for a decision tree node based on population size. If a node's population exceeds 10% of the main node's population, it splits data into left/right branches (continuous) or value-based branches (categorical), handling missing values by assigning them to the most populated branch... | def createBranches(self, node, StoppingCriterionPopulation = 0.1):
"""
this method creates the branches for a specific node.
It is a recursive function and the stopping criterion used is
the size of the population in the node.
-> if more than 10% of mainNode populatio... |
def initializeMainNode(self , node):
"""
we initialize the main node by defining the best split and its corresponding
prediction as well as its remaining splits. we will then use the recursion function
"createBranch()" to compute the rest of the tree.
Parameters
... | This code initializes a Decision Tree class by splitting a dataset into training and test sets, determining the tree type based on the target attribute's data type, and building the decision tree structure through node initialization, branch creation, and terminal node counting. | def __init__(self , dataSet, DTC, attrToPredict, trainingProportion):
"""
this class represents the decision tree class.
the original size of the training set is set at 66% but can be modified at will
@parameters :
dataSet -> a pandas DataFrame
... |
def draw_grid(self):
'''
Draw a background grid of size (nx, ny)
Parameters
----------
ax : graphical/plotting axes, generated with
fig, ax = plt.subplots()
nx : integer
Number of squares in the grid horizontally (in the x-dimension)
ny : integer
Number of squares in t... | The main task of the code is to draw a maze based on the initial layout specified during object creation. It renders the grid structure, adds a pond if defined, and overlays maze elements if enabled. The method updates the plot associated with `self.ax`, ensuring the maze, grid, and optional features like ponds are vis... | def draw(self):
'''
Draw the maze
Note the maze drawn is the one specified when you first created this layout
with create_layout(...)
Parameters
----------
None
Returns
-------
The plot corresponding to self.ax has the maze plotted on it
'''
self.draw_grid()
if (se... |
def smart_pronoun_replace(sentence: str, token: str, choices: list) -> str:
"""
use an LM to choose between multiple options for a replacement (e.g. her --> their / them)
:param sentence: input sentence
:param token: token with more than one choice for replacement
:param choices: the options for rep... | The code converts a sentence to a gender-neutral form by replacing pronouns, verbs, and gendered terms using NLP techniques. It handles edge cases like single non-function pronouns, employs a language model for ambiguous mappings, and uses SpaCy to identify and pluralize verbs, creating a new document with replacements... | def convert(sentence: str) -> str:
"""
convert a sentence to gender-neutral form
:param sentence: sentence meeting SNAPE criteria (meaning 1 entity and 1 gender)
:return: sentence in gender-neutral form
"""
# check error case when input is a single word and the word is a non function pronoun
... |
def _singularize_verb_forms(self, sent: 'spacy.Doc') -> str:
'''
Singularize verb forms.
'''
verb_auxiliaries = self._find_all_verb_candidates(sent, ['they'])
verb_replacements = self._find_singular_forms(verb_auxiliaries)
new_toks = []
for tok in sent:
... | (The function rewrites gender-fair sentences by converting normalized inputs into generic male and female forms using linguistic rules. It checks for gendered terms, processes text with spaCy, singularizes verbs, and generates separate male/female versions while preserving original sentences. The output includes four v... | def reverse(self, sent: str, norm_sent: str) -> str:
'''
Rewrite a gender-fair sentence to use generic male and female forms using rules.
'''
if not self.contains_gendered_form(norm_sent):
return sent, norm_sent, norm_sent, norm_sent
tagged = self.spacy_tagger(norm_s... |
def calculate_state(self, initial=None):
if initial is None:
self.state = self.parent_state
initial_i, initial_j = 0, 0
for i in range(0, 3):
for j in range(0, 3):
if self.state[i][j] is None:
try:
... | This code initializes a new state object in a search algorithm, setting up a 3x3 grid, tracking parent state/action/cost, calculating available moves, generating a unique key, and determining the node's cost by incrementing the parent's cost. It handles state construction and prepares the node for traversal in problems... | def __init__(self, parent_state=None, parent_action=None, parent_cost=-1, state=None):
self.state = [[0 for i in range(0, 3)] for j in range(0, 3)]
self.i, self.j = 0, 0
self.parent_state = parent_state
self.parent_action = parent_action
try:
self.calculate_state(stat... |
def perr(filename, msg, option_or_alias = None):
msg_suffix = ''
if option_or_alias:
if isinstance(option_or_alias, Option):
msg_suffix = 'option '
if option_or_alias.name:
msg_suffix = "{} '{}' ".format(msg_suffix, option_or_alias.name)
else:
... | The function `check_long` validates a long command-line option name by ensuring it: (1) doesn't start with `--`, (2) matches a regex allowing alphanumeric, hyphens, and equals signs, (3) is unique in a global cache, and (4) for boolean types, its negated form is also unique. It reports errors via `perr` for invalid for... | def check_long(filename, option_or_alias, long_name, ctype=None):
"""
Check if given long option name is valid.
"""
global g_long_cache
if long_name is None:
return
if long_name.startswith('--'):
perr(filename, 'remove -- prefix from long', option_or_alias)
r = r'^[0-9a-zA-Z\... |
def format_include(include):
"""
Generate the #include directive for a given header name.
"""
if '<' in include:
return '#include {}'.format(include)
return '#include "{}"'.format(include)
def docgen_option(option,
help_common, man_common, man_common_smt, man_common_int,
... | The function `codegen_all_modules` generates code for handling command-line options across multiple modules, producing files like `options.cpp` and `options_holder.h`. It processes module-defined options, aliases, and their handlers, generating boilerplate code for parsing, default values, and documentation. It also cr... | def codegen_all_modules(modules, dst_dir, tpl_options, tpl_options_holder,
doc_dir, tpl_man_cvc, tpl_man_smt, tpl_man_int):
"""
Generate code for all option modules (options.cpp, options_holder.h).
"""
headers_module = [] # generated *_options.h header includes
headers_... |
def usage():
print('mkoptions.py <tpl-src> <tpl-doc> <dst> <toml>+')
print('')
print(' <tpl-src> location of all *_template.{cpp,h} files')
print(' <tpl-doc> location of all *_template documentation files')
print(' <dst> destination directory for the generated files')
print(' <toml>+ o... | The main task of the code is to generate module and option-related code files (e.g., .h, .cpp) and documentation based on configuration files and templates. It validates input arguments, checks directory/file existence, parses TOML configuration files to create module/option objects, ensures long option uniqueness and ... | def mkoptions_main():
if len(sys.argv) < 5:
usage()
die('missing arguments')
src_dir = sys.argv[1]
doc_dir = sys.argv[2]
dst_dir = sys.argv[3]
filenames = sys.argv[4:]
# Check if given directories exist.
for d in [src_dir, doc_dir, dst_dir]:
if not os.path.isdir(d):... |
def register_doctor(self, doctors):
register_window = tk.Toplevel(self.master)
register_window.title("Register Doctor")
tk.Label(register_window, text="Enter the doctor's details:").pack(pady=10)
first_name = tk.StringVar()
surname = tk.StringVar()
speciality = tk.Strin... | The code defines a method `handle_doctor_operation` that executes different doctor-related actions based on the input `operation` parameter. It triggers registration, viewing, updating, or deleting doctors by calling corresponding methods like `register_doctor`, `view_doctors`, `update_doctor`, and `delete_doctor`, ena... | def handle_doctor_operation(self, operation):
if operation == "Register Doctor":
self.register_doctor(self.doctors)
elif operation == "View Doctors":
self.view_doctors()
elif operation == "Update Doctor":
self.update_doctor()
elif operation == "Delete ... |
def register_view_update_doctor(self):
doctor_window = tk.Toplevel(self.master)
doctor_window.title("Doctor Management")
tk.Label(doctor_window, text="Choose the operation:").pack(pady=10)
operations = [
"Register Doctor",
"View Doctors",
"Update Doc... | This function routes user-selected options to corresponding methods for managing doctors, patients, and administrative tasks, including registration, viewing, updating, discharging, grouping patients, generating reports, and quitting, which saves data and exits the application. | def handle_option(self, option):
if option == "Register/view/update/delete doctor":
self.register_view_update_doctor()
elif option == "view patients":
self.view_patients()
elif option == "Discharge patients":
self.discharge_patients()
elif option == "V... |
def Update_Date(self):
self.CurrentTime = get_time() #Update "CurrentTime" attribute
self.month = (self.CurrentTime).strftime("%B") #Slice the necessary information from the attribute
self.date = int((self.CurrentTime).strftime("%d"))
self.DateLabel.configure(text = f"{self.month} {self... | This method updates specific widgets daily by checking which widgets are present in the Current_Widgets list and invoking their respective update methods, such as Update_Date(), Update_Compliment(), and Update_Quote(), based on their names. | def Update_Day(self): #This method is caleld to update widgets that are required to be updated daily
self.Current_Widgets = [self.UppL_Widget, self.UppR_Widget, self.Centre_Widget, self.Bott_Centre_Widget] #Update current widgets list attribute
if "Time/Date" in self.Current_Widgets: #Use selection to ... |
def update_date(self):
self.CurrentTime = get_time()
self.month = (self.CurrentTime).strftime("%B")
self.date = int((self.CurrentTime).strftime("%d"))
self.DateLabel.configure(text = f"{self.month} {self.date} {self.Get_Date_Prefix(self.date)}")
def update_quote(self):
self.Quote... | The main task of the code is to periodically update the date, quote, and greeting every 24 hours by sleeping for 86400 seconds (1 day), then printing "new day!" and recursively restarting the process to maintain continuous daily updates. | def update_day(self):
self.update_date()
self.update_quote()
self.update_greeting()
time.sleep(86400)
print("new day!")
self.update_day() |
def Update_Weather(self): #Method called to update weather widget
self.Weather_Data = Get_Weather_Data(self.Location[0], self.Location[1]) #Call the "Get_Weather_Data()" method with the location attribute as arguments
self.WeatherIcon_Path = self.Weather_Data["Image_Path"] #Fetch the weather icon path f... | The code periodically checks the current time and date, updating specific widgets (e.g., weather, news, reminders) when the hour or date changes. It ensures UI elements like greetings and daily data are refreshed hourly, using a loop with a 1-minute sleep to conserve resources, while handling exceptions to prevent cras... | def Update_Hour(self):
try:#Try except statement to prevent thread from crashing
Start_Time = None #Set local variable start time to none
Start_Date = self.date #Store the date the application has started in "Start_Date" attribute
while True: #Due to recusrison depth limits... |
def Get_IP_Location(): #This function is used to get the location of the users IP it returns this data as a list
try: #if an errror occurs during the API requests it will be caught
IpRequest = requests.get("https://api.ipify.org/?format=json") #Make the request using requests library to API web address spe... | This code initializes a Smart Mirror GUI application by setting up default data attributes (news, reminders, timetable, weather icon), configuring time/date information, and arranging widgets (upper left, upper right, center, bottom center) with specific content types like Time/Date, Weather, News, and Compliment. It i... | def __init__(self, *args, **kwargs): #Constructor with Non-keyword and keyword arguments so they can be passed in, packed as dictionary
super().__init__(*args, **kwargs) #Expand non-keyword and keyword dictionary into arguments and inherit atributes from superclass
#----------------- Attributes -------... |
def Upp_Left(self,type): #Used to configure the upper left widget in the window
if type == self.UppR_Widget: #Use selection to check if this widget is the same as the one on the left if so then a swap should be made, only one instance of each widget is possible due to hardware limitations
self.Widg... | The code updates interface preferences by receiving Bluetooth data, modifying global variables (Wi-Fi credentials, user settings), and adjusting widget layouts. It handles Wi-Fi connection status via JSON storage and triggers widget-specific updates (weather, news, reminders) based on received data. | def Update_Interface(self): #Called to update interface preference options
global WifiConnection,Wifi_Pass,Wifi_Login
blusock.listen(1) #Allow one connection request
while True: #Required to avoid recursion depth limit
self.recvdata = []
data = None
... |
def applyChangesToGraph(originalgraph, changes, areaCosts):
graph = originalgraph.copy()
for node in changes:
area = changes[node]
cost = areaCosts[area]
graph.nodes[node]["area"] = area
graph.nodes[node]["cost"] = cost
for nei in graph.adj[node]:
graph[node][nei]["area"] = area
grap... | This function implements an A* algorithm to find a path in a graph that matches a desired route by iteratively modifying the graph's areas. It uses heuristic search with a priority queue, checks path alignment, and returns the modified graph if a match is found, otherwise returns None. | def astarPolyLabels(graph, desiredPath, areaCosts, allowedAreaTypes, verbose):
# Chakraborti et al, "Plan Explanations as Model Reconciliation: Moving Beyond Explanation as Soliloquy", 2017
# https://github.com/TathagataChakraborti/mmp/
# note: using heuristic successors for speed, bypassing original implementati... |
def optInvLP(graph, desiredPath):
# Roland 2014 "Inverse multi-objective combinatorial optimization", eq. 5.10
# variables:
# x_j: indicator variable, whether edge j is part of the shortest path
# A_ij: node-arc incidence matrix (rows are nodes, columns are edges) = 1 if j leaves i, -1 if j enters... | The code benchmarks inverse optimization and path diversity methods to adjust graph weights/area costs so the desired path becomes the shortest. It evaluates methods like invLP, invCOT, and ksp/kdp-brandao by computing explanations, measuring L1 norm changes, variable modifications, and path distance from the desired r... | def benchmarkExplanationISP(graph, start, goal, area_costs, desired_path, problem_type, verbose, acceptable_dist):
# conclusions so far:
# 1.often no need for more than one path (no need for diverse paths), it's better to just get the shortest path
# then obtain a graph explanation, and use the shortest path of... |
def s_cube_root(a: Decimal):
if a == 0:
return 0
elif abs(a) <= 1:
leader = Decimal((abs(a)/a)*Decimal(abs(a)**Decimal(1/3)))
else:
if a < 0:
leader = -int(Decimal(abs(a))**(Decimal(1/3))) - 1
else:
leader = int(Decimal(a)**(Decimal(1/3))) + 1
powe... | The function computes the cube root of a complex number $ a + bi $, returning its real and imaginary parts (R, I) in proper form. It uses three strategies based on the ratio $ |b/a| $: (1) for $ 0.8 \leq |b/a| \leq 1.25 $, it applies a series expansion with adjustments; (2) for $ |b/a| \leq 0.8 $, it directly computes ... | def c_cube_root_proper_form(a: Decimal, b: Decimal):
# .8 ≤ |b/a| ≤ 1.25 or
# 0 ≤ |b/a| ≤ .8 or
# 1.25 ≤ |b/a|
if .8 <= abs(b/a) and abs(b/a) <= 1.25:
# cube_root(1 + bi/a) = (i - 1)*cube_root( (1 + b/a) + (b/a - 1)i )/cube_root(4)
# cube_root( (1 + b/a) + (b/a - 1)i ) = guess*∑cn( ((1 ... |
def s_cube_root(a: Decimal):
if a == 0:
return 0
elif abs(a) <= 1:
leader = Decimal((abs(a)/a)*Decimal(abs(a)**Decimal(1/3)))
else:
if a < 0:
leader = -int(Decimal(abs(a))**(Decimal(1/3))) - 1
else:
leader = int(Decimal(a)**(Decimal(1/3))) + 1
powe... | The code computes the cube root of a complex number `a + bi` using special cases for zero components and a helper function for general cases. It returns real (R) and imaginary (I) parts, handling scenarios where either `a` or `b` is zero separately, applying specific transformations before returning results. | def c_cube_root(a: Decimal, b: Decimal):
if a == 0 and b == 0:
R, I = Decimal(0), Decimal(0)
return R, I
elif a == 0:
R, I = Decimal(0), -s_cube_root(b)
R, I = AZeroSM(R, I, b)
return R, I
elif b == 0:
R, I = s_cube_root(a), Decimal(0)
R, I = BZeroSM(R... |
def window_setup():
"""
The "window_setup" functions creates a the playing window. The indent and the header are
the blank spaces between the walls of the window and the drawn matrix. The program builds
the height and width of the window taking in the consideration the indent and number of c... | This code implements a Minesweeper game using Pygame, handling mouse interactions for revealing cells and placing flags. It manages game states, bomb detection, win/loss conditions, a timer, and a return-to-menu button. The core tasks include initializing the board, processing user inputs, updating the game display, an... | def main():
global clickable
LEFT_MB = 1
RIGHT_MB = 3
# Names for the types of mouse buttons
window_setup()
# Creating the game window
matrix = np.zeros((rows + 1, cols + 1), dtype=int)
unveil_matrix = np.zeros((rows, cols), dtype=int) # (0 - hidden, 1 - revealed)
flag_matrix = n... |
def process_multiattack(multi_split, action_names):
# Set keywords to look for in multi_split strig
attack_words = ["attacks", "attacks.", "attacks:"]
multi_words = ["one", "once", "two", "twice", "three", "four", "five"]
multi_words_num = [1, 1, 2, 2, 3, 4, 5]
pop_words = ["with", "its", "and", "to... | The code processes an enemy's actions by extracting and organizing multiattack descriptions into individual attacks, removing duplicates, and aligning them with the original action list. It also handles legendary actions, marking their presence, and returns the structured processed enemy data with adjusted actions and ... | def process_actions(enemy):
processed_enemy = {}
attacks = {}
# List of actions from enemy API
action_names = []
# List of actions for processed enemy
attack_list = []
# List of actions in multiattack to remove from attack list
pop_list = []
# Create action list to use for multiattac... |
def getDocument( content ):
return BeautifulSoup( content, 'html5lib', from_encoding = 'utf-8' )
def processJavascriptModule( module_path, already_processed, final_doc ):
if module_path in already_processed:
return
already_processed.add( module_path )
content = open( p.abspath(module_path) ).read()
# Pr... | The code generates a new document by inlining JavaScript modules from the source file, appending original head elements, adding a `createCustomElement()` script, and integrating a `stat-block` from the original body. It processes each module, resolves their paths, and replaces them with processed content, then combines... | def generateInlineFile( source_file_path ):
final_doc = getDocument( '' )
doc = getDocument( open( source_file_path ).read() )
already_processed = set()
# Process each javascript module declared in the original file
modules = doc.select( 'script[type="module"]' )
for module in modules:
module_path = p.... |
def get_spells():
spells = []
with open(PATH + 'static/files/spells.csv', 'r', encoding='utf-8-sig') as csvfile:
spell_info = csv.DictReader(csvfile)
for spell in spell_info:
spells.append(spell)
return spells
def pull_monster(name, slug):
url = f"https://api.open5e.com/monst... | The code retrieves enemy data by fetching spell information, pulling monster details using a name and slug, processing the enemy object, and returning it for further use. | def get_enemy(name, slug):
spell_dict = get_spells()
enemy = pull_monster(name, slug)
process_enemy(enemy)
return enemy |
def GotoScreen(self, screenType: str, final = False):
if final:
self.loop = False
self.track.log("S: showing screen %s" % screenType)
self.timeOnScreen = 0
self.screenCurrent = self.Screen(screenType)
self.disp.fill(self.screenCurrent.screen)
self.disp.show()... | The code manages a loop that processes frames at a consistent interval. It starts at a specified screen, repeatedly calls rules processing, and adjusts timing by pausing if frame processing is too fast, ensuring each frame adheres to a predefined maximum duration (self.frameTime). The loop continues until self.loop is ... | def Loop(self, libTime, startingScreen):
self.GotoScreen(startingScreen)
startTime = libTime.get_time()
frameStart = startTime
while(self.loop):
frameStart = libTime.get_time()
self.CallRules(frameStart)
frameTime = libTime.get_time() - frameStart
... |
def isEmpty(self) -> bool:
return self.n == 0
def exchange(self, i: int, j: int):
swap = self.pq[i]
self.pq[i] = self.pq[j]
self.pq[j] = swap
def topDownHeapify(self, i: int):
temp = 2 * i + 1
if (temp + 1) < self.n and self.compareTo(temp, temp + 1):
temp = temp + 1
if temp < self.n a... | This code extracts the minimum element from a priority queue by removing the root node, replacing it with the last element, and restoring the heap property through top-down heapification, then returns the extracted key. | def extract(self) -> int:
if self.isEmpty():
print("Priority queue is empty")
key = self.pq[0]
self.n = self.n - 1
self.exchange(0, self.n)
self.topDownHeapify(0)
self.pq[self.n] = None
return key |
def get_token():
auth_data = {
"username": settings.USER_EMAIL,
"password": settings.USER_PASSWORD
}
header_data = {
"accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
}
auth_response = requests.post(
url=settings.AUTHORIZATION_... | The main task of the code is to insert a new item into a database via an API and update a PLC system. It retrieves an authentication token, locates an empty storage space, prepares item data, sends a POST request to the API with the item details, and instructs the PLC to store the item at the identified coordinates. Th... | def insert_new_item(new_item):
# Get Auth Token
token = get_token()
post_header = {
"accept": "application/json",
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
print("Authorization Successful !")
# Get empty space
empty_space = get_fir... |
def watch_left(piece,chessboard): # return an array with all the cordinate free in the direction the function is checking plus the eventually possible capture
i = copy.copy(piece.column)
j = copy.copy(piece.row)
team = copy.copy(piece.team)
starting_i = i
starting_j = j
move = []
while(i-1... | The function `possible_moves_check` generates all valid moves for a chess piece by checking left, right, up, down, and castling directions, aggregating results into a list. It skips rechecking pin status to prevent infinite loops between pin and check functions, ensuring efficient move generation without redundant vali... | def possible_moves_check(self,chessboard): # check the same possible moves without checking if the piece is pinned cause it was already check and to avoid an infinite loop caused by the pinned function asking for the in check function having another request from the pinned function and so on
move = []
... |
def pinned(piece,chessboard): # return true or false if the piece passed is pinned or not checked by removing that piece and watch if the number of piece giving check would increase
i = piece.column
j = piece.row
team = piece.team
x = king_position(team,chessboard)
piece_giving_check_before = in_c... | The code determines possible moves for a chess piece by checking if it's pinned. If pinned, it retrieves restricted moves via `watch_pinned`. Otherwise, it aggregates moves from all directions (left, right, up, down) and castling using helper functions, returning a consolidated list of valid moves. | def possible_moves(self,chessboard): # check if the piece is pinned, then, if available return an array with all the possible move
if (pinned(self,chessboard)):
move=[]
x = watch_pinned(self,chessboard)
if(x):
move.extend(x)
return move
el... |
def pinned(piece,chessboard): # return true or false if the piece passed is pinned or not checked by removing that piece and watch if the number of piece giving check would increase
i = piece.column
j = piece.row
team = piece.team
x = king_position(team,chessboard)
piece_giving_check_before = in_c... | This function determines possible moves for a chess piece. If the piece is pinned, it retrieves moves from `watch_pinned`; otherwise, it checks knight-specific moves via `watch_knight`. The result is a list of valid moves, conditionally populated based on the piece's state and type. | def possible_moves(self,chessboard):
if (pinned(self,chessboard)):
x = watch_pinned(self,chessboard)
if(x):
move.extend(x)
return move
else:
move = []
x = watch_knight(self,chessboard)
if(x):
move... |
def pinned(piece,chessboard): # return true or false if the piece passed is pinned or not checked by removing that piece and watch if the number of piece giving check would increase
i = piece.column
j = piece.row
team = piece.team
x = king_position(team,chessboard)
piece_giving_check_before = in_c... | This function determines the possible moves for a chess piece. If the piece is pinned, it retrieves moves from the `watch_pinned` function. Otherwise, it checks all four diagonal directions (up-left, down-left, down-right, up-right) using corresponding `watch_*` functions, compiling valid moves into a list. The result ... | def possible_moves(self,chessboard):
if (pinned(self,chessboard)):
x = watch_pinned(self,chessboard)
if(x):
move.extend(x)
return move
else:
move = []
x = watch_up_left(self,chessboard)
if(x):
mov... |
def pinned(piece,chessboard): # return true or false if the piece passed is pinned or not checked by removing that piece and watch if the number of piece giving check would increase
i = piece.column
j = piece.row
team = piece.team
x = king_position(team,chessboard)
piece_giving_check_before = in_c... | The function determines possible moves for a chess piece. If the piece is pinned, it retrieves moves from `watch_pinned`. Otherwise, it checks all eight cardinal and diagonal directions using functions like `watch_left`, `watch_right`, etc., collecting valid moves into a list and returning them. | def possible_moves(self,chessboard):
if (pinned(self,chessboard)):
x = watch_pinned(self,chessboard)
if(x):
move.extend(x)
return move
else:
move = []
x = watch_left(self,chessboard)
if(x):
move.exten... |
def pinned(piece,chessboard): # return true or false if the piece passed is pinned or not checked by removing that piece and watch if the number of piece giving check would increase
i = piece.column
j = piece.row
team = piece.team
x = king_position(team,chessboard)
piece_giving_check_before = in_c... | The function determines possible moves for a chess piece. If the piece is pinned, it returns moves from `watch_pinned`. Otherwise, it collects moves from `watch_pawn` and `watch_enpassant`, combining them into a list. The result is a list of valid moves considering pawn movements, en passant captures, and pin constrain... | def possible_moves(self,chessboard):
if (pinned(self,chessboard)):
x = watch_pinned(self,chessboard)
return x
else:
move = []
x = watch_pawn(self,chessboard)
if(x):
move.extend(x)
x = watch_enpassant(self,chessbo... |
def in_check(king,chessboard): # return an array containing all the coordinate of the moves giving check
if(type(king) == King):
move = []
coordinate_pieces_that_are_giving_check = [] # check all the coordinates where a piece could possibly give the king check
x = watch_up(king,chessboard... | The function `possible_moves` generates all valid moves for a chess piece, prioritizing defense against check by identifying threatening pieces. If under check, it extends moves from `watch_check_defense` to counter threats. Otherwise, it appends moves from `watch_king` (for king's mobility) and `watch_castling` (for c... | def possible_moves(self,chessboard):
move = []
coordinate_pieces_that_are_giving_check = in_check(self,chessboard) # it ask for the pieces giving check in order to give the array to watch check defense function that return all the possible moves to avoid the check
if(coordinate_pieces_that_are_... |
def create_prefix(self):
# read the environment file
env_name = "xeus-env"
root_prefix = Path(self.cwd.name) / "env"
env_file = Path(self.manager.lite_dir) / self.environment_file
# open the env yaml file if it's provided
if env_file.exists():
with open(env_f... | The post_build method configures the environment by checking for an environment file (yml/yaml) in the lite directory, ensuring a prefix is set (creating it if missing), and copying kernels and JupyterLab extensions from the prefix. It enforces that either a prefix or environment file must be specified to establish the... | def post_build(self, manager):
if self.environment_file is None:
if (Path(self.manager.lite_dir) / "environment.yml").exists():
self.environment_file = "environment.yml"
if (Path(self.manager.lite_dir) / "environment.yaml").exists():
self.environment_file... |
def register_job_type(message, option):
"""save the job type
Args:
message (types.Message): information about the user
option (string): the option chosen by the user
"""
chat_id = message.chat.id
bot.send_message(chat_id, f"Okay {option.data} is the type of your job")
JOB[option... | This function handles callback queries from custom keyboards by determining the action based on the callback data. It registers job types/formats or adds filters when the data matches specific patterns, then responds to the callback without alerts. | def callback_query(call):
"""function to handle all the callbacks from custom keyboards
Args:
call (types.CallbackQuery): the callback data to be handled
"""
if call.data in (job.lower() for job in JOB_TYPES):
register_job_type(call.message, call)
elif call.data in ("find_" + job.lo... |
def _check_collision_corners(self, ball, *areas):
for a in areas:
if ball.rect.colliderect(a.rect):
ball.tl = a.rect.collidepoint(ball.rect.topleft)
ball.tr = a.rect.collidepoint(ball.rect.topright)
ball.bl = a.rect.collidepoint(ball.rect.bottomleft)
... | This code updates game elements by decrementing time, handling ball-paddle and ball-block collisions, updating scores, managing block and bonus states, and transitioning to the next level or ending the game when conditions are met. It also manages ball activation, player lives, and sound effects. | def update(self):
self.time_left -= 1
for ball in self.balls:
if self._check_collision_corners(ball, self.paddle):
ball.custom_angle = self.paddle.get_bounce_angle(ball.rect.centerx)
ball.update()
continue
ball.hit = self._check_col... |
def get_coeffs(N):
# get the coefficients of the functions Chebyshev expansion
coeffs = np.zeros(N)
Tmax = cheby.ChebyshevK(N + 1, 32)
zeros = Tmax.get_zeros_cosless()
for i in range(0, N):
coeffs[i] = calculate_coeff(i, N, zeros)
return coeffs
def f(z):
# function... | The main task of the code is to approximate a function and its first, second, and fourth derivatives using Chebyshev polynomials of order 8, with 1000 points. It constructs derivative coefficient matrices (D₁, D₂, D₄), computes polynomial coefficients, evaluates the function and derivatives at grid points, and plots co... | def main():
order = 8
accuracy = 1000
D_1 = D1(order + 1)
D_2 = D2(order + 1)
D_4 = D4(order + 1)
# get the approximation coefficients
coeffs = get_coeffs(order + 1)
# work out the coefficients of the derivatives using D matrices
firstDiffCoeffs = np.matmul(D_1, coeffs... |
def sum_data(data, maintain_threads=False):
master = {}
for (k, v) in data:
for (tn, td) in v.items():
if maintain_threads:
kn = "|".join(k + [ str(tn) ])
else:
kn = "|".join(k)
if kn in master:
md = master[kn]
... | The code processes input data to generate visualizations of operational metrics, focusing on read, write, compare-and-swap (CAS), and abort operations across different data subsets. It filters and aggregates data for single/isolated vs. multi-threaded scenarios, varying operation sizes (32/64-bit), and specific operati... | def plot_data(fn, data):
ops_read = ['x_read32', 'x_read64', 'u_read32', 'u_read64']
ops_write = ['x_write32', 'x_write64', 'u_write32', 'u_write64']
ops_cas = ['x_cas32', 'x_cas64', 'u_cas32', 'u_cas64']
ops_wc = ['u_write64', 'x_write64', 'x_cas64']
ops_rw32 = ['x_read32', 'x_write32', 'x_cas32']
... |
def die(*s):
warn(*s)
sys.exit(1)
def warn(*s):
print("".join(map(str, s)), file=sys.stderr)
def parse_log(fn):
mode = None
memory = "isolated"
mode_line = re.compile(r'(single|homogenous|heterogenous) thread tests')
memory_line = re.compile(r'(isolated|shared) memory tests')
thread_line... | The main task of the code is to parse a log file into structured data, then either plot the data to an output file or print parsed entries based on command-line arguments. It validates input parameters, processes log content, and conditionally executes plotting if enabled, while handling errors and warnings for missing... | def main(args):
if len(args) < 2:
die('rtm-graph.py <log-file> <output-file> [<plot-log>]')
log_file = args[0]
out_file = args[1]
global plot_log
plot_log = False
if len(args) == 3:
plot_log = True
if not can_plot:
warn('unable to plot')
print('parsing', log_f... |
def _parse_args(self) -> None:
parser = ArgumentParser()
parser.add_argument(
"-e",
"--encode",
action="store_true",
default=True,
required=False,
help="Encode the text",
)
parser.add_argument(
"-d",
... | The code initializes a class to handle encoding/decoding operations using predefined segments ("ku", "ra", etc.). It parses arguments, validates input type, reads input data, performs transformation (encode/decode), and outputs the result. The core task is to process input strings through a sequence of steps defined by... | def __init__(self) -> None:
# k: u -> a, r: a -> u
self.segments: tuple[str, ...] = (
"ku",
"ra",
"ko",
"re",
"ki",
"ri",
"ke",
"ro",
"ka",
"ru",
)
self.idx: int = 0
... |
def squareUnderAttack(self, r, c):
self.whiteToMove = not self.whiteToMove # switch to get opponents moves
oppMoves = self.getAllPossibleMoves()
self.whiteToMove = not self.whiteToMove # switch back
for move in oppMoves:
if move.endRow == r and move.endCol == c: # square i... | This function generates valid castling moves for a chess game. It checks if the king is not in check and verifies castle rights (king/queen side) based on the current player's turn. If conditions are met, it calls helper methods to add king-side or queen-side castling moves to the provided list. | def getCastleMoves(self, r, c, moves):
if self.squareUnderAttack(r, c):
return # Can't castle in check
if (self.whiteToMove and self.currentCastleRights.wks) or (not self.whiteToMove and self.currentCastleRights.bks):
self.getKingSideCastleMoves(r, c, moves)
... |
def checkForPinsAndChecks(self):
pins = [] # Squares where a piece is pinned and direction it is pinned from
checks = [] # Squares where there is a check from
inCheck = False
if self.whiteToMove:
enemyColour = "b"
allyColour = "w"
startRow = s... | This function determines valid moves for the current player by checking if the king is in check, generating possible moves, and filtering them to block checks or capture attackers. If in check, it handles single/double check scenarios, removing invalid moves. If not in check, it adds castling moves. Finally, it checks ... | def getValidMoves(self):
# Checking move is legal
moves = []
self.inCheck, self.pins, self.checks = self.checkForPinsAndChecks()
if self.whiteToMove:
kingRow = self.whiteKingLocation[0]
kingCol = self.whiteKingLocation[1]
else:
kingRow = self.blac... |
def opening(game_in_question):
ply_count = 0
root_node = game_in_question.parent
node = game_in_question.end()
url = urllib.request.urlopen(
"https://raw.githubusercontent.com/CoderAryanAnand/pythonChessAnalyzer/main/chessAnalyzer/eco_codes/eco"
".json")
content = url.read()
eco_... | The main task of the code is to analyze a chess game from a PGN file by categorizing each player's moves into quality ratings (e.g., "Best move," "Blunder") based on evaluation deltas compared to the best move. It generates move statistics, saves problematic positions as SVGs, creates a directory structure for reports,... | def game_report(self, pgn_loc: str, annotate=False) -> tuple:
# Read game and create starting position
pgn = chess.pgn.read_game(open(pgn_loc))
board = chess.Board()
opening(pgn)
# Mark the end of the game
pgn.end().comment = "End of game. " \
... |
def partition(_dist_,_borough_,_pop_):
m_ = int(subway_prop_population(_dist_,_borough_)*_pop_)
c_ = int(car_prop_population(_dist_,_borough_)*_pop_)
i_ = int(in_commute_prop_population(_dist_,_borough_)*_pop_)
h_ = int(_pop_ - (m_+c_+i_))
return [m_,c_,i_,h_]
def compute_effectives(_nta_dict_,_mode... | The main task of the code is to simulate a disease spread model across New York City's NTAs using a 4D array to track population dynamics in different compartments (S, E, I, R, D) and SIR boxes (metro, car, in-borough, home). It initializes populations, applies government interventions (e.g., reduced metro usage, stay-... | def main(time,beta_metro):
# initialize a 4-D array
# dim
# 1: time
# 2: NTA
# 3: category
# 4: SIR box
model = np.zeros([time,len(ntas),4,6])
# map the NTA names to numbers in array
nta_dict = {}
# for all the NTAs with nonzero populations
for i in range(len(ntas)):
... |
def query(stmt, args=()):
db = get_db()
if db["db"] == "postgres" or db["db"] == "mysql":
stmt = re.sub("[?]", "%s", stmt)
return (db['cursor'].execute(stmt, args))
def fetch():
db = get_db()
return db['cursor'].fetchone()
def commit():
db = get_db()
return db['commit']() | This function stores a variable-value pair in a database. It checks if the variable exists; if not, it inserts a new entry, otherwise it updates the existing value. The operation ensures consistent storage of variables with atomic database transactions. | def setvar(name, val):
query("select val from vars where var = ?", (name,))
if fetch() is None:
query("insert into vars (var, val) values (?, ?)", (name, val))
else:
query("update vars set val = ? where var = ?", (val, name))
commit() |
def query(stmt, args=()):
db = get_db()
if db["db"] == "postgres" or db["db"] == "mysql":
stmt = re.sub("[?]", "%s", stmt)
return (db['cursor'].execute(stmt, args))
def fetch():
db = get_db()
return db['cursor'].fetchone()
def commit():
db = get_db()
return db['commit']() | The code generates a sequence number by querying a database table 'seq' for the last value. If the table is empty, it initializes the sequence at 100. Otherwise, it increments the last value by 1, updates the table, and returns the new value. This ensures a unique, sequential ID is produced each time the function is ca... | def get_seq():
query("select lastval from seq")
result = fetch()
if result is None:
curval = 100
query("insert into seq (lastval) values (?)", (curval,))
commit()
else:
curval = result[0] + 1
query("update seq set lastval = ?", (curval,))
commit()
... |
def get_db():
global db
if db is not None:
return db
cfg = psite.get_cfg()
db = dict(db=cfg["db"])
if cfg["db"] == "sqlite3":
import sqlite3
filename = "{}/{}.db".format(cfg['aux_dir'], cfg['dbname'])
db['conn'] = sqlite3.connect(filename)
make_writable_for_... | This function creates a database table or adds a column to an existing table. It checks if the table exists; if not, it creates it with the specified column and data type. If the table exists but the column is missing, it appends the column using ALTER TABLE. For MySQL, it adds "null" to timestamp columns. The SQL stat... | def make_column(table, column, coltype):
db = get_db()
if not table_exists(table):
stmt = "create table {} ({} {})".format(table, column, coltype)
print(stmt)
db['cursor'].execute(stmt)
elif not column_exists(table, column):
stmt = "alter table {} add {} {}".format(table, col... |
def setup_siteid(site_name_arg, conf_key_arg):
cfg = psite.get_cfg()
if 'site_name' not in cfg:
if site_name_arg is None:
print("must specify site_name for first call to install-site")
sys.exit(1)
else:
cfg['site_name'] = site_name_arg
if 'conf_key' not ... | The main task of the code is to install and configure a web site by setting up database connections, SSL settings, directories, URLs, Apache or .htaccess, cron jobs, and a daemon. It processes input parameters, generates configuration data, writes it to a JSON file, and outputs key URLs. The function handles optional s... | def install(site_name_arg=None, conf_key_arg=None):
cfg = psite.get_cfg()
setup_siteid(site_name_arg, conf_key_arg)
cfg['db'] = psite.get_option("db", "")
cfg['dbname'] = psite.get_option("db_dbname", cfg['siteid'])
setup_name_and_ports()
if psite.get_option('skip_ssl', 0) == 1:
cfg['s... |
def sceneToNormalMap(scene):
''' Draws faces in 2D map, coloring slopes
Returns PNG, pixels as map cells
'''
minX, minY, minZ = float('inf'), float('inf'), float('inf')
maxX, maxY, maxZ = float('-inf'), float('-inf'), float('-inf')
print("analyzing ...")
for x, y, z in scene.vertices:
minX = x if ... | The main task of the code is to convert a 3D model (OBJ file) into a normal map, process geographic data, generate a path on a TIFF image using scaling factors and coordinates, visualize the path, and composite it with the normal map to produce a final PNG image for QGIS analysis and visualization. | def main():
scene = pywavefront.Wavefront(path_to_obj, collect_faces=True)
slopeMap = sceneToNormalMap(scene)
Image.MAX_IMAGE_PIXELS = None
tif = Image.open(path_to_tif)
res = Image.new("RGBA", slopeMap.size, (0,0,0,0))
path = doPF(slopeMap)
[pw, _a, _b, ph, oriLat, oriLong] = getGEOData()
print(pw, _... |
def drawOutline(self, qp):
circle_pen = QtGui.QPen(
self._palette.color(QtGui.QPalette.Active, QtGui.QPalette.Midlight)
)
circle_pen.setWidth(8)
qp.setBrush(self._palette.brush(QtGui.QPalette.Active, QtGui.QPalette.Mid))
qp.setPen(circle_pen)
qp.drawEllipse(... | This code renders a graphical widget by initializing a QPainter, enabling antialiasing, and drawing an outline, progress arc, and text. It manages the painting process by beginning and ending the QPainter operations to display the visual elements on the widget. | def render(self):
qp = QtGui.QPainter()
qp.begin(self)
qp.setRenderHints(qp.Antialiasing)
self.drawOutline(qp)
self.drawProgressArc(qp)
self.drawText(qp)
qp.end() |
def msm_projection_trajectories(hp_dict, feat_trajs, seed, lag, processes) -> List[np.array]:
# Estimate MSM
tica, kmeans = discretize_trajectories(hp_dict, feat_trajs, seed)
disc_trajs = kmeans.dtrajs
mod = estimate_msms(disc_trajs, [lag])[lag]
# Project onto MSM right eigenvectors
ptrajs = g... | (The function generates and saves enhanced sampling trajectories using metastable state projections from input trajectory data. It processes multiple trajectories, projects them into metastable states, samples enhanced paths (ev), saves each as XTC files, and stores metadata (indices and parameters) in a pickle file fo... | def bs_ev_sample(hp_dict: Dict[str, List[Union[str, int]]],
feat_trajs: List[np.ndarray], bs_ix: np.ndarray, seed: Union[int, None],
out_path: Path, hp_idx: int,
lag: int, processes: int, num_cuts: int, traj_paths: List[str], top_path: str) -> bool:
bs_traj_paths = [traj_paths... |
def get_ttps_from_dir(dir: Path, top: str) -> Dict[str, Union[str, List[str]]]:
ev_traj_paths = list(dir.glob('*.xtc'))
ev_traj_paths.sort()
ev_traj_paths = [str(x) for x in ev_traj_paths]
return {'trajs': ev_traj_paths, 'top': top}
def get_feature_trajs(traj_top_paths: Dict[str, List[str]],hp_dict: Dic... | This function projects enhanced sampling trajectories onto the right eigenvectors of a Markov State Model (MSM). It discretizes feature trajectories, estimates an MSM from the data, and projects each trajectory onto the MSM's eigenvectors. Results are saved as pickled data, enabling analysis of conformational dynamics ... | def project_single_evs(hp_dict: Dict, lag: int, top_path: str, all_ftrajs: List[np.ndarray], seed: int,
output_path: Path, ev_dir: Path):
ttps = get_ttps_from_dir(ev_dir, top_path)
ev_ftrajs = get_feature_trajs(ttps, hp_dict)
ftrajs = randomize_trajs_from_metadata(ev_dir, all_ftrajs)... |
def get_feature_trajs(traj_top_paths: Dict[str, List[str]],hp_dict: Dict[str, List[Union[str, int]]]) -> List[np.ndarray]:
traj_top_paths['trajs'].sort()
feat_trajs = create_features(hp_dict, traj_top_paths)
logging.info(f"Added features")
return feat_trajs
def get_rng(seed: Union[int, None]) -> Any:
... | (The function performs bootstrap sampling on feature trajectories for multiple lag times. It prepares input data, initializes parallel processing, and executes the bootstrap function across specified samples. Results are saved in designated directories, with parallel execution optimized for core count. The task involve... | def bootstrap(config: Tuple[str, Dict[str, List[Union[str, int]]]],
traj_top_paths: Dict[str, List[str]], seed: int,
bs_samples: int, n_cores: int, output_dir: Path, bs_func: Callable[..., bool],
**kwargs) -> None:
""" Bootstraps the count matrices at a series of lag times.... |
def create_ouput_directory(path: Path) -> Path:
path.mkdir(exist_ok=True)
return path
def setup_logger(out_dir: Path) -> None:
logging.basicConfig(filename=str(out_dir.joinpath('log')),
filemode='w',
level=logging.INFO,
format='%(asctim... | This function samples metastable states from molecular dynamics trajectories by discretizing them using specified hyperparameters, then generates samples based on metastable state counts, lag time, and trajectory data, saving results to a designated output directory. | def sample_metastable(hp_ix, n_metastable, lag,n_samples, hp_sample, data_dir, topology_path, trajectory_glob,
output_dir, seed):
output_dir = create_ouput_directory(output_dir.absolute())
setup_logger(output_dir)
hp_dict = get_hyperparameters(hp_sample, [hp_ix])
hp_dict = {k: v[hp... |
def create_ouput_directory(path: Path) -> Path:
path.mkdir(exist_ok=True)
return path
def setup_logger(out_dir: Path) -> None:
logging.basicConfig(filename=str(out_dir.joinpath('log')),
filemode='w',
level=logging.INFO,
format='%(asctim... | The main task of the code is to process trajectory data using specified hyperparameters, perform dimensionality reduction (TICA) and clustering (K-means), then save cluster centers and discrete trajectories for each hyperparameter configuration. It iterates over input trajectories, generates feature trajectories, appli... | def dump_dtrajs(hp_sample, data_dir, topology_path, trajectory_glob, output_dir, seed, hp_ixs) -> None:
output_dir = create_ouput_directory(output_dir.absolute())
setup_logger(output_dir)
print('HP_IXs', hp_ixs)
hps = get_hyperparameters(hp_sample, hp_ixs)
traj_top_paths = get_input_trajs_top(data_d... |
def create_ouput_directory(path: Path) -> Path:
path.mkdir(exist_ok=True)
return path
def setup_logger(out_dir: Path) -> None:
logging.basicConfig(filename=str(out_dir.joinpath('log')),
filemode='w',
level=logging.INFO,
format='%(asctim... | This function processes trajectory data using specified hyperparameters by creating an output directory, retrieving input trajectories and topology paths, configuring hyperparameters, and executing a parallelized projection task via `project_bs` with given settings like lag, cores, and seed, saving results to the desig... | def project_evs(lag, hp_sample, data_dir, topology_path, trajectory_glob, num_cores,
output_dir, seed, hp_ix, project_dir, project_ixs):
output_dir = create_ouput_directory(output_dir.absolute())
setup_logger(output_dir)
hps = get_hyperparameters(hp_sample, [hp_ix])
traj_top_paths = g... |
def create_ouput_directory(path: Path) -> Path:
path.mkdir(exist_ok=True)
return path
def setup_logger(out_dir: Path) -> None:
logging.basicConfig(filename=str(out_dir.joinpath('log')),
filemode='w',
level=logging.INFO,
format='%(asctim... | The function `score` evaluates hyperparameters by bootstrapping performance scores across multiple trajectories and lags. It sets up an output directory, retrieves hyperparameters and trajectory-topology paths, parses lags, and iterates over each hyperparameter configuration. For each configuration, it logs details and... | def score(hp_sample, hp_ixs, data_dir, topology_path, trajectory_glob, num_repeats, num_cores, lags, output_dir, seed) -> None:
output_dir = create_ouput_directory(output_dir.absolute())
setup_logger(output_dir)
hps = get_hyperparameters(hp_sample, hp_ixs)
traj_top_paths = get_input_trajs_top(data_dir.a... |
def create_ouput_directory(path: Path) -> Path:
path.mkdir(exist_ok=True)
return path
def setup_logger(out_dir: Path) -> None:
logging.basicConfig(filename=str(out_dir.joinpath('log')),
filemode='w',
level=logging.INFO,
format='%(asctim... | (The main task of the code is to perform bootstrap sampling for each set of hyperparameters specified by `hp_ixs`, using trajectory and topology data from the given directory. It iterates over hyperparameter configurations, logs each run, and executes a bootstrap analysis (`bs_ev_sample`) with parameters like lag, proc... | def sample_evs(lag, processes, num_cuts, hp_sample, data_dir, topology_path, trajectory_glob, num_repeats, num_cores,
output_dir, seed, hp_ixs):
output_dir = create_ouput_directory(output_dir.absolute())
setup_logger(output_dir)
print('HP_IXs', hp_ixs)
hps = get_hyperparameters(hp_sample,... |
def create_ouput_directory(path: Path) -> Path:
path.mkdir(exist_ok=True)
return path
def setup_logger(out_dir: Path) -> None:
logging.basicConfig(filename=str(out_dir.joinpath('log')),
filemode='w',
level=logging.INFO,
format='%(asctim... | The code performs a bootstrap analysis on trajectory data using specified hyperparameters. It iterates over hyperparameter configurations, runs repeated tests (`bs_cktest`) with given lags and metastable states, and saves results. The task involves assessing stability or variability of outcomes across different paramet... | def ck_test(hp_ixs, n_metastable, lag, n_lags, num_repeats, num_cores, hp_sample, data_dir, topology_path, trajectory_glob,
output_dir, seed):
output_dir = create_ouput_directory(output_dir.absolute())
setup_logger(output_dir)
hps = get_hyperparameters(hp_sample, hp_ixs)
traj_top_p... |
def __get_next_lines(self):
"""
Increases the position of both lines
"""
if self.__line_number >= self.__matrix.shape[1]:
self.__line_one = self.__line_two
else:
self.__line_one = self.__matrix[:, self.__line_number - 1]
self.__line_two = self.... | This function updates the status of two lines by analyzing obstacles and cells. It calculates obstacle counts, continuity between lines, and sets a state based on comparisons like obstacle numbers and continuity checks. The state determines conditions such as beginning, end, or transitions between line configurations, ... | def update(self, start = False):
"""
Updates the status of both lines after checking them in the final_decomposition function
"""
self.__line_number = 0 if start else self.__line_number + 1 # coordinates of the obstacle being searched
if not start:
self.__get_next_lin... |
def update(self, start = False):
"""
Updates the status of both lines after checking them in the final_decomposition function
"""
self.__line_number = 0 if start else self.__line_number + 1 # coordinates of the obstacle being searched
if not start:
self.__get_next_lin... | The code performs Boustrophedon decomposition by dividing a space into cells based on obstacle configurations. It iteratively updates the decomposition, handling scenarios like continuous/discontinuous obstacles, adjusting cell assignments dynamically. The method checks states such as obstacle continuity, merges or spl... | def final_decomposition(self):
"""
Performs Boustrophedon decomposition (divides space into cells)
"""
while(self.__line_number < self.__matrix.shape[1]-1):
self.update()
if(self.__state["EquObst_AbsContin"]): #
for i in range(len(self.... |
def heb_to_num(M, D, Y):
year = 1
days = 0
previous_days = 0
year_type = ""
while year < Y+1:
year_type, hours_past_day, parts_into_week, day_in_week, total_days = yearLength(year)
if year_type == "kesidrah" and parts_into_week > (2*24*1080+9*1080+204):
total_days += 2
elif le... | The code converts a given number of days into a Gregorian calendar date (month, day, year), handling both positive and negative day counts. It adjusts for leap years, subtracts days to determine the year, and iterates through months to find the correct month and day. The function involves Hebrew-to-Gregorian date conve... | def num_to_eng(days):
if days >= heb_to_num(4, 17, 3761):
days -= heb_to_num(4, 17, 3761)
Year = 1
while days > 365:
days -= gregLeap(Year)
Year += 1
Month = 1
if gregLeap(Year) == 366:
while (days > 31 and Month in [January, March, May, July, August, October, December]) or (days... |
def heb_to_num(M, D, Y):
year = 1
days = 0
previous_days = 0
year_type = ""
while year < Y+1:
year_type, hours_past_day, parts_into_week, day_in_week, total_days = yearLength(year)
if year_type == "kesidrah" and parts_into_week > (2*24*1080+9*1080+204):
total_days += 2
elif le... | The function converts a Gregorian date (month M, day D, year Y) into a total number of days since a specific Hebrew date (4/17/3761), accounting for leap years and varying month lengths. It handles positive and negative years differently, using a 365.2425-day year average for negative years. The result is adjusted by s... | def eng_to_num(M, D, Y):
if Y > 0:
daysTot = heb_to_num(4, 17, 3761)
year = 1
while year < Y:
daysTot += gregLeap(year)
year +=1
for i in range(1, M):
daysTot += greg_months(Y, i)
daysTot += D
else:
start = heb_to_num(4, 17, 3761)
daysTot = ((Y))*365.2425
daysT... |
def create_tensor(val):
t = torch.Tensor([val])
t.requires_grad = True
return t
def add_val(val, name):
"""Add the val and grad of a torch.Tensor."""
torch_res.append([name, val.item(), val.grad.item()])
def test_against_cn(code, show=False):
"""Do the test."""
my_impl_res = get_res(code)
... | This function tests PyTorch tensor operations and gradient calculations. It creates tensors, performs mathematical operations (multiplication, addition, subtraction, tanh), retains gradients, executes backpropagation via g.backward(), and stores results in a global list for validation against expected values using test... | def do_test_one():
"""Test general things one."""
global torch_res
torch_res = []
a = create_tensor(-2)
b = create_tensor(3)
c = a * b
d = a + b
e = c * d
f = a - e
g = torch.tanh(f)
c.retain_grad()
d.retain_grad()
e.retain_grad()
f.retain_grad()
g.retain_gra... |
def create_tensor(val):
t = torch.Tensor([val])
t.requires_grad = True
return t
def add_val(val, name):
"""Add the val and grad of a torch.Tensor."""
torch_res.append([name, val.item(), val.grad.item()])
def test_against_cn(code, show=False):
"""Do the test."""
my_impl_res = get_res(code)
... | The main task of the code is to test tensor operations and gradient calculations in a PyTorch-like environment. It creates tensors, performs arithmetic operations (addition, multiplication, ReLU), tracks gradients, computes backward passes, and compares results against expected values using `test_against_cn("2")` for v... | def do_test_two():
"""Test general things two."""
global torch_res
torch_res = []
a = create_tensor(-4)
b = create_tensor(2)
c = a + b
c.retain_grad()
d = (a * b) + b
c += c + 1 # -3
c += 1 + c + (-a) # -3+=2, -1
d += d * 2 + (b + a).relu()
d += 3 * d + (b - a).relu()
... |
def create_tensor(val):
t = torch.Tensor([val])
t.requires_grad = True
return t
def add_val(val, name):
"""Add the val and grad of a torch.Tensor."""
torch_res.append([name, val.item(), val.grad.item()])
def test_against_cn(code, show=False):
"""Do the test."""
my_impl_res = get_res(code)
... | This function tests power operations in a computational graph by raising tensor 'a' to the power of tensor 'b', squaring the result, computing gradients via backpropagation, and verifying outcomes against a reference implementation ("pow") for correctness. | def do_test_pow():
"""Test raising things to a power."""
global torch_res
torch_res = []
a = create_tensor(5)
b = create_tensor(10)
c = a**b
c = c**2
c.retain_grad()
c.backward()
add_val(a, 'a')
add_val(b, 'b')
add_val(c, 'c')
test_against_cn("pow") |
def create_tensor(val):
t = torch.Tensor([val])
t.requires_grad = True
return t
def add_val(val, name):
"""Add the val and grad of a torch.Tensor."""
torch_res.append([name, val.item(), val.grad.item()])
def test_against_cn(code, show=False):
"""Do the test."""
my_impl_res = get_res(code)
... | The code tests tensor operations and gradient calculations by creating tensors, performing arithmetic operations (addition, multiplication, subtraction), retaining gradients, and executing a backward pass to compute gradients. It verifies how in-place modifications and dependencies affect gradient propagation in a comp... | def do_test_on_itself():
"""Test adding variables to themselves."""
global torch_res
torch_res = []
a = create_tensor(3)
b = create_tensor(7)
c = a + b
c.retain_grad()
c += 2
c += 2
c *= a
c -= b
d = 5
d -= c
d += d
d.retain_grad()
d.backward()
add_val... |
def create_tensor(val):
t = torch.Tensor([val])
t.requires_grad = True
return t
def add_val(val, name):
"""Add the val and grad of a torch.Tensor."""
torch_res.append([name, val.item(), val.grad.item()])
def test_against_cn(code, show=False):
"""Do the test."""
my_impl_res = get_res(code)
... | The main task of the code is to test the PyTorch `tanh` activation function by computing its output and gradients for a simple linear combination of tensors, then comparing results against a custom implementation. It initializes tensors for inputs, weights, and bias, computes `n = x1*w1 + x2*w2 + b`, applies `tanh(n)`,... | def do_test_tanh():
"""Test tanh function."""
global torch_res
torch_res = []
x1 = create_tensor(2)
x2 = create_tensor(0)
w1 = create_tensor(-3)
w2 = create_tensor(1)
b = create_tensor(7)
n = x1*w1 + x2*w2 + b
o = torch.tanh(n)
o.backward()
add_val(x1, "x1")
add_... |
def create_tensor(val):
t = torch.Tensor([val])
t.requires_grad = True
return t
def add_val(val, name):
"""Add the val and grad of a torch.Tensor."""
torch_res.append([name, val.item(), val.grad.item()])
def test_against_cn(code, show=False):
"""Do the test."""
my_impl_res = get_res(code)
... | This code tests the ReLU activation function in PyTorch by creating tensors with gradients, computing their product, applying ReLU, performing backward propagation, and verifying results against expected values through gradient checks and value comparisons. | def do_test_relu():
"""Test relu function."""
global torch_res
torch_res = []
a = create_tensor(10.0)
a.requires_grad = True
b = create_tensor(5.0)
b.requires_grad = True
c = a * b
d = torch.relu(c)
c.retain_grad()
d.retain_grad()
d.backward()
add_val(a, 'a')
add... |
def create_tensor(val):
t = torch.Tensor([val])
t.requires_grad = True
return t
def add_val(val, name):
"""Add the val and grad of a torch.Tensor."""
torch_res.append([name, val.item(), val.grad.item()])
def test_against_cn(code, show=False):
"""Do the test."""
my_impl_res = get_res(code)
... | The code tests the correctness of a PyTorch sigmoid function implementation by constructing a computational graph with tensors `a`, `b`, and `c`, computing intermediate values `d`, `e`, and `f` (where `f = sigmoid(e)`), and performing backpropagation to calculate gradients. It retains gradients for `d`, `e`, and `f`, t... | def do_test_sigmoid():
"""Test sigmoid function."""
global torch_res
torch_res = []
a = create_tensor(0.3)
a.requires_grad = True
b = create_tensor(0.5)
b.requires_grad = True
c = create_tensor(-1.0)
c.requires_grad = True
d = (a + b) * c
e = d * a
f = torch.sigmoid(e)
... |
def create_tensor(val):
t = torch.Tensor([val])
t.requires_grad = True
return t
def add_val(val, name):
"""Add the val and grad of a torch.Tensor."""
torch_res.append([name, val.item(), val.grad.item()])
def test_against_cn(code, show=False):
"""Do the test."""
my_impl_res = get_res(code)
... | This function tests PyTorch's LeakyReLU implementation against ClearNet's version by constructing a computational graph with tensor operations, computing gradients via backward propagation, and collecting results for comparison. It creates tensors with gradients, applies mathematical operations, and validates LeakyReLU... | def do_test_leaky_relu():
"""Test against clear net leaky relu."""
global torch_res
torch_res = []
leaky_relu = torch.nn.LeakyReLU(0.1)
a = create_tensor(72)
a.requires_grad = True
b = create_tensor(38)
b.requires_grad = True
c = create_tensor(-10.0)
c.requires_grad = True
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.