dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def read_basin(case):
with open(f'day9/{case}', 'r') as f:
floor = [[int(x) for x in line] for line in f.read().splitlines()]
return floor
def find_lowers(case):
risk_level = 0
lower_points = []
floor = read_basin(case)
for i, row in enumerate(floor):
for j, col in enumerate(row)... | The main task of the code is to identify and count the number of elements in each basin by exploring from lower points, following upward flows, and collecting all connected elements. It returns a list of basin sizes based on the input case. | def locate_basins(case):
floor = read_basin(case)
basins = []
lowers, _ = find_lowers(case)
for l in lowers:
explored = set()
basin_elements = set()
frontier = [l]
while frontier:
i, j = frontier.pop(0)
if (i,j) not in explored:
e... |
def load(self, inputFile='C:/test.json'):
"""
Create a new data structure to vend the hierarchy in a format that is compatible with Angular Fannie Mae
component.
"""
with open(inputFile) as hierarchyFile:
self.hierarchy = json.load(hierarchyFile)
def genAPIFormat(self... | The code initializes a data structure to organize hierarchical data in a format compatible with Angular Fannie Mae components. It loads data, generates an API-compatible structure, and prepares it for export as JSON, storing results in `self.exportJSON` for external use. | def __init__(self):
"""
Create a new data structure to vend the hierarchy in a format that is compatible with Angular Fannie Mae
component.
"""
self.data = []
self.exportJSON = {
'data': self.data
}
self.load()
self.genAPIFormat()
... |
def init_quantize_net(net):
for name,m in net.named_modules():
if isinstance(m,nn.Conv2d) or isinstance(m,nn.Linear):
quantized_layers.append(m)
m.weight.weight_float = m.weight.data.clone()
def quantize_layers(bitwidth,rescale=True):
for i, layer in enumerate(quantized_layers):
... | This code defines a training pipeline for Spiking Neural Networks (SNNs) with configurable parameters like model type, dataset (MNIST/CIFAR10/CIFAR100), batch sizes, learning rates, and LIF neuron attributes. It supports quantization-aware training, distributed training (DP/DDP), checkpointing, and TensorBoard logging.... | def main():
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('model', type=str,
help='network model type: see detail in folder ''models'' ')
parser.add_argument('--dataset', type=str, default='MNIST',
... |
def get_datetime(site_url, str_date):
try:
netloc = urlparse(site_url).netloc
# logging.debug("transforming date to datetime")
if site_url not in date_string_format and netloc not in date_string_format:
logging.error(f"string format unknown for {site_url} ")
return
... | The function `just_save_data` filters and saves article data based on keyword matches in titles/contents and date ranges. It iterates through `page_data`, checks if title/body keywords match `match_keywords`, validates dates against `from_date`/`to_date`, and appends qualifying entries to `filtered_data`. It then logs ... | def just_save_data(
page_data,
site_url,
output_manager,
url,
url_id,
from_date,
to_date,
title_body_decode,
mirror_site_url,
match_keywords,
current_page,
):
filtered_data = []
# data = next(page_data)
page_data_headers = [
"title",
"partial_body"... |
def get_datetime(site_url, str_date):
try:
netloc = urlparse(site_url).netloc
# logging.debug("transforming date to datetime")
if site_url not in date_string_format and netloc not in date_string_format:
logging.error(f"string format unknown for {site_url} ")
return
... | The main task of this code is to paginate through a website, extract structured data (title, date, author, body, links) using CSS selectors, filter results by a specified date range, and save the processed data via an OutputManager. It handles site-specific parsing rules, dynamically fetches additional data if required... | def paginate_filter_and_save_data(
output_manager: OutputManager,
site_url,
url_id,
paginator,
match_keywords,
title_selector,
link_selector,
title_body_selector,
date_selector,
author_selector,
from_date,
to_date,
visit_to_get=[],
timeout=3,
kill_thread=[],
... |
def find_max_list_graph(max_num):
i = 5
val = -1
while (val < max_num):
val = scipy.special.binom(i, 2)
i += 1
return i - 1
def build_tree(cmp,adj,device,flag_density = 'False'):
N = adj.shape[0] #original shape of the adjacency matrix
list_G = []
while(1):
#STEP 1: c... | This function generates a dataset of graph samples by processing multiple graphs through iterative transformations, controlling sample size, and handling graph density. It returns aggregated samples and associated values from each graph processing step. | def create_dataset_buffer(cmp, device, times, dim_datasamples, list_G,show_graphs_stats = True,flag_density = 'False'):
list_val = []
list_dataset = []
num = find_max_list_graph(dim_datasamples)
if flag_density == 'True':
num = int(num*2)
for G in list_G:
if show_graphs_stats == Tr... |
def get_img(self,file):
path_img = os.path.join(self.dir_data, 'img', 'img{}.nii.gz'.format(file))
image_3d = nib.load(path_img)
image_3d = image_3d.get_fdata()
if self.axis =='axial':
image_3d = image_3d.transpose((2, 0, 1))
if self.axis == 'sagittal':
pa... | This method loads 3D medical images and masks, applies background replacement, normalization, and data augmentation (organ masking). It returns processed tensors for images and spleen-specific masks, or just images if no labels are required. | def __getitem__(self, idx):
if self.to_ram:
image_3d=self.image_3d_all[idx]
if self.no_label is False:
mask_3d = self.mask_3d_all[idx]
else:
image_3d = self.get_img(self.fileIDs[idx])
if self.no_label is False:
mask_3d = sel... |
def login():
creds = None
print('Checking credentials...')
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from... | The main task of the code is to retrieve and save Gmail messages in batches using the Gmail API. It first saves the first 500 messages, then iteratively saves subsequent batches of 500 messages each, using pagination tokens to handle large result sets. The process continues for 500 iterations, ensuring efficient handli... | def main():
creds = login()
try:
service = build('gmail', 'v1', credentials=creds)
print('Saving batch 1...')
next_page_token = save_first_five_hundred_messages(service, creds)
for x in range(500):
print(f'Saving batch {x+2}...')
next_page_token = save_five_hundred_messages(service, next_page_token... |
def forward_prop(X,thetas):
"""
Calculates a1, z2, a2, z3 and h using forward propagation algorithm
:param X: matrix containing train features
:param thetas: dictionary of theta having theta1 and theta2
:return: dictionary containing values - a1, z2, a2, z3, h
"""
m = int(X.shape[0])
a1 ... | The function performs backpropagation in a neural network to compute gradients of the cost function with respect to parameters, including L2 regularization. It reshapes input parameters into weight matrices, executes a forward pass, calculates the cost, iterates over training examples to compute deltas, accumulates gra... | def backward_prop(params, input_size, hidden_size, num_labels,X, y, lambda_reg):
#def backward_prop(forward_params,thetas,X,y):
m = int(X.shape[0])
X_train = np.matrix(X)
y = np.matrix(y)
# Reshape the parameter array into parameter matrices for each layer
theta1 = np.matrix(np.reshape(params[:hidd... |
def _register(self, fdists, points_x, points_y, inlier_threshold):
"""
Args:
fdists (torch.Tensor): (M, N)
points_x (torch.Tensor): (M, 3)
points_y (torch.Tensor): (N, 3)
inlier_threshold (float):
Returns:
torch.Tensor: R, t, from Y to... | The main task of the code is to compute the orthogonality error (R_ortho_err) and cycle consistency error (R_cycle_err) between two point cloud registrations. It uses the _register method to derive transformation matrices (R_y2x, t_y2x and R_x2y, t_x2y) from input distance and keypoint tensors, then evaluates geometric... | def forward(self, fdists_xy, kpts_x, kpts_y, points_x, points_y):
"""
Args:
fdists_xy (torch.Tensor): (M, N)
kpts_x (torch.Tensor): (M, 3)
kpts_y (torch.Tensor): (N, 3)
points_x (torch.Tensor): (M', 3)
points_y (torch.Tensor): (N', 3)
... |
def drawBoard (tank1box, tank2box, obstacleBox, playerNum):
"""
draws the game board, pre-shot
parameters
----------
tank1box : tuple
(left,right,bottom,top) location of player1's tank
tank2box : tuple
(left,right,bottom,top) location of player1's tank
obstacleBox : tuple
... | The code simulates a single turn in a two-player tank shooting game. It takes tank positions, an obstacle, and the current player's number, then prompts the player to input a velocity and angle for their shot. The trajectory is calculated from the tank's center, checking if it hits the opponent's tank or obstacle. If s... | def oneTurn (tank1box, tank2box, obstacleBox, playerNum, g = 9.8):
"""
parameters
----------
tank1box : tuple
(left,right,bottom,top) location of player1's tank
tank2box : tuple
(left,right,bottom,top) location of player1's tank
obstacleBox : tuple
(left,right,bottom,t... |
def parse(lines):
for line in lines:
yield tuple(map(int, line.split(",")))
def count_visible_faces(cubes):
result = 0
for cube in cubes:
# Count the number of neighbors
neighbor_count = 0
for neighbor in neighbors(cube):
if neighbor in cubes:
neig... | The code calculates the number of visible cube faces in a 3D structure. It subtracts visible faces of air pockets (empty spaces) connected to the bounds of the 3D grid from the total visible faces of solid cubes. This determines the net visible surface area of the structure, excluding external air pockets. | def main():
cubes = set(parse(sys.stdin))
# Count the visible faces
count = count_visible_faces(cubes)
# Mark all the cubes connected to the bounds
for dimension in range(3):
for i, j in itertools.product(RANGE, repeat=2):
bound_cube = [i, j]
bound_cube.insert(dimen... |
def parse_args():
"""
Parse command line arguments.
Returns a tuple of: (options, js_shell, requested_paths, excluded_paths)
options :object: The raw OptionParser output.
js_shell :str: The absolute location of the shell to test with.
requested_paths :set<str>: Test paths specially r... | The main task of the code is to run JavaScript tests with configurable options, including debugging, test path filtering, and environment setup. It parses command-line arguments, validates the JavaScript shell executable, loads test cases, executes them in a modified environment, and reports results. Debug mode restric... | def main():
options, prefix, requested_paths, excluded_paths = parse_args()
if options.js_shell is not None and not (isfile(options.js_shell) and
os.access(options.js_shell, os.X_OK)):
if (platform.system() != 'Windows' or
isfile(options.js_shell)... |
def topoInstance(topo, hw):
inst = None
if topo == "tetra":
inst = mn.topo.Topos.TetraTopo(hw=hw)
elif topo == "paper":
inst = mn.topo.Topos.PaperTopo(hw=hw)
else:
print("[ERROR] Invalid topology: %s" % topo)
return inst
def addDummyHost(net, topo):
print('**Adding dummy... | The code initializes a Containernet network topology, starts a REST server for VNF management, configures hardware/emulated settings, executes ARP resolution, sets up dummy hosts, runs test applications (ping, whack-a-mole), and manages network lifecycle via CLI, ensuring proper cleanup. | def main():
parser = argparse.ArgumentParser(description='Starts a containernet topology and a REST server for VNF instantiation from controller.')
parser.add_argument('topology', metavar='T', type=str, nargs=1, help="the topology to start")
parser.add_argument('--hw', action='store_true')
args = parser... |
def addNodes(self):
self.addDxtt()
self.addDxt()
self.addTbs()
def addLinks(self):
self.addDxttInterconnectLinks()
self.addDxtToDxttLinks()
self.addTbsToDxtLinks()
def addServer(self):
print("adding server..")
server = self.addHost('shost', ip='10.0.0.1')
... | This code initializes a network topology by setting up nodes, links, servers, and clients. It creates lists to track different components (e.g., dxtt, tbsHosts) and calls methods to add network elements, with 'hw' determining client type. The main task is to configure a structured network environment for simulation or ... | def __init__(self, hw=False):
Topo.__init__(self)
self.dxtt = []
self.dxt = []
self.tbs = []
self.tbsHosts = []
self.dwsHosts = []
self.addNodes()
self.addLinks()
self.addServer()
self.addClients(hw) |
def load_csv_file(filename, skip_columns=0):
with open(filename, 'r') as f:
reader = csv.reader(f)
next(reader, None) # skip the headers
segmentations_per_image = {}
for row in reader:
image_name = row[0]
segm = row[1:]
if skip_columns > 0:
... | The code evaluates a model's performance by comparing its results (from `filename_results`) against ground truth data (from `filename_solution`). It calculates a score using `get_score`, then appends this score along with the model name to a specified CSV file (`filename_write_score`). The ground truth data skips the f... | def evaluate(filename_results, filename_solution, filename_write_score, model):
print("Evaluating")
results = load_csv_file(filename=filename_results)
ground_truth = load_csv_file(filename=filename_solution, skip_columns=3)
score = get_score(results=results, ground_truth=ground_truth)
append_score_t... |
def select_body():
global previous_hovered_body, hovered_start, selected_body
hovered_over = mouse_over()
if hovered_over is None:
previous_hovered_body = None
selected_body = None
else:
if hovered_over is previous_hovered_body:
if time() >= hovered_start + DELAY:
... | This function handles mouse hover interactions on celestial bodies, updating UI information display. It selects a body, updates tips, checks if a body is selected, erases info if none is selected, and shows detailed information only when the hovered body changes, ensuring efficient UI updates without redundant displays... | def info_handle():
'''Handling the mouse hovering upon bodies and displaying all of the needed info.'''
global selected_body, body_info_shown_for
select_body()
show_tips()
global_items.canvas.update()
if selected_body is None:
body_info_shown_for = None
erase_information()
... |
def generate_params(value_functions, address=None):
values = [get_value(v, address=address) for v in value_functions]
return values
def encode_args(types, values):
abi = encode_abi(types, values)
hex_args = binascii.hexlify(abi)
return hex_args.decode('utf-8')
def create_deployment_bytecode(bytecode... | This function deploys a smart contract to an EVM environment by encoding constructor arguments into bytecode, handling large bytecode via temporary files, executing deployment via subprocess, and parsing the output to return the contract address with a '0x' prefix. | def deploy_contract(bytecode, *constructor_args, dirname=evm_data_dir):
start = time.time()
if constructor_args:
arg_types, arg_values = constructor_args
arg_values = generate_params(arg_values)
bytecode += encode_args(arg_types, arg_values)
print('Encoding params', time.time()-start... |
def generate_params(value_functions, address=None):
values = [get_value(v, address=address) for v in value_functions]
return values
def get_value(value_function, address=None):
if callable(value_function):
if address:
return value_function(address)
return value_function()
eli... | The main task of the code is to execute a transaction plan by generating parameters, retrieving caller and function details, and invoking a transaction execution function. It calculates and returns the total time along with individual execution, initialization, and I/O time components for the transaction process. | def perform_transaction(address, txn_plan, root_hash=None):
args = generate_params(txn_plan['values'], address=address)
caller = get_value(txn_plan['caller'])
function = txn_plan['function']
block_timestamp = txn_plan.get('time', 0)
amount = txn_plan.get('amount', 0)
exec_time, init_time, io_tim... |
def get_experiment_label_long(path):
"""Extracts long experiment name from file path"""
label = path.split("/")
label = ".".join([*label[1:4], label[5]])
label = label.replace(".metrics", "")
label = label.replace(".main", "")
return label
def parse_main_file(f):
"""Parses the metrics out of... | The code generates LaTeX tables and visualizations from experimental results. It aggregates metrics from specified directories, processes data into labeled dictionaries, creates a LaTeX table, and generates plots for main paper figures and supplementary materials, saving outputs as PNG and TEX files. | def generate_figures():
"""Main method for generating latex table and plots"""
os.makedirs("plots", exist_ok=True)
exps_to_path = {}
results_dict_all = {}
for path, directories, files in os.walk(RESULTS_DIR):
if "metrics" in path:
exp_name = get_experiment_label_long(path)
... |
def is_running(self):
inspect = self.inspect0()
return inspect.get('State', {}).get('Running', False)
def stop(self):
cmd = 'docker stop {container}'.format(container=self.name)
utils.run(cmd)
def release_ip(self):
for ip in self.ip():
cmd = 'calicoctl ipam release --... | The code's main task is to restart a service by first checking if it's running, stopping it if necessary, releasing its IP address, and then restarting it. This ensures proper resource cleanup before restarting, preventing conflicts or errors from residual processes or IP allocations. | def restart(self):
if self.is_running():
self.stop()
self.release_ip()
self.start() |
def execute_cmd(self, cmd_list):
for c in cmd_list:
if self.dryrun:
print(c)
else:
os.system(c)
def create_cali_net(self, network):
self.create_pool_yaml(network)
cmd_list =[
'calicoctl create -f ippool-{name}.yaml'.format(name=... | The code's main task is to create or delete specified networks based on the `to_create` or `to_delete` flags. If `to_create` is True, it iterates through `network_list` and executes commands to create each network using `create_cali_net`. If `to_delete` is True, it deletes each network via `delete_cali_net`. If neither... | def execute(self):
if self.to_create:
for n in self.network_list:
self.execute_cmd(self.create_cali_net(n))
elif self.to_delete:
for n in self.network_list:
self.execute_cmd(self.delete_cali_net(n))
else:
self.usage() |
def get_avg_interior_temps():
TEMP2 = int(float(get_temp2()))
TEMP3 = int(float(get_temp3()))
#Temp4 is the probe right across the intake finns of the AC
TEMP6 = int(float(get_temp6()))
TEMP7 = int(float(get_temp7()))
#Temp8 is the probe in the 5 gallon bucket of water.
AVG_TEMP_IN_C = ((TEMP2 + TEMP3 +... | The main task of the code is to regulate an AC system based on temperature thresholds: it monitors average interior temperature, adjusts the AC power (on/off), and sets a "liar" target temperature (50°F or 70°F) to maintain desired cooling. It triggers safety measures like 1-minute or 10-minute shutdowns if temperature... | def main():
start_http_server(8004)
#pdb.set_trace()
while True:
try:
AVG_TEMP_IN_F = get_avg_interior_temps()
logging.info('AVG_TEMP_IN_F: %s', AVG_TEMP_IN_F)
avg_temp_f_control.set(AVG_TEMP_IN_F)
#We believe the AC will turn off when it'... |
def print_options_from_file(file_path):
try:
with open(file_path, "r") as file:
lines = file.readlines()
if len(lines) < 2:
print(
"Invalid file format. The file should contain at least two lines."
)
return
... | The main task of the code is to provide an interactive menu-driven interface for managing and manipulating data. It allows users to print data, modify entries, compare databases, view specific datasets, check recent changes, or save and exit. The function continuously prompts users for actions, executes corresponding o... | def questions_and_actions(variable_data, data_dict, input_directory, output_directory):
while True:
print_options_from_file("TextFiles/options.txt")
question = int(input("What would you like to do? "))
# 1| Print data to terminal
# 2| Modify data
# 3| Display differences betw... |
def load_credentials():
if os.path.exists("credentials.yaml"):
with open("credentials.yaml", "r") as f:
return yaml.safe_load(f)
else:
secret_id = input("Enter your Nordigen Secret ID: ")
secret_key = input("Enter your Nordigen Secret Key: ")
credentials = {"SECRET_ID... | The main task of the code is to create and configure a Nordigen client for accessing financial data. It loads credentials, initializes the client with API keys, generates or refreshes access tokens as needed, handles authentication errors, and verifies connectivity. The function ensures valid token management, updates ... | def create_nordigen_client():
# Load credentials from file or prompt user
credentials = load_credentials()
# Initialize Nordigen client with SECRET_ID and SECRET_KEY
nordigen_client = NordigenClient(
secret_id=credentials["SECRET_ID"],
secret_key=credentials["SECRET_KEY"]
)
# C... |
def getMdMc():
# ask user how many clusters
while True:
try:
clusterNum = input("\nHow many clusters would you like to use (2 - 8)?\n")
clusterNum = clusterNum[0]
if(ord(clusterNum) >= 50 and ord(clusterNum) <= 56):
break
else:
print("*Invalid choice. Please give a number... | The main task of the code is to allow users to either generate a new cluster matrix or display a pre-saved matrix, using specified clustering parameters (cluster number, method, metric). It reads user inputs, retrieves chromosome data from files, validates choices, and executes the selected action (new matrix creation ... | def main():
print('\033[1m' + "---Welcome to the clustermap program---" + '\033[0m')
# get all the user input
clusterNum, theMethod, theMetric = getMdMc()
with open("chromDict.txt", "r") as f:
savedChroms = f.readline()
while True:
currentLine = f.readline()
if ("_" in currentLine):
... |
def UpdatePropertiesTable(self):
self.Props = {'Node':[1]}
self.PropsTable = pd.DataFrame(self.Props)
Values = [0,0,0,0,0,0]
a = 0
self.PropsTable['R_Left'] = 0
self.PropsTable['R_Right'] = 0
self.PropsTable['R_Top'] = 0
self.PropsTable['ThermCap'] = 0
... | The main task of the code is to calculate and return the temperature at a specified node between a given time interval. It validates the node number, adjusts time steps if misaligned with the simulation's time increment, and iteratively computes temperatures by advancing through time steps. The function handles cases w... | def GetTempatureAtNodeAtTime(self,StartTime,EndTime,Node):
self.UpdatePropertiesTable()
if Node > self.NumNodes or Node <= 0:
return "Error: Node Number Invalid"
Time = EndTime - StartTime
if Time % self.TimeInc != 0:
# print("Time Invalid, rounding...")
... |
def SetHeatSource(self, InputTemp):
self.TempLeftEnd = InputTemp
def SuggestedTimeInc(self,Return):
NN= 0
self.SugTime.clear()
self.UpdatePropertiesTable()
while NN < 4:
NN = NN + 1
self.Properties(NN)
TimeSuggestion = (self.PropsTable.iloc[(NN... | This function advances a simulation over a specified time period by setting a heat source, calculating recommended time steps, generating a time sequence with adjusted increments, iterating through these steps to compute node values, and updating the properties table to reflect simulation progress and results. | def AdvanceSimulationByTime(self, timeIncrement, temperatureHeatSource):
self.SetHeatSource(temperatureHeatSource)
dTimeRecommend = self.SuggestedTimeInc(True)
timeStart = np.max(self.AllTemp.Time)
timeEnd = timeStart + timeIncrement
noStepsMin =timeIncrement/dT... |
def move_possible(canvas, player, variables):
# input from player
key = canvas.get_last_key_press()
if key == "ArrowLeft" and (variables["direction"] != [1,0] or len(player)==1):
variables["direction"] = [-1,0]
if key == "ArrowRight" and (variables["direction"] != [-1,0] or len(pla... | The code implements a simple game where a player-controlled snake moves across a canvas, aiming to reach a goal. It initializes game variables, sets up the canvas with a background, score display, and goal. The main loop handles movement, checks for valid moves, updates the score upon hitting the goal, and triggers a g... | def main():
#setup variables
variables = {
"delay": 0.2,
"direction": [1,0],
"score" : 0,
"colours": [[LIGHTEST,LIGHTEST,LIGHTEST]],
"colour_change": [-1,-1,-1],
"colour" : "#ffffff"
}
#setup initial canvas
canvas = Canvas(CANVAS_WIDTH, CANVAS_HEIGHT)
... |
def render_circle(image, identifier):
if circle_storage.get(identifier) is not None:
x, y, radius, color = circle_storage.get(identifier)
cv2.circle(image, (x, y), radius, color, 4)
def render_button(image):
if button_storage.get() is not None:
for (x, y, radius, color) in button_storage... | The main task of the code is to render graphical elements (circles, button, score) onto an image using specified functions, then clear associated storage structures (circle_storage, button_storage, score_storage) to reset their contents after rendering. | def draw(image):
render_circle(image, "15")
render_circle(image, "10")
render_circle(image, "5")
render_button(image)
render_score(image)
circle_storage.empty()
button_storage.empty()
score_storage.empty() |
def get_idle_instances(self):
"""
return idle instances
:return: instances: list
"""
instances_tag_raw = self.get_tag_instances()
instances_target_raw = self.get_target_instances()
instances_tag =[]
instances_target = []
for item in instances_tag_r... | This function adds an EC2 instance to a target group by either starting an idle instance or creating a new one. It waits for the instance to reach the 'running' state, then registers it with the ELB using the specified TargetGroupArn and port 5000. The function returns the HTTP status code of the registration or -1 on ... | def grow_worker_by_one(self):
"""
add one instance into the self.TargetGroupArn
:return: msg: str
register_targets(**kwargs)
"""
idle_instances = self.get_idle_instances()
new_instance_id = None
if idle_instances:
new_instance_id = idle_instan... |
def get_healthy_instances(self):
target_instances = self.get_target_instances()
healthy_target_instances_id = []
for instance_id in target_instances:
if instance_id['State'] == 'healthy':
healthy_target_instances_id.append(instance_id['Id'])
return healthy_tar... | This function reduces the number of worker instances in a target group by a specified ratio, ensuring at least one instance remains. It checks validity conditions (ratio ≤1, sufficient healthy instances), calculates the number of instances to remove, and iteratively shrinks the worker pool by calling `shrink_worker_by_... | def shrink_worker_by_ratio(self, ratio):
"""
shrink one instance into the self.TargetGroupArn
:return: msg: str
"""
healthy_instances_id = self.get_healthy_instances()
target_instances_id = self.get_valid_target_instances()
response_list = []
if ratio > 1:... |
def captures_available(self, board, player):
# Iterate over all cells on the board
for r in range(BOARD_SIZE):
for c in range(BOARD_SIZE):
# Check if there is a piece in the current cell and it belongs to the current player
if isinstance(board[r][c], Piece) an... | This code handles the selection of a game piece by a player. It checks if the selected piece belongs to the current player, validates available moves (prioritizing captures), highlights valid moves, and enforces capture rules. If invalid (e.g., wrong player or no captures), it resets selections and shows errors. | def select(self, row, col):
# Get the piece at the specified position on the board
piece = self.board[row][col]
# Check if the piece is of the same player as the current player
if isinstance(piece, Piece) and piece.player == self.current_player:
self.valid_move_squares.clear(... |
def detect_platform():
try:
platforms = {
'linux': 'Linux',
'linux1': 'Linux',
'linux2': 'Linux',
'darwin': 'OS X',
}
logger.info("[*] Detect Platform")
if sys.platform not in platforms:
logger.error("[x_x] Your platform cur... | The main task of the code is to detect the operating system, execute platform-specific checks (e.g., macOS or Linux), handle keyboard interrupts, and terminate services accordingly. It logs platform identification, runs OS-specific validation functions, and ensures service shutdown on both Darwin (macOS) and Linux vari... | def main():
try:
detect_platform()
if (sys.platform == 'darwin'):
logger.info("[*] Darwin - MAC OS-X")
check_runon_osx()
if (sys.platform == 'linux') | (sys.platform == 'linux1') | (sys.platform == 'linux2'):
logger.info("[*] Linux - KALI LINUX - UBUNTU")
... |
def LUT(self, lut):
self.send_command(0x32)
self.send_data1(lut[0:153])
self.ReadBusy()
def send_command(self, command):
self.digital_write(self.dc_pin, 0)
self.digital_write(self.cs_pin, 0)
self.spi_writebyte([command])
self.digital_write(self.cs_pin, 1)
def send... | The code configures hardware parameters using a lookup table (LUT) by sending specific commands and data values. It initializes settings for gate voltage, source voltage (VSH, VSH2, VSL), and VCOM by extracting predefined values from the LUT array and transmitting them to the hardware via designated command codes (e.g.... | def LUT_by_host(self, lut):
self.LUT(lut) # lut
self.send_command(0x3F)
self.send_data(lut[153])
self.send_command(0x03) # gate voltage
self.send_data(lut[154])
self.send_command(0x04) # source voltage
self.send_data(lut[155]) # VSH
self.s... |
def send_command(self, command):
self.digital_write(self.dc_pin, 0)
self.digital_write(self.cs_pin, 0)
self.spi_writebyte([command])
self.digital_write(self.cs_pin, 1)
def send_data1(self, buf):
self.digital_write(self.dc_pin, 1)
self.digital_write(self.cs_pin, 0)
... | The main task of the code is to clear the display by sending a specific command (0x24) followed by a buffer of all 0xFF values, which fills the display area with white pixels, and then enabling the display output through the TurnOnDisplay() method. | def Clear(self):
self.send_command(0x24)
self.send_data1([0xff] * self.height * int(self.width / 8))
self.TurnOnDisplay() |
def send_command(self, command):
self.digital_write(self.dc_pin, 0)
self.digital_write(self.cs_pin, 0)
self.spi_writebyte([command])
self.digital_write(self.cs_pin, 1)
def send_data1(self, buf):
self.digital_write(self.dc_pin, 1)
self.digital_write(self.cs_pin, 0)
... | This code's main task is to display an image on a screen by sending command 0x24, transmitting image data via send_data1, and activating the display with TurnOnDisplay. It handles the process of preparing and rendering an image on an embedded display device through low-level hardware commands. | def display(self, image):
self.send_command(0x24)
self.send_data1(image)
self.TurnOnDisplay() |
def send_command(self, command):
self.digital_write(self.dc_pin, 0)
self.digital_write(self.cs_pin, 0)
self.spi_writebyte([command])
self.digital_write(self.cs_pin, 1)
def send_data1(self, buf):
self.digital_write(self.dc_pin, 1)
self.digital_write(self.cs_pin, 0)
... | The main task of the code is to display a given image on a connected device by sending specific commands (0x24 and 0x26) along with the image data to the display controller, followed by activating the display output via the TurnOnDisplay() method. | def Display_Base(self, image):
self.send_command(0x24)
self.send_data1(image)
self.send_command(0x26)
self.send_data1(image)
self.TurnOnDisplay() |
def reset(self):
self.digital_write(self.reset_pin, 1)
self.delay_ms(20)
self.digital_write(self.reset_pin, 0)
self.delay_ms(2)
self.digital_write(self.reset_pin, 1)
self.delay_ms(20)
def delay_ms(self, delaytime):
utime.sleep(delaytime / 1000.0)
def ReadBusy(self... | This code initializes a display device by performing a hardware reset, configuring driver output settings, setting data entry mode, defining display windows and cursor positions, configuring border waveform and update control parameters, reading temperature sensor data, and loading a partial Look-Up Table (LUT) for dis... | def init(self):
print('init')
self.reset()
self.delay_ms(100)
self.ReadBusy()
self.send_command(0x12) # SWRESET
self.ReadBusy()
self.send_command(0x01) # Driver output control
self.send_data(0xf9)
self.send_data(0x00)
s... |
def digital_write(self, pin, value):
pin.value(value)
def delay_ms(self, delaytime):
utime.sleep(delaytime / 1000.0)
def LUT_by_host(self, lut):
self.LUT(lut) # lut
self.send_command(0x3F)
self.send_data(lut[153])
self.send_command(0x03) # gate voltage
... | This code initializes and configures an e-paper display to show a partial image. It resets the display, sets look-up tables, configures display parameters, defines the display window, sends image data, and activates the partial display update. | def display_Partial(self, image):
self.digital_write(self.reset_pin, 0)
self.delay_ms(1)
self.digital_write(self.reset_pin, 1)
self.LUT_by_host(self.full_lut)
self.send_command(0x37)
self.send_data(0x00)
self.send_data(0x00)
self.send_dat... |
def wipeScreen():
for widget in root.winfo_children():
widget.destroy()
def loseHealth(opponentCanvas, opponentHealthBar):
global opx2, opx1, opy2, opy1, opponent
x,y,z=mpu.acceleration
movement = round(sumSquares(x,y,z),0)
if movement>=15:
print(movement)
if op == 1:
... | The code defines a function `paulScreen` that initializes a game UI with health bars for the player and opponent, displays character information, and triggers health loss mechanisms. It creates canvases for health visualization, adds labels for stats and hints, and schedules functions to reduce health for both sides us... | def paulScreen(event):
global images,x2,op
op+=1
wipeScreen()
opponentCanvas = Canvas(root, height = 50, width = 900)
opponentCanvas.create_rectangle(0,0,900,50, fill="red")
opponentHealthBar = opponentCanvas.create_rectangle(0,0,900,50, fill="green")
opponentCanvas.grid(row=0,column=0,colum... |
def wipeScreen():
for widget in root.winfo_children():
widget.destroy()
def loseHealth(opponentCanvas, opponentHealthBar):
global opx2, opx1, opy2, opy1, opponent
x,y,z=mpu.acceleration
movement = round(sumSquares(x,y,z),0)
if movement>=15:
print(movement)
if op == 1:
... | This function displays a game screen where the player faces an opponent (Tate), showing health bars, character bio, stats, and a challenge. It initializes UI elements like canvases for health visualization, labels for game info, and a "Back" button. The function schedules health loss mechanics for both player and oppon... | def tateScreen(event):
global images,x2,op
op+=2
wipeScreen()
opponentCanvas = Canvas(root, height = 50, width = 900)
opponentCanvas.create_rectangle(0,0,900,50, fill="red")
opponentHealthBar = opponentCanvas.create_rectangle(0,0,900,50, fill="green")
opponentCanvas.grid(row=0,column=0,colum... |
def wipeScreen():
for widget in root.winfo_children():
widget.destroy()
def loseHealth(opponentCanvas, opponentHealthBar):
global opx2, opx1, opy2, opy1, opponent
x,y,z=mpu.acceleration
movement = round(sumSquares(x,y,z),0)
if movement>=15:
print(movement)
if op == 1:
... | The function `tysonScreen` displays a UI for Mike Tyson's character in a game, showing his stats, health bars, and a "Back" button. It initializes opponent and player health bars, schedules health loss over time, and updates the screen with Tyson's details and hints. | def tysonScreen(event):
global images,x2,op
op+=3
wipeScreen()
opponentCanvas = Canvas(root, height = 50, width = 900)
opponentCanvas.create_rectangle(0,0,900,50, fill="red")
opponentHealthBar = opponentCanvas.create_rectangle(0,0,900,50, fill="green")
opponentCanvas.grid(row=0,column=0,colu... |
def wipeScreen():
for widget in root.winfo_children():
widget.destroy()
def loseHealth(opponentCanvas, opponentHealthBar):
global opx2, opx1, opy2, opy1, opponent
x,y,z=mpu.acceleration
movement = round(sumSquares(x,y,z),0)
if movement>=15:
print(movement)
if op == 1:
... | This code displays a game screen for a character (Ali) with health bars, stats, and a bio, scheduling health loss for both player and opponent. It updates the UI with labels, canvases, and a "Back" button, using global variables for game state tracking. | def aliScreen(event):
global images,x2,op
op+=4
wipeScreen()
opponentCanvas = Canvas(root, height = 50, width = 900)
opponentCanvas.create_rectangle(0,0,900,50, fill="red")
opponentHealthBar = opponentCanvas.create_rectangle(0,0,900,50, fill="green")
opponentCanvas.grid(row=0,column=0,column... |
def wipeScreen():
for widget in root.winfo_children():
widget.destroy()
def loseHealth(opponentCanvas, opponentHealthBar):
global opx2, opx1, opy2, opy1, opponent
x,y,z=mpu.acceleration
movement = round(sumSquares(x,y,z),0)
if movement>=15:
print(movement)
if op == 1:
... | This function displays a randomly selected fighter's information, including their image, name, bio, stats, and health bar. It initializes a health-decreasing mechanism for both the opponent and player using scheduled functions, setting up a battle interface with visual elements and dynamic health updates. | def randomFighterScreen(event):
global images,x2, opponent
wipeScreen()
opponentCanvas = Canvas(root, height = 50, width = 900)
opponentCanvas.create_rectangle(0,0,900,50, fill="red")
opponentHealthBar = opponentCanvas.create_rectangle(0,0,900,50, fill="green")
opponentCanvas.grid(row=0,column=0... |
def float_hack(self):
"""Our encoding of floating point numbers does the right thing when you
lexically shrink it, but there are some highly non-obvious lexical
shrinks corresponding to natural floating point operations.
We can't actually tell when the floating point encoding is being u... | The code's main task is to execute a sequence of operations: first applying a floating-point adjustment (`float_hack`), then minimizing data as integers (`minimize_as_integer`), and finally performing a partial sort (`partial_sort`). This likely processes or optimizes data structures, preparing them for further computa... | def run_step(self):
self.float_hack()
self.minimize_as_integer()
self.partial_sort() |
def get_row_bias(self, row_idx):
return self.__gamma_rows[row_idx]
def get_col_bias(self, col_idx):
return self.__gamma_cols[col_idx]
def get_distance(self, row_idx, col_idx, t):
z_row = self.get_position_of_row_at(i=row_idx, t=t)
z_col = self.get_position_of_column(col_idx=col_idx)
... | The code computes the likelihood of an interaction between a row and column at time `t` using a sigmoid function. It sums the row bias, column bias, and the negative distance between the row and column at time `t`, then applies the sigmoid to output a probability value. | def compute_likelihood_for(self, row_idx, col_idx, t):
return sigmoid( self.get_row_bias(row_idx) + self.get_col_bias(col_idx) - self.get_distance(row_idx, col_idx, t) ) |
def get_politican_bias(self, politician_idx):
return self.__gamma[politician_idx]
def get_bill_bias(self, bill_idx):
return self.__beta[bill_idx]
def get_distance(self, politician_idx, bill_idx, t):
z_p = self.get_position_of_politician_at(i=politician_idx, t=t)
z_b = self.get_positio... | This function calculates the likelihood of a politician supporting a bill at time t using a sigmoid function. It combines the politician's bias, the bill's bias, and the distance between them over time, returning a probability value between 0 and 1. | def compute_likelihood_for(self, politician_idx, bill_idx, t):
return sigmoid( self.get_politican_bias(politician_idx) + self.get_bill_bias(bill_idx) - self.get_distance(politician_idx, bill_idx, t) ) |
def get_row_bias(self, row_idx):
return self.__gamma_rows[row_idx]
def get_col_bias(self, col_idx):
return self.__gamma_cols[col_idx]
def get_distance(self, row_idx, col_idx, t):
z_row = self.get_position_of_row_at(i=row_idx, t=t)
z_col = self.get_position_of_column(col_idx=col_idx)
... | This function computes the likelihood of an interaction between a specific row and column at time `t` by combining their individual biases with a distance metric, then applying a sigmoid function to output a probability value between 0 and 1. | def compute_likelihood_for(self, row_idx, col_idx, t):
return sigmoid( self.get_row_bias(row_idx) + self.get_col_bias(col_idx) - self.get_distance(row_idx, col_idx, t) ) |
def set_gradients_of_latent_variables(self, index, value=True):
self.__z_rows[index].requires_grad = value
def set_gradient_of_bias_terms(self, value=True):
self.__gamma_rows.requires_grad = value
self.__gamma_cols.requires_grad = value
def forward(self, events, events_time):
return -... | The code trains a model sequentially by iterating over variables, setting gradients, using Adam optimizer, performing forward/backward passes on training batches, tracking losses, and returning training and test loss lists. It focuses on parameter updates via gradient descent for each variable and bias terms, with peri... | def learn(self, type="seq"):
# List for storing the training and testing set losses
train_loss_list, test_loss_list = [], []
# Learns the parameters sequentially
if type == "seq":
for inx in [i for i in range(1, self.__var_size + 1)] + [0]:
print("Index: {... |
def set_gradients_of_latent_variables(self, index, value=True):
self.__z_rows[index].requires_grad = value
def set_gradient_of_bias_terms(self, value=True):
self.__gamma_rows.requires_grad = value
self.__gamma_cols.requires_grad = value
def forward(self, events, col_indices, events_time):
... | This function trains a model sequentially by iterating over variables, updating parameters via gradient descent using an Adam optimizer, and tracking training losses. It processes batches of training data, computes loss, performs backpropagation, and accumulates losses per epoch. The 'seq' type specifies sequential lea... | def learn(self, type="seq"):
# List for storing the training and testing set losses
train_loss_list, test_loss_list = [], []
# Learns the parameters sequentially
if type == "seq":
for inx in [i for i in range(1, self.__var_size + 1)] + [0]:
print("Index: {... |
def set_gradients_of_latent_variables(self, index, value=True):
# self.__z_rows[index].requires_grad = value
pass
def set_gradient_of_bias_terms(self, value=True):
self.__gamma_rows.requires_grad = value
self.__gamma_cols.requires_grad = value
def forward(self, batch_events_mat, col_id... | This code trains a neural network model using sequential gradient updates. It initializes an Adam optimizer, iterates over variables to update parameters sequentially, performs forward/backward passes on training data batches, accumulates losses, and prints progress every 50 epochs. The 'seq' type enables variable-spec... | def learn(self, type="seq"):
# List for storing the training and testing set losses
train_loss_list, test_loss_list = [], []
# Define the optimizer
optimizer = torch.optim.Adam(self.parameters(), lr=self.__lr)
# Learns the parameters sequentially
if type == "seq":
... |
def set_gradients_of_latent_variables(self, index, value=True):
self.__z_p[index].requires_grad = value
def set_gradient_of_bias_terms(self, value=True):
self.__beta.requires_grad = value
self.__gamma.requires_grad = value
def forward(self, events, events_time):
neg_logLikelihood = 0.... | This code trains a model sequentially by optimizing parameters using Adam, tracking training losses over epochs, and optionally computing test losses. It iterates through variables, sets gradients, performs forward/backward passes, and appends losses. The function returns lists of training and test losses for analysis. | def learn(self, type="seq"):
# List for storing the training and testing set losses
train_loss_list, test_loss_list = [], []
# Learns the parameters sequentially
if type == "seq":
for inx in [i for i in range(1, self.__number_of_variables + 1)] + [0]:
prin... |
def write_peripheral_header(
output: PeripheralOutputStructure, peripheral: Peripheral
):
with output.header.open("w", encoding="utf-8") as f:
f.write("/**\n")
f.write("* @file\n")
try:
f.write(f"* @version {peripheral.parent.version}\n")
except AttributeError:
... | The code generates peripheral-related files by initializing a PeripheralOutputStructure, creating necessary directories, opening a header file, and writing peripheral-specific content including headers, registers, structures, and footers. | def write_peripheral(output: OutputStructure, peripheral: Peripheral):
p_out = PeripheralOutputStructure(output.output_root, peripheral)
p_out.header.parent.mkdir(parents=True, exist_ok=True)
p_out.header.open("w", encoding="utf-8")
write_peripheral_header(p_out, peripheral)
write_peripheral_registe... |
def write_header(output: OutputStructure, device: Device):
with output.main_header.open("a", encoding="utf-8") as f:
f.write("/**\n")
f.write("* @file\n")
try:
f.write(f"* @version {device.version}\n")
except AttributeError:
pass
try:
f.wri... | The main task of the code is to parse a CMSIS-SVD XML file, convert it into C header and source files for microcontroller register descriptions, and generate a JSON output. It reads the input SVD file, extracts device data, creates output directories, writes JSON and C files, and populates them with register definition... | def main(input_file: Path, output_dir: Path): # pragma: no cover
"""Generate C header and dir from CMSIS-SVD which is often used to provide register descriptions for microcontrollers"""
with input_file.open("r", encoding="utf-8") as f:
data = f.read()
svd_dict = xmltodict.parse(data)
device = ... |
def display_welcome_menu():
"""
()->None
Displays to the screen a menu with a welcome message and the three options available to the user.
Exemple:
>>> display_welcome_menu()
Welcome To The Best Pizza Place. And if you don't want pizzas we have wheels.
Please choose an option:
... | The main task of the code is to act as a menu-driven pizza calculator that displays options for special orders, formula mode, or quantity mode. It takes user input to determine which calculation method to use, executes the corresponding function, and handles invalid inputs by printing "Invalid mode." Each mode involves... | def run_pizza_calculator():
"""
()-> None
Takes no inputs and returns nothing. Displays a welcome message to the user and list of program options, asks
the user to input an option, and then calls the appropriate function. If the user inputs an invalid option,
prints out "Invalid mode.".
... |
def load_image(file_image):
"""
(str)->list<list<int/str>>
takes a filename (string) of a file as input. Checks the first line of the file. If it is 'P2',then loads in the file as a regular PGM image and
returns the image matrix. If it is 'P2C', thenloads in the file as a compressed PGM image and return... | The function `process_command` executes a sequence of image processing commands on an image matrix. It parses a string of space-separated commands, applying operations like loading, compressing, decompressing, inverting, flipping, cropping, and saving images. Each command modifies the image matrix sequentially, with th... | def process_command(string_command):
"""
(str)->None
takes a string as input corresponding to a series of space-separated image processing commands, and executes each command in turn.
Does not return anything.
>>> process_command("LOAD<comp.pgm> CP DC INV INV SAVE<comp2.pgm>")
>>> image = load_i... |
def draw_main(self,screen,inventory,stages,offset):
total_height = offset
width = (screen_width-(3*offset))//2
"""
Title, Selections and Gold, Time and Dragoons
"""
self.draw_title(stages,offset,width,total_height)
total_height += (screen_height-(2*offset)-(2*off... | The code renders different inventory interfaces based on `self.index` value. It blits the background, then calls specific drawing methods (`draw_main`, `draw_armed`, `draw_replace`) to update the inventory display. The function returns the modified inventory after rendering the appropriate UI state. | def draw(self,screen,inventory,stages,offset):
self.image.blit(self.bg,self.rect)
#If index is 0 or 1 draw main but with items opened else draw the rest
if self.index == 0 or self.index == 2:
inventory = self.draw_main(screen, inventory, stages,offset)
elif self.index == 3:
... |
def entrance_collision(self):
for x in self.stages.current_exits:
rect = Rect(x[0],x[1],x[2],x[3])
if rect.colliderect(self.stages.player.rect):
self.stages.update_stage_level(x[4],x[5],x[6],x[7])
if x[4]==-1 or x[4]==-2:
self.state = x... | The function `check_all_collisions` manages collision checks in a game by updating the player's position within boundaries, updating NPCs, and detecting interactions such as entrance triggers, boundary transitions, combat encounters, and chest openings. It ensures proper player-NPC-environment interactions, maintaining... | def check_all_collisions(self,screen):
boundary = self.stages.boundaries[self.stages.level][self.stages.boundary_index]
self.stages.player.rect.clamp_ip(pygame.display.get_surface().get_rect())
self.stages.player.update(boundary)
for npc in self.stages.npc_list:
npc.updat... |
def display_menu(self,screen):
clock = pygame.time.Clock()
running = True
self.menu.equipment_index = 0
self.menu.item_menu = False
self.menu.player_selected = None
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
... | This function manages a game stage loop, handling player input for movement, collision checks, NPC dialogue triggers, and rendering. It processes events like quitting, key presses for directional control, and menu access. The loop updates the screen, checks for level progression, and maintains game state until the stag... | def display_stage(self,screen):
clock = pygame.time.Clock()
running = True
#Break if exit goes into a cutscene maybe use -1 and then update the level.
display_npc_dialogs = None
npc_index = -1
previous_entry = False
space_released = False
while running:
... |
def _neuron_locations(m, n):
"""
iterator function that yields positions of SOM units.
"""
for i in range(m):
for j in range(n):
yield np.array([i, j])
def get_bmu_location(self, vect_input):
"""
This will extract the location of the BMU based ... | This code initializes a Self-Organizing Map (SOM) in TensorFlow, setting up parameters like grid dimensions, learning rate (alpha), and neighborhood radius (sigma). It constructs placeholders for input data and iteration counts, computes the Best Matching Unit (BMU), and defines the training operation to update neuron ... | def __init__(self, m, n, dim, c=1.0, n_iterations=10, n_episodes=100, alpha=None, sigma=None):
"""
Initializes all necessary components of the TensorFlow
Graph.
m X n are the dimensions of the SOM. 'n_iterations' should
should be an integer denoting the number of iterations unde... |
def move(self, _from, _to):
"""
takes _to and _from as a (let, num) tuple
"""
color = self.board[_from[0]][_from[1]][1]
if not self.canMove(_from, _to):
self.drawBoard()
print(_from, _to)
raise Exception ('Can\'t move here')
self.board[... | This function implements an AI's turn in a game by using the Minimax algorithm with a specified search depth to determine optimal moves and builds. It retrieves a strategy (move and build actions) from the MinMax result, executes the move, checks for a win/loss condition, and performs the build if applicable. It return... | def minmaxer_turn(self, depth=2):
"""
This function is a standin for the doAITurn() function that handles the automatic gameplay of the AI (as said
method is implemented for seperate move and build functions). The **DEPTH** parameter determines the size of tree
search, passed to the Min... |
def isDone(self):
### Check if any player has achieved victory.
### Used as a stopping criterion in several functions.
for row in self.board:
for col in self.board[row]:
if self.board[row][col][0] == 3 and self.board[row][col][1]:
return True
... | This heuristic evaluates game states by prioritizing the agent's high elevation and surrounding building heights, while minimizing the opponent's elevation. It calculates a score based on pawn heights, adjacent space heights (with special emphasis on height 3), and adjusts values depending on whether the pawn belongs t... | def pawn_height_proximity_value(self):
"""
Heuristic function that evaluates game states.
Favors situations where agent is standing as high as possible, surrounded
by buildings that are as high as possible, while the oponnent is as low as possible.
"""
winning_state = BI... |
def setupBlankBoard():
empty_space = (0, None)
board = {}
row = {}
for i in range(1, 6):
row.update({i : empty_space})
for letter in ['A', 'B', 'C', 'D', 'E']:
board.update({letter : row.copy()})
return board
def BlankPawnDict():
return {'W' : [], 'B' : []}
def wipe(self):
... | This code initializes a game state for a board game, setting up a new board or reusing an existing one. It determines the current player's turn, initializes pawn positions, and prepares for MinMax algorithm by evaluating the board state. The 'new' parameter controls whether to reset the board, while 'turn' sets the act... | def __init__(self, new=True, board=None, turn=0):
if new:
##Ensures that the board resets only if initializing new class
##(More santorini objects are initialized in the tree search for minmax)
self.board = setupBlankBoard()
self.pawns = BlankPawnDict()
... |
def load_points(self):
gpx = gpxpy.parse(open(self.fn))
return self.parse_points(gpx)
def add_smooth_elevation(self):
"""
add smoothed elevation to points
"""
elevations_smooth = savgol_filter([point.elevation for point in self.points], 101, 2)
for point, elevati... | The code processes elevation data by loading points, smoothing them with Savitzky-Golay, detecting peaks/valleys, and reducing complexity via Douglas-Peucker algorithm to simplify the dataset while preserving key features. | def __init__(self, fn, speed, min_size_peak):
self.fn = fn
self.avg_speed = speed
self.min_size_peak = min_size_peak
self.points = self.load_points()
# smoothen elevation with savitzky-golay
self.add_smooth_elevation()
# get hills, valleys
# https://stac... |
def get_summary(self):
""" get summary of track as string """
# print(sum([p[1].elevation - p[0].elevation for p in zip(self.points[1:], self.points) if p[1].elevation > p[0].elevation]))
# should return ~449m
# from scipy.ndimage import gaussian_filter1d
# choosing sigma, trun... | The main task of the code is to generate a multi-panel visualization of GPS track data, plotting elevation profiles, track routes, and optionally speed data. It extracts summary statistics, converts data to TCX format, and displays subplots with labels and titles. The plot dynamically adjusts to include speed data if a... | def plot(self):
# Gpxify.print_status("Hello")
summary = self.get_summary()
print(summary)
print(self.get_peaks_summary())
self.to_tcx()
has_speed = True if self.points[0].speed else False
fig, ax = plt.subplots(figsize=(20, 10), nrows=1, ncols=3 if has_speed e... |
def section_header(text):
log()
time = get_timestamp()
time_str = dim('(' + time + ')')
header = bold_yellow_underline(text)
print(header + ' ' + time_str, file=sys.stderr, flush=True)
def log(message='', end='\n'):
print(message, file=sys.stderr, flush=True, end=end)
def load_fasta(fasta_filena... | The main task of the code is to load two FASTA assembly files, verify they contain the same number of sequences, check for zero-length sequences, and ensure corresponding sequences between assemblies have lengths within a 10% ratio. It logs sequence details and exits with errors if validations fail, returning the valid... | def load_assemblies(assembly_1_filename, assembly_2_filename):
section_header('Loading assemblies')
log(assembly_1_filename)
assembly_1 = load_fasta(assembly_1_filename)
for name, seq in assembly_1:
log(f' {name}: {len(seq):,} bp')
log()
log(assembly_2_filename)
assembly_2 = load_fa... |
def log(message='', end='\n'):
print(message, file=sys.stderr, flush=True, end=end)
def get_aligned_seqs(assembly_1_seq, assembly_2_seq, aligner):
cigar = get_cigar(assembly_1_seq, assembly_2_seq, aligner)
expanded_cigar = get_expanded_cigar(cigar)
i, j = 0, 0
assembly_1_aligned, assembly_2_aligned,... | The function `output_differences` aligns two DNA sequences using a specified aligner, identifies differences between them, and formats these differences for display. It logs alignment details, groups differences into ranges (with optional padding/merging), converts alignment positions to original sequence coordinates, ... | def output_differences(assembly_1_name, assembly_1_seq, assembly_2_name, assembly_2_seq, padding, merge,
longest_label, aligner):
log(f'Aligning {assembly_1_name} to {assembly_2_name}:')
assembly_1_aligned, assembly_2_aligned, differences, assembly_1_pos, assembly_2_pos, diff_pos = \
... |
def section_header(text):
log()
time = get_timestamp()
time_str = dim('(' + time + ')')
header = bold_yellow_underline(text)
print(header + ' ' + time_str, file=sys.stderr, flush=True)
def get_longest_label(assembly_1, assembly_2):
longest_name, longest_seq = 0, 0
for name, seq in assembly_1... | The function `align_sequences` aligns sequences from two assemblies using a specified aligner, compares them to highlight differences, and formats the output with padding and merging options. It identifies the longest sequence label for consistent alignment, iterates through paired sequences from both assemblies, and u... | def align_sequences(assembly_1, assembly_2, padding, merge, aligner):
section_header('Aligning sequences')
longest_label = get_longest_label(assembly_1, assembly_2)
for b, a in zip(assembly_1, assembly_2):
assembly_1_name, assembly_1_seq = b
assembly_2_name, assembly_2_seq = a
output... |
def create_cycles_material(context, sliceName, img_spec):
image = img_spec
image.alpha_mode = "STRAIGHT" #or NONE
name_compat = sliceName
material = None
for mat in bpy.data.materials:
if mat.name == name_compat:
material = mat
if not material:
material = bpy.data.mat... | This function updates a 3D model's texture and geometry in real-time using incoming image data. It parses image dimensions, creates/updates a Blender material, adjusts mesh size if mismatched with the image plane, and sends updates to a slicer. The code ensures the model's mesh dimensions align with the provided image'... | def live_img_update(image):
sliceName, modelName, image_dim, plane_dim, image_np = image.split("_BREAK_")
image_dim = eval(image_dim)
plane_dim = eval(plane_dim)
image_w, image_h = image_dim[0], image_dim[1]
plane_w, plane_h = plane_dim[0], plane_dim[1]
image_np = eval(image_np)
#print(image... |
def create_puz(N):
global PUZZLE_SIZE
PUZZLE_SIZE = N
arr = numpy.arange(1, PUZZLE_SIZE * PUZZLE_SIZE + 1)
arr[PUZZLE_SIZE * PUZZLE_SIZE - 1] = 0
blank = PUZZLE_SIZE * PUZZLE_SIZE - 1
return arr.reshape(PUZZLE_SIZE, PUZZLE_SIZE), blank
def scramble_puz(puzzle, scramble):
blank = PUZZLE_SIZE ... | The code generates a sequence of images representing each move of a scrambled puzzle, compiles them into a video using ffmpeg, adjusts playback speed based on TPS, and cleans up temporary files. It creates puzzle states, renders SVG to PNG frames, and exports a smoothed video with specified resolution and speed adjustm... | def generateImages(scramble, moves, tps):
lens = [0, 0, 0, 17, 37, 64, 97, 136, 181, 232, 289]
mypuz, blank = create_puz(lens.index(len(scramble)))
mypuz, blank = scramble_puz(mypuz, scramble)
try:
shutil.rmtree("images")
except FileNotFoundError as e:
print("Old image folder was not... |
def create_puz(N):
global PUZZLE_SIZE
PUZZLE_SIZE = N
arr = numpy.arange(1, PUZZLE_SIZE * PUZZLE_SIZE + 1)
arr[PUZZLE_SIZE * PUZZLE_SIZE - 1] = 0
blank = PUZZLE_SIZE * PUZZLE_SIZE - 1
return arr.reshape(PUZZLE_SIZE, PUZZLE_SIZE), blank
def scramble_puz(puzzle, scramble):
blank = PUZZLE_SIZE ... | The main task of the code is to simulate solving a scrambled puzzle by applying each move in the provided solution step-by-step. It initializes a puzzle, scrambles it, processes the solution, and prints the puzzle's state after each move in the solution to visualize the solving process. | def getStates(scramble, solution):
mypuz, blank = create_puz(6)
mypuz, blank = scramble_puz(mypuz, scramble)
solution = badsolutionfix(solution)
print(solution)
print(toScramble(mypuz))
for move in list(solution):
mypuz, blank = doMoves(mypuz, blank, move)
print(toScramble(mypuz)... |
def getFrameCount(moves, fps):
msPerFrame = 1000/fps
lastMs = 0
counts = []
msArray = []
for id, item in enumerate(moves):
timing=int(item)
counter = 0
ms = msPerFrame
numberMs=0
while ms < timing-lastMs:
ms += msPerFrame
numberMs += ms... | The code reads puzzle movement data from a file, processes frame counts, generates images for each move step, and compiles them into a video using ffmpeg, simulating a puzzle-solving animation. | def movetimes():
with open("movetimes.txt", 'r') as file:
mymoves = file.readlines()
for id, i in enumerate(mymoves):
mymoves[id] = i.replace("\n", "")
FPS = int(mymoves[0])
scramble = mymoves[1]
moves = mymoves[2]
mymoves.pop(0)
mymoves.pop(0)
mymoves.pop(0)
frameCou... |
def create_puz(N):
global PUZZLE_SIZE
PUZZLE_SIZE = N
arr = numpy.arange(1, PUZZLE_SIZE * PUZZLE_SIZE + 1)
arr[PUZZLE_SIZE * PUZZLE_SIZE - 1] = 0
blank = PUZZLE_SIZE * PUZZLE_SIZE - 1
return arr.reshape(PUZZLE_SIZE, PUZZLE_SIZE), blank
def scramble_puz(puzzle, scramble):
blank = PUZZLE_SIZE ... | The code generates a video of a puzzle being solved step-by-step from a scramble. It creates SVG images for each move, converts them to PNGs, compiles them into an MP4 using ffmpeg, adjusts playback speed based on TPS, and cleans up temporary files. | def generateImages(scramble, moves, tps):
lens = [0, 0, 0, 17, 37, 64, 97, 136, 181, 232, 289]
mypuz, blank = create_puz(lens.index(len(scramble)))
mypuz, blank = scramble_puz(mypuz, scramble)
try:
shutil.rmtree("images")
except FileNotFoundError as e:
print("Old image folder was not... |
def evaluateFitness(self, lineup):
return sum([float(player._fitness_score) for player in lineup])
def performSelection(self, population):
selected_population = population[:10]
return selected_population
def createChildren(self, selected_population):
parents = [player for lineup in selec... | The function recursively evolves a population over generations by selecting high-fitness individuals, generating offspring, adding random members, and repeating until the specified generation count is reached, aiming to iteratively improve the population through genetic algorithm principles. | def performGeneration(self, generation_count, population):
if(generation_count == 0):
return population
sorted_population = sorted(population, key=lambda lineup: self.evaluateFitness(lineup), reverse=True)
selected_population = self.performSelection(sorted_population)
childre... |
def calc_new_position(game_obj, axis):
old_pos = game_obj.get_location()[axis]
if axis == X_AXIS:
return Screen.SCREEN_MIN_X + (old_pos + game_obj.get_speed()[axis] - Screen.SCREEN_MIN_X) % DELTA[axis]
if axis == Y_AXIS:
return Screen.SCREEN_MIN_Y + (old_pos + game_obj.get_speed()[axis] - Sc... | The main task of the code is to manage the game loop by updating the spaceship's position, handling user input for movement and torpedo firing, drawing and updating torpedos and asteroids, checking collisions between game elements, and determining win/loss conditions or game exit. It ensures real-time game state render... | def _game_loop(self):
self.__screen.draw_ship(self.__main_ship.get_location()[0],
self.__main_ship.get_location()[1],
self.__main_ship.get_direction())
self.__main_ship.set_location((calc_new_position(self.__main_ship, X_AXIS),
... |
def productive(g: Grammar) -> set[NonTerm]:
return _productive_0(set(), g)
def shrink(g: Grammar, p: set[NonTerm]) -> Grammar:
new_rules = { n : shrink_rules(rules, p) for n, rules in g.rules() if n in p }
return Grammar(g.start, new_rules)
def reachable(g: Grammar) -> set[NonTerm]:
return _reachable_0(... | The main task of the code is to preprocess a grammar by iteratively removing unproductive and unreachable symbols. It first identifies productive symbols (those generating terminal strings), shrinks the grammar using them, then finds reachable symbols in the reduced grammar and shrinks again. The result is a simplified... | def preprocess(g: Grammar) -> Grammar:
p = productive(g)
g1 = shrink(g, p)
r = reachable(g1)
g2 = shrink(g1, r)
return g |
def getInput(self, index, allowEnd=True):
if allowEnd and index == len(self.parseInput):
return self.grammar.end
elif index >= 0 and index < len(self.parseInput):
return self.parseInput[index]
else:
raise ValueError(f"GLLParser.getInput() index invalid")
def c... | This function processes parsing steps by iterating through a working set of descriptors, handling non-terminal and terminal symbols according to a grammar. It updates parsing state, prunes invalid paths, and manages call/return operations, returning the updated working set size after processing up to 'steps' iterations... | def continueParse(self, steps=-1):
# while more work to do and steps remaining
while len(self.workingSet) > 0 and steps != 0:
if steps > 0: steps -= 1
# grab descriptor
desc = self.workingSet.pop()
slot, callIndex, index = desc.slot, desc.callIndex, desc.... |
def preprocess(g: Grammar) -> Grammar:
p = productive(g)
g1 = shrink(g, p)
r = reachable(g1)
g2 = shrink(g1, r)
return g
def buildFirst(g: Grammar) -> dict[NonTerm, set[PseudoTerm]]:
return _buildFirst0(defaultdict(set), g)
def buildFollow(g: Grammar, first: set[PseudoTerm], end=Term("$")):
... | The code initializes a parser component by preprocessing a grammar, computing FIRST and FOLLOW sets for LL(1) parsing, and storing the end-of-input symbol. It processes the grammar to build essential data structures for determining valid production rules during parsing, using the provided grammar and an optional end ma... | def __init__(self, grammar: Grammar, end=Term("$")):
self.grammar = preprocess(grammar)
self.firstMap = buildFirst(self.grammar)
self.followMap = buildFollow(self.grammar, self.firstMap, end)
self.end = end |
def learn(self, batch_data, expected_outputs, learnRate):
for data_idx, data in enumerate(batch_data):
self.updateAllGradients(data, expected_outputs[data_idx])
#store and print the train accuracy and cost of the learning data to see if the network is improving
#---------------... | The code converts labels into one-hot encoded vectors for classification tasks (digits 0-9) and routes data through different modes: training (`learn`), testing (`test`), visualizing test results (`viewtest` with accuracy display and image plotting), or self-testing (`selftest` for user-drawn inputs without visualizati... | def run(self, mode, data, labels, learnRate=0.01):
expected_outputs = np.zeros((len(data), 10))
for idx, label in enumerate(labels):
if label==0:
expected_outputs[idx] = np.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0])
elif label==1:
expe... |
def _build_proto_srcs_commands(self):
commands = self._build_common_commands()
commands.append('//mediapipe_api:mediapipe_proto_srcs')
return commands
def _build_proto_dlls_commands(self):
return ['nuget', 'install', '-o', _NUGET_PATH, '-Source', 'https://api.nuget.org/v3/index.json']
def _build_resourc... | The code builds and installs MediaPipe components by compiling protobuf sources, downloading DLLs, handling platform-specific native libraries (Desktop/Android/iOS), and copying resources. It uses Bazel for builds, unzips assets, and conditionally executes tasks based on command-line arguments like resources, desktop, ... | def run(self):
self.console.info('Building protobuf sources...')
self._run_command(self._build_proto_srcs_commands())
self._unzip(
os.path.join(_BAZEL_BIN_PATH, 'mediapipe_api', 'mediapipe_proto_srcs.zip'),
os.path.join(_BUILD_RUNTIME_PATH, 'Scripts', 'Protobuf'))
self.console.info('Built pr... |
def print_instructions():
'''Prints the rules of the game'''
instruction = "----------Instruction----------\nYou have 2 players and each player has a chance to roll a die. If a player rolls any numbers except for 6, those numbers are added to your final score. If a player rolls a 6, then the total score f... | The code implements a turn-based game where a human and computer player alternately score points. It initializes scores, prompts the user to start, and loops through turns where each player's move updates their score. The game checks after each turn if the game is over, displays the final results, and terminates when t... | def main():
print_instructions()
#set initial scores
human_score = 0
computer_score = 0
input('Ready to play? (press any key) ')
game_running = True
while game_running:
#total computer score
won_points_computer = computer_move(computer_score, human_score)
computer... |
def validate(key, validator_conf, test_conf):
'''Validate a specific key'''
if check_missing(key, validator_conf, test_conf):
return True
if check_type(key, validator_conf, test_conf):
return True
if 'validator' in validator_conf[key] and validator_conf[key]['val... | This function recursively validates the structure of `instance_conf` against `validator_conf`, checking each key and nested configurations. It reports validation errors with their hierarchical paths using `parent_keys`, and returns a boolean indicating if any errors were found. | def validate_conf(validator_conf, instance_conf, parent_keys=[]):
'''Validate enire config'''
error = False
for key in validator_conf:
tmp_error = validate(key, validator_conf, instance_conf)
error |= tmp_error
if tmp_error:
eprint('\tFor key: ... |
def media_list_clear(media_list):
'''Removes all vlc.Media from a vlc.MediaList'''
while media_list.count() > 0:
media_list.remove_index(0)
def audio_file_dir_walk(directory, allowed_file_extensions={'mp3','wav'}):
'''VLC 3 does not auto-expand directories in media isntances.
This function walk... | This function sets or appends a playlist to a VLC media list. It clears existing entries if not appending, adds media files from a directory (or single file), flattens the list, applies shuffling if enabled, and optionally plays the first item via the media player. | def modify_media_list(mrl, media_list, media_player, shuffle=True, append=False, switch_current=False):
'''For setting a new playlist to a vlc.MediaList, or appending to it.
Shuffle is enabled by default.'''
if not append:
media_list_clear(media_list)
if os.path.isdir(mrl):
list_of_medi... |
def get_group_list():
if not os.path.isfile('group_list.json'):
print('No group_list.json found.')
print('Generating group_list.')
group_list = generate_group_list()
write_group_list(group_list)
else:
print('Reading group_list.json from file.')
group_list = read_g... | The code processes command-line arguments to either generate text models from user messages, combine multiple models into one, or generate text from existing models. It retrieves group/user data, builds individual models, combines them if specified, and outputs results or saves combined models while cleaning up tempora... | def main():
if len(sys.argv) == 1:
group_list = get_group_list()
message_list = get_message_list(group_list)
print(len(message_list))
user_list = get_user_list(message_list)
for user in user_list:
get_user_model(user, user_list[user]['message_list'])
elif sys.... |
def show_circle(self, coords, text):
x, y, r = coords
self.canvas.create_oval(x-r, y-r, x+r, y+r, outline="#f11", width=2, tags="state")
self.canvas.create_text(x, y, text=text, fill="#f11", font=("Arial", 24), tags="state")
#print(f"circle shown at {x}, {y}")
return
def... | This code handles mouse click events to manage a state machine diagram by adding/removing states, transitions, and setting initial/final states. It checks the current command state (`AddState`, `RmState`, etc.) to determine actions like drawing circles, removing elements, or updating transitions between states based on... | def mouse_click_1(self, event):
print(f"clicked at {event.x}, {event.y}")
if self.command_state == "AddState":
self.show_circle((event.x, event.y, 30), f"S{len(self.circles_holder)}")
self.circles_holder.append((event.x, event.y, 30))
elif self.command_state == "RmState"... |
def setup():
pg.display.init()
pg.font.init() #initializes the font module
pg.event.get()
display = pg.display.set_mode((display_x, display_y))
display.fill((10, 10, 10))
pg.display.set_caption('Tetris')
clock = pg.time.Clock()
#S... | The code implements a game loop for a falling block game. It initializes display/clock, manages a grid, and spawns figures. The loop checks for collisions when spawning new figures; if a collision occurs, the game exits. The counter_tick tracks game progression, and the loop continues until a figure cannot spawn due to... | def main():
display, clock = setup()
counter_tick = 0
figure = new_figure()
static_grid = [[0 for x in range(count_sqr_x)] #2d grid used for drawing
for y in range(count_sqr_y)] #static figures
while True: ... |
def buildMaxHeap(A):
A.heapLength = len(A)
for i in range((len(A) - 1) // 2, - 1, - 1):
maxHeapify(A, i)
def swap(A, a, b):
A[a], A[b] = A[b], A[a]
def maxHeapify(A, i):
l = left(i)
r = right(i)
if l < A.heapLength and A[l] > A[i]:
largest = l
else:
largest = i
if... | The code implements the heapsort algorithm by first building a max heap from the array, then repeatedly extracting the maximum element (root) and placing it at the end of the array, reducing the heap size each time, and restoring the heap property through maxHeapify. The main task is to sort the array in ascending orde... | def heapsort(A):
buildMaxHeap(A)
for i in range(A.heapLength - 1, 0, -1):
swap(A, 0, i)
A.heapLength = A.heapLength - 1
maxHeapify(A, 0) |
def calculate_p(cc):
"""
Calculates what percentage of the chords are longer than sqrt(3).
Parameters
----------
cc : numpy.ndarray of shape (-1, 2, 2)
List of coordinates of the endpoints of chords.
Returns
-------
P : float
Percentage of chords longer than sqrt(3).
""... | The main task of the code is to run multiple simulations of the Bertrand paradox using three different chord generation methods. It generates `n` random chords for each method, calculates their probabilities, and visualizes the results by plotting chord distributions and midpoints with distinct colors. The code compare... | def main() -> None:
n = int(sys.argv[1])
fs = [bertrand_1, bertrand_2, bertrand_3]
cs = ['#99004D', '#003CB3', '#226600']
for f, c in zip(fs, cs):
cc = np.array([f() for _ in range(n)]).reshape((-1, 2, 2))
P = calculate_p(cc)
plot_chords(f, cc, c, P)
plot_midpoints(f, cc... |
def read_input(file_name: str) -> list[str]:
with open(file_name, "r") as myfile:
lines = [line.strip() for line in myfile]
return lines
def transform_lines_to_nodes(lines: list) -> list[Node]:
return [transform_line_to_node(line) for line in lines if "=" in line]
def find_offset_and_loop_length(
... | The code processes input data to model nodes, identifies a starting node, and calculates the number of directions needed to navigate through a loop using given instructions, then outputs key details about the traversal path and loop length. | def part2():
lines = read_input("input_files/input_day_8.txt")
nodes_list = transform_lines_to_nodes(lines)
instructions = lines[0]
starting_node = next(item for item in nodes_list if item.value.startswith("A"))
print(f"{starting_node=}")
node, number_of_directions = find_offset_and_loop_length(... |
def generate_request_token(self, callback=None):
# for oauth1 only
if callback is not None:
callback = urljoin(request.url, callback)
client = self.make_client()
client.callback_uri = _encode(callback, self.encoding)
uri, headers, _ = client.sign(
self.ex... | The function generates an authorization URL for OAuth authentication, either using a request token (OAuth1) or OAuth2. It constructs a redirect URL with necessary parameters like the token or callback, handles scope encoding, and stores the callback in the session. The function returns a redirect response to the author... | def authorize(self, callback=None):
"""
Returns a redirect response to the remote authorization URL with
the signed callback given.
"""
if self.request_token_url:
token = self.generate_request_token(callback)[0]
url = '%s?oauth_token=%s' % (
... |
def handle_oauth1_response(self):
"""Handles an oauth1 authorization response."""
client = self.make_client()
client.verifier = request.args.get('oauth_verifier')
tup = session.get('%s_oauthtok' % self.name)
client.resource_owner_key = tup[0]
client.resource_owner_secret ... | This function handles OAuth response callbacks by checking request arguments for 'oauth_verifier' (OAuth1) or 'code' (OAuth2), then invokes the corresponding handler to process the response. It removes temporary session keys related to the OAuth flow and passes the processed data to the wrapped function along with orig... | def decorated(*args, **kwargs):
if 'oauth_verifier' in request.args:
data = self.handle_oauth1_response()
elif 'code' in request.args:
data = self.handle_oauth2_response()
else:
data = self.handle_unknown_response()
# free ... |
def draw_rounded_rect(surface, rect, color, corner_radius):
''' Draw a rectangle with rounded corners.
Would prefer this:
pygame.draw.rect(surface, color, rect, border_radius=corner_radius)
but this option is not yet supported in my version of pygame so do it ourselves.
We use anti-aliased cir... | This function handles button interactions in a Pygame application, detecting mouse hover/clicks on "Start," "How to Play," and "Purpose" buttons. It transitions to gameplay, displays instructional text, and manages return-to-home functionality via fade effects and dynamic UI updates, ensuring responsive navigation betw... | def buttonInteractions(screen):
mouse = pygame.mouse.get_pos() #get coordinates of mouse
# if x-pos + width > .... > x-pos and y-pos + height > ... >y-pos
#start screen button interactions
if ((225 + 350) > mouse[0] > 225 ) and ((180 + 110) > mouse[1] > 180):
start_button = pygame.Rect... |
def determine_most_common_target_label(self, data_target):
histogram = {}
for target_label in data_target:
if target_label in histogram:
histogram[target_label] += 1
else:
histogram[target_label] = 1
most_common_target_label = None
... | This function recursively builds a decision tree by selecting the optimal feature-threshold split, partitioning data, and creating nodes. It halts when max depth is reached, samples are insufficient, or all targets are uniform, returning a leaf node with the most common label. Otherwise, it splits data, recursively gro... | def grow_tree(self, data, data_target, depth=0):
number_of_samples, number_of_features = data.shape
number_of_target_labels = len(np.unique(data_target))
if depth >= self.max_depth or number_of_samples < self.min_samples_for_split or number_of_target_labels == 1:
return Node("Leaf",... |
def population_examination(changes):
global individuals
for i in range(0, len(individuals)):
v = [0] * n
for j in range(0, n):
r_individual = individual_generator()
sz_individual = random.randint(0, len(individuals)-1)
v[j] = individuals[i][j] ^ (r_individual... | The code evolves a population of individuals over 100 iterations, replacing unchanged individuals every 10 steps with new ones. It then identifies the individual with the highest fitness value, converts it to integers, and returns the best solution along with its fitness score. | def population_generator():
changes = [0] * len(individuals)
for i in range(0,100):
population_examination(changes)
if (i % 10 == 0):
for i in range (0, len(individuals)):
if (changes[i] == 0):
individuals[i] = individual_generator()
max_value... |
def input_from_file():
f = open("input1.txt")
knapsack_weight = int(f.readline())
weights = f.readline()
values = f.readline()
weights = list(map(int, weights.split()))
values = list(map(int, values.split()))
weights = list(map(int, weights))
f.close()
return knapsack_weight, weights... | The main task of the code is to solve a knapsack problem using a genetic algorithm. It reads problem parameters from a file, initializes a population of potential solutions, evolves the population to find the optimal solution, and returns the best solution along with its fitness value. | def main():
global knapsack_weight, weights, values, n, individuals
knapsack_weight, weights, values, n = input_from_file()
individuals = initialise_population(n)
best_solution, best_fitness = population_generator()
return best_solution, best_fitness |
def beolvasas():
f = open("input1.txt")
knapsack_weight = int(f.readline())
weights = f.readline()
values = f.readline()
weights = list(map(int, weights.split()))
values = list(map(int, values.split()))
return knapsack_weight, weights, values, len(weights)
def initialise_population(n):
i... | The code defines a `main()` function that solves a knapsack problem using a genetic algorithm. It reads input data (knapsack capacity, item weights, values, and count), initializes a population of potential solutions, and identifies the best individual (solution) along with its fitness value. The function returns the o... | def main():
global knapsack_weight, weights, values, n, individuals
knapsack_weight, weights, values, n = beolvasas()
individuals = initialise_population(n)
best_solution, best_fitness = population_generator()
return best_solution, best_fitness |
def successful(self):
if self.skip_environment_check:
return True
return self.check_os()
def check_cuda_devices_available(self):
if self.skip_environment_check:
return 0
if not self._check_package_installed("torch"):
return 0
with multiprocessi... | This function generates a warning message based on system requirements and configurations. It checks if the machine meets minimal criteria (Linux/Python 3), verifies CUDA availability and memory sufficiency, and assesses internet bandwidth. Warnings are appended for missing CUDA support, inadequate memory, or low bandw... | def set_warning_message(self):
warning = ""
if not self.successful():
warning += "Your machine does not support the minimal requirements (Requires Linux and Python 3)."
if self.successful():
if not self.check_cuda_devices_available():
warning += (
... |
def sort_bunch(user_query_list, sortcol, direction):
final_sorted_doc = {}
uqlupper = list(map(str.upper, user_query_list))
agglist = ["TOTALNUM", "SUM", "MEAN", "MIN", "MAX"]
agg_present = not set(agglist).isdisjoint(set(uqlupper))
if agg_present:
which_agg = tuple(set(agglist).intersection... | The main task of the code is to sort data based on user queries with specified sorting nodes, direction (ASC/DESC), and strategies (BUNCH/MERGE). It processes the query list, identifies sorting parameters, handles aggregation flags, and applies sorting logic either within or between data chunks, returning a structured ... | def sort(user_query_list):
sorted_dict = {}
uqlupper = list(map(str.upper, user_query_list))
aggset = {"SUM", "MEAN", "MIN", "MAX", "TOTALNUM"}
sortnode = user_query_list[uqlupper.index("SORT") + 1]
direction = None
if "ASC" in uqlupper:
direction = "ASC"
elif "DESC" in uqlupper:
... |
def bunch_agg(user_query_list, doc):
uqlupper = list(map(str.upper, user_query_list))
agg_list = ["SUM", "TOTALNUM", "MEAN", "MIN", "MAX"]
agg_func = (set(agg_list).intersection(set(uqlupper)).pop()).lower()
bunchkey = user_query_list[uqlupper.index("BUNCH") + 1]
unique_bunchkey_list = []
nodes_... | The code processes a JSON document by applying aggregation, sorting, merging, and node-based structuring operations based on user query keywords, then outputs the result and cleans up temporary files. | def fetch(user_query_list):
with open("./" + user_query_list[0] + "_chunks/" + user_query_list[0] + "_chunk1.json", "r") as docread:
doc = json.load(docread)
doc = json.dumps(doc, indent=1)
agglist = ["TOTALNUM", "SUM", "MEAN", "MIN", "MAX"]
uqlupper = list(map(str.upper, user_query_list))
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.