dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def cost(self):
"""
Computes the current cost of the NN.
"""
result = 0
# iterate through each sample of training data
for data in self._train:
x1 = data[0]
x2 = data[1]
# push the input values through each layer
y = self.fo... | The code defines the `__str__` method to generate a formatted string representing the model's current state. It includes parameters, their gradients, the computed cost, outputs for sample inputs, and neuron-specific outputs. The method structures information into labeled sections for clarity, rounding numerical values ... | def __str__(self):
"""
Returns a string - the current state of the model
"""
# show the current state of each parameter
output = "\n1)Parameters:\n"
for par_name, value in self._pars.items():
temp = par_name + " = " + str(round(value, 3)) + "\n"
ou... |
def finite_diff(self):
"""
Approximates values of partial derivatives of each parameter
in relation to the cost function (gradient), and stores them in <self._grad>.
The current parameter values remain unchanged.
"""
# compute the initial cost
c = self.cost()
... | The code trains a neural network (NN) using the finite difference method for `n` iterations. It initializes gradients, prints the NN's initial state, updates cost values iteratively, applies gradients to train the model, and prints the final state. After training, it plots the cost function over the iterations to visua... | def learn(self, n):
"""
Trains the NN on the training data set <n> times,
prints out NN state and plots the cost function.
Uses the finite difference approach.
"""
# lists of values for the plot of cost.
x_vals = []
y_vals = []
# compute the initia... |
def entryboxes(self):
self.e1 = tk.Text(root, height=18, width=40)
self.e2 = tk.Entry(root)
self.e1.grid(column=3, row=1)
self.e2.grid(column=1, row=2)
def savebutton(self):
self.savebutton = tk.Button(text='save', command=self.save)
self.savebutton.grid(column=3, row=2)
... | This code initializes a Tkinter GUI for an image processing application, setting up a window with a title, minimum size, descriptive label, and multiple UI components including input fields, buttons for saving/selecting images, running CPU/GPU processing, and navigation controls. The main task is to create an interacti... | def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
parent.title('Coco Leaf Image Processor')
parent.minsize(640, 400)
tk.Label(text="Description of this experiment and image series").grid(column=3, row=0)
... |
def filter_rules(rules: List[str]) -> List[str]:
if len(rules) == 0:
return []
all_rules = get_all_rules()
recognized: List[str] = []
unrecognized: List[str] = []
for rule in rules:
if rule in all_rules:
recognized.append(rule)
continue
unrecognized.... | The function `run_semgrep` executes the semgrep tool to scan a specified target file/directory for code issues using given rules. It filters input rules, defaults to all rules if none are provided, formats them with a config prefix, and runs the scan via subprocess, exiting with the tool's return code. | def run_semgrep(target: Path, rules: List[str]) -> None:
args = ["semgrep", "scan", "--error"]
rules = filter_rules(rules)
if len(rules) == 0:
rules = get_all_rules()
args.extend(rules_with_config_prefix(rules))
args.append(str(target))
process = subprocess.run(args)
exit(process.... |
def _clearSchematicFilters(self):
self._plugin.filter().clearSchematicFilter()
def _arkStatus(self, item):
haveArk = SearchStatus.NotFound
contextType = 'None'
contextDescription = ''
try:
if item in self._plugin.data().items['context']:
haveArk = Sear... | This function validates and updates the current context by clearing filters, checking context validity, applying schematic filters, and determining the presence of ARK data, features, schematics, and section schematics. It updates the UI dock with context status and metadata, ensuring accurate representation of availab... | def _findContext(self, context=Item()):
self._clearSchematicFilters()
if not context.isValid():
context = self._dock.contextItem()
self._plugin.filter().applySchematicFilter(context, self._filterAction)
self.applyItemActions(context, self._mapAction, FilterAction.NoFilterAc... |
def _arkStatus(self, item):
haveArk = SearchStatus.NotFound
contextType = 'None'
contextDescription = ''
try:
if item in self._plugin.data().items['context']:
haveArk = SearchStatus.Found
vals = self._plugin.data().getItemFields(item, ['conf_fi... | This method determines the valid source item, applies schematic filters, checks the source's status for ark, features, and schematics, then updates the dock's context with these status values and the source item. | def _findSource(self, source=Item()):
if not source.isValid():
source = self._dock.sourceItem()
self._plugin.filter().applySchematicFilter(source, self._filterAction)
self.applyItemActions(source, self._mapAction, FilterAction.NoFilterAction, self._drawingAction)
haveArk, c... |
def _clearSchematicFilters(self):
self._plugin.filter().clearSchematicFilter()
def _copySourceSchematic(self):
self.metadata.validate()
request = self._categoryRequest(self._dock.sourceItem(), 'sch')
features = layers.getAllFeaturesRequest(request, self.collection().layer('polygons'))
... | The main task of the code is to clone a source schematic by first clearing any existing filters, then copying the schematic data, and finally merging the copied data into the target structure to create a duplicate. | def _cloneSourceSchematic(self):
self._clearSchematicFilters()
self._copySourceSchematic()
self._mergeSchematic() |
def get_results(self,query):
#create url
query = urllib.parse.quote_plus(query)
#response = self.get_source('https://www.google.co.uk/search?q='+query)
response = self.get_source(query)
print('>> request on google on "{}"'.format(query))
return response
def parse_results(... | The code performs a Google search by querying an API, saves the HTML response to a file, extracts structured data such as snippets, FAQs, knowledge panels, and related keywords, and returns a dictionary containing parsed information. It handles errors, processes search results, and organizes content for further use. | def google_search(self,query):
print('>> api calling start...')
req = self.get_results(query)
if req['status'] == 'failed':
return{'status':'failed'},400
response = req['req']
try:
with open(f"html/{re.sub('[^A-Za-z0-9]+', '', query)}.html", "w",encoding="... |
def dependency_graph(key, json_filepath, unique_nodes, unique_edges, test, train):
# syntax: {"script_url": ["unique_identifier", "label", "tracking_count", "non-tracking_count", test, train]}
# count +1 for tracking & -1 for non-tracking
with open(json_filepath) as file:
for line in file:
data = json.l... | The code constructs a dependency graph from script and labeling data, processes nodes/edges with cookie-storage relationships, and visualizes the graph using graphviz. It categorizes nodes by labels (tracking, non-tracking, storage, cookies) with distinct colors, then generates a directed graph with edges and renders i... | def main():
# unique node and edges
# unique_nodes => script:[id, tracking, non-tracking, test, train] for cookie -1, -1 for storage -2, -2
# unique_edges => script_id@script_id: [script_id, script_id] or cookies_id, storage_id
unique_nodes = {}
unique_edges = {}
unique_nodes, unique_edges = de... |
def parse_arguments():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description='Create CoT instruction data.')
parser.add_argument('-i', '--input_dir', type=str, default='../../../datasets', help='Path to raw datasets')
parser.add_argument('-o', '--output_dir', type=str, default... | The code processes cross-claim annotation data to generate instruction data for fine-tuning a model on Task 2. It loads claim relations and frames, maps claim IDs to elements, creates dialogue prompts for each pair, and saves the structured data as a pickle file for training. | def main():
args = parse_arguments()
input_dir = Path(args.input_dir)
output_dir = Path(args.output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
print('Input directory:', input_dir)
print('Output directory:', output_dir)
ANNOTATION_PATH = f"{input_dir}/LDC/LDC2021E16_AIDA_Phase_3_TA3_... |
def getShuffledPaths(path):
lst = os.listdir(path)
removeRedundencies(lst)
random.shuffle(lst)
return lst
def getInput():
# printNextInfo()
return input("Waiting for input \n")
def playVideo(path):
runVideoThread(path)
def killMedia():
print("kill Media was requested")
os.system(QUIT... | The main task of the code is to play shuffled videos from commercial, trailer, and intro directories based on user input, cycling through each category's files using modulo indexing, while handling media control commands like 'kill' and displaying next video info. | def mainLoop():
path_to_commercials = "/Users/tomerlankri/Downloads/commercials"
path_to_trailers = "/Users/tomerlankri/Downloads/trailers"
path_to_intros = "/Users/tomerlankri/Downloads/sounds"
lst_commercials = getShuffledPaths(path_to_commercials)
lst_trailers = getShuffledPaths(path_to_trailers... |
def leftAns(self):
self.checkAnswer(2)
def rightAns(self):
self.checkAnswer(1)
def upAns(self):
self.checkAnswer(0)
def downAns(self):
self.checkAnswer(3)
def returnEvent(self):
if self.onInstructions:
self.drawGame()
if self.onMenu:
self.startGame... | This code initializes a GUI-based memory recency game, setting up states (menu/instructions/game), tracking scores, problem sequences, and user input handling via keyboard events. It configures a Tkinter window with a canvas, loads directional images, and prepares data structures for storing problems, answers, and perf... | def __init__(self):
self.onMenu = False
self.onInstructions = False
self.onGame = False
self.onProblem = False
self.finishedGame = False
self.menuItems = []
self.instructionsItems = []
self.score = 0
self.problemtime = 5.0
self.problem = ""... |
def path_length(path) -> int:
return 0xffffffff if path is None else len(path)-1
def compute_path(game: DungeonGame, p1: Point, p2: Point) -> List[Point]:
cache = game.cache()
if p1 not in cache:
from collections import deque
path_map = {p1: [p1]}
queue = deque([p1])
while qu... | This heuristic function evaluates the current game state to guide agent decisions in a dungeon game. It rewards key collection, monster elimination, and proximity to the exit while penalizing danger and distance. It returns a high value for winning states, low values for losing states, and adjusts for agent type (playe... | def dungeon_heuristic(game: DungeonGame, state: DungeonState, agent: int) -> float:
area = state.layout.width * state.layout.height
value = state.score()
INFINITY = int(1e8)
if state.player.inventory.keys != 0 and state.player.position == state.layout.exit:
# If the player won, return a very hi... |
def update_mini_batch(self, mini_batch, lr, lmbda, m_total):
"""
Computes gradients and updates the weights and biases
Arguments:
mini_batch -- a list of tuples (x, y)
lr -- the learning rate
Returns:
batch_cost_sum -- the sum of the cost of each training exampl... | The main task of the code is to implement Stochastic Gradient Descent (SGD) for training a neural network. It processes training data in mini-batches, updates model parameters using the specified learning rate and regularization, and optionally monitors/tracks training and evaluation costs/accuracies over epochs. The f... | def SGD(self, training_data, epochs, mini_batch_size, lr,
lmbda = 0,
evaluation_data=None,
monitor_training_cost=False,
monitor_training_accuracy=False,
monitor_evaluation_cost=False,
monitor_evaluation_accuracy=False):
"""
Perfor... |
def preprocessInputData(input, config = Config(), single= True):
input = preprocessAudio(input, config = config, single = single)
# convert from list to numpy array
input = np.array(input)
print(input.shape)
input = np.reshape(input, (input.shape[0], input.shape[1],input.shape[2], 1))
return input
def res... | The main task of the code is to validate a machine learning model's performance on a dataset containing audio files labeled "0no" and "1yes". It loads audio data from validation folders, preprocesses the inputs, predicts classifications using the model, and compares the predicted outputs with the expected labels. The f... | def validateData(model, config):
VALID_PATH = DATAPATH + "validate/"
nameIndex = []
i = 0
classification = []
output = []
for foldername in ["0no", "1yes"]:
folder_path = VALID_PATH+ foldername
print(folder_path)
# checking if it is a file
# if os.path.isfile(f):
nameIndex.append(f... |
def cloud_resolution(img):
shape = np.max(img.shape)
powers = [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
for power in powers:
if power > shape:
return power
def cloud_generation(shape, res, octaves):
fractal_noise = generate_fractal_noise_2d(shape, res, octaves)
mask... | The code generates a synthetic cloudy image by combining an input image with a procedurally generated cloud mask, then saves the original image, cloud mask, and resulting cloudy image in both 8-bit PNG and high-resolution TIFF formats for visualization and download. | def spliceCloudFromGenertedMask(input, res, octave):
u = iio.read(input)
cloud_resolution_size = cloud_resolution(u)
cloud, mask = cloud_generation((cloud_resolution_size, cloud_resolution_size), (res, res), octave)
cloudy, cloud_crop = cloud_copy(u, cloud)
if not os.path.exists('output/'):
... |
def luminance(img):
red = img[:, :, 0]
green = img[:, :, 1]
blue = img[:, :, 2]
return (.299 * red) + (.587 * green) + (.114 * blue)
def conv(u, radius, kernel):
"""This is much faster than scipy.ndimage.convolve"""
kernel = np.ones((2 * radius + 1,), dtype=np.float32) / (2 * radius + 1)
fo... | The function `splice_cloud` combines a cloud image with a background image using alpha matting and shadow effects. It processes each color channel separately, applies convolution and masking to generate a cloud alpha channel, normalizes cloud intensity, adds shadows to the background, and blends the cloud with the back... | def splice_cloud(background, cloud_image, mask, conv_size, radius, epsilon):
if len(background.shape) > 2:
cloudy_background = []
# Alpha matting only on grey level image
lumi_cloud = luminance(cloud_image)
mask_cloud_conv = (conv(mask, conv_size, None) > 0.9).astype(np.float32)
... |
def main(speed, level):
flag=0 #To see if game is paused or not
lost=0 #To see if the user loses or not
count=0 #count of the diffuse kits obtained
ret=-2
# global x ; global y
xnew=box.x; ynew=box.y #Make safe copies of x, y
win=addscreen() #adds the window
definecolors() #colors initialised
... | The code manages a game loop where the player progresses through 10 levels, earning points for successful completion. If the player loses, it displays a loss screen with their score. Upon completing all levels, a victory screen is shown. The game uses the `curses` library for terminal-based UI, handling ESC key presses... | def run():
score=0
level=1
levels=10
lost=main(100, level)
while(level<levels):
if lost ==0 :
score=score+box.s
box.s+=5
nxt=result(lost)
if(nxt=='y'):
level+=1
lost=main(180-20*level, level)
elif(nxt=='n'):
win=addscreen()
definecolors()
win.addstr(box.y-1, box... |
def docker_login_to_instance(instance_url, instance_email, instance_api):
print('logging in to {}'.format(instance_url))
cmd = ['sudo', 'docker', 'login', instance_url, '-u', instance_email,'-p',instance_api]
r = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE, universal_newlines=True)
r.wait()
... | The main task of the code is to gather gear information from multiple sites by authenticating with their APIs, generating structured data lists, and saving results to a JSON file. It checks for existing data to avoid reprocessing unless forced to refresh. If login fails, it skips the site. The code iterates through eac... | def site_main():
refresh = False
site_list = sl.get_site_list()
json_out = os.path.join(work_dir, 'instance_master_json.json')
if os.path.exists(json_out) and not refresh:
print('Found previous run, loading...')
with open(json_out, 'r') as j:
master_dict = json.loa... |
def check_all_apply(projection, match, match_id):
conflicts = []
start = match[0]
position = start
while position <= match[1]:
if len(projection[position]) > 0:
conflicts.extend(projection[position])
projection[position].append(match_id)
position += 1
return list(... | This function identifies non-overlapping matches of grammar rules in a given sequence, returning matched segments along with their corresponding rules. It enforces a maximum input length, uses a rule matcher to find initial matches, and constructs a tree structure to resolve overlaps. If overlaps are disallowed, it sel... | def find_matches(sequence, grammar, overlaps=False, allowed_length=120):
if len(sequence) > allowed_length:
raise TooLongInputError('Input is expected to be relatively short. For now'
'its length set to be equal {}'.format(allowed_length))
matches = {
'matches': ... |
def total_num_tasks():
return len(task_list)
def total_number_of_comp_tasks():
total_number_of_comp_tasks = 0
for t in task_list:
if t['completed'] == True:
total_number_of_comp_tasks += 1
return total_number_of_comp_tasks
def incomplete_and_overdue_tasks():
incomp_overdue_tasks ... | The function generates a task overview report, calculating total, completed, incomplete, and overdue tasks. It handles zero-division errors by returning 0 when no tasks exist. It computes percentages of incomplete and overdue tasks, formats the data into a string, and writes it to 'task_overview.txt' for storage or rev... | def generate_task_overview():
#logic that prevents zero division errors by returning 0
total_tasks = total_num_tasks()
if total_tasks == 0:
comp_tasks = 0
incomplete_tasks = 0
incomp_and_overdue_tasks_var = 0
percent_incomp = 0
percent_overdue = 0
else:
... |
def add_bias(self, X):
return np.insert(X, 0, 1, axis=1)
def one_hot(self, y):
return np.eye(len(self.classes))[np.vectorize(lambda c: self.class_labels[c])(y).reshape(-1)]
def _fit_data(self, X, y, batch_size, lr):
i = 0
while (not self.n_iter or i < self.n_iter):
current_lo... | The code trains a classification model by initializing weights, preparing data with bias terms and one-hot encoding, and performing batch gradient descent to minimize loss, returning the trained model instance. | def fit(self, X, y, batch_size=64, lr=0.001, rand_seed=42):
np.random.seed(rand_seed)
self.classes = np.unique(y)
self.class_labels = {c: i for i, c in enumerate(self.classes)}
X = self.add_bias(X)
y = self.one_hot(y)
self.loss = []
self.weights = np.zeros(shape... |
def getBody(self, url):
return bytes.decode(self.openURL(url).read())
def getInTag(self, body, startTag, endTag):
return body[body.find(startTag) + len(startTag): body.find(endTag)]
def crawlLinks(self, webpage):
# For the webpage supplied a list of links with the type of Webpage is returned, c... | This code crawls web pages up to a specified depth, extracting titles and links. It processes URLs from a queue, retrieves webpage content, stores keywords, and collects links for further crawling. The crawler maintains depth control, ensuring pages are processed level-by-level until the maximum depth is reached, retur... | def crawlWeb(self, maxDepth):
while self.toCrawl and self.currentDepth <= maxDepth:
currentPage = self.toCrawl.pop()# popping the seed from the list
if currentPage not in self.crawled:
currentPage.body = self.getBody(currentPage.url)
try:
... |
def _connect(self):
print("Opening connection to {}:{}...".format(self._host, self._port))
self._connection = socket.socket()
self._connection.connect((self._host, self._port))
self.send_password()
self.send_nickname()
self.join_channel()
def process_line(self, line):
... | The code's main task is to continuously receive data from a connection, split it into lines using a delimiter, process each line with `process_line`, and maintain a loop that runs until `self._running` is set to False, with a 5-second delay between iterations. | def start(self):
self._connect()
self._running = True
raw_data = ""
while self._running:
raw_data += self._connection.recv(1024).decode('UTF-8')
lines, raw_data = raw_data.rsplit(_DELIMETER, 1)
for line in lines.split(_DELIMETER):
self.... |
def v_x(self, x, bounds):
if self.BC_type == "DD":
v_x = tf.math.tanh(self.m * (x - bounds[0])) * tf.math.tanh(self.m * (bounds[1] - x))
elif self.BC_type == "DN":
v_x = tf.math.exp((x - bounds[0]) * (x - bounds[1])) - 1 - (x - bounds[0]) * (x - bounds[1])
elif self.BC_ty... | The code modifies a neural network model's output to enforce boundary conditions (BCs) by scaling and combining model predictions with boundary terms. It checks if Schwarz, system, or both boundaries are enforced, applying tanh/exponential scaling functions to zero-out outputs at boundaries. Depending on BC type (DD, D... | def get_u_hat(self, x, model):
# Check if only schwarz boundaries are enforced
if not self.sdbc[0]:
bounds = [model.xl, model.xr]
# Scaling functions to selectively enforce NN outputs to 0 at boundaries
v_lr = [tf.math.tanh(self.m * (x - bounds[0])), tf.math.tanh(sel... |
def get_residual(self, model, x):
u_x, u_xx = self.get_gradients(model, x)
return self.pde.f_r(u_x, u_xx)
def Dirch_Neuman_pts(self):
# function returns the x point at which the BC is dirchlet and at which it is neumann depending on iteration
if self.sch_iter % 2 == 0:
# eve... | The function `loss_weak` computes a total loss for Dirichlet-Neumann (DN) coupling with relaxation in a neural network model. It combines residual loss (`phi_r`), boundary condition losses (`phi_b`), interface losses (`phi_i`), and snapshot data loss (`phi_s`). Depending on the specified boundary type (DN, DD, RR), it ... | def loss_weak(self, x):
# this calculates the value of the loss function for Dirichlet-Neuman coupling with relaxation
# Compute phi_r
r = self.get_residual(self.model_r, x)
phi_r = self.a * tf.reduce_mean(tf.square(r))
# Initialize loss with residual loss function
loss... |
def _validate_numeric(category: str, msg: str) -> int or float:
"""
Validates user input as int for item_code or float for cash.
Parameters
----------
category : str
item_code or pay to determine function call on input
msg : str
message passed alo... | The main task of the code is to handle cash payments for an item purchase. It validates user input, ensures the cash amount meets or exceeds the item's price (prompting for additional funds if insufficient), calculates and dispenses change if overpaid, updates the account balance, reduces item stock, and maintains the ... | def cash(self):
"""
Accepts float input for cash amount.
Prints change if amount > item price
or
Requests more if amount < item price until > or ==
Adds price paid to balance and decrements item stock
"""
# validate cash input as float
self.tran... |
def IsItSafeToCross():
global ServoPosRight
global ServoPosLeft
global ServoPosCenter
global MinDistance
dist = dist_sens.read_mm()
serv.rotate_servo(ServoPosLeft)
time.sleep(0.5)
dist = dist_sens.read_mm()
if(dist <= MinDistance):
print("Obstacle Left")
ser... | The main task of the code is to adjust the robot's X-coordinate by moving horizontally (left/right) on a grid toward a destination. It checks the robot's heading, uses sensor data to navigate safely, and updates its position until it reaches the target X-coordinate. If unsafe, it halts. The function handles turning and... | def NeedToChangeX():
global myLocationX
global myLocationY
global destinationX
global destinationY
global myHeading
needToChangeX = True
while needToChangeX:
if(IsItSafeToCross()==False):
print("Seina perkele")
while(True):
time... |
def IsItSafeToCross():
global ServoPosRight
global ServoPosLeft
global ServoPosCenter
global MinDistance
dist = dist_sens.read_mm()
serv.rotate_servo(ServoPosLeft)
time.sleep(0.5)
dist = dist_sens.read_mm()
if(dist <= MinDistance):
print("Obstacle Left")
ser... | This function adjusts a robot's Y-coordinate on a grid to align with a destination Y-position. It checks if movement is safe, navigates by driving forward or turning as needed, updates the robot's location, and halts when the target Y is reached. | def NeedToChangeY():
global myLocationX
global myLocationY
global destinationX
global destinationY
global myHeading
needToChangeY = True
while needToChangeY:
if(IsItSafeToCross()==False):
print("Seina perkele")
while(True):
time.sleep(1)
... |
def localize_time(timedata):
"""
Convert to EST (both datasets east coast U.S.)
:param timedata: list<datetime>, list of UTC datetime
:return: shifted time
"""
return pd.to_datetime(list(timedata), unit="s").tz_localize("UTC").tz_convert('US/Eastern')
def fix_unlock_df_timing(df):
"""
... | This function processes unlock phone data from multiple studies by localizing timestamps, aligning start/end times, calculating unlock durations, and aggregating results by study ID, day, and time epochs. It cleans, groups, and pivots data to produce a consolidated daily unlock summary with duration metrics. | def clean_studentlife_unlock(dfs):
"""
Clean the unlock phone data
:param dfs: dict<pd.DataFrame>, dictionary of unlock dfs
:return: daily unlock df
"""
# Intialize df
unlock_df = []
for f in list(dfs.keys()):
df = dfs[f].copy()
df['study_id'] = int(f.split('_')[1][1:3... |
def set_logger(self):
if cfg.toy:
self.logger = SummaryWriter(utils.make_name(
self.opt, prefix="garbage/logs/", eval_=True, do_epoch=False))
else:
self.logger = SummaryWriter(utils.make_name(
self.opt, prefix="logs/", eval_=True, do_epoch=False))
... | The code trains a model and a knowledge model for a specified number of epochs. It initializes logging, iterates through epochs, sets both models to training mode, increments the optimizer's epoch counter, and executes the training process via `self.epoch()`. Logging is stopped after training completes. | def run(self):
self.set_logger()
self.count = 0
for epoch in range(self.epochs):
self.model.train()
self.model_knowledge.train()
self.opt.train.dynamic.epoch += 1
self.epoch()
self.stop_logger() |
def getVersion(self):
"""Get the version of the max17048 module."""
buf = self.__readRegister(self.REGISTER_VERSION)
return struct.unpack(">H", buf)[0]
def getID(self):
"""Get ID."""
buf = self.__readRegister(self.REGISTER_ID)
return struct.unpack(">B", buf)[0]
def getVCe... | The code defines the `__str__` method to generate a human-readable string representation of an object's attributes, including I2C address, version, ID, battery voltage, charge rate, SOC, alert threshold, and alert status. It formats these values for clarity and returns them as a structured string. | def __str__(self):
"""Get string representation of the values."""
rs = "i2c address is {}\n".format(self.max17048Address)
rs += "version is {}\n".format(self.getVersion())
rs += "id is {}\n".format(self.getID())
rs += "Battery voltage is {:.2f} V\n".format(self.getVCell())
... |
def init_map(self):
with open("map/map0", "r") as f:
w, h, n = [int(x) for x in next(f).split()]
self.map_h, self.map_w = h, w
for _ in range(w + 1):
self.map.append([0 for _ in range(h + 1)])
for _ in range(n):
x0, y0, x1, y1, t = ... | This code initializes a simulation environment by setting up a map, pedestrian spawn points, and an engine for vehicle and pedestrian interactions. It configures display elements like screens, legends, speed controls, and light modes using Pygame if visualization is enabled. It calculates scroll parameters for map navi... | def start(self):
self.init_map()
self.load_pedestrian_spawn_points()
self.engine = Engine.Engine(self.map, self.pedestrian_areas, self.chosen_mode)
Engine.RoadVehicle.engine = self.engine
if self.display_needed:
self.main_screen = pygame.display.set_mode(self.main_win... |
def crossing_loop_init(self):
stamp = 0
self.loop_timestapm.append((stamp, 0))
for elem in self.lights_loop:
stamp += elem
self.loop_timestapm.append((stamp, 1))
stamp += 15
self.loop_timestapm.append((stamp, 0))
self.loop_max_timestapm = s... | This code initializes a traffic simulation system, setting up a map grid, configuring traffic light control modes, tracking vehicle and pedestrian movement across predefined areas, and preparing statistical logging for car/pedestrian throughput and waiting times. It initializes queues for vehicle spawning, defines cros... | def __init__(self, map: list, pedestrian_areas: list, lights_mode: int):
self.map_w = len(map)
self.map_h = len(map[0])
self.map = map
self.crossing_closed = False
self.iter_counter = 0
self.budryka_cars = [[], []]
self.kawiory_cars = [[], []]
self.lights_... |
def spawn_cars(self):
# Budryka & Kawiory
prob_budryka_spawn = Fraction(14, 1000)
if rand_with_probability(prob_budryka_spawn):
car_scooter_prob = Fraction(10, 13)
initial_pos = (672, 35 + 10 * len(self.budryka_cars[1]))
if rand_with_probability(car_scooter_pr... | This code defines an 'iteration' method that simulates one time step of a traffic scenario. It spawns cars and pedestrians, moves them, manages traffic lights at crossings, updates statistics, and increments an iteration counter to track simulation progress. | def iteration(self):
self.spawn_cars()
self.traffic_lights_crossing()
self.spawn_pedestrians()
self.move_pedestrians()
self.move_cars()
self.update_stats_file()
self.iter_counter += 1 |
def cdf_times_to_np_date(times):
"""
Transform the times in cdf epoch into numpy dates, rounding month to nearest.
"""
dates = []
for t in times:
if t != t:
# if time is a nan, date should be a nan as well
dates.append(np.float('nan'))
continue
yea... | This function computes Gaussian coefficients using a Kalman filter approach by combining prior covariance information with observation data. It processes input files, extracts time-series measurements, constructs observation matrices, and applies inverse covariance operations to derive the final Gaussian coefficient ve... | def compute_gauss_coefs_vector(file, date_chosen, max_degree, N_VO, measure_MF, measure_sigma, cm_prior):
"""
params:
file: file chosen (swarm for instance, with os.path.join and cdf_dir)
date_chosen: date chosen
max_degree: max degree chosen
N_VO: number of observatories
measure_MF: list o... |
def cdf_times_to_np_date(times):
"""
Transform the times in cdf epoch into numpy dates, rounding month to nearest.
"""
dates = []
for t in times:
if t != t:
# if time is a nan, date should be a nan as well
dates.append(np.float('nan'))
continue
yea... | The function creates a histogram to visualize the distribution of differences between observed and estimated geomagnetic field components (B_CF). It processes time-series data, extracts relevant values, computes model estimates, calculates residuals, filters outliers, and reports statistics like mean deviation and outl... | def create_hist(fig, i, zone, alldata, L_max, unique_times_list, date, file, cm_prior, title):
N_VO = 300
index_temps = np.argwhere((cdf_times_to_np_date(alldata['Timestamp'])) == np.datetime64(date))[0][0]
radius = alldata['Radius'][index_temps:index_temps+N_VO]*10**(-3)
latitudes = alldata['Latitude']... |
def show_page1(self):
self.view.show_page1(**self.page1_config)
def _page1(self):
inp = ''
while inp != 'exit':
print('Please, choose the option:')
print('(1): change x0')
print('(2): change X')
print('(3): change y0')
print('(4): chang... | The main task of the code is to display a menu with options to show different pages or exit, handle user input to trigger corresponding page display methods, and loop back to the menu until the user selects 'exit' to terminate the program. | def run(self):
print('Please, choose the option:')
print('(1): show page #1')
print('(2): show page #2')
print('(3): show page #3')
print('(exit): close the program')
inp = input()
if inp == '1':
self.show_page1()
self._page1()
elif... |
def create_legend():
"""
Creates a legend widget with a gradient bar and labels.
:return: The legend widget
:rtype: QtGui.QWidget
"""
legend_widget = QWidget()
layout = QGridLayout()
legend_widget.setLayout(layout)
layout.addWidget(QLabel("Transition Frames"), 0, 0, Q... | The code initializes a GUI for an EMG Classifier application, setting up interactive elements like dataset selection, data navigation, table displays for signal data, and export functionality. It organizes UI components into group boxes with buttons, labels, and tables to manage EMG data visualization, user input handl... | def __init__(self):
super().__init__()
self.file_names = None
self.file_name = None
self.cur_individual = 0
self.cur_data = {}
self.final_dict = {}
self.all_data = {}
self.dictio = {1: "NM", 2: "WF", 3: "WE", 4: "WP", 5: "WS", 6: "CG", 7: "HO"}
s... |
def clear(self):
self.file_selector.clear()
self.file_name = None
self.file_names = None
self.cur_individual = 0
self.cur_data = {}
self.final_dict = {}
self.all_data = {}
def data_button_clicked(self):
"""
This function is called when the "Vie... | The code opens a directory dialog to select NPZ files, loads their data into a dictionary, validates required arrays, populates the UI with file names, and enables buttons after successful loading. Errors trigger alerts for invalid files or directories. | def file_select(self):
"""
Opens a file dialog to select a directory containing NPZ files, then loads the data from the selected file.
If the file contains the required data arrays, populates the UI with the data and enables the data button.
If the file is not valid, displays... |
def decompose_projection_matrix(P):
K, RT = qr_decomposition(inverse_matrix(submatrix(P, (3, 3))))
K /= K[2, 2]
RT = inverse_matrix(RT)
return K, RT
def concatenate_ones(matrix):
return [row + [1] for row in matrix]
def inverse_matrix(matrix):
det = matrix[0][0] * matrix[1][1] - matrix[0][1] * m... | The code performs 3D triangulation by decomposing a projection matrix into camera intrinsics (K) and extrinsics (RT), then using inverse projection and rotation/translation adjustments to compute world coordinates from 2D image correspondences. | def triangulation(correspondences, P):
K, RT = decompose_projection_matrix(P)
R = RT[:, :3]
t = RT[:, 3]
image_points_homogeneous = concatenate_ones(correspondences)
K_inv = inverse_matrix(K)
camera_coords = dot_product(K_inv, transpose(image_points_homogeneous))
world_coords = dot_produ... |
def deepcopy(matrix):
return [row[:] for row in matrix]
def zeros(shape):
return [[0] * shape[1] for _ in range(shape[0])]
def dot_product(matrix1, matrix2):
return [[sum(a * b for a, b in zip(row, col)) for col in transpose(matrix2)] for row in matrix1]
def transpose(matrix):
return list(map(list, zip(... | This code performs a simplified singular value decomposition (SVD) on a matrix using power iteration to approximate eigenvalues and eigenvectors. It computes the orthogonal matrices U and V, and singular values s by normalizing eigenvectors and deriving U from matrix multiplication with V. However, the implementation m... | def singular_value_decomposition(matrix):
A = deepcopy(matrix)
rows, cols = len(A), len(A[0])
U = zeros((rows, rows))
V = zeros((cols, cols))
s = [0] * min(rows, cols)
B = dot_product(transpose(A), A)
eigenvalues, eigenvectors = power_iteration(B)
for i in range(cols):
V[i] = e... |
def zeros(shape):
return [[0] * shape[1] for _ in range(shape[0])]
def singular_value_decomposition(matrix):
A = deepcopy(matrix)
rows, cols = len(A), len(A[0])
U = zeros((rows, rows))
V = zeros((cols, cols))
s = [0] * min(rows, cols)
B = dot_product(transpose(A), A)
eigenvalues, eigenv... | The main task of the code is to estimate a 3×4 camera projection matrix using corresponding 2D image points and 3D world points. It constructs an over-determined linear system (matrix A) based on the projection equation, performs Singular Value Decomposition (SVD), and extracts the last right singular vector to form th... | def estimate_camera_projection_matrix(image_points, world_points):
assert len(image_points) == len(world_points)
num_points = len(image_points)
A = zeros((2 * num_points, 12))
for i in range(num_points):
X, Y, Z = world_points[i]
x, y = image_points[i]
A[2 * i] = [-X, -Y, -Z, -... |
def unique_filename(file, timestamp=False):
"""This function returns a unique filename"""
return "{}{}.{}".format(file_hash(file), '_' + now() if timestamp else '', file_extension(file.filename))
def check_filename(file, patterns=None):
"""This function validates filename"""
# Check if its file is secur... | The function stores a file to the filesystem by generating a unique or checked filename, extracting metadata, saving the file, and returning either the metadata or the filename if metadata is unavailable. | def store_file(file, unique_id=True):
"""This function stores a file to filesystem"""
# Generate filename using file hash and timestamp
filename = unique_filename(file) if unique_id else check_filename(file)
metadata = file_metadata(file, filename)
# Write file to filesystem
file.save(filepath(f... |
def prepare_data(self):
self._tasks = self._tasks_provider.create_example_graph()
def _get_predecessors_for_multiple_nodes(self, tasks_matrix, nodes_list):
predecessors = []
for node in nodes_list:
predecessors.append(self._tasks_provider.get_predecessors(tasks_matrix, node))
... | The main task of the code is to schedule tasks in a specific order by iteratively selecting and labeling nodes whose successors are fully labeled, ensuring dependencies are respected. It starts with root nodes (no successors), then repeatedly identifies predecessors of labeled nodes, filters those with all successors l... | def main(self):
self.prepare_data()
# Find nodes with no successors.
roots = self._tasks_provider.get_root(self._tasks)
self._list_to_schedule = roots
while len(self._list_to_schedule) < len(self._tasks)-1:
# Find predecessors of labeled nodes.
possible... |
def chk_x_scte35(self, tags, line):
if "CUE" in tags["#EXT-X-SCTE35"]:
return self.add_cue(tags["#EXT-X-SCTE35"]["CUE"], line)
return line
def chk_x_cue_out_cont(self, tags, line):
"""
chk_x_cue_out_const processes
#EXT-X-CUE-OUT-CONT tags
"""
cont_tag... | This function processes SCTE-35 related tags in a given line by checking for specific markers like #EXT-X-SCTE35, #EXT-X-CUE-OUT-CONT, and #EXT-X-DATERANGE. Depending on the detected tag, it routes the processing to corresponding validation or handling methods (e.g., chk_x_scte35, add_cue). If no relevant tags are foun... | def scte35(self, line):
"""
scte35 processes SCTE-35 related tags.
"""
tags = TagParser([line]).tags
if "#EXT-X-SCTE35" in tags:
return self.chk_x_scte35(tags, line)
if "#EXT-X-CUE-OUT-CONT" in tags:
return self.chk_x_cue_out_cont(tags, line)
... |
def extinf(self, line):
"""
extinf parses lines that start with #EXTINF
for the segment duration.
"""
tags = TagParser([line]).tags
if "#EXTINF" in tags:
if isinstance(tags["#EXTINF"], str):
tags["#EXTINF"] = tags["#EXTINF"].rsplit(",", 1)[0]
... | The main task of the code is to parse and process lines from an m3u playlist. It checks if a line starts with "#EXTINF:" to handle metadata, processes target duration, checks AES encryption parameters, and applies SCTE-35 data parsing. The function returns processed line data for further handling, ensuring proper forma... | def parse_line(self, line):
if line.startswith("#EXTINF:"):
line = self.extinf(line)
return line
self.parse_target_duration(line)
self.chk_aes(line)
line = self.scte35(line)
return line |
def decode_lines(lines):
return [line.decode() for line in lines]
def mk_window_size(self, lines):
if not self.window_size:
self.window_size = len(
[line for line in lines if line.startswith("#EXTINF:")]
)
self.sliding_window.size = self.window_size
... | The code processes an M3U8 manifest by parsing media segments and headers, updating a sliding window of content panes, and managing reload states. It constructs a base URI from the manifest, decodes lines, detects end-of-list markers, and periodically updates the sliding window with new media data while sleeping betwee... | def pull(self, manifest):
print(f"{REV}Started{NORM}\n")
print(f"\n{REV}variant m3u8:{NORM} {manifest}\n")
self.base_uri = manifest.rsplit("/", 1)[0]
self.sliding_window = SlidingWindow()
while self.reload:
lines = []
self.headers = []
with rea... |
def find_best_feature(train_data, label, class_list):
feature_list = train_data.columns.drop(label)
max_info_gain = -1
max_info_feature = None
for feature in feature_list:
feature_info_gain = calculate_info_gain(feature, train_data, label, class_list)
if max_info_gain < feature_info_g... | This function recursively constructs a decision tree by selecting the best feature to split the training data, creating subtrees for each feature value, and attaching them to the root node. It checks if the current node is expandable, filters the data for the selected feature value, and continues building the tree unti... | def generate_tree(root, prev_feature_value, train_data, label, class_list):
if train_data.shape[0] != 0:
best_feature = find_best_feature(train_data, label, class_list)
tree, train_data = generate_sub_tree(best_feature, train_data, label, class_list)
if prev_feature_value != None:
... |
def hover_and_click(self, element):
# simulates hover and click on element
self.mouse_hovering.move_to_element(element).click().perform()
self.wait_for_seconds()
def wait_for_seconds(seconds=3):
"""
a helper function that creates a pause in code execution for a specified number o... | The main task of the code is to automate a comprehensive website functionality test, simulating user interactions such as searching, scrolling, navigating menus, logging in, creating albums, uploading photos, verifying UI elements, and testing deletion/cancel actions. It validates the correctness of website features li... | def run_test(self):
# runs the website functionality test
try:
# validation of search field
search_field = self.wait.until(EC.presence_of_element_located((By.NAME, "search")))
assert search_field.is_displayed(), "Search field not displayed."
print("E... |
def build_guard_shift_dict():
guard_id = None
shift = None
guard_to_shifts = {}
for timestamp, event in build_timeline():
match = _BEGIN_SHIFT_REGEX.match(event)
if match:
if guard_id is not None:
assert shift is not None
guard_to_shifts.setd... | The code identifies the guard with the longest total sleep time, determines the minute they slept most frequently, and returns the product of their ID and that minute. It uses helper functions to build shift data, calculate total sleep, and find the optimal minute. Your return | def solve_part_1():
guard_to_shifts = build_guard_shift_dict()
guard_id, shifts = max(guard_to_shifts.items(), key=lambda t: compute_total_sleep_time(t[1]))
best_minute, sleep_count = compute_best_minute(shifts)
return guard_id * best_minute |
def _create_nodes_data(self):
self.reroutes = set()
self.node_by_socket = dict()
self.nodes_by_type = defaultdict(list)
for node in self.nodes.values():
if node.bl_idname == "NodeReroute":
self.reroutes.add(name)
for socket in chain(node.inputs, ... | The code initializes an object with node and link data from a provided tree structure, then processes this data to create structured node/link representations and identify connections between them. | def __init__(self, node_tree):
self.nodes = dict(node_tree.nodes)
self.links = list(node_tree.links)
self._create_nodes_data()
self._create_links_data()
self._find_data_connections() |
def get_all_input_sockets(self):
return list(getattr(self.input_node, "outputs", []))
def get_all_output_sockets(self):
return list(self.output_node.inputs)
def generate_compute_module(module_name, function_name, input_sockets, output_sockets):
assert len(output_sockets) > 0
module = ir.Module(... | The main task of the code is to generate a compiled compute module that processes only the outputs specified by the given output_mask. It filters relevant input/output sockets, validates the mask length, constructs an IR module using the selected outputs, compiles it, and returns the resulting module for partial comput... | def create_partial_compute_module(self, output_mask):
output_mask = tuple(output_mask)
used_inputs = self.get_all_input_sockets()
all_outputs = self.get_all_output_sockets()
if len(output_mask) != len(all_outputs):
raise Exception("invalid output mask")
used_output... |
def _find_interface_nodes(self):
inputs = get_nodes_by_type(self.tree, "cn_InputNode")
outputs = get_nodes_by_type(self.tree, "cn_OutputNode")
if len(inputs) > 1 or len(outputs) != 1:
raise Exception("a tree must have at most one input and exactly one output node")
self.inp... | The code initializes an object with a given tree structure, identifies interface nodes, creates target/engine modules, and initializes attributes for a Python function and compute module, setting them to None. | def __init__(self, tree):
self.tree = tree
self._find_interface_nodes()
self._create_target_and_engine()
self._create_globals_module()
self.py_function = None
self.compute_module = None |
def ensure_compute_module(self):
if self.compute_module is None:
output_amount = len(self.get_all_output_sockets())
module = self.create_partial_compute_module([True] * output_amount)
self.compute_module = module
def get_all_output_sockets(self):
return list(self.outp... | This code creates a Python wrapper for a C function using ctypes, converting input/output types and pointers. It retrieves a function address, defines a compatible C function type, and wraps it with error checking, argument conversion, and result extraction for a compute module's main function. | def get_function(self):
if self.py_function is None:
self.ensure_compute_module()
address = self.engine.get_function_address("Main")
from ctypes import CFUNCTYPE, POINTER, pointer
output_sockets = self.get_all_output_sockets()
input_types = [s.c_type ... |
def fill_degenerate_bases(seq):
while seq.find("N") != -1:
n_index = seq.find("N")
base = np.random.choice(['A','C','T','G'])
seq = seq[:n_index] + base + seq[n_index+1:]
return seq
def calculate_gc(s):
s = s.upper()
return (s.count('G') + s.count('C')) / len(... | The main task of the code is to generate and optimize pairs of iBARs (indexed barcodes) for high-throughput sequencing by filtering barcodes based on GC content, homopolymer constraints, and compatibility with flanking sequences. It then randomly pairs filtered barcodes, evaluates their sequencing efficiency (minimal c... | def complete_iBARs_v1(
df, n_constructs,
max_it_degenerate_bases = 25,
max_it_bc_pairing = 1000,
verbose=1
):
df_barcodes = df.sample(frac=1).copy() # important to randomize barcode order!
# bring barcodes to length 12 with degenerate bases
if len(df_barcodes['barcode'][0])!=12:
... |
def clear(self):
self._image = np.zeros((self._height, self._width, 3), np.uint8)
self._z_buffer = np.full((self._height, self._width, 1), np.inf)
def _rasterize(self):
if self._render_mode == RenderingMode.Wireframe:
self._draw_wireframe()
return
for i in range(... | The code renders a scene using specified rendering and lighting modes by clearing the context, setting internal modes, rasterizing the scene, and binding a texture to the bitmap if enabled. | def render(self, render_mode: RenderingMode, light_mode: LightingMode):
self.clear()
self._render_mode = render_mode
self._light_mode = light_mode
self._rasterize()
if self._bind_texture:
self._bitmap.bind_texture(pixels=self.get_image()) |
def gram_loss(style_image, output_image):
'''Calculate style loss between style_image and output_image
'''
assert 3 == K.ndim(style_image) == K.ndim(output_image)
if K.image_data_format() == 'channels_first':
style = style_image
output = output_image
num_channels = K.shape(style_... | The function `style_loss` computes a style loss between a style image and an output image based on the specified loss type in `args.loss`. It dispatches to different loss calculation methods like Gram matrix, statistical, L2, histogram, or MRF, returning the corresponding loss value. The choice of method determines how... | def style_loss(style_image, output_image):
if args.loss=='gram':
return gram_loss(style_image, output_image)
elif args.loss=='gram_offset':
return gram_offset_loss(style_image, output_image, args.loss_arg)
elif args.loss=='stat':
return stat_loss(style_image, output_image, args.loss_... |
def get_game_states(self) -> dict:
game_state = {}
# Game score
game_state['blue_score'] = self.game.score['Blue']
game_state['red_score'] = self.game.score['Red']
# Game time and state
game_state['count_down_time'] = self.game.time_countdown
game_state['playing'... | The code's main task is to execute an agent's action in a Pygame environment, update the game state, calculate the resulting reward, determine if the episode has terminated, and return a tuple containing the next observation, reward, termination status, and auxiliary information for reinforcement learning training. | def step(self, action) -> list([np.array, float, bool, dict]):
'''
Steps the pygame environment forward using the agent's actions
Input: action -> int
outputs: tuple (next_observation, reward, done, info)
next_observation = np.array - updated state based on... |
def _find_open_location(self, sprite, other_sprites):
possible_locs = []
for pos in self.game.open_pos:
dis_to_others = []
for other_sprite in other_sprites:
dis_to_others.append(other_sprite.pos.distance_to(vec(pos)))
if all(dis >= SPAWN_MIN_DIS_F... | The `reset` method initializes a game environment for reinforcement learning by resetting the game state, repositioning players, mobs, and goals to non-overlapping random locations, disabling human control, and returning the initial observation as a NumPy array for the agent. | def reset(self) -> np.array:
'''
Resets the game and gets the initial observation
'''
self.game.new()
# move player and mobs to random open spot
moving_sprites = [*self.game.players.sprites(), *self.game.mobs.sprites(), *self.game.goals.sprites()]
for sprite in ... |
def advance_time(self):
self.dt_ms = self.clock.tick(FPS)
if self.dt_ms > 500:
self.dt_ms = 500
self.dt = self.dt_ms / 1000
def events(self):
# catch all events here
for event in pg.event.get():
if event.type == pg.QUIT:
self.quit()
... | The main task of the code is to execute a game loop that continuously advances time, processes events, updates game state, manages timing, and renders visuals until the game ends. The loop runs while `self.playing` is True, and terminates by calling `self.game_over()` when the loop exits. | def run(self):
# game loop - set self.playing = False to end the game
self.playing = True
while self.playing:
self.advance_time()
self.events()
self.update()
self.timer()
self.draw()
self.game_over() |
def convert_from_game_loc(game_location):
map_ind = game_location // TILESIZE
array_location = (int(map_ind[1]), int(map_ind[0]))
return array_location
def astar(self, start, goal):
close_set = set()
came_from = {}
gscore = {start:0}
fscore = {start:heuristic(start, goal)}
... | The code finds a route from a start to a goal location using the A* algorithm. It converts game coordinates to map coordinates, reverses the A* path, and transforms it into a map-specific route format. If no route is found, it returns None. | def find_route(self, start, goal):
start_location = convert_from_game_loc(start)
goal_location = convert_from_game_loc(goal)
route = self.astar(start_location, goal_location)
if route is not None:
#route = route + [start_location]
route = route[::-1]
m... |
def _determine_ms_filename(usi):
"""
We are going to get the URL and the filename, the URL will be omitted if we can figure it out with an API call
"""
usi_splits = usi.split(":")
fileportion = usi_splits[2]
# Checking if filename is valid extension that we could infer the filename
lower_f... | This function manages the downloading and organization of mass spectrometry data files based on a USI identifier. It determines target filenames, checks for existing files in output/cache/dataset directories, creates symlinks if needed, and downloads files if missing. It supports extension filtering, nested folder stru... | def download_helper(usi, args, extension_filter=None, noconversion=False):
processdownloadraw = False
try:
if len(usi) < 5:
return None
output_result_dict = {}
output_result_dict["usi"] = usi
target_filename = None # This is the target converted filename
... |
def similarity(item1, item2, index1, index2):
dotProd = np.dot(item1, item2)
normProd = la.norm(item1) * la.norm(item2)
cosTheta = min(dotProd / normProd, 1)
angle = math.acos(cosTheta)
angle = math.degrees(angle)
sim[index1, index2] = angle
def neighborhood(similarity):
for i in range(50):
... | The code generates random data, computes pairwise similarities, constructs a neighborhood matrix, and fills missing values using these matrices, saving intermediate results and the final filled data to CSV files. | def main():
data = np.random.randint(6, size=(50, 25))
print("data original ground truth")
for i in range(len(data)):
print(data[i,:])
np.around(data, decimals=2)
np.savetxt("../data/before_filling.csv", data, delimiter=",", fmt ='%f')
for i in range(50):
for j in range(50):
... |
def wicket(self, method: str):
self.data["bowler_stats"][self.bowler]["overs"] = (
self.record_increment_ball(
self.data["bowler_stats"][self.bowler]["overs"]
)
)
self.data["batter_stats"][self.firstbatter]["balls"] += 1
self.data["batter_stats"][s... | This function simulates a cricket ball's outcome during a match. It calculates required runs and remaining balls when chasing, generates status messages, processes the result of the ball (runs/wicket/declaration), updates game state (score, wickets, overs), and handles transitions to the next ball. It also records outc... | def play_ball(self):
print("Ball", self.ball + 1)
if self.chasing:
required_runs = self.target - self.data["score"]
balls_left = (6 * (self.max_overs - self.over)) - self.ball
if (required_runs == 1):
target_required_string = (
"Nee... |
def set_team_name(self, name=None) -> None:
""" Sets the name of the team """
# If the name is not passed, prompt the user
if name is None:
name = input("Team name: ")
# The name must be a string
if not isinstance(name, str):
raise TypeError("Team name mu... | This code initializes a team by either creating a new one with set methods and registration messages if no name is provided, or loading an existing team, checking a blacklist, and setting attributes. It handles user input for confirmation and security prompts. | def __init__(self, name=None) -> None:
if name is None:
# Create a new team
self.set_team_name()
self.set_team_members()
self.set_team_pass()
self.commit()
print("Your team,", self.name, ", was successfully registered.")
print("... |
def is_playing(self) -> bool:
return (not self.completed)
def is_bowler_exhausted(self, bowler: str) -> bool:
if self.test:
return False
current = self.data["bowler_stats"][bowler]["overs"]
if current < ceil(self.max_overs / 5):
return False
else:
... | This code manages the end of a cricket over by updating bowler statistics, removing exhausted bowlers, selecting the next bowler, playing six balls, recording over outcomes, and resetting variables for the next over. It ensures proper bowler rotation, tracks maidens if all deliveries are dot balls, and clears temporary... | def play_over(self):
if self.is_playing():
if self.previousbowler is not None:
self.previousbowler = self.bowler
self.bowler_list.pop(
self.bowler_list.index(self.previousbowler)
)
for i in range(len(self.bowler_list) - ... |
def get_team_data(self, position: int, name: str) -> None:
team_data = Team(name=name)
if position == 1:
self.team1 = team_data.name
self.team1_human = team_data.is_human
elif position == 2:
self.team2 = team_data.name
self.team2_human = team_data.... | The code initializes a game pairing by either retrieving existing team data (if `exists=True` and `name` is provided) or creating a new pairing, selecting an opponent, and setting a game ID. It checks if the pairing already exists, logs the game, and outputs the match ID for sharing with an opponent. If the pairing exi... | def __init__(self, exists=False, name=None) -> None:
# Use this if you want to remove
# old and unused pairings
# self.remove_unused_games()
# Init code
if exists:
if name is not None:
self.get_team_data(1, name)
else:
self.new_pair... |
def new_batter_stats(self) -> dict:
return {
"runs": 0,
"balls": 0,
"fours": 0,
"sixes": 0,
"dismissed": False,
"dismissal": "Not out"
}
def new_bowler_stats(self) -> dict:
return {
"overs": 0,
"maide... | This code initializes a cricket game simulation by setting up batting and bowling teams, match parameters (like max overs/wickets), and player statistics. It populates data structures for batter and bowler stats, initializes team members, and prepares game-specific attributes. The `new_game()` method is called to start... | def __init__(
self,
batting_team: str,
bowling_team: str,
test: bool,
data: dict,
max_overs=20,
max_wickets=10,
chasing=False,
target=0
) -> None:
self.batting_team = Team(batting_team)
self.bowling_team = Team(bowling_team)
... |
def set_download_dir(docker: bool=True):
if docker:
return Path('/code') / 'data' / 'Race_downloads'
else:
return Path.home() / 'gugs_db' / 'data' / 'Race_downloads'
def csv_to_xls(dir_list: list) -> None:
count = 0
for folder in dir_list:
print(f'Searching folder {folder.stem} f... | The main task of the code is to aggregate and clean race results data from CSV files in specified directories. It processes Excel sheets, compiles data into a structured DataFrame, removes irrelevant columns, standardizes column names, selects specific fields, cleans time formats, and returns a validated DataFrame cont... | def append_results(download_path: str=None, year: int=None):
if download_path is None:
if year is None:
year = datetime.datetime.now().year
download_path = set_download_dir() / str(year)
dir_list = [x for x in download_path.iterdir() if x.is_dir()]
csv_to_xls(dir_list)
shee... |
def scrape_all(download_path: str=None, year: int=None):
if download_path is None:
download_path = set_download_dir()
for i in range(1, 13):
wpa_scrape.main(month=i, download_path=download_path, year=year)
def append_results(download_path: str=None, year: int=None):
if download_path is None... | The main task of the code is to connect to a PostgreSQL database, scrape data using `scrape_all()`, process/clean it into a DataFrame with `append_results()`, and load the cleaned data into the 'race' table in the database using `load_to_db_table`. | def main():
engine = create_engine(
'postgresql+psycopg2://postgres:gugulethu@localhost/gugs')
scrape_all()
race_table_full_clean = append_results()
load_to_db_table(df=race_table_full_clean, engine=engine, table_name='race') |
def probe(self, v):
"""
- Returns the distance from v to the target
"""
if self["probeNum"] is None:
self["probeNum"] = 0
self["probeList"] = []
if self["t"] is None:
self["t"] = [choice(range(len(self.tree)))]
self["probeList"].app... | The code implements Theorem 8's strategy by probing the root node, checking if Lemma 1 holds, and verifying the root's child count. If conditions are met, it locates a specific node; otherwise, it invokes Lemma 4 with parent nodes and depth to process the tree structure. Your return | def solve(self):
"""
- Carries out the strategy of theorem 8.
"""
d = self.probe(0) #Probe root
if lemma1(self) != -1 and d != -1: #Organise tree and check for hideouts
if len(self.lDict[d]) == 1:
return self.located(self.lDict[d][0])
... |
def setState(self, state):
"""
Setter for _state attribute
"""
assert self.isValidState(state)
self._state = state
def setWave(self, wave):
"""
Setter for _wave attribute
"""
assert self.isWave(wave)
self._wave = wave
def setText(self, text... | The main task of the code is to initialize the game application by setting up initial attributes, ensuring invariants, and displaying a welcome screen. It transitions the game state to inactive, resets wave/text attributes, initializes key tracking, and prepares a prompt for user input to start the game. | def start(self):
"""
Initializes the application.
This method is distinct from the built-in initializer __init__ (which you
should not override or change). This method is called once the game is running.
You should use it to initialize any game specific attributes.
This... |
def pausedScreen(self):
"""
Creates the paused screen
This method creates a Glabel with the text 'press 'F' to resume' when the
state is STATE_PAUSED, meaning the text will only show when a ship has
been destroyed. It calls draw at the end.
"""
# creates welcome ... | This function handles the paused state by displaying the paused screen, detecting key presses (specifically 'F' to resume), updating the game state to active, resuming the wave, initializing the ship, and updating UI elements like lives. It tracks key input changes and adjusts the paused state accordingly. | def updatePaused(self):
"""
Helper function to update when state is STATE_PAUSED
"""
self.pausedScreen()
change = self.input.key_count > 0 and self.lastkeys == 0 #ADD MORE ATTRIBUTES
if change:
keyPressed = self.input.is_key_down('f') or \
self.inp... |
def getWave(self):
"""
Getter for _wave attribute
"""
return self._wave
def boltshoot(self):
"""
Checks when the player shoots
When spacebar is pressed, boltInit() in Wave will be called, causing the
palyer to shoot a bolt
"""
if self.inpu... | The code's main task is to update game elements when the state is "STATE_ACTIVE," including updating the wave with input and delta time, triggering a bolt-shooting action, and updating the lives screen display. | def updateActive(self, dt):
"""
Helper function to update when state is STATE_ACTIVE
"""
self.getWave().update(self.input, dt)
self.boltshoot()
self.livesScreen() |
def livesScreen(self):
"""
Creates the lives text
This method creates a Glabel with the text 'Lives:'
when the state is STATE_ACTIVE or STATE_PAUSED, meaning the text will
only show when the game is being played. It calls draw at the end.
"""
# creates welcome sc... | The main task of the code is to handle the game state transition when the state is "STATE_COMPLETE." It displays the "lives screen," checks if remaining lives are zero, and shows either the "death screen" or "win screen" accordingly. The function determines the game outcome based on lives and updates the visual state o... | def updateComplete(self):
"""
Helper function to update when state is STATE_COMPLETE
"""
self.livesScreen()
if self.getWave().getLives() == 0:
self.deathScreen()
else:
self.winScreen() |
def getState(self):
"""
Getter for _state attribute
"""
return self._state
def updateInactive(self):
"""
Helper function to update when state is STATE_INACTIVE
"""
change = self.input.key_count > 0 and self.lastkeys == 0 #ADD MORE ATTRIBUTES
if cha... | The code's main task is to animate a single game frame by managing state transitions (e.g., inactive, new wave, active, paused, complete) and delegating gameplay to the Wave class when active. It checks the current state, updates accordingly, and handles input to switch between states, ensuring proper flow from initial... | def update(self,dt):
"""
Animates a single frame in the game.
It is the method that does most of the work. It is NOT in charge of playing the
game. That is the purpose of the class Wave. The primary purpose of this
game is to determine the current state, and -- if the game is a... |
def setTime(self,time):
"""
Setter for _time attribute
Parameter: time represents the amount of time since the last Alien step
Precondition: time is an int or float >= 0
"""
assert type(time) == int or type(time) == float
assert time >= 0
self._time = tim... | This code updates game elements (Ship, Alien, Bolt) during each frame by adjusting time, handling movement, collisions, alien status, shooting mechanics, and health bar updates. It increments time, triggers shooting when conditions are met, and ensures all game components are synchronized for the next frame. | def update(self, input, time):
"""
Updates Ship, Alien, and Bolt objects with each frame
"""
self.setTime(self.getTime() + time)
self.updateShip(input)
self.updateAliens()
self.updateBolt()
self.updateAlienColl()
self.updateShipColl()
self.... |
def migrate_file(filename: str, adding: bool = True) -> None:
"""Migrates a file between the imports and movies directory.
Args:
filename: The filename to migrate.
adding: True when moving to movies folder; False for the imports.
"""
imports = get_movie_path(PathType.IMPORT)
movies... | This function removes a specified movie file from the movies folder and dissociates it from all related entities (actors, categories, series, studio) by updating their links to exclude the movie. It performs this by calling `migrate_file` with `False` to delete the file and using various `update_*_link` functions with ... | def remove_movie(movie: models.Movie) -> None:
"""Removes a movie file from the movies folder and all propery links.
Args:
movie: The movie to be removed.
"""
migrate_file(movie.filename, False)
for actor in movie.actors:
update_actor_link(movie.filename, actor.name, False)
f... |
def generate_movie_filename(movie: models.Movie) -> str:
"""Generates a filename based on the movie information.
Args:
movie: The movie.
Returns:
filename: The generated filename.
"""
# start with a blank filename
filename = ""
# save the file extension for later
_, e... | This function renames a movie file based on updated metadata, updates its filename, and synchronizes all associated property links (actors, categories, series, studio). It generates a new filename, checks for conflicts, renames the file if valid, and updates links for existing and new filenames. Raises an exception if ... | def rename_movie_file(
movie: models.Movie,
actor_current: Optional[str] = None,
category_current: Optional[str] = None,
series_current: Optional[str] = None,
studio_current: Optional[str] = None,
) -> None:
"""Renames a movie, and updates its filename and all property links.
Args:
... |
def init():
# Initialize scoreboard, textfields, freefields and decisionlists
scoreboard = [None] * 21
textfields = [
"Name ",
"Ones ",
"Twos ",
"Threes ",
"Fours ",
"Fives ",
"Sixes ",
"Sum ",
"Bonus ",
"T... | The function simulates a dice game with customizable parameters, allowing players to score points by strategically choosing where to place their rolls. It initializes a scoreboard, iterates through rounds of dice rolls and rerolls, updates scores based on optimal decisions, handles special scoring rules (e.g., 50-point... | def run_game(
name="Test",
throws=3,
n=5,
k=6,
printscoreboard=True,
printinfo=False,
randomseed=False,
):
if randomseed:
random.seed(randomseed)
if printinfo:
print(
"Game with", throws, "throw(s) per round and", n, "dice with", k, "sides."
)
... |
def get_rerolls(state):
# Get all rerolls of the state
state_count = np.zeros((6), dtype=np.uint8)
for roll in state: # Get the counts of the state
state_count[roll - 1] += 1
# Initialize
reroll_counts = np.zeros((1, 6), dtype=np.uint8)
append_count = np.zeros(6, dtype=np.uint8)
ind... | The function evaluates potential reroll decisions by calculating expected scores for each reroll option, weighted by their probabilities, and returns the reroll with the highest expected value based on field-specific scoring rules and optimization parameters. | def collect_decision_parameters(
input_state, fields, maxpoints, optimizer, states, n=5, k=6
):
# Collect decision parameters for the reroll decision
rerolls = get_rerolls(input_state)
propabilities = get_reroll_state_propability(input_state, rerolls, states)
decision_score_matrix = np.zeros_like(pr... |
def init():
# Initialize scoreboard, freefields and decisionlists
scoreboard = np.empty(20, dtype=np.int16)
scoreboard[:] = -1
freefields = np.array(
[0, 1, 2, 3, 4, 5, 9, 10, 11, 12, 13, 14, 15, 16, 17], dtype=np.uint8
)
maxpoints = np.array(
[5, 10, 15, 20, 25, 30, 12, 22, 18, ... | The main task of the code is to simulate a game of Kniffel (Yahtzee) by iteratively rolling dice, using an optimizer to determine optimal scoring decisions, updating a scoreboard with achieved points, handling special Kniffel (five-of-a-kind) scoring rules, and saving valid final scores to a CSV file. The function runs... | def run_game(
all_states,
optimizer,
throws=3,
n=5,
k=6,
):
# Run a game of Kniffel
scoreboard, freefields, maxpoints = init() # optimizer
count_round = 0
while count_round < 15:
count_round += 1
roll = first_roll(n, k)
for i in range(throws - 1):
... |
def move(self, cell, player) -> bool:
'''
Return True if move is valid (AND claim cell, AND swap player), else False
'''
if cell is None:
return False
x, y = self.get_cell_coords_by_label(cell)
if self.board[x][y] == ' ':
self.board[x][y] = player
... | The main task of the code is to manage a Tic-Tac-Toe game loop, alternating between two players (p1 and p2) to make moves, checking for win/draw conditions after each move, and returning the game outcome ('X', 'O', or 'Draw'). It also handles viewer updates, turn pauses, and resets the game state after completion. | def play_game(self, p1, p2, viewer) -> str:
'''
The Tic-Tac-Toe game loop: calls p1 and p2 for plays until a match concludes; returns outcome (X, O, Draw).
'''
if self.AI_ONLY_MODE:
pause = TURN_PAUSE
else:
pause = 0
turn = 0
... |
def read_input():
error = 0
f = open("input.txt",'r')
inputs = dict()
for line in f.readlines():
sline = line.split(' = ')
if sline[0]=="spin" and int(sline[1])==0:
inputs[sline[0]] = 0.5
else:
inputs[sline[0]] = int(sline[1])
# Define error checking o... | The main task of the code is to validate and parse input parameters from a file, checking for required values (spin, chain length, charge, dipole moment) and handling errors. It processes spin to calculate `sps`, determines `Np` via subsector logic or direct input, and returns `sps`, `N`, and `Np` for further computati... | def input_routine():
err, inputs = read_input()
if inputs["use file input"]:
if err:
print(Fore.RED + "Detected only ", len(inputs)-1,
" inputs from file, but 4 are required: ")
print("- spin (0=spin-1/2, 1=spin-1)")
print("- chain length (between 2 ... |
def get_data_by_date(date, ds=None):
if (ds is None):
ds = fetch_data_from_url() # get the list of all days
one_day = ds.loc[ds['airdate'] == date]
return one_day
def write_show_lookup(date, schedule=None):
ds = build_lookup_for_day(date, schedule)
path = FS.show_lookup_filepath(date)
logging.info('w... | The code generates daily files by retrieving schedule data for a given date, writing show lookup information, and saving episode show data, returning True upon completion. | def create_daily_files(date):
schedule = get_data_by_date(date)
write_show_lookup(date, schedule)
write_ep_show_data(date, schedule)
return True |
def fetch_data_from_url():
config = get_config()
url = config['schedule_url']
logging.info('hitting schedule service at ' + url)
f = urllib.request.urlopen(url)
schedule = pd.read_json(f.read())
return schedule
def write_show_lookup(date, schedule=None):
ds = build_lookup_for_day(date, schedule)
pat... | The main task of the code is to fetch schedule data from a URL, then generate two files/outputs: a show lookup and episode show data, both labeled "ALL_DAYS", using the retrieved schedule. The function returns True upon completion. | def create_files_all_days():
schedule = fetch_data_from_url()
write_show_lookup('ALL_DAYS', schedule)
write_ep_show_data('ALL_DAYS', schedule)
return True |
def calculate_missing_data_flags(merged_df, cards=True, elo=True):
'''
Returns the same dataframe back with two extra columns if the parameters are set
for missing cards and elo data
'''
merged_df_new = merged_df.copy()
if cards:
merged_df_new = (merged_df_new
.assign(missing... | The main task of the code is to systematically clean a merged DataFrame by identifying and filling missing values using median imputation. It applies league- and year-specific median values for yellow/red cards, team capacity, and ELO ratings, ensuring all missing data is addressed step-by-step to produce a complete Da... | def clean_data_pipeline(merged_df):
'''
This function is a data pipeline for cleaning all the data in the dataframe
Returns:
A cleaned dataframe with no missing data
'''
merged_missing_flags_df = calculate_missing_data_flags(merged_df)
fill_cards_full_season_missing_df = fill_median_yellow... |
def change_player():
global player
if player == "X":
player = "O"
logger.info('player changed to "O". ')
else:
player = "X"
logger.info('player changed to "X".')
logging.info("completed.")
def win_lines(buttons, info, count_win):
global game_over, x_winner, o_winner
... | This function handles player moves in a Tic-Tac-Toe game, updates the UI with the current player's symbol, switches turns, checks for a win, and triggers AI responses in "Normal" or "Hard" modes when it's the AI's turn (player "O"). It maintains game state and enforces rules while interacting with game components like ... | def on_click(button, top_info, buttons, count_win, game_mode):
global player, game_over
if not game_over and button["text"] == "":
button["text"] = player
change_player()
if player == "X":
top_info["text"] = "Player X move"
else:
top_info["text"] = "Playe... |
def load_and_process_image(self, im_path):
"""Read image file and return as tensor in range [-1, 1]."""
image = Image.open(im_path).convert('RGB')
image = transforms.ToTensor()(image)
image = 2 * image - 1
return image
def load_and_process_iuv(self, iuv_path, i):
"""Read ... | This method loads and preprocesses image data along with associated UV maps, masks, and person IDs for a neural network. It reads an image, processes layered IUV data, constructs background layers, concatenates tensors, applies transformations (resizing, normalization), and returns a dictionary containing the original ... | def __getitem__(self, index):
"""Return a data point and its metadata information.
Parameters:
index - - a random integer for data indexing
Returns a dictionary that contains:
image (tensor) - - the original RGB frame to reconstruct
uv_map (tensor) - - the U... |
def _check_dataset_age(self):
try:
with open('dataset/timestamp.txt', 'r') as file:
timestamp = file.read()
if pd.Timestamp.now() - pd.Timestamp(timestamp) > pd.Timedelta(days=7):
print('Dataset is too old. Downloading a new one...')
... | This code initializes a movie data analyzer by loading parameters, checking dataset validity, reading movie data, filtering it based on criteria, counting genres and genre combinations, and printing analysis duration and movie count. | def __init__(self, params=None):
self.genres = {}
self.genres_combinations = {}
self.network = pyvis.network.Network()
if params is not None:
self.params = params
else:
# default parameters
self.params = {
'minimal_rating': 0.0... |
def convert_world_to_local(self, x: int, y: int) -> Tuple[int, int]:
"""
Convert world position to local position in the grid
"""
return x // self.cellSize, y // self.cellSize
def get_piece_at_position(self, x: int, y: int, grid=None) -> Optional[Piece]:
"""
Return the pi... | This method handles the initiation of dragging a game piece by detecting a click on the player's piece, removing it from the board's grid, and preparing it for visual dragging by updating the game state and rendering the board. | def handle_drag_start(self, button_press: Event):
"""
Handle click event on the board
"""
(x, y) = self.convert_world_to_local(button_press.x, button_press.y)
piece = self.get_piece_at_position(x, y)
# If there is no piece at the clicked position, ignore the left click
... |
def convert_world_to_local(self, x: int, y: int) -> Tuple[int, int]:
"""
Convert world position to local position in the grid
"""
return x // self.cellSize, y // self.cellSize
def check_piece_at_position(self, x: int, y: int, grid=None) -> bool:
"""
Check if there is a pi... | This method handles mouse hover events by converting coordinates to local grid positions, updating the last known position, and checking if the hovered cell contains a piece. If so, it sets the hover position and triggers a render; otherwise, it clears the hover state and re-renders, ensuring visual feedback for user i... | def handle_hover(self, motion: Event):
"""
Handle mouse over
"""
(x, y) = self.convert_world_to_local(motion.x, motion.y)
# Don't update the board if the mouse didn't move in another cell
if x == self.last_x and y == self.last_y:
return
# Set last po... |
def convert_world_to_local(self, x: int, y: int) -> Tuple[int, int]:
"""
Convert world position to local position in the grid
"""
return x // self.cellSize, y // self.cellSize
def render(self):
"""
Render the board
"""
# Clear existing canvas, as we will ... | This function retrieves the king piece of the specified color from the game grid. It first checks if the king is being dragged, returning its position and the piece if true. Otherwise, it searches the grid for the king. If not found, it triggers a game-over message indicating the king was captured, displays the winner,... | def get_king_piece(self, color: str, grid=None):
"""
Return the king piece of the given color
"""
if not grid:
grid = self.grid
# Check if the king is not actually dragged.
if type(self.draggedPiece) is King:
(x, y) = self.convert_world_to_local(
... |
def previously_open_check(self):
#checks for the existence of settings file
if os.path.isfile('settings.json'):
#if settings exist, return true
print('settings detected')
return True
else:
#otherwise, return false
print('no settings det... | The code's main task is to initialize the app upon GUI creation by setting the current stop to 'home' if it's afternoon, opening the settings screen if the app is首次 run, refreshing all data, and scheduling a bus time refresh in 30 seconds. | def on_start(self):
#once the GUI is created, the following code is run
#setting the current stop to school, if it is the afternoon
import datetime
dt = datetime.datetime.now()
if dt.time() < datetime.time(12, 30):
self.currentStop = 'home'
if not se... |
def mutate_for_Non_Duplication(x, gene_pool, pmut):
if random.uniform(0, 1) >= pmut:
return x
mutate_population = x[:]
mutate_population.remove(start_point)
random.shuffle(mutate_population)
mutate_population.insert(0, start_point)
return mutate_population
def recombine_for_Non_Duplicati... | This function implements a genetic algorithm to evolve a population of individuals toward a fitness threshold. It uses selection, recombination, and mutation (with optional non-duplication constraints) across generations, returning the fittest individual once the threshold is met or after max generations. | def genetic_algorithm(population, fitness_fn, gene_pool, f_thres=None, ngen=1200, pmut=0.1, start = None, non_duplication = True):
global start_point
start_point = start
if non_duplication:
for generation in range(ngen):
population = [mutate_for_Non_Duplication(recombine_for_Non_Duplicat... |
def entropy(rows):
# Simple entropy calculation for a list of rows
entries = decision_counter(rows)
avg_entropy = 0
size = float(len(rows))
for decision in entries:
prob = entries[decision] / size
avg_entropy = avg_entropy + (prob * math.log(prob, 2))
return -1*avg_entropy
def pa... | This function identifies the optimal feature-value pair to split a dataset in a decision tree by calculating information gain. It iterates through each feature and unique value, partitions the data, computes information gain for each split, and retains the split with the highest gain. The result is the maximum informat... | def calculate_best_splitter(rows, header):
# The method of finding the best inquiry to split the tree on
# Here we want to keep track of the best gain from a question
best_gain = 0
# We also want to keep track of the inquiry that gave the best gain
best_inquiry = None
current_entropy = entropy(r... |
def calculate_best_splitter(rows, header):
# The method of finding the best inquiry to split the tree on
# Here we want to keep track of the best gain from a question
best_gain = 0
# We also want to keep track of the inquiry that gave the best gain
best_inquiry = None
current_entropy = entropy(r... | The code builds a decision tree recursively by calculating information gain to determine the optimal feature split. If no gain is possible, it creates a leaf node. Otherwise, it partitions data into true/false branches, recursively constructing subtrees, and returns a decision node with the split criteria and branches. | def build_decision_tree(rows, header, depth=0, id=0):
# Start by partitioning the dataset between unique features and calculating information gain
# Then return the inquiry that will result in best information gain
gain, inquiry = calculate_best_splitter(rows, header)
# If there is no more possible ga... |
def over(self, player, opponent, turn):
if self.end(self.possible_moves(player, opponent)):
if self.end(self.possible_moves(player, opponent)) and self.end(self.possible_moves(opponent, player)):
if player.score() > opponent.score():
return True, turn, "No more mo... | The code implements the minimax algorithm with alpha-beta pruning and memoization to determine the optimal move in a game state. It evaluates game states recursively, exploring possible moves, and selects the best heuristic value while avoiding redundant calculations via a hash map. The function alternates between maxi... | def minimax(self, root, depth, alpha, beta, maximizer, hash_map):
player, opponent = root.data[0], root.data[1]
end, winner, type = self.over(player, opponent, "p")
if end == True or depth == 0:
return self.heuristic_score(root.data[0], root.data[1]), root.data[0], root.data[1]
... |
def draw_first_row_line(self):
print("\n" + "{:_<49}".format(""))
def draw_all_fields(self, board_suggest):
for i in range(63, -1, -1):
self.draw_field(board_suggest, i)
self.draw_row_number_and_line(i)
def draw_column_names(self):
rows = "ABCDEFGH"
for i in rows... | The code's main task is to render a board structure by drawing the first row line, all fields (cells), and column names. It uses optional `board_suggest` to customize the board layout. The method orchestrates visual elements to display a structured grid, likely for games or data visualization, ensuring proper formattin... | def draw(self, board_suggest = None):
self.draw_first_row_line()
self.draw_all_fields(board_suggest)
self.draw_column_names() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.