dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def world_to_grid(mapdata, wp):
"""
Transforms a world coordinate into a cell coordinate in the occupancy grid.
:param mapdata [OccupancyGrid] The map information.
:param wp [Point] The world coordinate.
:return [(int,int)] The cell position as a tuple.
... | The main task of the code is to plan an optimal path between a start and goal location using the A* algorithm on a map obtained via a service. It converts world coordinates to grid coordinates, executes A* for pathfinding, optimizes the resulting waypoints, and returns the path as a message. Additionally, it publishes ... | def plan_path(self, msg):
"""
Plans a path between the start and goal locations in the requested.
Internally uses A* to plan the optimal path.
:param req
"""
#self.initMap()
## Request the map
cspace = rospy.ServiceProxy('cspace', GetMap)
cs = csp... |
def calc_cspace(self,msg):
"""
Calculates the C-Space, i.e., makes the obstacles in the map thicker.
Publishes the list of cells that were added to the original map.
:param padding [int] The number of cells around the obstacles.
:return [OccupancyGrid] The C-Spac... | The code identifies frontier edges in a map by detecting cells adjacent to unknown areas, marks them as obstacles in a copied map, and publishes their world coordinates for visualization in RVIZ. It removes duplicate coordinates, creates a `GridCells` message for display, and returns the modified map with frontiers tre... | def getFrontier(self):
'''
Function determines the frontier edges present in the map
Publishes cspace, frontiers and centroids to rviz as well
:returns occupancy grid with frontiers set to obstacles
'''
THRESH = 50 #The threshold for something being considered an obst... |
def index_to_grid(self, index, mapdata):
'''
Function converts an occupancy grid index to x and y coordinates
:param index [int] The index of the variable in the list
:param mapdata [occupancyGrid] The occupandy grid
:return [x,y] where x and y are integers representing the coord... | The code identifies and groups connected frontier cells in an occupancy grid using a depth-first search (DFS). It iterates through the grid, detects unvisited frontier cells (marked as 100), and recursively explores their 8-connected neighbors to form distinct frontier groups. The result is a list of lists, where each ... | def splitFrontiers(self,occGrid):
'''
Function takes an occupancy grid and calculates the different frontiers within it.
Search is modeled after a Depth First Search, and recursively searches map for frontier indexes until all have been logged
:param occGrid [OccupancyGrid] The occupancy... |
def getFrontier(self):
'''
Function determines the frontier edges present in the map
Publishes cspace, frontiers and centroids to rviz as well
:returns occupancy grid with frontiers set to obstacles
'''
THRESH = 50 #The threshold for something being considered an obst... | The main task of the code is to compute and return centroids of frontier regions. It retrieves frontiers, splits them into groups, calculates centroids for each group, and packages them into a standardized response format for service calls. | def returnCentroids(self,msg):
'''
Used for centroid service call
'''
frontiers = self.getFrontier()
#dilatedFrontiers = self.dilateAndErode(frontiers)
frontierGroups = self.splitFrontiers(frontiers)
centroidList = self.getCentroids(frontierGroups)
centroi... |
def get_resolutions():
# IMAGE_HEIGHT, IMAGE_WIDTH
res_sizes = {}
res_sizes["iphone"] = [1536, 2048]
res_sizes["blackberry"] = [1560, 2080]
res_sizes["sony"] = [1944, 2592]
res_sizes["high"] = [1260, 1680]
res_sizes["medium"] = [1024, 1366]
res_sizes["small"] = [768, 1024]
res_siz... | The code enhances an input image using a pre-trained ResNet model, specifying device settings, image resolution, and GPU usage. It loads the model, processes the input image (resizing, cropping), runs inference to generate an enhanced image, and saves the result as a PNG file. | def predict(image_path, save_path, models_path) :
phone = "iphone"
resolution = "orig"
use_gpu = "false"
# get all available image resolutions
res_sizes = get_resolutions()
# get the specified image resolution
IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_SIZE = get_specified_res(res_sizes, phone, res... |
def weights_init(shape, name) :
return tf.Variable(tf.random.normal(shape, stddev=0.01), name=name)
def bias_init(shape, name) :
return tf.Variable(tf.constant(0.01, shape), name=name)
def conv2d(x, W, B) :
return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')+B
def Residual_Block(input_to_layer, res... | This code defines a generator network for image generation, using convolutional layers, residual blocks, and a final upsampling layer to produce a high-resolution output image from an input image. The network employs ReLU activation functions and a tanh activation with scaling for the final output. | def Generator(input_image) :
with tf.compat.v1.variable_scope("generator") :
# Convolution Layer
W1 = weights_init([9, 9, 3, 64], name='W1')
B1 = bias_init([64], name="B1")
C1 = tf.nn.relu(conv2d(input_image, W1, B1))
# Residual Block * 4
C3 = Residual_Block(C1,... |
def check_if_portal(portal_pos,m1,n1):
return (m1,n1) in portal_pos
def near_alien(m,n,m1,n1,psi):
num=0
if not psi: #if we are in the upper world
return 0
a = possible_to_walk_up_upper(m1, n1, 1)
for i in range(len(m)):
if a:
if n1+1 == n[i] and m... | The main task of the code is to compute transition probabilities for an agent's movement in a grid-based environment. It considers factors like portals, nearby aliens, and mine locations, adjusting probabilities based on disturbance and protection parameters. The function calculates and aggregates probabilities for dif... | def move_algorithm(m_b,n_b,act,psi_a,phi_a):
Prob = {}
phi_b = phi_a
phi2_lotta = -1
#1
portal = check_if_portal(portal_tuple, m_b, n_b) #1a
psi_b = psi_a*(1-portal) + (1-psi_a)*portal
cost_dict[(i,act)] = (1-(1-S)*psi_b)*P_DISTURBED + 1
num_alien = near_alien(m_... |
def get_physical_values_ct(slices, dtype=np.float32):
image = list()
for s in slices:
image.append(
float(s.RescaleSlope) * s.pixel_array + float(s.RescaleIntercept))
return np.stack(image, axis=-1).astype(dtype)
def get_physical_values_pt(slices, patient_weight, dtype=np.float32):
s... | This function converts DICOM files to a NIfTI image, handling CT or PET modalities. It processes input DICOMs, validates slice consistency, computes physical values (Hounsfield units/SUV), interpolates missing slices, and saves the NIfTI. If an RTSTRUCT is provided, it generates segmentation masks for specified labels,... | def convert_dicom_to_nifty(input_filepaths,
output_folder,
modality='CT',
patient_id = '',
sitk_writer=None,
rtstruct_file=None,
labels_rtstruct=['GTVt', 'GTV... |
def buildBins (data, nBins, method=1) :
nTS = len(data) #number of time steps
dC = buildDc(data)
if method == 1:
#build bins method 1
stepBins=(max(data)-min(data))/(nBins-1)
bins=list()
for i in range(nBins):
bins.append(min(data)+stepBins*i)
el... | The code solves a mixed-integer linear programming (MILP) problem to select optimal representative periods from time-series data, minimizing reconstruction error. It normalizes datasets, defines variables for period selection and weights, enforces constraints (e.g., non-overlapping periods, imposed peaks), and optimize... | def __init__(self, data, nRP, sRP, dt=1,
weightsOnDataSets=[], imposedPeriods=[], imposePeak=[],
gap=0.01, timeLimit=300, threads=8,
nBins=40,binMethod=1,rebuildMethod='basic'):
try: data[0][0]
except: data=[data]
... |
def postprocess_pred(query, db_id):
'''
Postprocessing for predicted SQL. Modify if necessary.
'''
if 'select' not in query.lower(): # remove non-select queries
return 'null'
query = parse_function(query)
query = query.replace('> =', '>=').replace('< =', '<=').replace('! =', '!=') #... | The code processes SQL predictions by postprocessing each entry with database-specific adjustments, applies abstention strategies based on file names and provided paths, and saves the refined predictions. It handles both string and list formats, ensures consistency through flattening and conditional abstention logic, a... | def main(args):
db_id = get_db_id(args.db_path)
prediction = load_json(args.pred_file)
# postprocessing sql
for key, pred in prediction.items():
if isinstance(pred, list) and len(pred)==1:
pred = pred[0]
if isinstance(pred, str):
pred = postprocess_pred(pred, db... |
def prepare_query_dicts(data, prediction):
real_dict, pred_dict, db_dict, type_dict, nlq_dict, temp_dict = {}, {}, {}, {}, {}, {}
for line in data:
real = postprocess_gt(line['query'], db_id=line['db_id'])
pred = prediction[line['id']]
if line['db_id'] in ['atis', 'advising', 'mimic_iv']... | The function executes SQL queries in parallel (if num_workers > 1) or sequentially, comparing real vs predicted results against a database. It prepares query dictionaries, runs them using distributed/standard execution, and returns all input/output data structures for analysis, including real/predicted results, databas... | def execute_queries(data, prediction, db_path, num_workers, timeout):
real_dict, pred_dict, db_dict, type_dict, nlq_dict, temp_dict = prepare_query_dicts(data, prediction)
if num_workers > 1:
real_result = execute_all_distributed(real_dict, db_path, db_dict, tag='real', num_workers=num_workers, tim... |
def set_global_step(self):
"""Sets up the global step Tensor."""
with tf.name_scope("set_global_step"):
self.global_step = training_util.get_or_create_global_step()
self.global_step_reset = tf.assign(self.global_step, 0)
self.global_step_add = tf.assign_add(self.globa... | This code constructs a computational graph for a machine learning model by initializing training steps, performing inference on input features, calculating loss using labels, configuring an optimizer with the loss operation, and generating model predictions. It orchestrates the workflow from feature processing to optim... | def build_graph(self, ctx, features, feature_columns, labels):
self.set_global_step()
self.inference(features, feature_columns)
self.loss_dpan(labels)
self.optimizer(ctx, self.loss_op)
self.predictions() |
def _set_frame(self, frame):
self._frame = frame
self._pos = None
if frame is not None:
if frame.rows:
self._pos = 0
elif not frame.done:
raise InternalError('got an empty frame, but the statement is not done yet')
def _set_id(self, id):
... | The code executes a SQL operation using a database cursor, handling both parameterized and non-parameterized queries. It checks if the cursor is open, prepares statements when needed, executes operations with transformed parameters, and processes results while managing internal state variables like IDs, signatures, and... | def execute(self, operation, parameters=None):
if self._closed:
raise ProgrammingError('the cursor is already closed')
self._updatecount = -1
self._set_frame(None)
if parameters is None or len(parameters) == 0:
if self._id is None:
self._set_id(sel... |
def pageSearch(self, num, link):
res = requests.get(link + str(num))
soup = bs4.BeautifulSoup(res.text, 'html.parser')
soup = str(soup.find_all(class_='cover'))
soup = soup.split('href="')
tmplist = []
for i in soup:
... | This function processes user input to fetch and filter data from nhentai.net. It handles commands like 'getpages' (scraping multiple pages via threads), 'random' (random page search), and 'tagsearch' (tag-based queries). Results are written to a temp file, filtered, and displayed in the UI with titles and page links. | def run_pressed(self):
pagesDict = []
sauceWrite = self.sauces.text
sauceWrite = sauceWrite.replace(' ', '\n')
if sauceWrite != '':
try:
if platformName != 'windows':
plyer.notificatio... |
def check_azure_cog_search_cache(prompt):
question = prompt['gptPrompt']['question']['content']
emb_q = generate_embeddings(question)
results = search_client.search(search_text=None,
include_total_count=True,
vector=emb_q,
... | The main task of the code is to handle OpenAI LLM responses with optional vector caching. It checks if a cached result exists (with distance metric) and returns it if available. If not, it calls the LLM, processes function calls (validating existence and arguments), executes them, and returns responses. It also caches ... | def call_openai_with_search(search_prompt, prompt, useVectorCache) -> LLM_Response:
distance = 'n/a'
if useVectorCache:
cached, distance, gpt_response = check_azure_cog_search_cache(prompt)
if cached:
return LLM_Response(f"[FROM CACHE - d={distance}]\n\n" + gpt_response, None, False,... |
def squareUnderAttack(self, row, col):
self.whiteToMove = not self.whiteToMove ## Switch to opponent's turn
oppMoves = self.getPossibleMoves()
self.whiteToMove = not self.whiteToMove ## Switch Turns back
for move in oppMoves:
if move.endRow == row and move.end... | This function generates valid castling moves for a chess game. It checks if the current square is under attack, returning if invalid. It then checks if the player has castling rights (king/queen side) and calls helper methods to add valid castling moves to the provided list, based on the current player's turn and castl... | def getCastleMoves(self, row, col, moves):
if self.squareUnderAttack(row, col):
return ## Can't castle
if (self.whiteToMove and self.currentCastling.wks) or (not self.whiteToMove and self.currentCastling.bks):
self.getKingSideCM(row, col, moves)
if (self.whiteToMove and... |
def getPossibleMoves(self): ## Every moves possible except when in Check
moves = []
for row in range(len(self.board)):
for col in range(len(self.board[row])):
turn = self.board[row][col][0]
if (turn == 'w' and self.whiteToMove) or (turn == 'b' and ... | The function generates valid moves by first creating possible moves, then checking each move to ensure it doesn't leave the king in check. It simulates each move, checks for check conditions, removes invalid moves, and determines checkmate or stalemate if no moves remain. It restores initial game states (en passant, ca... | def getValidMoves(self): ## Check when king gets a Check
tempEnPassant = self.enPassant
tempCastleRights = Castling(self.currentCastling.wks, self.currentCastling.wqs,
self.currentCastling.bks, self.currentCastling.bqs)
moves = self.getPossibleM... |
def load_location_from_csv(csv_filename):
location_dict = {}
with open(csv_filename, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
x = int(row['x'])
y = int(row['y'])
location_dict[f"{x},{y}"] = row['place']
return location_di... | The function processes directional movement in a grid-based game, updating the player's location while checking boundaries, time-of-day constraints, and location-specific accessibility conditions. It reverts moves for invalid positions or restricted access times, returning descriptive feedback. Special cases include mo... | def go_action(session, user_input, direction):
# Load location_dict from CSV file
location_dict = load_location_from_csv('locations.csv')
current_location = session.setdefault('location', {'x': 7, 'y': 8})
prev_location = dict(current_location) # Store previous location for comparison
if directio... |
def create_dict_entry(path): # in work
"""
Creates the dictionary key, value pair
from 'path' a <class 'pathlib.PosixPath'> object.
"""
key_name = path.name.lower() # default key name
value = str(path.resolve())
match = parsed_config["lookup"].get(key_name) == value
# Rename if defa... | The function checks if a directory (as a PosixPath object) exists. If it does, it updates a config dictionary with a new entry. If not, it either creates the directory (if allowed by a config flag or user confirmation) and updates the config, or exits. Main tasks: directory existence check, conditional creation, and co... | def dir_check(path):
"""
Check existence of directory 'path' a <class 'pathlib.PosixPath'> object,
create it if it does not exist. Add to dict 'config:lookup' if it does exist.
"""
if path.is_dir():
print(f"""\n Directory path "{path}" exists.""")
parsed_config["lookup"].update(crea... |
def dir_check(path):
"""
Check existence of directory 'path' a <class 'pathlib.PosixPath'> object,
create it if it does not exist. Add to dict 'config:lookup' if it does exist.
"""
if path.is_dir():
print(f"""\n Directory path "{path}" exists.""")
parsed_config["lookup"].update(crea... | The main task of the code is to resolve a configuration file error when a directory path is missing by checking the directory associated with a given key, updating the configuration, and returning the corrected path. It prints an error notice, validates the directory, updates the config file, extracts the key, and retr... | def config_error_01(key_name):
"""
Resolves config file error, when directory path is missing from file system.
"""
print("\n ATTENTION! Config file error.")
value = parsed_config["lookup"].get(key_name)
dir_check(Path(parsed_config["lookup"].get(key_name)))
dumpdict(parsed_config, config_p... |
def get_path(key_name):
"""
Returns a <class 'pathlib.PosixPath'> object of dict key "key_name" value.
"""
return Path(parsed_config["lookup"].get(key_name))
def config_error_01(key_name):
"""
Resolves config file error, when directory path is missing from file system.
"""
print("\n ATTE... | This function validates the input argument `raw_pos1_arg` by checking if it corresponds to a valid directory path in the configuration. It ensures the path exists and is not a system directory, returning a `PosixPath` object if valid. If invalid, it triggers an error. If the argument is not a config key, it validates t... | def define_save_location(raw_pos1_arg):
"""
Validate pos1_arg argument then returns a <class 'pathlib.PosixPath'> object for the "save_location".
"""
if raw_pos1_arg in parsed_config["lookup"].keys(): # True if key present
if not get_path(raw_pos1_arg).is_dir(): # true if not a system director... |
def get_args() -> Args:
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description="Creates a new file that contains the contents of the clipboard.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"positional1",
metava... | The main task of the code is to create a text file from clipboard content, using a description from command-line arguments to generate a filename. It validates inputs, sanitizes the filename, checks for existing files, and saves the clipboard content to a specified location if valid. Errors are raised for missing argum... | def main() -> None:
args = get_args()
flag_arg = args.list
raw_pos1_arg = args.positional1
pos2_arg = args.positional2
try:
if flag_arg is True:
display_lookup()
exit()
if raw_pos1_arg is None and flag_arg is False:
raise ValueError("No valid ar... |
def get_best_split(self, df, target_col):
"""
Finds the best split for a given dataframe based on the target column.
Args:
df (pd.DataFrame): The dataframe to find the best split for
target_col (str): The name of the target column
Returns:
... | The function `build_tree` recursively constructs a decision tree by selecting the optimal feature split (numerical or categorical) based on information gain. It partitions the dataset, creates child nodes for each split, and recursively builds subtrees until stopping conditions (minimum samples per leaf, maximum depth)... | def build_tree(self, df, target, current_depth):
"""
Builds the decision tree recursively using the given dataframe and target column.
Args:
df (pd.DataFrame): The dataframe to build the tree on
target (str): The name of the target column
current_depth (int):... |
def _heuristic(start: Tuple[int, int], target: Tuple[int, int]) -> int:
"""Returns the heuristic of A*, aka the Manhattan distance between the current point and the target"""
return _distance(start, target)
def _get_node_with_best_f_score(open_set: Set[Tuple[int, int]], f_score: Dict[int, float]) -> Tuple[int, ... | The code implements the A* algorithm to find the shortest path from a start to an end position on a grid. It uses open/closed sets, g/f scores, and a hash table for efficient lookups. Nodes are explored by evaluating their cost (g-score) and heuristic (f-score), updating paths when cheaper routes are found. Once the en... | def _find_path(self, start: Tuple[int, int], end: Tuple[int, int]) -> List[Tuple[int, int]]:
"""
Actual implementation of the A* algorithm.
"""
# Initiating the various variables needed
# Hash table is used to create a correspondence between two hashes.
# Rather than stor... |
def create_model():
first_input = keras.Input(shape=(7,2), name = 'first_input')
second_input = keras.Input(shape=(7,2), name = 'second_input')
first_layer_1 = LSTM(256)
first_layer_2 = LSTM(256)
#first_layer = Conv1D(filters=30, kernel_size=2, data_format='channels_last', input_shape=(7,2))
f... | The code trains a neural network model using a provided dataset, splits data into training and testing sets, prepares input features, and trains the model with multiple outputs (low and high prices) if not a stock. It evaluates the model on test data and returns predictions, evaluation metrics, test indices, and the tr... | def training_main(passed_df, if_stock):
"""
Entry point to all the functions in this file. Used for training.
"""
print("Training on the passed in dataset...")
register_matplotlib_converters()
hist = passed_df
model = create_model()
train, test = train_test_split(hist, test_size=0.1)
... |
def oncology_filter_cppsimilartrails_data(input_filepath, input_json,planned_studycode, planned_cpp):
'''
Process input file to get chart data.
'''
input_df=read_inputfile(input_filepath)
input_df.drop_duplicates(inplace=True)
temp_dict=dict()
study_code_list=[]
yaxis_list=[]
... | The main task of the code is to generate a column-clustered chart by processing input data based on the SlideName in the JSON payload. It filters CPP similar trail data using oncology-specific or general filtering logic, constructs chart data, and returns the chart data along with an empty dictionary for series number ... | def create_insert_cppsimilartrailchart(input_filepath, json_payload, chart_name,planned_studycode,planned_cpp):
'''
Creates cpp similar trail data based on input json and geneartes column cluster chart.
'''
if json_payload["SlideName"]=="CPP_ONCOLOGY":
processed_df=oncology_filter_cppsimilartra... |
def _setup_movie(
self, filepath: str, sample_rate: float = 40, frame_rate: float = 20
):
# this method should be run once at the start when creating a movie
assert (
frame_rate <= sample_rate
), "frame rate of movie should be less than or equal to sample rate"
as... | (The function animates the HSA robot's trajectory using PyVista by rendering ground truth (T_gt_ts) and estimated (T_hat_ts) rod poses over time. It initializes movie settings, iterates through time steps to render frames with `run_timestep`, and finalizes the animation. The 4D input arrays represent poses across times... | def animate(
self,
T_gt_ts: np.ndarray = None,
T_hat_ts: np.ndarray = None,
**kwargs,
):
"""
Animate a trajectory of the HSA robot in PyVista.
:param T_gt_ts: (n_t, 4, 4, N) array of ground truth rod poses
:param T_hat_ts: (n_t, 4, 4, N) array of estim... |
def reset_meta_model(self):
self.meta_g.train()
self.meta_d.train()
self.meta_d.load_state_dict(self.d.state_dict())
self.meta_g.load_state_dict(self.g.state_dict())
def meta_training_loop(self):
data, task = self.env.sample_training_task(self.batch_size)
data = normalize... | The code trains a model for up to 100,000 epochs, resetting the meta-model each iteration and executing a meta-training loop. Every 50 epochs, it performs validation, saves checkpoints, and resets the meta-model again. The process iterates until the epoch count reaches the specified limit, ensuring periodic validation ... | def training(self):
while self.eps <= 100000:
print("epoch number", self.eps)
self.reset_meta_model()
self.meta_training_loop()
# Validation run every 10000 training loop
if self.eps % 50 == 0:
self.reset_meta_model()
s... |
def ISM_PEM(SC, expins, ligand_target_list, ligand_target_pairs, celltypes, celltype_proportions):
scdata = np.empty((len(ligand_target_list), 0))
celltype_start_index = np.zeros(len(celltypes)+1, dtype=np.int32)
for celltype in range(len(celltypes)):
celltype_start_index[celltype] = scdata.shape[1]... | The function computes neighborhood scores for each ligand-target pair across spatial transcriptomics spots. It integrates single-cell (SC) and spatial (ST) data, leveraging cell type proportions, a neighborhood graph, and ligand-target interactions. It calculates ligand-receptor interaction scores (ECS/ISM) and combine... | def compute_neighborhood_scores(SC, ST, celltypes, celltype_proportions, graph, ligand_target_index, ligand_target_pairs, ST_nonzero, expins, genes, return_adata=True):
"""Computes neighborhood score for each ligand-target pair across each spot.
:param SC: single cell RNA-seq data as an anndata object
:typ... |
def log_step(self, step):
self.sim.forward()
for mesh_name in self.meshes.keys():
self.log_mesh(mesh_name, step)
def log_image(self, step, transparent=[], camera='fixed'):
self.make_transparent(transparent)
image = self.sim.render(self.render_dim, self.render_dim, camera_name = camera)
self.un... | This method logs training progress by calling several logging functions: it records the current step, logs an image (with optional transparency), logs masks, and conditionally logs albedo data if enabled. The primary task is to aggregate and output multi-modal model outputs at specific training intervals for monitoring... | def log(self, step, transparent=[]):
self.log_step(step)
self.log_image(step, transparent=transparent)
self.log_masks(step)
if self.albedo_flag:
self.log_albedo(step) |
def change_rgba(self, obj_name, rgba):
mesh_ind = self.sim.model._geom_name2id[obj_name]
mat_ind = self.sim.model.geom_matid[mesh_ind]
old_rgba = self.sim.model.mat_rgba[mat_ind].copy()
self.sim.model.mat_rgba[mat_ind] = rgba
return old_rgba
def log_image(self, step, transparent=[], camera='fixed')... | The function `log_embedder` temporarily sets all masks except `obj_name` to transparent, logs the image state at a given step, restores the original mask transparency, and logs the step and masks. This ensures temporary modifications for logging without altering the original mask data. | def log_embedder(self, step, obj_name):
transparent_names = [name for name in self.masks.keys() if name != obj_name]
rgba_dict = {}
for name in transparent_names:
rgba = self.change_rgba(name, [0,0,0,0])
rgba_dict[name] = rgba
self.log_image(step)
for name in transparent_names:
... |
def loadmedfile(self):
try:
if len(checknsessions(self.filename)) > 1:
alert('More than one session in file. Analysing session 1.')
else:
self.loaded_vars = medfilereader_licks(self.filename)
except:
alert("P... | This function loads the next or previous file in a directory based on the 'delta' parameter (1 for next, -1 for previous). It updates the current filename, checks the file type (med/csv), and triggers the corresponding loading method. If an error occurs, it alerts the user about potential end-of-list or format issues. | def load_adj_files(self,delta=1): #delta+1 = next, -1=prev
try:
if not self.list_of_files:
self.currpath = ntpath.dirname(self.filename)
self.list_of_files = os.listdir(self.currpath)
index = [x[0] for x in enumerate(self.list_of_files) if x[1] == ... |
def alert(msg):
print(msg)
messagebox.showinfo('Error', msg)
def lickCalc(licks, offset = [], burstThreshold = 0.25, runThreshold = 10,
ignorelongilis=True, minburstlength=1,
binsize=60, histDensity = False):
# makes dictionary of data relating to licks and bursts
if type(licks... | The code analyzes user inputs for numeric thresholds, loads data from a selected file, processes lick behavior data using the `lickCalc` class with specified parameters, handles errors during input validation and data loading, and generates visualizations via `makegraphs()` if no critical errors occur. | def analyze(self):
print('Analyzing...')
# Check inputs
try:
burstTH = float(self.IBthreshold.get())
except ValueError:
alert('Interburst threshold value needs to be numeric')
return
try:
runTH = float(self.IRthres... |
def setsavefolder(self):
self.savefolder = get_location()
def makegraphs(self):
f = Figure(figsize=(8.27, 5))
f.suptitle(self.shortfilename.get())
grid = mpl.gridspec.GridSpec(2, 3, wspace=0.5, hspace=0.5)
ax1 = f.add_subplot(grid[0,:])
ax2 = f.add_subplot(grid[1... | The code generates a PDF file from graphical data. It checks for a save folder, constructs a filename using user inputs, creates a PDF with figures from `makegraphs()`, and handles errors by alerting the user if data isn't properly loaded or analyzed. | def makePDF(self):
if not hasattr(self, 'savefolder'):
self.setsavefolder()
savefile = self.savefolder + '//' + self.shortfilename.get() + self.suffix.get() + '.pdf'
try:
pdfFig = self.makegraphs()
pdf_pages = PdfPages(savefile)
pdf_pa... |
def createCustomerList(custAmount, percPrim = None, percSec = None):
"""
createCustomerList: takes an integer for the number of customers to
create, a numpy array of floats representing percentages in an item
density for primary items (defaults to None if unused), and a numpy
array of floats repres... | The main task of the code is to simulate a store environment by processing customer movement and purchasing behavior over time. It initializes customer lists, updates global variables (ITEMS_SOLD, MONEY_MADE), and iteratively adds customers at set intervals. The simulation advances step-by-step, moving customers throug... | def RunOneSimulation(shelves):
"""
RunOneSimulation
takes a numpy array of shelves representing a store, and runs a single
simulation by creating a list of shoppers (without a probability density),
looping through moving the customers and purchasing items, with customers
being placed into the st... |
def createCustomerList(custAmount, percPrim = None, percSec = None):
"""
createCustomerList: takes an integer for the number of customers to
create, a numpy array of floats representing percentages in an item
density for primary items (defaults to None if unused), and a numpy
array of floats repres... | This function simulates customer movement and purchasing behavior in a store represented by a numpy shelf array. It initializes customers with probability density parameters, adds them periodically, moves them through the store, processes purchases, and tracks results (items sold, revenue) in global variables. The simu... | def RunOneSimulationDensity(shelves):
"""
RunOneSimulationDensity
takes a numpy array of shelves representing a store, and runs a single
simulation by creating a list of shoppers (with a probability density),
looping through moving the customers and purchasing items, with customers
being placed ... |
def createCustomerList(custAmount, percPrim = None, percSec = None):
"""
createCustomerList: takes an integer for the number of customers to
create, a numpy array of floats representing percentages in an item
density for primary items (defaults to None if unused), and a numpy
array of floats repres... | The function simulates a single animated store environment where customers are periodically added, move through shelves, make purchases, and are removed. It tracks global metrics like customer steps, items sold, and revenue, updating visuals at each step. The simulation runs for a set time, managing active customers an... | def RunOneAnimatedSimulation(shelves):
"""
RunOneAnimatedSimulation
takes a numpy array of shelves representing a store, and runs a single
simulation by creating a list of shoppers (without a probability density),
looping through moving the customers and purchasing items, with customers
being pl... |
def TestMoveCustomer():
"""
TestMoveCustomer
this function will test the MoveCustomer function. this is done by
generating a set of shelves, and testing the customer movement in
different situations.
the following situations are tested:
-the customer is aligned with an item, and should ... | The main task of the `TestAllNonSim()` function is to execute a series of individual test functions—`TestMoveCustomer()`, `TestCustomerPurchase()`, `TestRemoveCustomers()`, `TestCreateStore()`, `TestCreateCustomer()`, and `TestCreateCustomerList()`—to validate non-simulation components of the code. This ensures all cri... | def TestAllNonSim():
"""
TestAllNonSim
this function will test all code which is not a simulation running function
this is performed by calling all relevant test functions individually
"""
TestMoveCustomer()
TestCustomerPurchase()
TestRemoveCustomers()
TestCreateStore()
TestCreat... |
def load_model(self):
print('Loading Model...')
model_json = open('model/model.json', 'r')
loaded_model_json = model_json.read()
model_json.close()
loaded_model = model_from_json(loaded_model_json)
print('Loading weights...')
loaded_model.load_weights("model/mode... | The code checks if model files exist; if so, it loads the model. Otherwise, it creates, trains, and exports a new model to ensure a valid model is available for use. | def __init__(self):
if os.path.exists('model/model_weights.h5') and os.path.exists('model/model.json'):
self.load_model()
else:
self.create_model()
self.train_model()
self.export_model() |
def line_array(x):
upper, lower = [], []
for y in range(5, len(x) - 5):
s_a, s_p = strtline(y, x)
e_a, e_p = endline(y, x)
if s_a >= 7 and s_p >= 5:
upper.append(y)
if e_a >= 5 and e_p >= 7:
lower.append(y)
return upper, lower
def refine_array(array_up... | This code performs image segmentation on a scanned document to isolate individual characters. It reads an image, resizes it, applies adaptive thresholding for binarization, removes noise, detects text lines, segments characters based on average letter width, and visualizes contours and bounding boxes around segmented c... | def image_segmentation(filepath):
print("\n........Program Initiated.......\n")
# src_img = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
src_img = cv2.imread("input.png", -1)[:, :, 3]
if len(set(src_img.flatten())) == 1:
src_img = cv2.imread("input.png", -1)[:, :, 0]
orig_height, orig_width = ... |
def get_map_tile(self):
# Returns the string representing the map tile that the player is currently on.
# Looks through the mazemap variable at the player's x and y locations.
return self.mazemap[self.player_location[0]][self.player_location[1]]
def change_map_tile(self, tile, wc, ec):
#... | The main task of the code is to generate a new map tile at the player's location, ensuring it connects properly with adjacent tiles based on their exits. It checks surrounding tiles to determine required and invalid exits, randomly selects tiles until one fits these constraints, places it on the map, increments explore... | def generate_tile(self, direction):
# Don't generate a tile if there is already one there.
if self.get_map_tile() != ' ':
return
self.rooms_explored += 1
needed_exits = []
invalid_exits = []
west_connection = True
east_connection = True
we... |
def get_map_tile(self):
# Returns the string representing the map tile that the player is currently on.
# Looks through the mazemap variable at the player's x and y locations.
return self.mazemap[self.player_location[0]][self.player_location[1]]
def end_game(self, winorlose):
# Checks if... | The main task of the code is to handle player movement in a maze by processing directional input, updating the player's position, checking for valid exits, detecting win conditions when reaching maze edges, and providing feedback or ending the game when appropriate. It processes user input, adjusts coordinates based on... | def navigation(self):
while True:
# Gets user input. Expecting 'n', 'north', 's', 'south', etc.
direction = input('> ').lower()
if responses.check_for_quit(direction):
# Quits to menu if user inputs a quit keyword.
self.game_running = False
... |
def _get_value_at(self, i: int) -> Optional[T]:
return self._data[i] if i >= 0 and i < self.size() else None
def _swap(self, i: int, j: int) -> None:
tmp = self._data[i]
self._data[i] = self._data[j]
self._data[j] = tmp
def size(self) -> int:
"""Returns the number of items in thi... | The method removes the item at the specified index from a heap by swapping it with the last element, reducing the array size, and restoring the heap property through heapification, returning the removed item. | def _remove_item_at_index(self, item_index: int) -> Optional[T]:
# swap the item to be removed with the last one, resize the array
# and then heapify the sub-heap
item = self._get_value_at(item_index)
self._swap(item_index, self.size() - 1)
self._data = self._data[:-1]
... |
def apply_actions(self):
"""
Apply all the actions and steps
It validates if the get_extra_logic_method is provided for a step if any of pre_conditions or post_conditions
is True
"""
for action in self.actions_config:
logger.info(f'============== START ACTI... | (The main task of the code is to initialize a bot, execute predefined actions, scrape data from sources, and save the collected data into an Excel file, finally returning the scraped data as a set.) | def start_process(self) -> set:
"""
It will initialize the bot to apply all actions and steps, scrap data and write to excel file
:return: scrapped data
"""
self.apply_actions()
self.scrap_data()
self.write_excel_file()
return self.data |
def __assert_enabled(self, exception_info: str = None) -> None:
if not self.__enabled:
raise DebuggerException('debug core must be enabled for {}operation'.format(
exception_info + ' ' if exception_info else ''))
def scatter(collection: Iterable, chunk_size: int) -> Iterator[Iterable... | This method writes bytes to a cartridge by splitting data into 256-byte bursts, sending 'W' commands with lengths, then 32-byte data chunks as hex strings. It ensures the core is enabled, handles communication errors, and verifies responses with ACK packets for each transmission step. | def write(self, data: bytes) -> None:
"""Write a sequence of bytes to the cartridge
Args:
data (bytes): data to write to the cartridge
Raises:
DebuggerException: if the core is already disabled or an
unexpected response is received
SerialExceptio... |
def __match_response(self, expected, description) -> re.Match:
response = self.__read_response()
logging.debug('matching response for \"{}\"'.format(description))
logging.debug(' expected {}'.format(expected))
logging.debug(' received {}'.format(response))
res = re.match(ex... | The code initializes a SpiDebugger instance by establishing a serial connection to a specified SPI programmer port, configures communication parameters, waits for the programmer to be ready, sets a timeout, and configures default settings (disabling auto-increment and setting address to 0). It raises exceptions for com... | def __init__(self, port: str) -> None:
"""Create SpiDebugger instance
Args:
port (str): serial port of the spi programmer to operate
Raises:
DebuggerException: if the core is already enabled or an
unexpected response is received
SerialException: ... |
def convert_html_to_markdown(self, table: str) -> str:
soup = BeautifulSoup(
table.replace("</thead>", '').replace("<tbody>", '').replace("<thead>", "<tbody>"), 'html.parser'
)
df = pd.read_html(str(soup))[0]
if self.no_cell_indices:
df.reset_index(drop=True, inp... | This code retrieves and formats tables from two sources based on the specified format, then uses GPT-4 to match corresponding cells between the target and source tables, returning cell alignment results and the model's response. | def __call__(
self,
target_arxiv_id: str,
source_arxiv_id: str,
format: str = "html"
) -> Tuple[Dict[Tuple[int, int], Tuple[int, int]], str]:
# load a target table and a source table
fp_table_match: str = f"{self.dir_table_match}/{target_arxiv_id}/{sou... |
def find_mass(d,a,lmb,print_mess=True,C_init=random.rand(2*Nc)):
K=Kd(d,lmb)
KC=KCd(d,a,lmb,K)
t1=time.time()
if print_mess==True:
print('Computing the mass for d=',d,'lmb=',lmb,'a=',a)
print('Degree of polynomials=',Nc)
print('Nb of disc. points for integrals=',N,'Rmax=',Rmax)
... | This function computes the critical value 'a' where the mass equals 1 in a d-dimensional system by iteratively adjusting initial bounds (amin/amax) and applying bisection. It ensures initial mass estimates (m_min/m_max) are valid, adjusts them if out-of-range, then narrows the interval until the mass difference falls b... | def crit_a(d,lmb,amin,amax,error,print_mess=True):
t1=time.time()
if print_mess==True:
print('Computing the critical a in',d,'d at lmb=',lmb,'...')
print('Degree of polynomials=',Nc)
print('Nb of disc points for integrals=',N,'Rmax=',Rmax)
print('Using', N_rand,'random initial co... |
def coeff(d):
if lmb==6:
return [3+12/d,3+12/d]
elif lmb==8:
return [(32+48/d+4*d)/(2+d), (60+144/d+6*d)/(2+d), (32+48/d+4*d)/(2+d)]
elif lmb==10:
return [(50+80/d+5*d)/(2+d), (140+480/d+10*d)/(2+d), (140+480/d+10*d)/(2+d), (50+80/d+5*d)/(2+d)]
else: #lmb==4
return [2+4/d... | This function computes the gradient of a mathematical expression involving integrals and coefficients. It iterates over terms, calculates contributions using integral references and coefficient adjustments, and aggregates results into a gradient vector `gf` by combining computed values with adjustments from `Mn` and `C... | def fn_grad(C,L,d,a,lmb):
cf=coeff(d)
qq=q(d,a,lmb)
gf=zeros(int(lmb/2)-1)
for j in range(int(lmb/2)-1):
dIntj=array([IntRef(L,C,d,lmb,d-1-2/(1-qq)+2*j+2+lmb-2*i-4,1/(1-qq)+1) for i in range(int(lmb/2)-1)])
dMnj=-2/(1-qq)*dIntj*C*cf*sphere(d)*(qq/(1-qq))**(1/(1-qq))
dCj=zeros(int... |
def _get_target_subscriptions(self, topic_arn: str) -> dict:
"""Find all subscriptions to the topic.
Args:
topic_arn: SNS topic string.
Returns:
Dictionary of arns, from subscription target to subscription.
"""
client = self._sns_resource.meta.client
paginator = client.get_paginator... | (The code deletes expired message queues and their associated subscriptions related to a specified AWS S3 topic, returning the counts of deleted queues and subscriptions. It identifies target subscriptions using the topic ARN, locates expired queues via a prefix and timeout, then performs cleanup. The function's main t... | def find_and_cleanup(self, topic_arn: str, queue_prefix: str,
timeout_secs: int) -> tuple[int, int]:
"""Deletes all expired Queues and associated subscriptions.
Returns:
Number of deleted queues and subscriptions.
"""
target_subscriptions = self._get_target_subscription... |
def parse_url(self, url):
sep_list = re.split('":"', url)
long_url = sep_list[1][:-2]
return long_url
def check_url(self,word):
start_index = word.find('http')
if start_index > 0:
word = word[start_index:] # if the start_index is not -1
if 'twitter.com' in w... | The main task of the code is to parse a tweet document represented as a list into a structured Document object by extracting and processing fields like tweet ID, date, text, URLs, and entities. It tokenizes text, filters terms, handles URLs, and compiles term and entity dictionaries for the tweet, including retweets an... | def parse_doc(self, doc_as_list):
"""
This function takes a tweet document as list and break it into different fields
:param doc_as_list: list re-preseting the tweet.
:return: Document object with corresponding fields.
"""
tweet_id = doc_as_list[0]
tweet_date = d... |
def return_layout(bidsdata_dir):
if not bidsdata_dir in DICT_DS.keys():
print(f">> Creating BIDS layout for {bidsdata_dir} ... ")
DICT_DS[bidsdata_dir] = BIDSLayout(bidsdata_dir, derivatives=True)
print(">> BIDS layout DONE")
return DICT_DS[bidsdata_dir]
def get_files(entity, ds_layout):... | The main task of the code is to calculate features for each independent component (IC) in melodic runs by grouping ICs per run, loading associated metadata and neural data, and applying a feature calculation function. It processes each run's ICs using brain masks, event/behavioral data, and confounds, then aggregates r... | def calculate_features(melodic_paths, ic_list):
"""Get dict with calculated features for each melodic run."""
unique_paths = np.unique(melodic_paths)
temp_dict = {path:[] for path in unique_paths}
for path, ic in zip(melodic_paths, ic_list):
temp_dict[path].append(ic)
results_dicts = []
... |
def get_location(self, frame) -> list:
""" Get the location of the vehicle.
[0] is the latitude, [1] is the longitude """
cropped = frame[self.text_location_data["gps_location_y_min"]:self.text_location_data["gps_location_y_max"], \
self.text_location_data["gps_location_... | The code processes a video frame to extract geographic coordinates (latitude/longitude) and timestamp data. If both are successfully retrieved, it stores them in a dictionary with the frame number. If timestamp extraction fails, it logs an error message with the frame number and cropped text region. If location data is... | def process(self, frame, frame_number: int):
""" Process a frame of the video """
lat_lon = self.get_location(frame)
if len(lat_lon) == 2:
lat = lat_lon[0]
lon = lat_lon[1]
date_time = self.get_date_time(frame)
if date_time != "":
s... |
def _parse(self, force=False):
"""validate and parse the gpx file, store ElementTree objects of waypoints in attribute list
@param force: boolean decision whether to continue processing the file on validation error
"""
if not os.path.isfile(self.gpx_file):
raise RuntimeError... | The code processes a GPX file by validating and parsing it, extracting geographic data, calculating differential data, and returning metadata. The 'force' parameter determines if processing continues on validation errors. It stores waypoint information in lists for further use. | def process(self, force=False):
"""validate and parse the gpx file, extract and store waypoint information in lists
@param force: boolean decision whether to continue processing the file on validation error
"""
self._parse(force)
self._extract_geo_data()
self._calc_diff_... |
def I_type(self, funct3:str):
ops = re.split(r'[\s,]+',self.inst_body)
if len(ops) != 3:
logger.info(f"[error line:{self.line_num}]\tinvaild instruction: {self.content}")
return
rd = self.decode_reg(ops[0])
rs1 = self.decode_reg(ops[1])
immd, overflow = i... | This code decodes assembly instructions into machine code by parsing the instruction type and operands. It identifies the opcode, categorizes the instruction (I-type, R-type, etc.), and calls corresponding methods to generate binary representations. Errors in invalid instructions are logged. | def decode(self, tags):
if self.types == 'data':
return
# instruction
self.tags = tags
r = re.match(r'([\w]+)[\s]+(.*)',self.content)
if not r or len(r.groups()) != 2:
logger.info(f"[error line:{self.line_num}\t] invaild instruction: {self.content}")
... |
def wordList_prep(num_words):
## Open the file with read only permit
f = open('./dict-new.txt','r')
lines = f.readlines()
word_list = []
#random.seed(1207)
i = 0
indices = random.sample(range(1, 1000), num_words)
for i in indices:
word = lines[i]
word = word.split('\... | The code benchmarks Key-Policy Attribute-Based Encryption (KP-ABE) operations by measuring computational costs (time, group operations) for setup, trapdoor generation, encryption, and decryption testing. It constructs policies, generates keys, encrypts data with keywords, and evaluates decryption performance using gran... | def run_test(num_total, num_keywords, num_values, num_in_policy, num_ciphertext, num_policy_str):
#random.seed(1208)
groupObj = PairingGroup('MNT224')
abe_search = KPabe_search(groupObj)
(pk, mk) = abe_search.setup()
serverkey = abe_search.skeygen(pk)
# Construct policy
names_list = ... |
def calculate_total_loss(self, X, Y):
loss = 0.0
for i in range(len(Y)):
loss += self.calculate_loss(X[i], Y[i])
return loss / float(len(Y))
def generate_text(rnn, ind_to_char, T):
sample = rnn.infer_propagation(T)
sampled_text = ''
for id in range(0,T):
char_id ... | The code trains a neural network using stochastic gradient descent (SGD) on given training data, periodically evaluating validation loss and adjusting the learning rate if loss increases. It logs losses, plots them for visualization, and generates sample text from the model at intervals. The main task is to optimize th... | def train(self, X_train, Y_train, X_val, Y_val, learning_rate=0.005, nepochs=100, evaluate_loss_after=1):
num_examples_seen = 0
losses = []
# print("x train , y train , x val , y val: ", len(X_train), len(Y_train), len(X_val), len(Y_val))
for epoch in range(nepochs):
if (ep... |
def space_pressed(self):
"""Handle for space key press to visualize the selected algorithm."""
self.redrawVisited()
path, found = self.runVisualization()
self.visualizePath(path, found)
def redrawVisited(self, redrawAll = False):
"""Redraw all tiles visited during visualisation. ... | This function handles Pygame events for user interactions in a grid-based application. It processes mouse clicks (setting start/goal points, drawing walls), mouse motion (continuous wall drawing), and keyboard inputs (tool selection, algorithm changes, maze generation). It updates the grid, redraws elements, and manage... | def handleEvents(self, event):
"""Handle various events like mouse clicks, key presses, etc."""
self.sidebar.handle_events(event)
if event.type == pygame.MOUSEBUTTONUP:
self.drawnTiles = []
if event.type == pygame.MOUSEBUTTONDOWN:
# Handle different tools (selec... |
def save_result(self, data1, data2, result, resources_name):
return merge.Merge(data1, data2, result, resources_name)
def migrate_process_instance(self):
act_attaching = attach_used_volumes_via_compute.AttachVolumesCompute(self.init, cloud='dst_cloud')
act_stop_vms = stop_vm.StopVms(self.init, c... | The code defines a method to migrate instances by orchestrating a pipeline of operations: fetching filtered instance data, initializing iteration, processing each instance, saving results, checking iteration status, renaming data, and cleaning up images. It uses a workflow of interconnected actions to systematically tr... | def migrate_instances(self):
name_data = 'info'
name_result = 'info_result'
name_backup = 'info_backup'
name_iter = 'info_iter'
save_result = self.save_result(name_data, name_result, name_result, 'instances')
trans_one_inst = self.migrate_process_instance()
init_i... |
def unique_bonds(atoms_obj):
u_bond_dict = get_unique_bonds(atoms_obj)
output = []
for i in range(len(u_bond_dict)):
for j in u_bond_dict[i]:
output.append(tuple([i, j]))
return output
def bond_vec(posns, idcs):
vec = get_bond_disp_vec(posns, idcs)
return stretch_posn_vec(vec... | The function generates a matrix of bond vectors for all unique bonds in an atomic structure, filling remaining entries with empty vectors. It takes an atoms object, extracts atomic positions and unique bonds, computes bond vectors for each unique bond, and populates a 3D matrix with these vectors, supplementing with ze... | def bond_disp_vecs_sq(atoms_obj):
posns = atoms_obj.get_positions()
u_bonds = unique_bonds(atoms_obj)
n_atoms = len(atoms_obj.get_atomic_numbers())
m_bonds = len(u_bonds)
output = np.empty(tuple([3 * n_atoms, 3 * n_atoms]))
for m in range(m_bonds):
output[m] = bond_vec(posns, [u_bonds[m]... |
def get_updates(offset=None):
url = URL + "getUpdates"
if offset:
url += "?offset={}".format(offset)
js = get_json_from_url(url)
return js
def get_last_update_id(updates):
update_ids = []
for update in updates["result"]:
update_ids.append(int(update["update_id"]))
return max(... | The code continuously polls for updates using an infinite loop. It retrieves updates, checks if new ones exist, updates the last processed ID, and handles them. The loop pauses briefly between checks to avoid excessive resource use. | def main():
last_update_id = None
print("before loop")
while True:
updates = get_updates(last_update_id)
if len(updates["result"]) > 0:
last_update_id = get_last_update_id(updates) + 1
handle_updates(updates)
time.sleep(0.5) |
def update_vnc_ids(self):
if self.is_shutting_down:
return
path = Globals.TOKENS_FILE_DIR
print("Updating VNC tokens file %s" % path)
with open(path, "w") as f:
for vnc_id in self.pool:
if self.pool[vnc_id].state == State.Ready:
... | The code monitors and manages the states of VNC instances and a websockify service. It tracks counts of serving, requested, ready, and unavailable instances, removes stale or dead instances from the requested list, logs status changes, and updates the pool. It adjusts pool size based on thresholds, replaces dead instan... | def check_state(self):
if self.is_shutting_down:
return
count_serving = 0
count_requested = 0
count_ready = 0
count_unavailable = 0
dead_instances = []
changes = [self.websockify.check_state()]
for vnc_id in self.pool:
changes.appen... |
def trim_annotations(self, annotations, text):
tidy_annotations = []
annotations = [(int(a),int(b),c) for (a,b,c) in annotations]
for i, (b, e, a) in enumerate(annotations):
if len(text) > b:
while text[b] == ' ':
b += 1
if len(text... | This function converts annotated text into BILUO format for Named Entity Recognition (NER). It trims annotations, merges overlapping intervals, assigns "ADR" labels, processes text with a NLP model, generates BILUO tags from offsets, and applies postprocessing to refine tokens and tags, removing meaningless annotations... | def biluo_tagging(self, text, annotations):
annotations = self.trim_annotations(annotations, text)
annotations = IntervalMerger().merge([[s,e] for (s,e,t) in annotations])
annotations = [(s[0],s[1],"ADR") for s in annotations]
text = self.tidy_text(text)
doc = self.nlp(text)
... |
def biluo_tagging(self, text, annotations):
annotations = self.trim_annotations(annotations, text)
annotations = IntervalMerger().merge([[s,e] for (s,e,t) in annotations])
annotations = [(s[0],s[1],"ADR") for s in annotations]
text = self.tidy_text(text)
doc = self.nlp(text)
... | The code annotates text with tokens and tag formats (BILUO, IOB, IO) using annotations, then adds these as columns to the text data. It also applies custom tagging for 'polarity' and 'modality' if present, returning the enriched text with structured annotations. | def tagging(self, text, annotations):
tags = []
for i, t in text.iterrows():
a = annotations[['begin','end','type']].loc[annotations['text_id']==t['text_id']]
(tokens, biluo_tags) = self.biluo_tagging(t['text'], [tuple(x) for x in a.to_numpy()])
tag = Tag(i, tokens, b... |
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
return count_empty(board) == 0 or winner(board) is not None
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
win = winner(board)
if win is None:
return 0
... | The function implements a minimax algorithm with alpha-beta pruning to determine the optimal value of a game state. It alternates between minimizing and maximizing players (based on 'index') recursively, evaluating terminal states with 'utility' and pruning branches when a move's value reaches a threshold (-1 or 1), th... | def mostValue(state,index):
"""
The value of this node is not determined by its utility,
but is recursively determined by the values of the lower level nodes of this node
"""
vals = [9999, -9999]
funcs = [min, max]
targets = [-1, 1]
val = vals[index]
if terminal(state):
ret... |
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
return count_empty(board) == 0 or winner(board) is not None
def player(board):
"""
Returns player who has the next turn on a board.
"""
return X if count_empty(board) % 2 == 1 else O
def actions(board):
"""
... | The code implements the Minimax algorithm with alpha-beta pruning to determine the optimal move for the current player on a board game. It evaluates all possible actions, recursively calculating their values, and selects the best action based on maximizing/minimizing scores. If a winning move is found, it prunes furthe... | def minimax(board):
if terminal(board):
return None
most_value = None
most_action = None
index = 0 if player(board) == X else 1
funcs = [min, max]
targets = [1, -1]
for action in actions(board):
val = mostValue(result(board,action), index)
if most_value is None ... |
def fk(theta):
_tm1 = trans_mat(0., LINK_LEN[0], 0., theta[0])
_tm2 = trans_mat(0., LINK_LEN[1], -np.pi/2, theta[1])
_tm3 = trans_mat(0., LINK_LEN[2], np.pi/2, theta[2])
_tm4 = trans_mat(LINK_LEN[3], 0., -np.pi/2, theta[3])
_tm5 = trans_mat(0., LINK_LEN[4], np.pi/2, theta[4] + np.pi/2)
_tm6 = tr... | This code performs inverse kinematics with collision avoidance by iteratively optimizing joint angles (theta) to minimize the error between the robot's end-effector and target pose, while considering elbow and wrist positions. It uses weighted least squares, Jacobian matrices, and damping parameters to adjust theta, en... | def ik_collision(tgt_pose, tgt_elbow_pos, tgt_wrist_pos, theta_init):
# _W_E_mat = np.diag(np.concatenate((np.ones(len(tgt_pose)), _weight_param)))
_LINK_LEN_SUM = np.sum(LINK_LEN)
_W_E_mat = np.diag(np.array([1/_LINK_LEN_SUM, 1/_LINK_LEN_SUM, 1/_LINK_LEN_SUM, 1/(2*np.pi), 1/(2*np.pi), 1/(2*np.pi)]))
_L... |
def tm2pvrm(self, tm):
return tm[:3,3], tm[:3,:3]
def tm_arm(self, theta):
self.dh_arm = self.dh.arm_right(theta)
return self.tm_chain_part(self.dh_arm, self.dh_arm.shape[0])
def tm_arm_thumb_right(self, theta):
self.dh_thumb = self.dh.thumb_right(theta)
return self.tm_chain_part... | This function computes the right thumb's position/orientation in PVRM coordinates by combining arm and thumb-specific transformations using the input theta, then converting the result via tm2pvrm. | def fk_thumb_right_pvrm(self, theta):
return self.tm2pvrm(self.tm_arm(theta) @ self.tm_arm_thumb_right(theta)) |
def tm2pvrm(self, tm):
return tm[:3,3], tm[:3,:3]
def tm_arm(self, theta):
self.dh_arm = self.dh.arm_right(theta)
return self.tm_chain_part(self.dh_arm, self.dh_arm.shape[0])
def tm_arm_index_right(self, theta):
self.dh_index = self.dh.index_right(theta)
return self.tm_chain_part... | The function computes a transformation matrix for the right index finger by combining two arm-specific transformations (tm_arm and tm_arm_index_right) using matrix multiplication, then applies a final conversion (tm2pvrm) to derive the resulting value based on input parameters theta. | def fk_index_right_pvrm(self, theta):
return self.tm2pvrm(self.tm_arm(theta) @ self.tm_arm_index_right(theta)) |
def tm2pvrm(self, tm):
return tm[:3,3], tm[:3,:3]
def tm_arm(self, theta):
self.dh_arm = self.dh.arm_right(theta)
return self.tm_chain_part(self.dh_arm, self.dh_arm.shape[0])
def tm_arm_middle_right(self, theta):
self.dh_middle = self.dh.middle_right(theta)
return self.tm_chain_p... | The function computes the forward kinematics for the middle-right arm segment by combining transformation matrices from `tm_arm` and `tm_arm_middle_right` via matrix multiplication, then converting the result to PVRM coordinates using `tm2pvrm`.) | def fk_middle_right_pvrm(self, theta):
return self.tm2pvrm(self.tm_arm(theta) @ self.tm_arm_middle_right(theta)) |
def tm_arm(self, theta):
self.dh_arm = self.dh.arm_right(theta)
return self.tm_chain_part(self.dh_arm, self.dh_arm.shape[0])
def tm2pv(self, tm):
return tm[:3,3]
def tm_arm_thumb_right(self, theta):
self.dh_thumb = self.dh.thumb_right(theta)
return self.tm_chain_part(self.dh_thum... | This function calculates the position and orientation of the right hand's thumb, index, and middle fingers using transformation matrices derived from input angles theta. It combines these values into a single array for output. | def fk_fingers_right_pvs(self, theta):
self._tm_arm = self.tm_arm(theta)
self.pv_thumb = self.tm2pv(self._tm_arm @ self.tm_arm_thumb_right(theta))
self.pv_index = self.tm2pv(self._tm_arm @ self.tm_arm_index_right(theta))
self.pv_middle = self.tm2pv(self._tm_arm @ self.tm_arm_middle_right... |
def _get_flat_grad(
self, y: torch.Tensor, model: nn.Module, **kwargs: Any
) -> torch.Tensor:
grads = torch.autograd.grad(y, model.parameters(), **kwargs) # type: ignore
return torch.cat([grad.reshape(-1) for grad in grads])
def _conjugate_gradients(
self,
minibatch: torch.T... | The main task of the code is to perform policy optimization using natural gradient descent and value function updates in a reinforcement learning algorithm. It iteratively computes actor losses via natural gradient steps (using conjugate gradients and KL divergence), updates the actor network, and trains the critic net... | def learn( # type: ignore
self, batch: Batch, batch_size: int, repeat: int, **kwargs: Any
) -> Dict[str, List[float]]:
actor_losses, vf_losses, kls = [], [], []
for _ in range(repeat):
for minibatch in batch.split(batch_size, merge_last=True):
# optimize actor
... |
def findAllCombinations(self):
total = len(self.graph.nodes)
for node in self.graph.nodes:
self.all_combinations.extend(self.findPaths2(node, self.M - 1))
def getDistinctNeighbors(self, array):
allNeighbors = []
for city_id in array:
city_node = self.graph.get... | The code identifies the combination of cities (or nodes) with the minimal number of distinct neighbors in a graph. It iterates through all generated combinations, calculates their distinct neighbor counts, and updates the optimal solution when a lower count is found. Finally, it prints the best combination and its neig... | def solve_graph(self):
self.findAllCombinations()
solution_path = []
solution_neighbors = []
solution_neighbor_count = 99999999
i = 1
total = len(self.all_combinations)
for comb in self.all_combinations:
comb_array = [cities.get_id() for cities in ... |
def get_best_path_from_node(self, node_id):
# Initializing our kingdom with starting node
current_kingdom = [node_id]
# Included cities
included_cities = self.included_cities_dict[node_id]
# Adding the best neighbor to the kingdom until size reached
while len(included_... | This function identifies the optimal 'kingdom' path in a graph by evaluating each node's best path, calculating the distinct neighbor count of its neighbors, and selecting the path with the highest distinct count. It iterates through all nodes, avoids revisiting cities, and returns the included cities of the best kingd... | def find_best_kingdom_in_graph(self):
best_kingdom = None
best_kingdom_distinct_count = None
visited_cities = []
for node in self.graph.nodes:
if node.get_id not in visited_cities:
path = self.get_best_path_from_node(node.get_id())
distinct... |
def get_best_path_from_node(self, node_id):
# Initializing our kingdom with starting node
current_kingdom = [node_id]
# Adding the best neighbor to the kingdom until size reached
while len(current_kingdom) < self.M:
best_neighbor = self.select_best_neighbor(current_kingdom... | The main task of the code is to find the "best kingdom" in a graph by identifying the path starting from each node that yields the maximum number of distinct neighboring nodes. It iterates through all nodes, computes the best path from each, evaluates the distinct neighbor count of that path's neighbors, and retains th... | def solve_graph_1(self):
best_kingdom = None
best_kingdom_distinct_count = None
visited_cities = []
for node in self.graph.nodes:
self.node += 1
if node.get_id not in visited_cities:
path = self.get_best_path_from_node(node.get_id())
... |
def get_best_path_from_node(self, node_id):
# Initializing our kingdom with starting node
current_kingdom = [node_id]
# Adding the best neighbor to the kingdom until size reached
while len(current_kingdom) < self.M:
best_neighbor = self.select_best_neighbor(current_kingdom... | The code identifies the optimal "kingdom" path in a graph by iterating through each node, computing the best path from that node, and evaluating the number of distinct neighbors in that path. It retains the path with the highest distinct neighbor count, updating its record whenever a better path is found. Finally, it p... | def solve_graph_2(self):
best_kingdom = None
best_kingdom_distinct_count = None
visited_cities = []
for node in self.graph.nodes:
self.node += 1
if node.get_id() not in visited_cities:
path = self.get_best_path_from_node(node.get_id())
... |
def compress_graph_first_time(self):
new_graph = g.Graph()
pairs = self.pair_all_nodes()
for key in pairs:
pair = pairs[key]
id = key
kingdoms = []
neighbors = []
for city_id in pair:
self.index[city_id] = id
... | The main task of the code is to compress a graph initially, divide nodes based on their included city counts, identify the best kingdom in the graph, and return 0. The loop for further compression does not execute as it is set to run zero times. | def solve_graph(self):
self.compress_graph_first_time()
print("Compression 1 completed\n")
for i in range(0):
self.compress_again()
print("Compression ", i + 2, " completed.\n")
nodes_dict = self.divide_nodes_by_included_city_count()
kingdom = self.fin... |
def build_network(self, model_id, built_for_training=False):
self.build_fcn(model_id, built_for_training)
def calc_sum_rate(self, power, abs_H, noise_power, binary_enabled):
abs_H = tf.reshape(abs_H, [-1, self.top_config.user_num, self.top_config.user_num])
abs_H_2 = tf.square(abs_H)
if ... | The code trains a neural network to maximize sum rate metrics (sum_rate_dnn and sum_rate_dnn_binary) using TensorFlow. It initializes data loading, builds the network, defines loss functions, and employs Adam optimizer for training. The model trains for a specified number of epochs, using either preloaded data or onlin... | def train_network(self, model_id):
last_update = 0
data_io = DataIO(self.top_config) # construct class for loading data
self.build_network(model_id, True) # build the network for training
assign_net_in_test = self.net_in_test.assign(data_io.load_all_test_data())
## define l... |
def affected_format_list(self) -> List[dict]:
return [
{
'package': self._package_format_dict(affected.package),
'ranges': self._ranges_format_list(affected.ranges),
} for affected in self.affected_packages
]
def published_format_str(self) -> str:
... | This method converts an object's attributes into a JSON-formatted string with indentation for readability. It serializes properties like 'id', 'summary', 'affected', 'related', 'published', 'modified', 'details', and 'references' (after formatting via specific methods) into a structured JSON representation, ensuring da... | def to_json_str(self) -> str:
return json.dumps({
'id': self.db_id,
'summary': self.summary,
'affected': self.affected_format_list(),
'related': self.related,
'published': self.published_format_str(),
'modified': self.modified_format_str(),... |
def short_path(dir):
if len(dir) <= 77:
return dir
else:
return f'{dir[0:76]}...'
def list_pics():
global main_pic_list
main_pic_list = glob(source_path + '/*.jpg')
main_pic_list.extend(glob(source_path + '/*.jpeg'))
main_pic_list.extend(glob(source_path + '/*.png'))
mai... | The function allows users to select a source folder, updates the UI with the chosen path, checks for photos, and either displays the photos or a default view based on their presence, updating UI elements like photo counts and button states accordingly. | def browse_source():
global source_path
global user_dir
source_path = filedialog.askdirectory(initialdir = user_dir, title = 'Browse Folder')
# when user selects a folder
if source_path != None and source_path != '':
# display source folder in text label
source_lbl... |
def short_path(dir):
if len(dir) <= 77:
return dir
else:
return f'{dir[0:76]}...'
def speci_list_pics():
global speci_files
global main_pic_list
main_pic_list = []
file_types = ['jpg', 'jpeg', 'png']
for i in speci_files:
if i.rsplit('.', 1)[1] in file_types:
... | The function allows users to select files, determines the source directory, checks for images, updates UI elements based on photo presence, and manages navigation and display settings. It handles cases where no files are selected or no photos exist, updating labels and button states accordingly. | def browse_speci_files():
global speci_files
global source_path
global user_dir
speci_files = filedialog.askopenfilenames(initialdir = user_dir, title = 'Browse File(s)')
try:
source_path = speci_files[0].rsplit('/', 1)[0]
except:
pass
# when user selects a folder
i... |
def check_collectibles(self):
hit_list = arcade.check_for_collision_with_list(self.zombie,
self.level.collectibles)
for item in hit_list:
self.level.collectibles.remove(item)
self.score += 1
def update_enemies(self):
... | This code updates the game state by moving the zombie, checking for collectibles, updating enemies, and checking for game over conditions. If the game is over, it restarts the game. Finally, it updates the physics engine to handle movement and collisions. The function is called repeatedly with a delta_time parameter to... | def on_update(self, delta_time):
self.zombie.move(can_jump=self.physics_engine.can_jump())
self.check_collectibles()
self.update_enemies()
self.check_for_game_over()
if self.game_over:
self.restart_game()
self.physics_engine.update() |
def display_basket():
headers = ["#", "Kind", "Name", "Treatment Name", "Price"]
formatted_data = [
[idx, item["kind"], item["name"], item["treatment"], item["price"]]
for idx, item in enumerate(basket, start=1)
]
print()
print(tabulate(formatted_data, headers=headers, tablefmt="sim... | This module manages a pet clinic's treatment basket, allowing users to add treatments, remove specific items, clear the basket, or proceed to the home screen. It displays options, validates input, handles errors, and executes corresponding actions like checkout or removal based on user choices. | def module():
err_msg = ""
while True:
clear_screen()
show_title("Pet Clinic")
if basket:
display_basket()
print(
dedent(
"""
Options:
1. Request a treatment
2. Cancel a treatment
3. Clear a... |
def preprocess():
""" main function that does the preprocessing """
train_path = "Dataset_crimes.csv"
train_path2 = "crimes_dataset_part2.csv"
train = process_data(pd.read_csv(train_path)).dropna()
train2 = process_data(pd.read_csv(train_path2)).dropna()
train_co = pd.concat([train, train2], axi... | The code trains an ensemble model by preprocessing data, creating classifiers, applying Bagging and Adaboost, combining the trained models, and serializing them into pickle files for later use. | def train():
""" main function to train the model """
X_train, y_train = preprocess()
CLASSIFIERS = create_classifiers()
CLASSIFIERS_1 = Bagging(X_train, y_train, T, CLASSIFIERS[1:2])
CLASSIFIERS_2 = Adaboost(X_train, y_train, T, CLASSIFIERS[2:])
models = CLASSIFIERS_1 + CLASSIFIERS_2
pkl_fi... |
def get_all_actions(self):
self.action_space()
self.get_all_payoffs()
self.get_pure_nash()
self.count_nash()
self.get_pne()
def all_binary_strategies(length=3):
from itertools import product
strategies = []
dummies = list(product(range(2), repeat=length))
for i i... | This function maps each naive best reply profile to all strategies that produce it. It iterates through all binary strategies for the game's players, computes the naive best reply for each strategy, and groups strategies by their resulting profile in a dictionary. The dictionary keys are string representations of profi... | def naive_best_replies(self):
self.get_all_actions()
from collections import defaultdict
d = defaultdict()
for strategy in all_binary_strategies(len(self.players)):
naive_profile = self.naive_best_reply(strategy)
key = str(naive_profile)
if key not in ... |
def free_spaces(board=board):
freeSpaces = 0
for key in board.keys():
if board[key] == ' ':
freeSpaces += 1
return freeSpaces
def print_board(board=board):
for i in range(1, 8, 3):
print('|' + board[i] + '|' + board[i + 1] + '|' + board[i + 2] ... | This function handles a player's move in a game by prompting for a valid position (1-9), validating input, and updating the board with the player's letter. It first checks if there are at least 9 free spaces to print the board, then ensures the input is within range, and finally calls make_move to place the player's ma... | def player_move(playerLetter='O'):
if free_spaces(board) >= 9:
print_board(board)
position = int(input("Enter your position (1-9): "))
print()
while not (1 <= position <= 9):
print("Invalid choice.")
position = int(input("Enter new position: "))
... |
def space_is_free(position):
if board[position] == ' ':
return True
else:
return False
def minimax(board, is_maximising=False):
if check_for_win_letter(computerLetter):
return 1 * (free_spaces(board) + 1)
elif check_for_win_letter(playerLetter):
... | The main task of the code is for the computer to determine its optimal move in a game (likely Tic-Tac-Toe) using the minimax algorithm. It evaluates all free positions on the board by temporarily placing its letter, calculating the resulting score via the minimax function, and selecting the position with the highest sc... | def computer_move(computerLetter='X'):
time.sleep(1.5)
bestScore = -math.inf
bestPosition = 0
for key in board.keys():
if space_is_free(key):
board[key] = ' ' + computerLetter + ' '
score = minimax(board)
board[key] = ' '
... |
def int_to_list(item):
"""Helper function to turn int input to list
Args:
item (int or list): Integer or List of integers
Returns:
list: List of integers
Raises:
ValueError: If the input is not an integer or a list
"""
if isinstance(item, int):
return [item]
... | This function maps each supervoxel ID in `sv_id` to its agglomerated group members by retrieving parent agglomeration IDs, querying associated children, and constructing a dictionary where each original ID points to its parent and all child supervoxel IDs within the same agglomerated object. | def get_groups(self, sv_id):
"""Returns the list of all segments belonging to the same agglomerated
supervoxel ids as the segment(s) in sv_id.
Args:
sv_id (int or list): supervoxel ids
Returns:
dict: maps each entry in sv_id onto a list of members of the
... |
def get_value(comp): #Function geneates a random fraction and returns it
if(comp==1):
return rand.randint(5,10)
elif(comp==2):
return rand.randint(11,20)
else:
return rand.randint(21,25)
def get_deciding_fraction():#Function generates random fraction to make options more randomized
... | The function generates multiple-choice options for a fraction-based math problem. It creates a base answer by either adding or subtracting the input fraction from a computed value, then appends five random variations by adding arbitrary fractions to the base answer. The options are passed to another function to form a ... | def get_options(_Frac_, comp): #Function generates options for the passed the fraction
temp = rand.randint(0,1)
value = get_value(comp)
temp_answer = value + _Frac_ if(temp==0) else value - _Frac_
count=5
options=[temp_answer]
while(count>0):
options.append(get_deciding_fraction()+temp_... |
def pretrain_value_model(model: torch.nn.Module, optimizer: torch.optim, epochs=1, single_batch=False):
print('Pretraining Value model')
data = minerl.data.make('MineRLTreechop-v0', data_dir=os.environ['DATASET_DIR'])
criterion = MSELoss()
for idx, (frames, target_rewards) in enumerate(next_batch(data... | The code trains an Actor-Critic model (policy and value networks) on the MineRLTreechop-v0 environment using PyTorch. It pretrains the value model, runs episodes with the policy, optimizes both models via gradient updates, logs metrics with TensorBoard, and saves checkpoints every 10 episodes. The training involves rei... | def main(policy_model: torch.nn.Module, value_model: torch.nn.Module,
episodes: int, iterations: int, eps: float, reset_step: bool, reg: float, run_timestamp: str):
policy_model.train()
value_model.train()
global REG
REG = reg
policy_optimizer = torch.optim.Adam(policy_model.parameters(),... |
def current_token(self):
if self.current < len(self.tokens):
return self.tokens[self.current]
else:
return Token(TOKEN_TYPE.END_OF_FILE)
def parse_exit(self):
self.consume(TOKEN_TYPE.EXIT)
self.consume(TOKEN_TYPE.OPEN_PARENTHESES)
exit_code = self.current_... | This code parses input tokens into a list of nodes. It processes tokens sequentially, appending parsed EXIT or PRINT commands to self.nodes. If an unrecognized token is encountered, it raises an error. The method returns the list of parsed nodes once the input reaches the end of the file. | def parse(self):
self.nodes = []
while self.current_token().type != TOKEN_TYPE.END_OF_FILE:
if self.current_token().type == TOKEN_TYPE.EXIT:
self.nodes.append(self.parse_exit())
elif self.current_token().type == TOKEN_TYPE.PRINT:
self.nodes.append(... |
def extact_activations(layers):
model = torch.hub.load("pytorch/vision:v0.10.0", "googlenet", pretrained=True)
model.eval()
get_activations(model, layers)
def concat_batches(
layers, folder="activations", save_location="activations/ILSVRC2015"
):
if not os.path.exists(save_location):
os.make... | The main task of the code is to process activations from specified Inception layers in a neural network model. It sets a random seed for reproducibility, extracts activation data from the listed layers, concatenates batch data, and converts the results to NumPy arrays for further analysis or storage. | def main():
random.seed(17)
layers = [
"inception3a",
"inception3b",
"inception4a",
"inception4b",
"inception4c",
"inception4d",
"inception4e",
"inception5a",
"inception5b",
]
extact_activations(layers)
concat_batches(layers)
... |
def getPieceFromLocation(square: tuple[str, int]) -> Union[Piece, str]:
try:
r, c = getBoardIndexFromRankAndFile(square)
except ValueError:
return "Invalid"
return BOARD[r][c]
def oppositeColour(colour):
return "Black" if colour == "White" else "White"
def getBoardIndexFromRank... | This function checks if a given piece can defend a specified square on a chessboard. It first checks if the square is empty, returning whether the piece can move there. For pawns, it adjusts for capture rules by temporarily changing the occupant's color and checking capture moves. For other pieces, it simulates removin... | def squareDefended(square: tuple[str, int], piece: Piece) -> bool:
occupant = getPieceFromLocation(square)
pieceMoves = piece.getValidMoves()
if occupant == emptySquare:
return square in pieceMoves
# if a pawn defends the square, it needs to capture it
if isinstance(piece, Pawn):... |
def getOneSquareLeft(piece: Piece, currentSquare: tuple[str, int]) -> Union[bool, tuple[str, int]]:
file, rank = currentSquare
if file == "a":
return False
newFile = chr(ord(file) - 1)
newSquare = (newFile, rank)
occupant = getPieceFromLocation(newSquare)
if isinstance(occupant, Pi... | The function identifies valid en passant capture moves for a pawn by checking adjacent squares for opponent pawns that moved two squares forward on their first turn. It verifies conditions like opposite color, correct rank alignment, and captures the diagonal squares if empty, appending valid moves to a list. The resul... | def getEnPassantCaptureMoves(self):
validMoves = []
selfRank = self.location[1]
# maps pawn colour to rank for meeting the en passant capture conditions
colourToCurrentRank = {"White": 5, "Black": 4}
adjacentLeftSquare = getOneSquareLeft(self, self.location)
... |
def oppositeColour(colour):
return "Black" if colour == "White" else "White"
def kingIsInCheck(king: King, piece: Piece) -> bool:
if piece.colour == king.colour:
return False
validMoves = piece.getValidMoves()
# if a piece can capture the king, return True
if king.location in validMoves:
... | The code determines if a king is in checkmate by checking if all possible escape routes (capturing attacking pieces, blocking checks, or moving the king) are blocked by the opponent's pieces, ensuring no valid move or defense exists for the king. | def checkmate(king: King) -> bool:
playerPieces = colourToPlayer[king.colour].pieces
opponentPlayer = colourToPlayer[oppositeColour(king.colour)]
opponentPieces = opponentPlayer.pieces
piecesThreateningTheKing = [piece for piece in opponentPieces if kingIsInCheck(king, piece)]
if not kingIs... |
def getPawnCaptureMoves(self) -> list[tuple]:
capturableMoves = []
captureSquares = self.getPawnCaptureSquares()
# tracking occupants of the opposite colour for each diagonal move
for square in captureSquares:
occupant = getPieceFromLocation(square)
if isinstanc... | The main task of the code is to generate a list of valid moves for a pawn by combining pawn capture moves, pawn advance moves, and the first en passant capture move. It aggregates these move sets into a single list, which represents all legally valid pawn movements and captures, including the en passant special rule. | def getValidMoves(self):
# valid moves from Pawn capture and move functions
validMoves = self.getPawnCaptureMoves() + self.getPawnAdvanceMoves() + self.getEnPassantCaptureMoves()[0]
return validMoves |
def getSquaresInStraightDir(piece: Piece, getOneSquareDirFunction, square: tuple[str, int]) -> list:
validMoves = []
nextSquare = getOneSquareDirFunction(piece, square)
occupant = getPieceFromLocation(nextSquare)
if isinstance(occupant, Piece) and occupant.colour != piece.colour:
validMoves.app... | The code generates valid castling moves for a king by checking if it's in its starting position, verifying empty squares between the king and rook, ensuring no threats on those squares, and confirming the rook is in its original position and hasn't moved. It returns valid moves for both kingside and queenside castling ... | def getCastleMoves(self):
validMoves = []
kingStartingSquare = {"Black": ("e", 8),
"White": ("e", 1)}
if self.location != kingStartingSquare[self.colour] or self.canCastle == False:
return validMoves
# both sets of squares for t... |
def index(self, node):
return (node[0], node[1], node[2])
def child_generator(self, node, cost):
valid_children = []
n1 = self.move1(node, cost)
n2 = self.move2(node, cost)
n3 = self.move3(node, cost)
n4 = self.move4(node, cost)
n5 = self.move5(node, cost)
n6 = self.move6(node, cost)
... | The code implements the A* algorithm to find the shortest path from a start node to a goal node. It explores nodes in a priority queue, expands valid children, and checks for goal proximity using Euclidean distance. Upon reaching the goal, it backtracks to construct the path, returning both the path and explored nodes. | def astar(self):
print('Started Search ... ')
explored_nodes = [(0, self.start_node, self.index(self.start_node), self.parent_node)]
explored.append(self.start_node)
valid_childs_dict[self.index(self.start_node)] = [self.start_node, self.parent_node]
cum_cost = 0
itr = 0
while len(explored_n... |
def _componentwise_inverse(x):
if _is_container(x):
T = type(x)
return T([_componentwise_inverse(xi) for xi in zip(x)])
else:
return 1.0 / x
def _inner_product(x, y) -> float:
if _is_container(x):
return np.sum([_inner_product(xi, yi) for xi, yi in zip(x, y)])
else:
... | This function computes the product of the inverse Hessian approximation (H_k) and a gradient vector (q) using L-BFGS's two-loop recursion. It first updates q via stored s/y vectors and alphas, applies an initial inverse Hessian approximation, then adjusts the result using reversed s/y vectors and betas to produce r = H... | def matvec(self, q: VecType) -> VecType:
"""Computes
r = H_k grad f_k
via L-BFGS two-loop recursion.
Algorithm 7.4 on page 178 of Nocedal and Wright.
"""
rhos = [
_componentwise_inverse(_inner_product(y, s))
for s, y in zip(self.ss, self.yy)
... |
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
p... | The code calculates pass statistics for each player in `df` by analyzing event data in `dfEvent`. It counts total, completed, failed, key, and assist passes, and identifies "dangerous" passes (e.g., high-risk or critical-area passes) using specific event tags. Results are added to `df` as new columns and returned along... | def computeTotalPasses(df, dfEvent):
"""
For each player in df look the number of air duel inside a match
Parameters
----------
df : match_id gameweek team_id playerId minutes_played red_card yellow_card goals
The dataset extracted with playerMatchExtraction from json file of Wyscout matche... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.