dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def encode_date(date_repr):
"""Encode a date"""
if isinstance(date_repr, date):
return date_repr.strftime("%Y-%m-%d")
return date_repr
def encode_decimal(value):
"""Encode a decimal value"""
return str(value)
def get_transaction(conn, tx_id):
"""Get a transaction by id"""
qry = """
... | This function inserts a new transaction into a database, using provided or default values for fields like date, account name, amount, and description. It executes an SQL INSERT statement with parameterized queries, encodes date and decimal values, retrieves the inserted record's ID, commits the transaction, and returns... | def add_transaction(conn, transaction):
"""Add a transaction"""
today = date.today()
tx_date = transaction.get("date", today)
qry = """
INSERT INTO transactions (
member_id,
date,
account_name,
amount,
description
) VALUES ( ?, ?, ?, ?, ... |
def gen_comute_avg_speed(data, output):
data = data.groupBy(["PUborough", "DOborough"]).agg(F.avg("speed"))
data = data.toPandas()
data.to_csv(output + '/borough_speed')
def gen_commute_total_freq(data, output):
data = data.groupBy(["PUborough", "DOborough"]).count()
data = data.toPandas()
data.to_csv(output + '/... | The code processes trip data by joining it with location data to add pickup and drop-off boroughs. It then generates average commute speed metrics, total commute frequency, and creates a histogram from input2, outputting results to specified paths. | def main(inputs, input2, output):
#generate pickup and dropoff borough column
data, loc_data = read_ETL(inputs, output)
loc_data = loc_data.select("LocationID", "borough")
data = data.alias('a').join(loc_data.alias('b'), data["PULocationID"] == loc_data["LocationID"])
data = data.withColumnRenamed("borough", "PUbo... |
def train_model_with_hp(model,hyperparameters,X_train,y_train):
if model == 'rf':
model = train_random_forest_model_with_hp(hyperparameters,X_train,y_train)
# elif model == 'gbm':
# model = train_gradient_boost_model_with_hp(hyperparameters,X_train,y_train)
return model
def get_model_po... | The code runs a machine learning experiment using specified hyperparameters, trains a model, and evaluates it across multiple out-of-sample scenarios. It iterates through scenarios, loads JSON data, generates predictions, and saves results with timestamps. The function prints setup details, scenario progress, and total... | def run_hp_experiment(m, hp, X_train, X_test, y_train,n_oos,n_scenarios,y_scaler):
print(f"\n=== starting experiment with {m} model ===")
print(f"--- number of scenarios {n_scenarios} ---")
print(f"--- n_estimators {hp['n_estimators']} ---")
print(f"--- max_depth {hp['max_depth']} ---")
print(f"--- ... |
def select_unassigned_var(self, csp, assignment):
# Choose the variable with the fewest legal values
if self.run_MRV == True:
return self.MRV()
# Choose the variable with most constraints
elif self.run_degree == True:
return self.degree(csp, self.domains... | This function implements backtracking search for solving Constraint Satisfaction Problems (CSPs) with AC-3 consistency checking. It recursively selects unassigned variables, assigns values, checks consistency, and applies AC-3 to prune domains. If AC-3 detects a solution, it returns the assignment. Otherwise, it backtr... | def rec_backtracking(self, assignment, csp):
self.num_calls += 1
# self.depth += 1
# if assignment is complete return assignment
if csp.goal_test(assignment):
return assignment
var = self.select_unassigned_var(csp, assignment)
# print("selected ", var, flus... |
def _lin_coef(self, dist):
# return the damage coeficient in the drop off range using linear model
grad = ((self._dam_prof[1][1] - self._dam_prof[0][1])
/ (self._dam_prof[1][0] - self._dam_prof[0][0]))
return grad * (dist - self._dam_prof[0][0]) + 1
def _bez_coef(self, dist, bez_... | This function calculates and returns a damage coefficient based on distance and a specified model type (linear, cubic, or bezier). It uses different internal methods (_lin_coef, _cubic_coef, or _bez_coef) depending on the model, defaulting to bezier if the input model is unrecognized. The coefficient represents weapon ... | def _falloff_coef(self, dist, model='cub',
bez_exprs={}, offset=0.15):
# Return the damage coefficient for a distance within the falloff range
# of weapons based on the given damage model
if model == 'lin':
coef = self._lin_coef(dist)
elif model == 'bez'... |
def swap_barrel(self, attachment):
"""Swap the gun's current barrel out for the given one.
attachment - class object, the attachment you want to put on the
gun, eg: 'EmptyBarrel'.
Raises:
ValueError - if the given attachment isn't in the gun's val_barrels
... | This function swaps the attachment in a specified gun slot with a new attachment. It takes parameters 'slot' (e.g., 'barrel', 'mag') and 'attachment' (an object like 'EmptyBarrel'), then delegates to specific swap methods like swap_barrel() or swap_mag() based on the slot. The core task is to replace a gun component's ... | def swap_attach(self, slot, attachment):
"""Change the attachment in the slot given to the one given.
slot - str, the part of the gun the attachment is to go on.
attachment - attachment class object eg: 'EmptyBarrel'
"""
if slot == "barrel":
self.swap_barrel(at... |
def FindAllBranches(FabPartInput, FabPartList):
allBranches = [] #All the branches in the route as a nested list
allTaps = [] #All the taps attached to the main branches ordered from first to last seen
listLength = len(FabPartList)
FabPartList.remove(FabPartInput)
allBranches.append(FabPartInput)
nextFabPa... | The function `GetOutput` generates an ordered list of fabrication parts starting from a given `startpoint`. It identifies all connected branches and taps, determines the longest route, and appends it to the output. Taps are recursively processed, ensuring their paths are added after the main route. Used parts are remov... | def GetOutput(startpoint, FabPartList):
output = []
branches, allTaps = FindAllBranches(startpoint, FabPartList) #Return all the branches and any tap Fabpart connected to the branches
level, longestRoute, b = FindLongestRoute(branches) #From the branches, return the longest route in the system
b = b[::-1] #Reverse ... |
def end(self):
curses.nocbreak()
self.stdscr.keypad(True)
curses.echo()
curses.endwin()
self.generate_new_world()
def show_world(self, iter):
self.stdscr.clear()
self.stdscr.addstr(self.title+'\n')
self.stdscr.addstr(self.introduction+'\n')
self.st... | This code generates a terminal-based simulation using curses. It validates world dimensions against the window size, initializes the curses environment, displays the initial world state, runs iterative updates, and cleans up resources. Error checks ensure the world isn't too large or too small for the terminal window. | def auto_generate(self):
self.stdscr = curses.initscr()
win_size = self.stdscr.getmaxyx()
if self.row+4 >= win_size[0] or self.column*2 >= win_size[1]:
self.end()
print("[ERROR] The size of world is too large. Please reduce the size or maximize your windows")
... |
def print_setting(self):
print("1: size = "+str(self.row)+"*"+str(self.column))
print("2: iteration = "+str(self.iteration))
print("3: init mode = "+self.mode)
print("world:"+str(self.live_symbol)+" is live cell, "
+str(self.dead_symbol)+" is dead cell")
self.prin... | The main task of the code is to run a Game of Life simulation with user-configurable settings. It welcomes the user, asks if they want to use default settings or adjust them, then enters a loop where it starts the game, auto-generates states, and lets users choose to end the game or modify settings repeatedly until the... | def main(self):
print("Welcome to Game of Life")
# use default setting?
self.print_setting()
default = True if input("Use default setting?(y or n)") == 'y' else False
if not default: self.change_setting()
print("======================================")
start = T... |
def get_from_clipboard():
try:
print("Getting from clipboard")
cmd = 'pbpaste'
output = subprocess.check_output(cmd, shell=True)
output = str(output)[2:][:-1]
return(output)
except Exception as e:
print("Exception at get_from_clipboard()")
print("e = {}".format(e))
def get_from_db():
if(not os.path.... | The main task of the code is to monitor clipboard content, compare it with stored database data, and if different, update the database, notify Android devices of the new clipboard text, and handle exceptions. It checks clipboard data against existing records, updates timestamps, and triggers notifications for changes. | def data_from_clipboard():
try:
output = get_from_clipboard()
message = ""
timestamp = ""
# print("CLIPBOARD-" + get_from_clipboard())
# print(get_from_db())
if(get_from_db() is not None):
data = get_from_db()
message, timestamp = data['cliptext'], data['timestamp']
print("message-" + str((mes... |
def roll_dice(self):
return random.randint(1,6) + random.randint(1,6)
def distribute_resources(self, roll):
"""
Given a dice roll value, will find all tiles that have that dice value,
then find all vertices which have a settlement. For each vertex with settlement,
a helper functi... | The main task of the code is to simulate a player's turn in a board game by rolling dice, distributing resources, and allowing the player to build roads/settlements, trade, or buy development cards. It checks for a win condition (10+ victory points) and saves the game state. Non-implemented features include trading and... | def start_turn(self):
"""
Simulate the dice roll and allocate resources to all players.
Allow the current player to build roads, settlements, and cities as desired.
Will eventually implement trading functionality and dev cards
"""
print("start_turn() called")
pri... |
def divide_teams(self):
if len(self.cupTeams) % 2 == 0:
for i in range(0, len(self.cupTeams), 2):
self.group1.append(self.cupTeams[i])
self.group2.append(self.cupTeams[i + 1])
else:
for i in range(0, len(self.cupTeams) - 1, 2):
self... | The main task of the code is to simulate a tournament by dividing teams into two groups, iteratively processing matches in each group until one team remains in each, then conducting a final round to determine the winner. It uses a GUI to display round details, match results, and the final outcome in a structured format... | def runCup(self,gui):
self.divide_teams()
while len(self.group1) > 1 or len(self.group2) > 1:
gui.print_in_ouput_box('*************************** Round '+str(len(self.group2)*2)+' ***************************\n')
if len(self.group1) > 1:
gui.print_in_ouput_box(... |
def goal(node):
if ((node.state[1][1] == 'A') and (node.state[2][1] == 'B') and (node.state[3][1] == 'C')):
return True
return False
def children_astar(state):
addchild = []
add_hscore = []
y, x = actions.position(state,':)') #row,col
first_child = actions.up(state,y,x) #UP
... | This function implements the A* algorithm to find a path to a goal state. It explores the current state, generates successors, adds unvisited ones to the fringe (priority queue sorted by fcost), and recursively continues. It tracks visited states, state count, space complexity, depth, and constructs the solution path i... | def a_star(fringe,No_states,time_complex,space_complex,all_depth_list,visited):
cur_state = fringe.pop()
No_states = No_states + 1
#visited.append(cur_state.state) #comment for tree, uncomment for graph
#print('Depth: ',cur_state.depth) #Prints current node. (Mute it unless you want to verify corec... |
def generate_colosseum_list():
pokemon_colosseum = []
with open(f'{os.path.abspath("scraper.py").replace("flask\\scraper.py","")}\\input\\pokemon_colosseum.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in reader:
pokemon_colosseum.a... | The main task of the code is to initialize a Pokémon encounter database by generating Colosseum/XD Pokémon lists, connecting to a SQLite database (with Flask mode path handling), setting up database structures/views, and timing the process. It prepares data for an encounter dex system, though some JSON-related steps ar... | def setup_encounter_dex(FLASK_MODE = True):
start_time = time.time()
# Initial Setup
# compose_offline_api([False, False, False])
global pokemon_colosseum, pokemon_xd
pokemon_colosseum = generate_colosseum_list()
pokemon_xd = generate_xd_list()
# SQLite
if FLASK_MODE:
print(f'... |
def extend_obstacles(self):
final_obs = []
for obstacle in self.allObs:
addition= []
padding = 1.5
for obs in obstacle:
new_obs1 = (obs[0]-padding,obs[1])
new_obs2 = (obs[0],obs[1]-padding)
new_obs3 = (obs[0]+padding,obs... | The code implements a Probabilistic Roadmap Method (PRM) for path planning in a cluttered environment. It generates random samples (milestones), checks for collisions, connects them to form a graph, and uses Dijkstra's algorithm to find the shortest collision-free path from start to goal. The process repeats with varyi... | def runPRM(self,screen,initialRandomSeed=0):
seed = initialRandomSeed
# Keep resampling if no solution found
pygame.draw.circle(screen, BLACK, (200,200), 100)
# Create new obstacle map
self.obsmap = self.extend_obstacles()
# print('watch this',self.obsmap)
while(n... |
def scan_gid(self, id):
if self.cli:
print()
print(Fore.GREEN + "Using {} for Reverse Lookup".format(id))
URLs = {}
if self.spyonweb:
if self.cli:
print(Fore.GREEN + "Querying SpyOnWeb")
uniqueurls = self.query_spyonweb(id,... | The code processes input parameters (`id` or `url`) to scan data, writing a timestamp to an output file if specified. If a `gid` (Google tracking ID) is provided, it retrieves associated URLs. If a `url` is provided, it extracts GIDs and scans them. If no valid input is given, it raises an error. The task involves data... | def run(self,id=None,url=None):
gid = id
if self.outfile != None:
# write date and time to file to initialize
with open(self.outfile,'w') as fObj:
dt = datetime.utcnow().strftime("%Y-%m-%d %H:%M")
fObj.write("{}\n".format(dt))
if gid != No... |
def init_train_dl(self, csv_data_file):
train_ds = LoesScoreDataset(
csv_data_file,
use_gd_only=self.cli_args.use_gd_only,
val_stride=10,
is_val_set_bool=False,
)
batch_size = self.cli_args.batch_size
if self.use_cuda:
batch_si... | The main task of the code is to train and evaluate a machine learning model using specified datasets. It initializes training and validation data loaders, iterates over epochs to perform training and validation, logs metrics, saves the model's state, computes standardized RMSE, generates scatter plots, and calculates P... | def main(self):
log.info("Starting {}, {}".format(type(self).__name__, self.cli_args))
train_dl = self.init_train_dl(self.cli_args.csv_data_file)
val_dl = self.init_val_dl(self.cli_args.csv_data_file)
for epoch_ndx in range(1, self.cli_args.epochs + 1):
log.info("Epoch {} o... |
def chkAccessMode(interface):
if chkAccess(interface) == False:
return False
if "Cisco-IOS-XE-switch:mode" not in interface["Cisco-IOS-XE-native:GigabitEthernet"]["switchport"]:
return False
if "access" not in interface["Cisco-IOS-XE-native:GigabitEthernet"]["switchport"]["Cisco-IOS-XE-swit... | This function enables port security on a Cisco device's interface by configuring access mode, setting VLANs (1164 for access, 1165 for voice), and applying port-security parameters like sticky MAC addresses, max address limits (1 for voice VLAN, 2 for others), and violation restrictions. It sends these configurations v... | def enablePortSecurity(device,interface):
if chkAccessMode(interface) == False:
interface=setAccessMode(device,interface)
if chkVoiceVlan(interface) == False:
setVlan(device,interface,vlantype.access,1164)
setVlan(device,interface,vlantype.voice,1165)
interface["Cisco-IOS-XE-native:G... |
def read_cache():
global cache_data
if cache_data == {}:
if os.path.exists(cache_path):
with open(cache_path, "r", encoding='utf-8') as read_file:
cache_data = json.load(read_file)
else:
cache_data = {"series": []}
def get_series_node(series):
data_pat... | The code retrieves a TV episode's title by parsing input parameters, using a regex to extract season/episode numbers, querying a JSON data structure via cached nodes, and returning the matched title. | def get_episode_title(series, episode):
title = None
# load the cache
read_cache()
# get season and episode numbers
matches = re.search(r"S(\d+)E(\d+)", episode)
season_number = matches[1].lstrip('0')
episode_number = matches[2].lstrip('0')
# get title
series_node = get_series_node(s... |
def get_pkl_filename(self, model_params):
params_suffix = f"i{model_params['interpolation_type']}_tf{model_params['max_number_tf_factors']}_mg{model_params['num_main_genes']}"
output = os.path.join("results",model_params['name'], f"best_fit_result_{params_suffix}.pkl")
return output
def populate... | This code fits a model to gene expression data for a specified experiment, either using precomputed results or forcing a new fit. It normalizes sensitive/resistant gene data, selects model genes, and performs hypothesis testing by comparing predicted vs. actual resistance data using a difference model with interpolatio... | def run(self, experiment_name, model_params, force_fit = False):
pkl_fit_filename = self.get_pkl_filename(model_params)
gene_names, sensitive, resistant, unknown = self.data_source.get_data_and_filter(experiment_name)
self.populate_gene_idx_map(gene_names)
norm_data_sens = self.normalize... |
def malformed_groceries_warning(groceries):
warn_msg = "!!!!!!!\n"
warn_msg += "The groceries is not not a dictionary. "
warn_msg += "Failed to create the webpage.\n"
warn_msg += f"data recieved = '{groceries}'"
warn_msg += "\n!!!!!!!"
logger.warning(warn_msg)
def update_prof_page(self, rmp_dat... | This method processes incoming messages by checking the topic. If the topic is "rmp data", it validates the message as a dictionary, warns if invalid, then updates the profile page. For "db data", it parses JSON data to update courses and schedule pages. The core task is handling message events to update specific UI co... | def notify(self, topic: str, message: object):
""" Do something when this component recieves a message. """
if topic == "rmp data":
if isinstance(message, dict) == False:
malformed_groceries_warning(message)
return None
self.update_prof_page(rmp_da... |
def load_data(root, imagepairs, type, fold=0, celebA=True, transform=None, invert=False, shuffle=True, restricted=False, bsize=64, MMO=False, isClean=False):
# print(imagepairs)
data = SiameseNetworkDataset(root=root,
imageVerificationPairs=imagepairs, type=type, fold=fold, cel... | The code trains a neural network (VGG or ResNet) for image recognition tasks, handling multiple datasets (CelebA, webcaricature, combined) with configurable parameters like alignment type, restricted/unrestricted data, and multi-modal outputs (MMO). It sets up directories for saving models, metrics, and figures, applie... | def Train(RunNum, dataset, alignmentType, lr= .0001, device="cuda:0", finetune=False,pickupOld = False, foldNum=0,
debug=False, doTrainEval = False, eval_gender = False, run_thresholding = False, restricted=False, out=64,
MMO=False, isClean = False, eval_pairs = False, vgg=True, epochStart=0, epochE... |
def run(self, pkg=[], out=[]):
if pkg is None:
return
in_dir = pjoin(self.pkg_dir, *pkg)
out_dir = pjoin(self.apis_dir, *out)
run_model_api([in_dir], out_dir)
def run_same(self, pkg):
self.run(pkg=[pkg], out=[pkg])
def run_model(self, svc):
self.run(pkg=[svc, ... | This function orchestrates the generation of cloud common components by executing multiple build tasks. It runs packages like 'cloudcommon', 'db', 'proxy', and processes models for compute, image, cloudid, notify, and cloudevent, outputting specific modules such as 'identity' and 'proxy' to structure cloud infrastructu... | def gen_cloudcommon(self):
self.run(pkg=["cloudcommon", "db"])
self.run(pkg=["cloudcommon", "db", "proxy"], out=["cloudcommon", "proxy"])
self.run_same("cloudprovider")
self.run(pkg=["keystone", "models"], out=["identity"])
self.run_model("compute")
self.run_model("image"... |
def _create_model(self, agent) -> BaseLanguageModel:
llm = self._get_agent_model(agent)
(_, name) = llm.split(".")
return self._create_model_by_name(name)
def _create_typed_agent(self, name, agent, model: BaseLanguageModel) -> Agent:
if agent["type"] == "summarize":
return se... | The code creates an agent instance based on its configuration. It retrieves the agent's settings, generates a model, sets an LLM cache, and returns either a typed agent (if 'type' exists in the config) or a bot using helper methods._create_typed_agent/_create_bot. | def create(self, name) -> Agent:
agent = self.project["agent"][name]
model = self._create_model(agent)
set_llm_cache(InMemoryCache())
if "type" in agent:
return self._create_typed_agent(name, agent, model)
return self._create_bot(name, agent, model) |
def with_remote():
# connect to a remote server that is compatible with the Gremlin Server protocol. for those who
# downloaded and are using Gremlin Server directly be sure that it is running locally with:
#
# bin/gremlin-server.sh console
#
# which starts it in "console" mode with an empty in-... | The main task of the code is to initialize and configure a system by sequentially enabling remote connectivity, authentication, Kerberos security, and configuration management. The function orchestrates these components to establish a secure, configured environment for remote operations, likely in a networked or distri... | def main():
with_remote()
with_auth()
with_kerberos()
with_configs() |
def _check_keydown_events(self, event):
"""Respond to keyboard presses"""
if event.key == pygame.K_RIGHT:
self.tank.moving_right = True
elif event.key == pygame.K_LEFT:
self.tank.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif ... | This method handles user input events by checking for quit signals, key presses, key releases, and mouse clicks. It triggers appropriate responses like exiting the game, processing keyboard actions, or checking if the play button is clicked, delegating specific tasks to other methods for detailed handling. | def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(ev... |
def _check_fleet_edges(self):
"""Respond if any jets have reached an edge"""
for jet in self.jets.sprites():
if jet.check_edges():
self._change_fleet_directions()
break
def _tank_hit(self):
"""Respond to the tank being hit by an jet"""
if self.... | The function `_update_jets` updates jet positions, checks for edge collisions, detects tank-jet collisions to trigger a hit response, and verifies if jets reach the screen's bottom, managing game interactions and boundaries for a fleet of jets. | def _update_jets(self):
"""check if the jet is at the eadge, and then
update the positions of all jets in the fleet"""
self._check_fleet_edges()
self.jets.update()
# Look for jet-tank collisions
if pygame.sprite.spritecollideany(self.tank, self.jets):
self._t... |
def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(ev... | The code runs the game's main loop, continuously checking for events, updating game elements (tank, bombs, jets) if the game is active, and rendering the screen to maintain gameplay and visuals. | def run_game(self):
"""Start the main loop for the game."""
while True:
self._check_events()
if self.stats.game_active:
self.tank.update()
self._update_bombshells()
self._update_jets()
self._update_screen() |
def get_color_type(self):
if self._mesh.visual.material.baseColorTexture is not None:
self.color_type = ColorType.textureColor
else:
try:
a = self._mesh.visual.to_color().vertex_colors
self.color_type = ColorType.vertexColor
except Type... | This code initializes a 3D voxel model by setting up mesh, voxel grid, and texture data. It processes voxel colors, applies dithering, matches voxels to blocks, and prepares textures for rendering. Key tasks include calculating voxel positions, determining color types, and assembling textures for efficient rendering or... | def __init__(self, mesh, voxel_grid, texture_pack, dither=0):
self._mesh = mesh
self._voxel_grid = voxel_grid
self._texture_pack = texture_pack
self._dither = dither
self.used_blocks = None
self.texture_image = None
self.transposed_block_indexes = None
se... |
def get_color_type(self):
if self._mesh.visual.material.baseColorTexture is not None:
self.color_type = ColorType.textureColor
else:
try:
a = self._mesh.visual.to_color().vertex_colors
self.color_type = ColorType.vertexColor
except Type... | This code processes a mesh by assigning it to an object, determining its color type, calculating voxel points and colors, applying dithering for smoother gradients, aligning voxels to block structures, and finally assembling the result into a texture. The main task is to convert and refine a 3D mesh into a voxel-based ... | def mesh(self, mesh):
self._mesh = mesh
self.get_color_type()
self.calc_voxel_points()
self.calc_voxel_colors()
self.apply_dither()
self.match_to_blocks()
self.assemble_texture() |
def calc_voxel_points(self):
voxel_points = self._voxel_grid.points
self._closest, self._distances, self._face_indexes = ProximityQuery(self._mesh).on_surface(voxel_points)
def calc_voxel_colors(self):
match self.color_type:
case ColorType.textureColor:
self.calc_voxe... | The code processes a voxel grid by calculating its 3D points and colors, applying dithering for visual optimization, aligning voxels to block structures, and assembling the final textured output. The main task is to transform raw voxel data into a coherent 3D model with proper texturing and structural alignment for ren... | def voxel_grid(self, voxel_grid):
self._voxel_grid = voxel_grid
self.calc_voxel_points()
self.calc_voxel_colors()
self.apply_dither()
self.match_to_blocks()
self.assemble_texture() |
def validate_wms(url, layer_name, srs, bbox, result_array, service_version):
"""Fetch image for the corresponding layer and search for variation with
the same parameters in both the image and the result produced by the tool.
:param str url: First part of URL pointing to a particular service
:param s... | The code validates geospatial data from a WMS/WFS service by comparing a generated raster (`result_path`) with data fetched from the service. It adjusts the bounding box, retrieves service data, and computes discrepancies (correct, false positives/negatives) between the two datasets. Results are saved as a raster (`out... | def validate(url, layer_name, srs, bbox, result_path, output_path, service_type, service_version,\
max_features_for_validation, flip_features, data_bounds, service_number):
"""Fetch data for the corresponding layer and generate an array
that maps the spatial extent of the data
:param str u... |
def add_logo(png_file):
logo_markup = build_markup_for_logo(png_file)
st.markdown(
logo_markup,
unsafe_allow_html=True,
)
def load_lottieurl(url: str):
r = requests.get(url)
if r.status_code != 200:
return None
return r.json()
def load_checkpoint(checkpoint_path):
che... | The main task of the code is to create a Streamlit web application that uses a pretrained VGG19 model to predict flower species from user-uploaded or camera-captured images. It displays prediction results with probabilities, shows the input image, and provides a Google search link for the predicted flower. If confidenc... | def main():
# args = arg_parser()
add_logo("logo.png")
st.header('FLower species prediction using pretrained vgg19 Network')
lootie_url = 'https://assets9.lottiefiles.com/packages/lf20_l0segmbm.json'
lootie_robot = load_lottieurl(lootie_url)
col1,col2,col3 = st.columns([1,2,1])
with co... |
def menu_title():
pygame.mixer.music.play(-1)
ren = font.render("Paddle Mans Evloutionary Grinding Adventure", True, white)
screen.blit(ren, (30, 100))
ren = font.render("PRESS SPACE", True, white)
screen.blit(ren, (225, 500))
pygame.display.update()
key_wait()
ren = font.render("AKA", T... | The main task of the code is to initialize a Pygame window for a "Pong Legacy" game, set up the display, display a menu title, and enter a game loop that runs the game logic until the `Done` flag is triggered. It configures the screen size, sets the window caption, and orchestrates game initialization and execution thr... | def main():
global screen
screen = pygame.display.set_mode(WINSIZE)
pygame.display.set_caption('pong legacy')
menu_title()
initialize_game()
while not Done:
run_game() |
def play_sound(event):
#play sound based on what event is given when called
if event == "bounce":
bump1.play()
if event == "hit":
hit1.play()
if event == "coin":
coin1.play()
def win():
pygame.mixer.music.play(-1)
ren = titlefont.render("You Defeated", True, white)
sc... | This function handles ball collision detection in a game. It reverses the ball's vertical direction when hitting top/bottom walls, deducts player health and triggers game restarts when the ball exits left/right edges, and adjusts the ball's trajectory upon hitting paddles. Collision with player1's paddle reverses direc... | def col_check(self):
global aiOffset
global score
#ball hits top screen will set y velocity to be opposite
if self.y < 0:
if self.dirY < 0:#this checks to make sure that ball hasn't been bounced a bit out of bounds and is in the process of bouncing back in
sel... |
def get_path_to_node(path_dict,start,target,path_list):
previous_node=path_dict[target]
path_list.append(previous_node)
print('path list',path_list)
if previous_node==start:
return path_list
else:
get_path_to_node(path_dict, start, previous_node,path_list)
return p... | This code implements Dijkstra's algorithm to find the shortest path from a starting node to all other nodes in a graph. It initializes distances, uses a priority queue to explore nodes, updates shortest paths via edge relaxation, reconstructs the path using a dictionary, converts node indices to names, and plots the fi... | def Djisktra(graph,starting_node):
graph.path_dict[starting_node]=0
my_dict={}
for i in range(graph.num_vertices):
if i==starting_node:
my_dict[i]=0
else:
my_dict[i]=float('inf')
print('dictionary:',my_dict)
pq=Priorit... |
def _read_from_directory(self, directory_path, join_similar, config_df_names, **kwargs):
files = [os.path.join(directory_path, f) for f in os.listdir(directory_path) if
os.path.isfile(os.path.join(directory_path, f))]
return self._read_files_parallel(files, join_similar, config_df_names... | This method reads data from various sources (directory, file, or ZipFile), processes it, and applies optional deduplication and filtering. It handles different input types, logs progress, and returns cleaned data. | def read_data(self, source,
join_similar=False,
duplicated_subset_dict: dict = None,
filter_subset: dict = None,
config_df_names: dict = None,
**kwargs):
self.logger.info("Starting data reading process")
if config... |
def count_chars(self):
"""
Return quantity of characters in the text file.
"""
chars_quantity = 0
for char in self.text():
if not char.isspace():
chars_quantity += 1
return chars_quantity
def count_words(self):
"""
Return quant... | The code defines a `__str__` method that returns a formatted string summarizing a file's content by counting characters, words, and sentences using helper methods. It provides a human-readable description of the file's data when converted to a string. | def __str__(self):
return f"File contains {self.count_chars()} characters, "\
f"{self.count_words()} words, "\
f"{self.count_sentences()} sentences." |
def create_topic(topic_name, number_partitions):
try:
global admin_client
if admin_client == None:
admin_client = connect_admin_client()
topic_list = []
topic_list.append(NewTopic(name = topic_name, num_partitions = number_partitions , replication_factor = 1))
admin_client.create_topics(new_topics =... | The code defines a function `run_all()` that attempts to perform three main tasks: creating a Kafka topic using `create_topic()`, reading data from a MySQL database with `read_mysql_data()`, and listing messages via `list_messages()`. It uses a global variable `topic_name` for the topic. If any step fails, it catches e... | def run_all():
try:
global topic_name
create_topic(topic_name, 1)
read_mysql_data()
list_messages()
except Exception as e:
print(e) |
def load_opponent_policy(self):
with open(self.OPPONENT_POLICY_PATH, 'rb') as f:
return pickle.load(f)
def load_policy(self):
with open(self.POLICY_PATH, 'rb') as f:
self.policy = pickle.load(f)
def train(self, num_episodes=1_00_000, split_ratio=0.5):
x_episodes = int(spl... | This code initializes a reinforcement learning agent for a two-player game, setting parameters like exploration rate (epsilon), learning rate (alpha), and discount factor (gamma). It configures epsilon-greedy behavior policy, loads an opponent's policy, initializes Q-value tables for both players, and determines the st... | def __init__(self, epsilon=0.2, alpha=0.1, gamma=0.9):
super().__init__()
self.epsilon = epsilon
self.alpha = alpha
self.gamma = gamma
self.target_policy = {}
self.behavior_policy = self.epsilon_greedy_policy
self.opponent_policy = self.load_opponent_policy()
... |
def load_opponent_policy(self):
with open(self.OPPONENT_POLICY_PATH, 'rb') as f:
return pickle.load(f)
def load_policy(self):
with open(self.POLICY_PATH, 'rb') as f:
self.policy = pickle.load(f)
def train(self, discount_factor=0.9, num_episodes=1_000_000, split_ratio=0.5):
... | The code initializes a reinforcement learning agent with epsilon-greedy exploration. It sets up policies for the target, behavior, and opponent, loads a pre-existing policy if available, or trains and saves a new policy otherwise. The agent alternates between PLAYER_X and another player, using epsilon for exploration d... | def __init__(self, epsilon=0.2):
super().__init__()
self.epsilon = epsilon
self.target_policy = {}
self.behavior_policy = self.epsilon_greedy_policy
self.opponent_policy = self.load_opponent_policy()
self.policy = {}
self.current_player = self.PLAYER_X
if... |
def data_regression(data,target_col,regressor):
x_train = data.loc[:,['x','y']].values
y_train = data.loc[:,[target_col]].values
x_train_scaler = StandardScaler().fit(x_train)
y_train_scaler = StandardScaler().fit(y_train)
x_train_scaled = x_train_scaler.transform(x_train)
y_train... | The code generates a contour plot using a regression model on scaled data, visualizes prediction grids with a colorbar, and overlays reference lines for geological and analytical boundaries, setting axis limits for a focused visualization. | def create_contour(data,regressor,target_col,vmax_in):
x_train_scaler, y_train_scaler, data, regressor = \
data_regression(
data,
target_col,
regressor)
prediction_grid = regression_contour(x_train_scaler,y_train_scaler,regressor)
fig,ax = plt.sub... |
def uses_task_grouping(api: TodoistAPI) -> bool :
"""Detects if user uses the task grouping feature.
Arguments:
api {TodoistAPI} -- todoist api
"""
return len(api.state["projects"]) > 1
def detect_exhaustion(api: TodoistAPI, threshold: int=6) -> bool:
"""Detects if user assigns too... | The code's main task is to compile a dictionary of task management issues from a Todoist API. It checks for task grouping, user exhaustion, missing priorities, and regular API usage, returning these as boolean values in a structured format for analysis or reporting. | def get_combined_problems(api: TodoistAPI) -> dict:
problems_dict = {}
problems_dict["task_grouping"] = uses_task_grouping(api)
problems_dict["exhaustion"] = detect_exhaustion(api)
problems_dict["lack_priorities"] = detect_lack_priorities(api)
problems_dict["regular_use"] = detect_regular_use(api)
... |
def samechk(A):
C =[]
for i in range(0, len(A)):
d = 0
for j in range(0, i):
if (A[i] == A[j]):
d = 1
break
if (d == 0):
C.append(A[i])
return C
def init(A):
for i in range(len(A)):
A[i] = A[i] + '0'
return A
def nxtbl(A): ####m ------ no of tures for output
C =[]
for i in range(len(... | The code processes input data from a file by filtering lines, converting them into a structured numpy array, and applying transformations to generate patterns. It uses helper functions to check similarities, initialize structures, and create charts, ultimately returning processed data, a minimized result, and timing me... | def main(file_name):
lines = open(file_name).readlines()
A=open('newfile.txt', 'w').writelines(lines[4:])
data = np.loadtxt("newfile.txt")
B = []
for i in range(len(data)):
B.append([int(x) for x in data[i]])
B = np.asarray(B)
C = []
inp = lines[:2][0][3]
out = lines[:2][1][3]
nv = int(inp)
k=0
input... |
def samechk(A):
C =[]
for i in range(0, len(A)):
d = 0
for j in range(0, i):
if (A[i] == A[j]):
d = 1
break
if (d == 0):
C.append(A[i])
return C
def init(A):
for i in range(len(A)):
A[i] = A[i] + '0'
return A
def nxtbl(A): ####m ------ no of tures for output
C =[]
for i in range(len(... | The main task of the code is to process a matrix `C` through a series of steps: checking for duplicates, initializing data, generating tables, trimming redundant entries, creating a chart, minimizing it, and extracting specific elements and expressions. It returns minimized indices, generated expressions, original inpu... | def main_without_txt(C):
I =C
start_time = time.time()
C = samechk(C)
C = init(C)
m = len(C)
k = len(C[0])
#C = order(C)
A = []
A.append(C)
A.append(nxtbl(C))
for i in range(1,m-1):
if(A[i] !=[]):
A.append(nxtbl(A[i]))
#print(A[i])
else:
break
A = A[:-1]
B = samechk(primertr(A))
#print(B)
#p... |
def __getTotalOfEntries(self):
if self.__checkIfConnectionAvailable():
response = requests.get('https://api.fbi.gov/@wanted')
if response.status_code != 200:
return -1
return int(json.loads(response.... | This method loads a database from a specified file or API, checking if the local file exists. If not, it verifies network connectivity and loads via API if possible. Otherwise, it loads from the local file, returning error codes for failures. | def loadDatabase(self, fileName):
self.databaseFile = fileName
# Get the total count of entries.
self.totalOfEntries = self.__getTotalOfEntries()
# Check if database is saved locally.
if self.__checkLocalDBFile() == False:
... |
def last_updated_key(self, org_logins):
last_updated_module_key = self.NULL_MODULE_KEY
timestamp = 0
for module_key, module_values in self.data.items():
# search the latest timestamp
if timestamp < module_values['timestamp']:
timestamp = module_values['tim... | The code's main task is to process each organization's repositories by scanning them with specified Odoo versions, updating a tracking key for last updates, and resetting the last updated repository reference after each scan to track progress or state changes during the collection process. | def collect(self, org_logins, odoo_versions):
self.last_updated_key(org_logins)
for org_login in self.ordered_org_logins(org_logins):
self.scan_organization(org_login, odoo_versions)
self.last_updated_repo = None |
def find_node(self, letter):
return self._find_node_aux(self.root, letter)
def count_up(self, node):
self._count_up_aux(node)
def get_code_from_letter(self, letter):
node = self.find_node(letter)
# if letter not found
if node is None:
return None
curr_node =... | The code's main task is to add a letter to a data structure, either updating an existing entry's count and returning its code or adding a new entry and returning -1 if the letter isn't found. It checks for the letter's existence, increments the count if found, retrieves the code, updates the structure, and returns the ... | def add(self, letter):
node = self.find_node(letter)
# if letter found
if node is not None:
self.count_up(node)
code = self.get_code_from_letter(letter)
self.update()
return code
# add new letter if not found
node = self.add_new_l... |
def processMention(api, mention):
try:
if hasattr(mention, "extended_entities") and mention.extended_entities["media"][0]['type'] == "video":
#If you are in this block, they must have posted a video and you haven't replied to them yet.
timestamp = getTimestamp(mention)
return [mention.id, mention.id, None, ... | This code processes a social media mention by retrieving video/audio data, using Shazam to identify music, and notifying the user with the result. It handles errors, edge cases like deleted tweets, and wraps up tasks by updating job status. The main task is to analyze mentioned content, extract audio, identify tracks, ... | def handleMention(api, mention, serviced):
unknownUsername = "UNKNOWN"
vidAndAsker = processMention(api, mention)
vid = vidAndAsker[0] #Stores whichever tweet id posted the actual video
asker = vidAndAsker[1] #Stores whichever tweet id asked for help
link = vidAndAsker[2] #Stores whether or not it was a link inste... |
def create_bingo_boards(filename):
f = open(filename)
bingo_boards = []
puzzle_numbers = f.readline().strip("\n").split(",")
f.readline()
bingo_board = []
for row in f:
row = row.strip("\n").split(" ")
if row != [""]:
bingo_board.append([[a, False] for a in row if a ... | The code simulates a Bingo game by reading boards and puzzle numbers from a file, determining the winning board and last called number, displaying the winning board, calculating the result, and returning the boards, numbers, and winning turn. | def play_bingo():
bingo_boards, puzzle_numbers = create_bingo_boards("inputs/adventofcode4.txt")
winning_board, last_number, nth = mark_boards(bingo_boards, puzzle_numbers)
display_board(winning_board)
calculate_answer(winning_board, last_number)
return bingo_boards, puzzle_numbers, nth |
def on_accept(self):
client_socket, client_addr = self.cs_socket.accept()
print('client connected: %s <==> %s' % (client_addr, self.cs_socket.getsockname()))
# select a server that forwards packets to
server_ip, server_port = self.select_server(SERVER_POOL, self.algorithm)
# in... | This code uses the `select` module to monitor sockets for incoming data. It continuously checks for readable sockets, handling new client connections via `on_accept()` and receiving data from clients via `on_recv()`. If a socket closes or an error occurs, `on_close()` is called. The loop processes events asynchronously... | def start(self):
while True:
read_list, write_list, exception_list = select.select(self.sockets, [], [])
for sock in read_list:
# new connection
if sock == self.cs_socket:
print('='*40+'flow start'+'='*39)
self.on_ac... |
def SearchNodeBST(self, data):
return self._SearchNodeBST(data=data, root=self.root)
def SuccessorNodeBST(self, root: Node):
if root is None:
return None
if root.right is not None:
return self._minimum(root=root.right)
y: Node = root.parent
while y is not ... | This code deletes a node with specified data from a binary search tree (BST). It handles three cases: (1) node with no children (removes it by updating parent's pointer), (2) node with one child (replaces it with its child), and (3) node with two children (replaces its value with successor's value and recursively delet... | def DelNode(self, data):
node: Node = self.SearchNodeBST(data=data)
if node is None:
return False
if node.left is None and node.right is None:
parent: Node = node.parent
if parent.left == node:
parent.left = None
else:
... |
def getData(movieName):
print("Sending request to get movies!!!!!!")
movies = getMovies(movieName)
data = []
for movie in movies:
reviews = getReviews(movie["id"])
data.append({"title": movie["title"], "image": movie["image"], "description": movie["description"], "reviews": reviews})
... | The code processes a movie search by fetching or reusing cached data, displays the API response, and visualizes movie analysis results with metrics and a pie chart, using Streamlit for dynamic UI elements. | def process(movieName, packageName):
global lastSearched, cacheData
if(lastSearched != movieName):
data = getData(movieName)
lastSearched = movieName
cacheData = data
else:
data = cacheData
if len(data)>0:
st.text("")
st.components.v1.html("""
... |
def add_title_left(self,string,x,y,w=1,h=1):
label = QLabel(string)
label.setAlignment(QtCore.Qt.AlignLeft)
self.vl.addWidget(label,x,y,w,h)
def add_editor(self,str,x,y,w=1,h=1):
line = QLineEdit(str)
self.vl.addWidget(line, x,y,w,h)
return line
def add_load_button(self,... | This code initializes a GUI application for mesh labeling using PyQt and VTK. It sets up a main window with input fields for mesh directories, label files, output paths, and hotkeys. The interface includes buttons for loading data, navigating through meshes, saving labels, and adjusting mesh opacity, enabling interacti... | def __init__(self, parent = None,
mesh_dir = "data/meshes",
label_dir = "",
id_csv = "data/ids.csv",
output_file = "output.json",
hotkey_file = "data/hotkeys.csv",
opacity = .5):
... |
def clearSombra(self):
if self.jugador_sombra != None:
self.canvas.delete(self.jugador_sombra)
self.jugador_sombra = None
def clearParedSombra(self):
if self.pared_sombra != None:
self.hideWall(self.pared_sombra)
self.pared_sombra = None
def drawWall(self,... | The main task of the code is to refresh the game state by clearing shadows and wall shadows, redrawing walls and players, updating the GUI, and checking for a winner. | def refresh(self):
self.clearSombra()
self.clearParedSombra()
self.drawWall()
self.drawPlayeres()
self.root.update()
self.handleGanador() |
def sigTurno(self):
self.regla.sigTurno()
self.turno = self.regla.actual
def refresh(self):
self.clearSombra()
self.clearParedSombra()
self.drawWall()
self.drawPlayeres()
self.root.update()
self.handleGanador()
def coordsToGrid(x, y):
x -= BORDER
y... | This function handles player or bot moves in a two-player game. If both are bots (bot_cont='2'), it alternates turns until a winner is determined. For human input, it converts coordinates to grid positions, validates legal moves/walls, updates game state, switches turns, and refreshes the display. It also checks for wi... | def handleClick(self, x, y):
if (self.bot_cont == '2'):
while not self.regla.jugadores[0].ganador_posicion and not self.regla.jugadores[1].ganador_posicion:
self.regla.jugadores[self.turno].finalMovimiento(self.regla)
self.sigTurno()
self.refresh()
... |
def handleQuit(self):
self.root.destroy()
def setMovement(self, movimiento):
self.movimiento = movimiento
self.refresh()
def handleMotion(self, x, y):
if self.bot_cont == '2' or (self.turno == 1 and self.bot_cont == '1'):
return
self.clearParedSombra()
i, j =... | This code initializes a game window using tkinter, setting up controls for movement ('m') and wall placement ('w'), binding keyboard/mouse events, drawing game elements like cells and walls, and displaying instructions. It manages the game interface, player turns, and rule logic, then starts the main event loop for int... | def makeGame(self, bot_cont):
if self.root:
self.root.destroy()
self.root = tkinter.Tk()
self.root.title("Press 'M' for movement and 'W' for put a wall")
self.root.bind("<Escape>", lambda e: self.handleQuit())
self.root.bind("w", lambda e: self.setMovement("putWall"... |
def calc_A(m: float,
T: float,
n: float,
alpha_L: float,
alpha_H: float,
rho: float,
R: float,
hr: float,
F: float,
r: float) -> float:
"""
Calculate PV expected payment.
Parameters
----------
m : flo... | The function calculates the CDO spread using Gaussian quadrature on three auxiliary functions (A, B, C) derived from input parameters like correlation, recovery rate, and hazard rate. It computes the spread as $ s = C / (A + B) $, returning the spread and intermediate values. | def calc_sprd(m: float,
T: float,
n: float,
alpha_L: float,
alpha_H: float,
rho: float,
R: float,
hr: float,
r: float) -> float:
"""
Calculate CDO spread.
Parameters
----------
m : float
... |
def get_c(kwargs):
c = Engine.get_Colour(kwargs, 'c', 'col', 'color', 'colour')
return c
def get_pos(self, kwargs):
pos = Engine.get_Vector2(kwargs, 'pos')
return pos + self.translation
def get_size(kwargs):
size = Engine.get_Vector2(kwargs, 'size')
return size
def get_scaled(kwargs):
scaled = get_first_f... | This method draws a rectangle on a display using parameters from keyword arguments, scaling position and size if specified, then renders it with the given color. | def rectangle(self, **kwargs):
c = self.get_c(kwargs)
pos = self.get_pos(kwargs)
size = self.get_size(kwargs)
scaled = self.get_scaled(kwargs)
self.not_None(colour=c, position=pos, size=size)
pos, size = self.__scale(pos, size, scaled=scaled)
draw.rectangle(
self.display,
( *(pos.tuple(int)), *(s... |
def get_c(kwargs):
c = Engine.get_Colour(kwargs, 'c', 'col', 'color', 'colour')
return c
def get_pos(self, kwargs):
pos = Engine.get_Vector2(kwargs, 'pos')
return pos + self.translation
def get_first_from_dict(d, *ks, default = None):
for k in ks:
v = get_from_dict(d, k)
if v is not None:
return v
retu... | This method draws a filled circle on a display using parameters from kwargs, retrieving color, position, and radius, validating non-null values, scaling coordinates and radius, then rendering the circle with specified attributes. | def circle(self, **kwargs):
c = self.get_c(kwargs)
pos = self.get_pos(kwargs)
r = get_first_from_dict(kwargs, 'r', 'radius')
scaled = self.get_scaled(kwargs)
self.not_None(colour=c, position=pos, radius=r)
pos, r = self.__scale(pos, r, scaled=scaled)
r = int(r)
draw.filled_circle(
self.display,
... |
def get_c(kwargs):
c = Engine.get_Colour(kwargs, 'c', 'col', 'color', 'colour')
return c
def get_Vector2(kwargs, *args):
v = get_first_from_dict(kwargs, *args)
v = Vector2(v) if v is not None else None
return v
def get_scaled(kwargs):
scaled = get_first_from_dict(kwargs, 'scaled', default=False)
return sc... | This method draws a line between two 2D points on a display, using parameters from kwargs. It retrieves color, points, and scaling factors, validates non-null values, scales coordinates, then renders the line with specified attributes. | def line(self, **kwargs):
c = self.get_c(kwargs)
a = self.get_Vector2(kwargs, 'a')
b = self.get_Vector2(kwargs, 'b')
scaled = self.get_scaled(kwargs)
self.not_None(colour=c, a=a, b=b)
a, b = self.__scale(a, b, scaled=scaled)
draw.line(self.display, *a.tuple(int), *b.tuple(int), c) |
def get_pos(self, kwargs):
pos = Engine.get_Vector2(kwargs, 'pos')
return pos + self.translation
def get_alignment(kwargs):
horiz_align = get_from_dict(kwargs, 'horiz_align', default=Engine.CENTERh)
vert_align = get_from_dict(kwargs, 'vert_align', default=Engine.CENTERv)
align = get_from_dict(kwargs, 'align',... | This code renders given text onto a display surface, applying specified positioning, alignment, and scaling parameters. It calculates the text's position based on alignment and scaling, then blits the rendered text surface to the display at the computed coordinates. | def text(self, text, **kwargs):
pos = self.get_pos(kwargs)
align = self.get_alignment(kwargs)
scaled = self.get_scaled(kwargs)
pos = self.__scale(pos, scaled=scaled)
text_surface, text_rect = self.render_text(text, **kwargs)
pos += self.align(text_rect.size, align)
text_rect.center = pos.tuple(int)
s... |
def get_c(kwargs):
c = Engine.get_Colour(kwargs, 'c', 'col', 'color', 'colour')
return c
def get_pos(self, kwargs):
pos = Engine.get_Vector2(kwargs, 'pos')
return pos + self.translation
def get_size(kwargs):
size = Engine.get_Vector2(kwargs, 'size')
return size
def get_outline(kwargs):
c = Engine.get_Colo... | This method draws a filled rectangle on a display with an outline. It retrieves parameters like color, position, size, and scaling status, validates non-None values, scales coordinates, and uses `draw.filled_rectangle` for the filled shape. It then calls `self.rectangle()` to add an outline, ensuring both filled and ou... | def filled_rectangle(self, **kwargs):
c = self.get_c(kwargs)
pos = self.get_pos(kwargs)
size = self.get_size(kwargs)
outline = self.get_outline(kwargs)
scaled = self.get_scaled(kwargs)
self.not_None(colour=c, position=pos, size=size)
pos, size = self.__scale(pos, size, scaled=scaled)
draw.filled_rect... |
def get_c(kwargs):
c = Engine.get_Colour(kwargs, 'c', 'col', 'color', 'colour')
return c
def get_pos(self, kwargs):
pos = Engine.get_Vector2(kwargs, 'pos')
return pos + self.translation
def get_first_from_dict(d, *ks, default = None):
for k in ks:
v = get_from_dict(d, k)
if v is not None:
return v
retu... | This code draws a filled circle on a display using specified parameters (color, position, radius), scales the dimensions if required, and then draws an outlined circle on top for visibility. It ensures non-null values for critical attributes and adjusts the circle's position and size before rendering. | def filled_circle(self, **kwargs):
c = self.get_c(kwargs)
pos = self.get_pos(kwargs)
r = get_first_from_dict(kwargs, 'r', 'radius')
outline = self.get_outline(kwargs)
scaled = self.get_scaled(kwargs)
self.not_None(colour=c, position=pos, radius=r)
pos, r = self.__scale(pos, r, scaled=scaled)
r = in... |
def valid_move_check(self, player_name, starting_square_location, destination_square_location):
"""Raises appropriate exception, if there is one. Otherwise returns [piece, player]"""
current_player = None
for player in self._players:
if player.get_name() == player_name:
... | The code handles a player's move in a checkers game by validating the move and executing it based on the piece type. It checks if the move is valid, identifies the current player and piece, then delegates the move logic to specific methods for normal, king, or triple king pieces, returning the result of the move. | def play_game(self, player_name, starting_square_location, destination_square_location):
"""Represents a move in a game of checkers."""
move_info = self.valid_move_check(player_name, starting_square_location, destination_square_location)
current_player = move_info[1]
current_piece = move... |
def _dicoms_to_dict(dicom_list):
fvr = lambda x: None if x.first_valid_index() is None else x[
x.first_valid_index()]
out_list = []
for in_dicom in dicom_list:
temp_dict = {a.name: a.value for a in in_dicom.iterall()}
if in_dicom.__dict__.get('_pixel_array', None) is not None:
... | The function converts a list of DICOM file paths into a structured DataFrame by reading metadata from each file, removing empty columns, and applying transformations. It returns a cleaned DataFrame containing key DICOM attributes and their corresponding file paths. | def _dicom_paths_to_df(in_path_list):
f_df = _dicoms_to_dict(
[pydicom.read_file(in_path, stop_before_pixels=True) for in_path in
in_path_list])
f_df['file path'] = in_path_list
rec_df = _remove_empty_columns(f_df)
conv_df = _conv_df(rec_df)
return conv_df |
def anneal(spectral_data, reference_data, n, block_size, spectral_test, reference_test):
N_succ = 100 # number successful cases needed in a block
T_fact = 0.9 # factor by which we decrease temp
num_hl = len(reference_data.half_level.data)
num_cols = len(reference_data.column.data)
num_wavenumbers = ... | The main task of the code is to iteratively perform annealing simulations, adjusting parameters (n) until the cost meets a specified accuracy threshold. It collects and returns all computed solutions, weights, costs, and error metrics from each iteration. The loop continues to increment n (with undefined n_incr) and re... | def sim_loop(n_start, block_size, spectral_data, reference_data, accuracy, spectral_test, reference_test):
# like buehler but increment default 1
go_on = True
i = 0
n = n_start
s_best, W_best, cost_best, t_hist, cost_hist, e_hist, e_testhist = anneal(spectral_data, reference_data, n, block_size... |
def _dump(self):
# complete headers instructions from other datastructures
self._add_header_from_datastructures()
# build header
self.header = Dataset(1, self, "header",
list(self._header_fields.items()))
# remove database reference in datasets for... | The code defines an `__exit__` method for a context manager, which performs three actions: dumps data using `_dump()`, closes a resource with `close()`, and then reopens it with `open()`. The primary task is to ensure proper cleanup and reinitialization of resources when exiting the context, possibly to release and rea... | def __exit__(self, *_):
self._dump()
self.close()
self.open() |
def _get_records(self, data):
domain, question_type = self._get_question_domain_type(data)
if question_type is None and len(domain) == 0:
return {}, "", ""
qt = ""
try:
qt = QUESTION_TYPES[question_type]
except KeyError:
qt = "a"
zone =... | The code's main task is to generate a DNS response message by combining a header, question, and answer sections. It retrieves DNS records and their details using `_get_records`, then constructs the response with `_make_header` (for record count), `_make_question` (for domain and type), and `_make_answer` (for record da... | def make_response(self):
records, record_type, domain_name = self._get_records(self.data[12:])
return self._make_header(len(records)) + self._make_question(len(records), record_type, domain_name) +\
self._make_answer(records, record_type, domain_name) |
def model_executor(training_data, training_label, testing_data, model_name, meta_data=None):
"""
Executor ml models
----------
Parameters
training_data, training_label, testing_data: data for model training
model_name: model we are using
meta_data: Meta data for norma... | The function determines the best model for a given feature type by training and evaluating classification or regression models on split datasets. For discrete/string features, it tests classifiers (e.g., KNN, random forest) using accuracy. For continuous features, it evaluates regressors (e.g., ridge, lasso) with MSE, ... | def find_best_model(training_data, training_label, col_type):
"""
Find best model for current column
----------
Parameters
training_data, training_label: data for model training
col_type: type of the feature
----------
Return
Best model for current col... |
def find_best_model(training_data, training_label, col_type):
"""
Find best model for current column
----------
Parameters
training_data, training_label: data for model training
col_type: type of the feature
----------
Return
Best model for current col... | The function imputes missing values in a target column by training either a classification or regression model based on the column's data type. For discrete/string columns, it uses a classification model; for continuous columns, it applies regression. It selects the best model if specified, normalizes data for regressi... | def impute_col(training_data, training_label, testing_data, col_type, classification_model, regression_model):
"""
Impute target column with specified model
----------
Parameters
training_data, training_label, testing_data: data for model training
col_type: type of the featur... |
def get_feature_type(data, has_empty=False):
"""
Get the type of all features
----------
Parameters
data: Dataset
----------
Return
List of feature types of each columns
"""
global config
feature_type = []
for i in range(len(data[0])):
... | The function imputes missing values in a dataset by identifying missing columns, preprocessing data (encoding strings, normalizing features), and using classification/regression models to predict missing values. It iteratively fills gaps in both non-target and target columns, adjusting the dataset with predicted values... | def impute(data, cols_target, cols_using, classification_model, regression_model):
"""
Impute all Missing Columns
----------
Parameters
data: dataset
cols_target: list of target columns
cols_using: list of columns we are using
classification_model: model for c... |
def match_opinion_words(content, opinion_word_lexicon):
opinion_words = []
for opinion in opinion_word_lexicon:
for token in content.split():
if token == opinion: opinion_words.append(token)
return list(set(opinion_words))
def pattern_extraction(domain, k, pattern_type, df, pattern_handl... | The main task of the code is to evaluate and compare different pattern extraction methods for target identification in text data across multiple domains using cross-validation. It processes raw data, extracts opinion words and linguistic patterns, trains models on split datasets, evaluates pattern quality, and reports ... | def main():
kf, kfold_results = KFold(n_splits=10), defaultdict(lambda: [])
pattern_handler, dependency_handler = PatternHandler(), DependencyGraphHandler()
for domain in domains: # raw_df['domain'].unique()
output_raw_df_pkl_filepath = output_raw_df_pkl_filepath_ % domain
if os.path.... |
def reset_grid(self):
self.LedCtrlXY(2,3,0,0)
self.LedCtrlXY(3,3,0,0)
self.LedCtrlXY(4,3,0,0)
self.LedCtrlXY(5,3,0,0)
self.LedCtrlXY(2,4,0,0)
self.LedCtrlXY(3,4,0,0)
self.LedCtrlXY(4,4,0,0)
self.LedCtrlXY(5,4,0,0)
self.LedCtrlXY(2,5,0,0)
se... | This function processes button inputs to control a robot's state. It toggles automatic mode, resets grid position, sends coordinate data, and manages gear shifts. It updates the robot's status via `net_table` and LED indicators based on button presses in specific zones of a control pad. | def check_buttons(self, button):
#check if auto has been toggled
#if y equals 0 and its pressed and basically if its one of those top circle buttons [2,7]
if button[1] == 0 and button[2] and button[0] >= 1 and button[0] <= 6:
self.automatic = not self.automatic
#send self... |
def initialize_media() -> Tuple[Optional[Media], Optional[str]]:
"""
Collect a new media collection.
Return the media collection, or an error if something could not be loaded.
"""
images_dir = PACKAGE_DIR / "media/images"
level_paths = [] # type: List[pathlib.Path]
for pth in sorted(image... | The main task of the code is to run a Pygame application that initializes a fullscreen display, processes real-time camera input using OpenCV, computes optical flow with an `OpticalFlower` class, updates a game state, renders visual effects based on motion data, and handles user input for quitting or resetting. It incl... | def main(prog: str) -> int:
"""
Execute the main routine.
:param prog: name of the program to be displayed in the help
:return: exit code
"""
parser = argparse.ArgumentParser(prog=prog, description=__doc__)
parser.add_argument(
"--version", help="show the current version and exit", ... |
def _remove_node(self, parent, x):
removed = False
if(parent.remove):
return removed
self._lock(parent)
self._lock(x)
##########critical section#######################
if not x.dele:
######end 1#####
self._unlock(parent)
se... | This function recursively traverses a tree, removing marked nodes, propagating counters, and splaying nodes when they have only one child, to maintain tree structure during deletion operations. | def _longSplayDFS(self, x: Optional[Node]):
if x is None:
return
self._longSplayDFS(x.left)
self._longSplayDFS(x.right)
if x.left is not None and x.left.dele:
self._remove_node(x,x.left)
if x.right is not None and x.right.dele:
sel... |
def load_cookies_db(self):
self.info("Loading cookies from db.")
self.cookies = self.load_from_db('cookie')
if self.cookies is None:
raise FileNotFoundError ("cookie not found in db")
self.cookies = pickle.loads(self.cookies)
if not self.check_cookie_valid():
... | The code's main task is to log into a website (tadpoles.com), manage cookies (load/save), and download the user's images. It first attempts to load existing cookies; if they're missing, it navigates to the login page, authenticates, saves cookies, and prepares them for requests. Finally, it initializes an API interface... | def download_images(self):
'''Login to tadpoles.com and download all user's images.
'''
try:
self.load_cookies_db()
except FileNotFoundError:
self.navigate_url('https://familyinfocenter.brighthorizons.com/Account/Login?ReturnUrl=%2fMyBrightDay%2fContents')
... |
def emit_instr(*args):
assert not cur_exchange
print(*args)
def warn(check_env, *msg):
if check_env and check_env not in os.environ: return
print('s2rop: warning:', *msg, file=sys.stderr)
def exchange_regs(mapping): # {dst: src, ...}
if mapping == None:
do_exchange_regs(cur_exchange)
... | The function `emit_mov` generates a `mov` instruction to transfer data from `reg_src` to `reg_dst`, prioritizing direct `rax` handling. If `reg_dst` is `rax` and no exchange is active, it emits `mov rax, reg_src` if `reg_src` ≠ `rax`. Otherwise, it warns about a fallback and triggers a register exchange for `reg_dst` a... | def emit_mov(reg_dst, reg_src):
if reg_dst == 'rax' and not cur_exchange:
if reg_src != 'rax':
emit_instr('mov rax,', reg_src)
else:
if reg_src != 'rax':
warn('CHECK_FALLBACK', 'mov %s, %s: fallback'%(reg_dst, reg_src))
exchange_regs({reg_dst: reg_src}) |
def warn(check_env, *msg):
if check_env and check_env not in os.environ: return
print('s2rop: warning:', *msg, file=sys.stderr)
def exchange_regs(mapping): # {dst: src, ...}
if mapping == None:
do_exchange_regs(cur_exchange)
cur_exchange.clear()
return
new_cur = {}
for k in s... | The function `emit_binary_op` emits a binary instruction with register handling, swapping `rax`/`rcx` as needed based on `reg_dst` and `reg_src` values. It uses conditional logic to manage register conflicts, ensuring correct operand order via `exchange_regs`, and applies mappings `m1`/`m2` for state preservation. The ... | def emit_binary_op(instr, reg_dst, reg_src, m1={}, m2={}):
if reg_dst != 'rax' or reg_src != 'rcx':
warn('CHECK_FALLBACK', '`%s` %s, %s: fallback'%(instr, reg_dst, reg_src))
if reg_src == reg_dst:
exchange_regs({reg_dst: 'rax', 'rax': reg_dst})
exchange_regs({'r11': 'rcx', 'rcx': 'rax'})... |
def make_label(_static_cntr=[0]):
# all user-provided labels are underscore-prefixed
ans = 'L%d'%_static_cntr[0]
_static_cntr[0] += 1
return ans
def exchange_regs(mapping): # {dst: src, ...}
if mapping == None:
do_exchange_regs(cur_exchange)
cur_exchange.clear()
return
ne... | This function emits a jump instruction to a specified destination label. It handles local labels by resolving them to predefined values or generating new ones if needed. It then exchanges registers (likely freeing up resources) and emits assembly instructions 'pop rsp' followed by a 'dp' (direct jump) to the resolved d... | def emit_jump_imm(dst):
if dst.startswith('.'):
if dst in local_labels:
dst = local_labels[dst]
else:
local_labels[dst] = make_label()
dst = local_labels[dst]
exchange_regs(None)
emit_instr('pop rsp')
emit_instr('dp', dst) |
def warn(check_env, *msg):
if check_env and check_env not in os.environ: return
print('s2rop: warning:', *msg, file=sys.stderr)
def exchange_regs(mapping): # {dst: src, ...}
if mapping == None:
do_exchange_regs(cur_exchange)
cur_exchange.clear()
return
new_cur = {}
for k in s... | This function emits x86 assembly instructions for binary operations with immediate values, handling register swaps and special cases. It checks if the target register is 'rax', warns if not, swaps registers to use 'rax' for operations, loads immediates into temporary registers, and emits the appropriate instruction. Sp... | def emit_binary_op_imm(instr, reg, imm):
if reg != 'rax':
warn('CHECK_FALLBACK', '`%s` %s, `%s`: fallback'%(instr, reg, imm))
exchange_regs({'rax': reg, reg: 'rax'})
if instr == 'add rax, rcx':
emit_load_imm('rsi', imm)
exchange_regs(None)
emit_instr('add rax, rsi')
elif ... |
def emit_load_imm(reg, imm):
exchange_regs({reg: imm})
def exchange_regs(mapping): # {dst: src, ...}
if mapping == None:
do_exchange_regs(cur_exchange)
cur_exchange.clear()
return
new_cur = {}
for k in set(cur_exchange.keys()) | set(mapping.keys()):
v = k
v = mapp... | This function emits assembly instructions to perform a logical operation (e.g., comparison) using an immediate value. It loads the immediate into rsi, swaps rax with register 'a', compares rax and rsi, sets al based on the comparison result, modifies the opcode for non-equality cases, and moves the result to eax while ... | def emit_logic_imm(opcode, a, imm):
emit_load_imm('rsi', imm)
exchange_regs({'rax': a, a: 'rax'})
exchange_regs(None)
emit_instr('cmp rax, rsi ; sete al')
if opcode != 'eq':
if opcode.endswith('t'): opcode = opcode[:-1]
emit_instr('set%s al'%opcode)
emit_instr('movzx eax, al')
... |
def make_label(_static_cntr=[0]):
# all user-provided labels are underscore-prefixed
ans = 'L%d'%_static_cntr[0]
_static_cntr[0] += 1
return ans
def emit_jump_imm(dst):
if dst.startswith('.'):
if dst in local_labels:
dst = local_labels[dst]
else:
local_labels[... | This function generates machine code for a conditional jump based on the comparison of operands a and b using the specified opcode. It handles label resolution, register swapping, and emits assembly instructions for conditional branching, including memory operations and label management to support dynamic jumps. | def emit_condjump(opcode, dst, a, b, imm=False):
if dst.startswith('.'):
if dst in local_labels:
dst = local_labels[dst]
else:
local_labels[dst] = make_label()
dst = local_labels[dst]
if a == b:
if 'e' in lbl and 'ne' not in lbl:
emit_jump_... |
def contains_key(self, pattern):
return self.search(pattern) != None
def Hash(self, pattern):
hashval = 0
for ch in pattern:
hashval = ord(ch) + 31 * hashval
hash = hashval % self.hSize
return hash
def search(self, pattern):
hash = self.Hash(pattern)
... | This method adds a new key-value pair to a hash table if the key doesn't exist, or updates the value of an existing key. It uses separate chaining for collision resolution, checking if the key is present via contains_key(), then either appending a new NList node to the appropriate bucket or modifying the value of an ex... | def add_or_update(self, pattern, value):
if (self.contains_key(pattern) == False):
nlist = self.hTable[self.Hash(pattern)]
nlist.next = NList(pattern, value)
else:
nlist = self.search(pattern);
nlist.Value = value |
def parse_args():
parser = argparse.ArgumentParser(
description='Download binaries for Electron build')
parser.add_argument('--base-url', required=False,
help="Base URL for all downloads")
parser.add_argument('--force', action='store_true', default=False, required=False)
return par... | The code's main task is to download and extract specified binaries from a base URL, manage an output directory by checking hash validity and forcing updates, and set execute permissions for 'sccache' binaries. It parses arguments/config, skips unnecessary downloads, extracts files, and records the config hash for futur... | def main():
args = parse_args()
config = parse_config()
base_url = args.base_url if args.base_url is not None else config['baseUrl']
output_dir = os.path.join(SOURCE_ROOT, 'external_binaries')
config_hash_path = os.path.join(output_dir, '.hash')
if (not is_updated(config_hash_path) and not args.force):... |
def TCDebug(self, msg):
if self.logLevel >= LOG_LEVEL_DEBUG:
print('TC DEBUG: {}'.format(msg))
def special_aug(self, data, ops_key, param):
"""
wrapper to call the augmentation operations specified in self.aops in initAugmentation
"""
for data_key in data:
if not self.dataCanAugment(data_key): continue... | This code applies a random uniform rotation to 2D or 3D data frames. It generates a rotation matrix using a random angle for 2D or a random quaternion for 3D, then applies the transformation to specified data components via matrix multiplication. The rotation is logged for debugging, and the modified data is returned a... | def rotate(self, data):
'''
random uniform rotation of low and high data of a given frame
'''
#check if single frame
if len(data[DATA_KEY_MAIN].shape)==4:
pass
#2D:
if self.dim==2:
theta = np.pi * np.random.uniform(0, 2)
rotation_matrix = np.array([[1, 0, 0, 0 ],
[0, np.cos(theta), ... |
def TCError(self, msg):
if self.logLevel >= LOG_LEVEL_ERROR:
print('TC ERROR: {}'.format(msg))
raise TilecreatorError(msg)
def TCDebug(self, msg):
if self.logLevel >= LOG_LEVEL_DEBUG:
print('TC DEBUG: {}'.format(msg))
def dataCanAugment(self, data_key):
return (self.dataIsActive(data_key) and (data_key in... | This function rotates data arrays by 90 degrees counterclockwise around specified axes using NumPy's rot90. It validates input axes, applies rotation to eligible data keys, executes special augmentation, and returns modified data. | def rotate90(self, data, axes):
'''
rotate the frame by 90 degrees from the first axis counterclockwise to the second
axes: 2 int, from axis to axis; see np.rot90
0,1,2 -> z,y,x
'''
if len(axes)!=2:
self.TCError('need 2 axes for rotate90.')
self.TCDebug('Rotate 90 degree from axis {} to axis {}... |
def TCDebug(self, msg):
if self.logLevel >= LOG_LEVEL_DEBUG:
print('TC DEBUG: {}'.format(msg))
def isFrameSequence(self, data):
return len(data.shape)==DATA_DIM_LENGTH_SEQUENCE
def dataCanAugment(self, data_key):
return (self.dataIsActive(data_key) and (data_key in self.aops))
def special_aug(self, data, ops_k... | The main task of the code is to flip data along specified axes (z, y, x) for multi-channel images, handling both single frames/tiles and sequences. It applies `np.flip` to each data key (e.g., low/high) along the given axes, adjusting axes for frame sequences, and invokes a special augmentation step. The function suppo... | def flip(self, data, axes, isFrame=True): #axes=list, flip multiple at once
'''
flip low and high data (single frame/tile) along the specified axes
low, high: data format: (z,x,y,c)
axes: list of axis indices 0,1,2-> z,y,x
'''
# axis: 0,1,2 -> z,y,x
axes = np.asarray(axes, dtype=np.int32)
self.TCDebu... |
def TCDebug(self, msg):
if self.logLevel >= LOG_LEVEL_DEBUG:
print('TC DEBUG: {}'.format(msg))
def dataCanAugment(self, data_key):
return (self.dataIsActive(data_key) and (data_key in self.aops))
def special_aug(self, data, ops_key, param):
"""
wrapper to call the augmentation operations specified in self.a... | This code scales the resolution of input data frames by a given factor, adjusting dimensions for 2D/3D cases. It calculates a normalized scaling factor, applies `scipy.ndimage.zoom` to each data element with specified interpolation and fill modes, and ensures consistent scaling across frames. Special augmentation is al... | def scale(self, data, factor):
'''
changes frame resolution to "round((factor) * (original resolution))"
'''
# only same factor in every dim for now. how would it affect vel scaling?
# check for 2D
scale = [factor, factor, factor, 1] #single frame
if self.dim==2:
scale[0] = 1
self.TCDebug('S... |
def TCError(self, msg):
if self.logLevel >= LOG_LEVEL_ERROR:
print('TC ERROR: {}'.format(msg))
raise TilecreatorError(msg)
def isFrameSequence(self, data):
return len(data.shape)==DATA_DIM_LENGTH_SEQUENCE
def isFrameSingle(self, data):
return len(data.shape)==DATA_DIM_LENGTH_SINGLE
def formatShape(self, srcS... | This function determines the tile shape from input data by checking if it's a numpy array, distinguishing between frame sequences and single frames, extracting the appropriate shape dimensions, and formatting the result according to the specified format. | def getTileShape(self, data, format=SHAPE_FORMAT_SINGLE):
if not type(data) is np.ndarray: self.TCError('Can\'t get tile shape from not np-array data')
if self.isFrameSequence(data): shape = data.shape[1:]
elif self.isFrameSingle(data): shape = data.shape[:]
else: self.TCError('Can\'t get tile shape from data w... |
def isValidMainTileShape(self, shape):
'''
includes channels
'''
if not self.isIntArray(shape): return False
if len(shape)!=(DATA_DIM_LENGTH_SINGLE-1): return False
# check compatible to scale factor
if self.dataIsActive(DATA_KEY_SCALED):
if not self.isIntArray(shape[:3]*self.upres): return False
# ... | This function adjusts an input shape to the nearest valid dimensions by scaling it to multiples of a minimum step size. If the shape is already valid, it returns a copy. Otherwise, it calculates the minimum valid step, then rounds the shape dimensions up or down (based on the 'ceil' flag) to the nearest multiple of thi... | def makeValidMainShape(self, shape, format=SHAPE_FORMAT_SINGLE_NOCHANNEL, ceil=True):
if self.isValidMainTileShape(shape): return np.copy(shape) # nothing to do
# per component: find next larger valid value
minStep = self.getMinValidMainStep()
minStep = self.formatShape(minStep, SHAPE_FORMAT_SINGLE_NOCHANNEL, f... |
def makeHighShape(self, shape, format=SHAPE_FORMAT_SINGLE_NOCHANNEL):
format = format.lower()
if len(shape) != len(format):
self.TCErrorInternal('Shape {} does not match shape format \'{}\'.'.format(shape, format))
#upRes = np.copy(self.upres)
'''
if format == 'zyx':
pass
elif format == 'bzyx':
... | The main task of the code is to extract a random tile (with specified dimensions) from input data arrays (low and high) while ensuring the tile meets a minimum density requirement. It avoids edge regions using bounds, validates input shapes, and iteratively selects valid tile positions. If a valid tile isn't found with... | def getRandomTile(self, low, high=None, tileShapeLow=None, bounds=[0,0,0]): #bounds to avoid mirrored parts
'''
cut a random tile (low and high) from a given frame, considers densityMinimum
input array shape is (block, z,y,x,c), tile shape is (z,y,x[,c])
bounds: ignore edges of frames, used to discard mirror... |
def TCError(self, msg):
if self.logLevel >= LOG_LEVEL_ERROR:
print('TC ERROR: {}'.format(msg))
raise TilecreatorError(msg)
def dataIsActive(self, data_key):
return self.data_flags[data_key][DATA_FLAG_ACTIVE]
def TCWarning(self, msg):
if self.logLevel >= LOG_LEVEL_WARNING:
print('TC WARNING: {}'.format(msg... | The main task of the code is to generate batches of random tiles from training/test data, handling data augmentation, block size constraints, and dimension squeezing. It validates data availability, constructs batches with specified shapes, and returns arrays of main data, scaled data, and labels, adjusting dimensions ... | def selectRandomTiles(self, selectionSize, isTraining=True, augment=False, blockSize = 1, squeezeZ=False, squeezeBlocks=True): # ,ouputBlockID=False
'''
main method to create baches
Return:
shape: selectionSize,[ blockSize,][ z,] y, x, channels
if 2D z = 1 unless squeezeZ is set
block dimension is r... |
def command_type(self):
c_type = None
if valid_A_command(self.command()):
c_type = 'A_COMMAND'
elif valid_C_command(self.command()):
c_type = 'C_COMMAND'
elif valid_L_command(self.command()):
c_type = 'L_COMMAND'
return c_type
def symbol(self) ... | This function processes assembly lines to build a symbol table for ROM addresses. It identifies 'L_COMMAND' labels, checks for duplicate symbols, and adds unique symbols with adjusted line numbers (accounting for L_COMMAND count) to the symbol table. It raises an error for non-unique symbols and resets the instruction ... | def get_L_command_symbols(self):
L_count = 0
for line_num in range(len(self._asm_lines)):
if self.command_type() == 'L_COMMAND':
symbol = self.symbol()
if self.sym_tab.contains(symbol):
raise ValueError(f'Line {line_num} symbol not unique.'... |
def command(self):
return self._asm_lines[self._current_index]
def symbol(self) -> str:
symbol = None
if self.command()[1].isalpha():
if self.command_type() == 'A_COMMAND':
symbol = self.command()[1:]
elif self.command_type() == 'L_COMMAND':
... | This function translates an assembly command into a 16-bit binary address. If the command contains a symbol, it looks up or adds the symbol in the symbol table, then converts the address to binary. If no symbol is present, it directly converts the command's operand part to a 16-bit binary string. | def _translate_a_command(self) -> str:
command = self.command()
if (symbol := self.symbol()):
if not self.sym_tab.contains(symbol):
self.sym_tab.add_RAM_entry(symbol)
address = int_to_binary(self.sym_tab.get_address(symbol), 16)
else:
address =... |
def command(self):
return self._asm_lines[self._current_index]
def valid_A_command(command: str) -> bool:
a_comm = False
if command.startswith('@') and len(command) > 1:
num_addr = command[1:].isdigit() and int(command[1:]) < 32768
sym_addr = command[1].isalpha()
a_comm = num_add... | The function translates a command line into its corresponding assembly code representation. It checks if the command is valid A or C type, invokes respective translation methods, appends a newline, and returns the result. If invalid, returns None. | def translate_line(self) -> str:
command = self.command()
trans = None
if valid_A_command(command):
trans = self._translate_a_command() + '\n'
elif valid_C_command(command):
trans = self._translate_c_command() + '\n'
return trans |
def print_board(board):
for row in board:
print(" ".join(row))
print()
def human_place_coin(board, human_player):
while True:
try:
i = int(input("Enter the row index to place your 'X' coin: "))
j = int(input("Enter the column index to place your 'X' coin: "))
... | This code simulates a turn-based game on a 3x3 grid where a human player ('X') and AI ('O') alternately place and drag coins. The game checks for a win or draw after each move, with the human starting first. The core task is to manage the game flow, handle player moves, and determine the outcome based on winning condit... | def play_game():
board = [[' ' for _ in range(3)] for _ in range(3)]
human_player = 'X'
ai_player = 'O'
print_board(board)
# Human places the 1st coin
human_place_coin(board, human_player)
if check_winner(board, human_player):
print("Congratulations! You win!")
return
e... |
def _contextFromEntity(self, entity):
'''convert *entity* to list of dicts'''
context = []
if not entity:
return context
try:
context = [
{
'entityId': entity['id'],
'entityType': entity.entity_type.lower(),... | The code initializes a GUI component for managing actions, setting up a layout with entity selection, recent actions, and all actions sections. It connects signals to handle user interactions, loads actions based on context, and prepares for dynamic updates and event handling. | def __init__(self, session, parent=None):
'''Initiate a actions view.'''
super(Actions, self).__init__(parent)
self.logger = logging.getLogger(
__name__ + '.' + self.__class__.__name__
)
self._session = session
layout = QtWidgets.QVBoxLayout()
self.s... |
def _contextFromEntity(self, entity):
'''convert *entity* to list of dicts'''
context = []
if not entity:
return context
try:
context = [
{
'entityId': entity['id'],
'entityType': entity.entity_type.lower(),... | The code handles context changes by reloading actions: it retrieves the new context from the entity, clears previous sections, updates recent actions, and loads actions specific to the new context. | def _onEntityChanged(self, entity):
'''Load new actions when the context has changed'''
context = self._contextFromEntity(entity)
self._recentSection.clear()
self._allSection.clear()
self._updateRecentActions()
self._loadActionsForContext(context) |
def _addRecentAction(self, actionLabel):
'''Add *actionLabel* to recent actions, persisting the change.'''
recentActions = self._getRecentActions()
self._moveToFront(recentActions, actionLabel)
recentActions = recentActions[: self.RECENT_ACTIONS_LENGTH]
encodedRecentActions = jso... | This method logs a launched action, updates recent actions by adding the action to the top of the list and refreshing the UI, displays results, extracts valid metadata from the action, and sends a 'LAUNCHED-ACTION' usage event with the metadata to track action usage, ensuring thread safety on Linux by executing it sync... | def _onActionLaunched(self, action, results):
'''On action launched, save action and add it to top of list.'''
self.logger.debug(u'Action launched: {0}'.format(action))
self._addRecentAction(action['label'])
self._moveToFront(self._recentActions, action['label'])
self._updateRece... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.