dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def pad(sequence: List[T], reqlen: int, pad: T) -> List[T]:
"""
Pad the given sequence to the given length.
:param sequence: the sequence to be padded
:param reqlen: the length the given sequence to be padded to
:param pad: padding element
:return: the padded sequence
... | This function processes a batch of sentences by padding them to the maximum sentence length, converting them into token ID tensors, and optionally generating character ID tensors if specified. It returns the token ID tensor with original lengths and an optional character ID tensor, both padded to their respective maxim... | def __call__(self, batch: List[Sentence],
use_char: bool) -> Tuple[Tuple[
torch.Tensor, List[int]], Optional[Tuple[torch.Tensor, List[int]]]]:
"""
Given a batch of sentences, return the (often padded) token ID tensor with its original
lengths before padding,... |
def viewEmployees():
while True:
clear()
choice = input("""
----------View Employees----------
Please choose:
1 - View all
2 - Search Employees
3 - Return
----------------------------------
""")
if choice == "1" :
viewall()
input("Press enter to continue...")
elif choice == ... | The main task of the code is to provide a menu-driven interface for managing employee information. It continuously displays options to view, add, edit, remove employees, or return, executing corresponding functions based on user input. The loop persists until the user selects "Return," ensuring interactive management o... | def main():
while True:
clear()
choice = input("""
-------Employee information-------
Please choose:
1 - View Employees
2 - Add Employees
3 - Edit Employee
4 - Remove Employees
5 - Return
----------------------------------
""")
if choice == "1" :
viewEmployees()
elif choice ==... |
def get_image(self, filename, folder='images'):
file_name = cwd + '\\' + folder + '\\' + filename + '.png'
return PhotoImage(file=file_name)
def load_settings(self):
# Fixed Game Settings
self.int_number_game_rows = [9, 16, 16]
self.int_number_game_columns = [9, 16, 3... | This code initializes a Minesweeper application by loading settings from a CSV file, setting up a Tkinter GUI with canvases and event handlers for user interactions, initializing sound effects with Pygame, loading highscores, and preparing the game environment with a startup screen and timer. | def __init__(self):
# Load Application Data
self.button_index = []
with open(cwd + '\\settings.csv') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=';')
for i, row in enumerate(csv_reader):
if i == 0: pass
eli... |
def load_highscores(self):
self.check_highscore_file()
with open(highscore_path, 'rb') as f:
self.high_scores = np.load(f, allow_pickle=True)
def get_button_names(self, menu='main_menu', index=-1):
for row in self.button_index:
if row[0] == menu:
if index... | This function displays high score statistics by loading saved scores, clearing the canvas, and rendering three difficulty-based scoreboards with ranked entries. It creates text labels for difficulty names, rectangular backgrounds, and positions high score data (rank and value) for each difficulty. Finally, it draws nav... | def menu_statistics(self):
self.load_highscores()
self.canvas.delete("all")
for i in range(3):
this_x = 150 + 250*i
this_y = 30
self.canvas.create_text(this_x, this_y, anchor=N, text='~ {0} ~'.format(self.button_names[int(self.get_bu... |
def play_sound(self, file_name):
""" Plays specified sound file """
for i, name in enumerate(sound_effect_names):
if name == file_name:
self.sound_effects[i].play()
return
def open_remaining_tiles(self):
for i in range(self.int_current_game_columns):
... | The code checks if all non-mine tiles are revealed by iterating through the game board. If any hidden, non-bomb tile exists, it returns early. If all are revealed, it sets the game state to "DONE," plays a win sound, opens remaining tiles, and displays a win screen, signaling victory. | def check_victory(self):
if self.int_current_flags > self.int_current_game_mines: return
for i in range(self.int_current_game_columns):
for j in range(self.int_current_game_rows):
tile = self.array_current_game_board[j, i]
not_bomb = not tile.get_bomb()
... |
def rule_4(algebric_query):
lst = []
index = 0
while index < len(algebric_query):
if isinstance(algebric_query[index], list):
lst.append(rule_4(algebric_query[index]))
elif algebric_query[index].startswith("SIGMA") and "AND" in algebric_query[index]:
lst += rule_4_inn... | The function `operateRule` selects and applies a specific rule (e.g., rule_4, rule_4a, rule_6) based on the `ruleToOperate` parameter. It acts as a dispatcher, returning the result of the corresponding rule function with the `original_query` and additional parameters like "NJOIN"/"CARTESIAN" and a boolean flag. Each ru... | def operateRule(ruleToOperate, original_query):
if ruleToOperate == 0:
print("operating rule 4")
return rule_4(original_query)
elif ruleToOperate == 1:
print("operating rule 4a")
return rule_4a(original_query)
elif ruleToOperate == 2:
print("operating rule 5a")
... |
def getQuery():
query = input("Please insert a query:\n")
if query[-1] == ";":
query = query[0:-1]
return treeBuilder(query)
def parseQueryToPrintingFormat(algebraic_query):
if isinstance(algebraic_query, list):
if algebraic_query[0].startswith("CARTESIAN") or algebraic_query[0].startswi... | The main task of the code is to process an algebraic query by displaying it, presenting a menu for rule selection, applying the chosen transformation rule to the query, and printing the modified query. It involves retrieving input, formatting output, and executing rule-based transformations based on user choices. | def part_1_menu():
algebraic_query = getQuery()
print("Query in algebric way: {0}".format(parseQueryToPrintingFormat(algebraic_query)))
choice = showMenu()
new_rule = operateRule(choice - 1, algebraic_query)
query_printer(new_rule) |
def complexQuery1():
query = """select h.blockID, count(h.incidentID)
from Crime c inner join happensAt h on c.incidentID = h.incidentID
where c.occuredAt between '2013-01-01' and '2020-12-31' and h.blockID != 0
group by h.blockID
order by count(h.inci... | The main task of the code is to handle a POST request by executing Complex Query 2, which retrieves crime data based on user-specified parameters (number of crimes and date). It processes form inputs, formats the date, calls `complexQuery2()` to fetch results, and renders a template with the fetched data alongside resu... | def query2():
query1Coords, query1Count = complexQuery1()
if request.method == 'POST':
print("Executing Complex Query 2")
# data = request.get_json()
numCrimes = str(request.form['topCrimeNum'])#str(data['numOfCrimes'])
crimeAfterDate = str(request.form['topCrimeTime'])#... |
def commit_search_action(self, emplid):
'''
Searching for courses often triggers multiple
activity_log actions as the search term is typed in.
We accumulate the typed into until either no more
activity records remain, or the end of the search text
input is detected. In ei... | The code processes a data row by determining the appropriate action based on `caller` and `action` values. It handles search term accumulation, activity logging, and delegates row processing to specialized methods (e.g., `extract_pins`, `handle_pin_unpin`). It skips activity records during ongoing searches and routes r... | def dispatch_row(self, row, row_id):
caller = row[CALLER_POS]
action = row[ACTION_POS]
emplid = row[EMPLID_POS]
# So far, it will be necessary further down
# to add an activity table record for this
# action:
add_activity_record = True
... |
def _load_crs_id_lookup_tbl(self):
cur_dir = os.path.dirname(__file__)
data_file = os.path.join(cur_dir, 'data/crs_id_lookup.csv')
with open(data_file, 'r') as fd:
reader = csv.reader(fd)
crs_nm2crs_id_dict = {row[0] : row[1]
for row
... | This code processes an activity log file, batching various user actions (pins, searches, selections) into memory buffers, then persisting them into a database. It initializes data structures for logging, database connections, and indexing, while handling compressed log files and progress tracking. The core task is impo... | def __init__(self,
activity_log_path,
db_user=None,
db_name=None,
db_pwd=None, # ******Remove
start_fresh = False,
unittesting=False):
'''
Constructor
'''
self.log = LoggingServ... |
def get_country_dict():
r = requests.get('https://api.teleport.org/api/countries/')
countries = r.json()
df_countries = pd.json_normalize(countries['_links']['country:items'])
df_countries['iso2'] = df_countries['href'].str.split('/', expand=True)[[5]]
return dict(zip(df_countries['iso2'].str.split(... | The function generates multiple visualizations (figures) using input lists (country, job, urban area) and predefined dictionaries. It creates four figures: two comparing job-country data, and two radial charts analyzing life/business quality parameters across urban areas, returning them as a list. | def return_figures(country_list, jobs_list, ua_list):
# Get dictionaries
country_dict = get_country_dict()
ua_id_dict = get_ua_id_dict()
job_dict = get_job_dictionary()
#print(f'{jobs_list}')
jobs_list_from_dict = []
for job in jobs_list:
jobs_list_from_dict.append(job_dict[job])
... |
def setup_logging():
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)
logging.info(Fore.RED + header)
def handle_create_wallet(quorum, relay_manager, private_key):
time_stamp = int(time.time())
req_id = str(uuid.uuid4())
new_wallet_payload = generate_nostr_message(
comman... | This code runs a signer for a cryptographic wallet system, enabling users to create wallets, generate public keys and addresses, and handle transaction signing via Nostr relays. It processes commands like creating wallets, posting public keys, generating addresses, spending funds, and signing transactions, using a rela... | def run_signer(wallet_id=None, key_pair_seed=None, nonce_seed=None):
setup_logging()
relay_manager = add_relays()
nostr_private_key, nostr_public_key = read_nsec('src/signer/nsec.txt')
# get the public keys for the coordinator so we can subscribe to messages from them
cordinator_pk = read_public_k... |
def show_message(message, fg_color, bg_color):
""" show messages on the screen
message: The message you would like to show on the screen
fg_color/bg_color: color for the texts and the background screen
"""
# clear the screen and blit the texts
win_surf = pygame.display.get_surface()
win_su... | The function `run_trial` conducts a single trial in an eye-tracking experiment. It displays a fixation cross, waits for the participant's gaze to stabilize, then presents an image while recording eye movements and response times. It handles recalibration, logs trial data (condition, image, RT), manages user inputs (abo... | def run_trial(trial_pars, trial_index, should_recal):
""" Helper function specifying the events that will occur in a single trial
trial_pars - a list containing trial parameters, e.g.,
['cond_1', 'img_1.jpg']
trial_index - record the order of trial presentation in the task
should_recal ... |
def is_empty(self):
return self.root is None
def _find_node(self, key: K) -> Optional[LeafNode]:
"""Gets the node that should return key if it is in this tree"""
if self.root is None:
return None
n = self.root
while isinstance(n, InternalNode):
n = n.follo... | The code inserts a key-value pair into a B-tree-like structure. If the tree is empty, it creates a new leaf node. Otherwise, it locates the appropriate leaf node. If the node has space or already contains the key, it inserts directly. If full, it splits the node into two, redistributing keys/values and updating pointer... | def insert(self, key: K, val: V):
if self.is_empty():
self.root = LeafNode()
self.root.pointers = [[val]]
self.root.keys = [key]
return
L = self._find_node(key)
if L.has_key(key) or len(L.keys) < self.n - 1:
L.insert(key, val)
e... |
def list_to_points(points) -> T.List[Point]:
ps = [Point.fromCSV(x) for x in points]
return ps
def process_image(img):
global params_
global args_
params_ = compute_foregrond_background_stats(img)
T = transform_axis(img, erase_near_axis=3)
assert img.std() > 0.0, "No data in the image!"
... | The code processes an image to extract a trajectory by converting it to grayscale, applying thresholding, morphological operations, grid removal, and normalization. It defines reference points/locations, generates a trajectory via image processing, optionally plots it, and saves the trajectory data to a CSV file. | def run(img_path, plot=None, output=None):
global locations_, points_
global img_, img_orig
global h_, w_
infile = Path(img_path)
assert infile.exists(), f"{infile} does not exists."
# reads into gray-scale.
img_orig = cv.imread(str(infile))
img_ = cv.imread(str(infile), 0)
(thresh... |
def predict(self, Xs):
'''Returns the model predictions (output of the last layer) for the given "Xs".'''
predictions = []
for i in range(len(Xs)):
preds = self.forward_pass(Xs[i,:].reshape((1, self.input_shape)))[-1]
predictions.append(preds.reshape((self.output_shape)))
return np.array(predictions)
d... | The code evaluates a machine learning model by computing cross-entropy loss and accuracy on provided datasets. It predicts outputs using `self.predict`, compares them to true labels via `accuracy`, and calculates loss with `cross_entropy_loss`, returning both metrics for performance assessment. | def evaluate(self, Xs, Ys):
'''Returns appropriate metrics for the task, calculated on the dataset passed to this method.'''
pred = self.predict(Xs)
acc = self.accuracy(pred.argmax(axis=1), Ys.argmax(axis=1))
loss = self.cross_entropy_loss(pred, Ys)
return loss,acc |
def forward_pass(self, input_data):
'''Executes the feed forward algorithm.
"input_data" is the input to the network in row-major form
Returns "activations", which is a list of all layer outputs (excluding input layer of course)
What is activation?
In neural network you have inputs(x) and weights(w).
What i... | The code trains a neural network model using gradient descent over multiple epochs. It iterates through each data sample, performs forward and backward passes to compute weight updates, and appends the loss after each epoch to a history list. The function returns this loss history for monitoring training progress. | def fit(self, Xs, Ys, epochs, t_array, acc_array, startTime, lr=1e-3):
'''Trains the model on the given dataset for "epoch" number of itterations with step size="lr".
Returns list containing loss for each epoch.'''
history = []
first_layer = []
for i in range(epochs):
for j in range(0,Xs.shape[0]):
X ... |
def calculate_shortest_path(current_location):
# Clearing selected packages lists every run to not accumulate data in current list
selected_packages.clear()
selected_packages_copy.clear()
# Sort the products and weights in ascending order of weight
sorted_package_weights = sorted(package_weights.it... | The code plans a delivery route for a drone, ensuring it can reach each destination by inserting charging points when necessary. It calculates the shortest path from the warehouse, checks battery sufficiency for each leg, adds charging stops if needed, and adjusts the route accordingly. Finally, it returns to the neare... | def deliver_packages(starting_warehouse_location):
drone_max_charge = 100
drone_max_distance = 20
current_charge = drone_max_charge
# Calculating route
route = calculate_shortest_path(starting_warehouse_location)
current_location = starting_warehouse_location[1]
for location in route:
... |
def PollPressure(self,ID,serP):
command = bytes('P\r','ascii')
print('Pressure poll command: ' + command.decode('ascii'))
serP.write(command)
reply = serP.read_until(expected=bytes('>','ascii'))
reply = reply.decode('ascii',errors = 'ignore')
print('Received: ' + reply)
... | The code's main task is to check connection status flags for sensors (P0, P1, flowmeter), poll data from connected sensors using corresponding methods, and update visualization plots with the acquired sensor data. It conditionally executes pressure and flow measurements based on hardware connection status flags, then t... | def PollSensors(self):
if P0_connected_flag:
self.PollPressure(1,serP0)
if P1_connected_flag:
self.PollPressure(2,serP1)
if flowmeter_connected_flag:
self.PollFlow()
self.UpdatePlots() |
def findrequests(graph, bucket):
reqs = {}
for node in bucket:
if node in graph["ginfo"]:
for j in range(len(graph["ginfo"][node]["nodes"])):
if graph["ginfo"][node]["nodes"][j] in reqs:
if reqs[graph["ginfo"][node]["nodes"][j]] > d[node] + graph["ginfo"][... | The code implements a parallel delta-stepping algorithm for shortest path computation in a graph. It initializes distances, processes nodes in B (a priority structure), relaxes edges, and iterates until no more updates. The algorithm uses rank checks for distributed execution, manages distance updates, and returns the ... | def deltastepping(graph):
if rank != 0:
for i in range(len(graph["ginfo"].keys())):
d[int(i)] = float("inf")
if rank != 0:
if source in graph["ginfo"]:
d[int(source)] = 0
B[0.0] = [ source ]
cycle = 0
existB = True
while existB:
if B:
... |
def general():
global frame_right1_container
frame_right1_container.destroy()
get_container_right1_for_delete()
frame_right1_container.pack(side=tk.TOP, fill=tk.BOTH)
frame_inside_container = tk.Frame(frame_right1_container,bg='#E9F7F8')
frame_inside_container.pack(side=tk.TOP, fill=tk.BOTH)
... | The code defines a GUI display function creating a frame with a styled label and three buttons ("View All", "Available Book", "Issued Book") for interacting with book data. Each button triggers specific actions (view_action, view_available_action, view_issue_action) to handle different book-related operations, likely i... | def display():
frame_inside_container = general()
name_label = tk.Label(frame_inside_container, text='Display Book',
relief=tk.RIDGE, height=1, width=25,
bg='#FF9A98', bd=7, font=(None, 24))
name_label.pack(side=tk.TOP, fill=tk.BOTH)
view_confirm_butto... |
def general():
global frame_right1_container
frame_right1_container.destroy()
get_container_right1_for_delete()
frame_right1_container.pack(side=tk.TOP, fill=tk.BOTH)
frame_inside_container = tk.Frame(frame_right1_container,bg='#E9F7F8')
frame_inside_container.pack(side=tk.TOP, fill=tk.BOTH)
... | The code creates a GUI interface for searching books by setting up input fields for book ID, author name, title, and year using Tkinter. It initializes variables to capture user input and includes a "Find" button that triggers a search action with the entered criteria. | def search():
frame_inside_container = general()
global id,name,title,year
id,name,title,year = tk.StringVar(),tk.StringVar(),tk.StringVar(),tk.StringVar()
view_action()
name_label = tk.Label(frame_inside_container, text='Search Book',
relief=tk.RIDGE, height=1, width=25,
... |
def general():
global frame_right1_container
frame_right1_container.destroy()
get_container_right1_for_delete()
frame_right1_container.pack(side=tk.TOP, fill=tk.BOTH)
frame_inside_container = tk.Frame(frame_right1_container,bg='#E9F7F8')
frame_inside_container.pack(side=tk.TOP, fill=tk.BOTH)
... | The code defines a GUI function `add()` to create an interface for inputting book details. It initializes global variables for author name, title, and year, then constructs labels, entry fields, and a confirmation button using Tkinter. The layout organizes these elements in a frame, allowing users to input data which i... | def add():
frame_inside_container = general()
global name,title,year
name,title,year=tk.StringVar(),tk.StringVar(),tk.StringVar()
view_action()
add_label = tk.Label(frame_inside_container, text='Add Book',
relief=tk.RIDGE, height=1, width=25,
bg='#... |
def general():
global frame_right1_container
frame_right1_container.destroy()
get_container_right1_for_delete()
frame_right1_container.pack(side=tk.TOP, fill=tk.BOTH)
frame_inside_container = tk.Frame(frame_right1_container,bg='#E9F7F8')
frame_inside_container.pack(side=tk.TOP, fill=tk.BOTH)
... | The code creates a GUI interface for issuing books, displaying a 'Book Id' input field and a 'Supply' button. It uses Tkinter widgets to structure the layout, binds the input to a global variable, and links the button to an `issue_action` function for processing the book issuance. | def issue():
frame_inside_container = general()
global id
id=tk.StringVar()
view_action()
issue_label = tk.Label(frame_inside_container, text='Issue Book',
relief=tk.RIDGE, height=1, width=25,
bg='#FF9A98', bd=7, font=(None, 24))
issue_label.pack... |
def general():
global frame_right1_container
frame_right1_container.destroy()
get_container_right1_for_delete()
frame_right1_container.pack(side=tk.TOP, fill=tk.BOTH)
frame_inside_container = tk.Frame(frame_right1_container,bg='#E9F7F8')
frame_inside_container.pack(side=tk.TOP, fill=tk.BOTH)
... | The code creates a GUI interface for returning a book, including a label, entry field for the book ID, and a "Return" button. It uses Tkinter widgets to structure the layout, binds the entry field to a global variable, and triggers a return_action function upon button click. The main task is to facilitate user input of... | def return_():
frame_inside_container = general()
global id
id=tk.StringVar()
view_action()
return_label = tk.Label(frame_inside_container, text='Return Book',
relief=tk.RIDGE, height=1, width=25,
bg='#FF9A98', bd=7, font=(None, 24))
return_label... |
def general():
global frame_right1_container
frame_right1_container.destroy()
get_container_right1_for_delete()
frame_right1_container.pack(side=tk.TOP, fill=tk.BOTH)
frame_inside_container = tk.Frame(frame_right1_container,bg='#E9F7F8')
frame_inside_container.pack(side=tk.TOP, fill=tk.BOTH)
... | This code creates a GUI interface for deleting a book by displaying a 'Delete Book' label, a 'Book Id' input field, and an 'Approve' button. It uses Tkinter widgets to structure the layout, captures user input via a StringVar, and links the 'Approve' button to a delete_action function for processing the deletion. The m... | def delete():
frame_inside_container = general()
global id
id=tk.StringVar()
view_action()
delete_label = tk.Label(frame_inside_container, text='Delete Book',
relief=tk.RIDGE, height=1, width=25,
bg='#FF9A98', bd=7, font=(None, 24))
delete_la... |
def clear():
window.destroy()
def delete_all_action():
delete = TableFn.delete_all(table_name=table_name)
if delete==0:
result_page(result_text='All data Deleted')
frame_inside_container = general1()
elif delete == 1:
result_page(result_text='Fail to Delete All')
def drop_action(... | The main task of the code is to create a graphical user interface (GUI) for a Library Management System using Tkinter. It sets up buttons for actions like displaying records, searching, adding, issuing, returning, and deleting items, along with controls for resetting, deleting all data, and clearing the interface. The ... | def main():
label_header = tk.Label(frame_top, text='Library Management System',
relief=tk.RIDGE, height=1, width=55,
bg='#6EAD50', bd=7, font=(None, 18))
label_header.pack(side=tk.LEFT, anchor=tk.W,expand=1,fill=tk.BOTH)
clear_button = tk.Button(frame... |
def get_parser():
''' Read commandline options and filenames '''
parser = argparse.ArgumentParser(description='Compares two Exodus II files')
parser.add_argument('file1')
parser.add_argument('file2')
parser.add_argument('--rtol', default = 1e-6, dest = 'rtol', type = float,
help = 'Relativ... | The code compares two Exodus II files by analyzing their dimensions, variable names, and values using specified tolerances. It parses command-line arguments, checks for differences, and reports results. If discrepancies are found, it prints details unless quiet mode is enabled, then confirms whether the files are ident... | def main():
''' Compare two Exodus II files and reports the differences '''
# Parse commandline options
parser = get_parser()
args = parser.parse_args()
# Compare the two Exodus II files
diff = exodiff(args.file1, args.file2, args.rtol, args.atol)
# If diff is not empty, then there are di... |
def get_disc_containers(self):
disc_containers = {}
if 'tracklist' in self.data:
self._get_tracks(self.data['tracklist'], disc_containers)
return disc_containers
def get_track_number(self, trackContainer):
number = trackContainer['track_number_string']
if not re.searc... | The main task of the code is to populate a result object with disc and track data by iterating through disc containers. For each disc, it creates a disc object, assigns a disc number, and processes track containers to generate tracks with numbers, titles, lengths, and artists. Each track is appended to the disc, which ... | def add_discs(self):
disc_containers = self.get_disc_containers()
for disc_nr in disc_containers:
disc = self.result.create_disc()
disc.set_number(disc_nr)
for track_container in disc_containers[disc_nr]:
track = disc.create_track()
tr... |
def _get_leaf_weight(self, y, y_hat):
"""
Returns the weight for each leaf
"""
grad = self.loss_function.get_gradient(y, y_hat)
hess = self.loss_function.get_hessian(y, y_hat)
return -np.sum(grad) / (np.sum(hess) + self.reg_lambda)
def _find_best_split(self, X, y, y_hat):... | This function recursively constructs a decision tree by evaluating stopping criteria (e.g., zero data, insufficient Hessian, max depth, split score < gamma) to return leaf nodes, or splitting data on the best feature to create inner nodes with left/right subtrees, ensuring tree growth adheres to regularization constrai... | def _build_tree(self, X, y, y_hat, depth):
"""
Recursivelly build the tree
- We don't create a new node if the shape the data is 0
- We return a leaf node if the total Hessian measured on the data
is smaller or equal than min_child_weight
- We return a leaf node if the ... |
def update_policy(self, name):
self.policy.save(BUFFER_PATH, "%s_copy" %name)
# To prevent failure of actors when reading the saved policy
shutil.move(
join(BUFFER_PATH, "%s_copy_actor" %name),
join(BUFFER_PATH, "%s_actor" %name)
)
shutil.move(
... | This method collects trajectories from containers by updating the policy, launching parallel actors to gather data, aggregating results, and expanding the buffer with new trajectories until the specified step count is reached. | def collect(self, n_steps):
""" This method searches the buffer folder and collect all the saved trajectories
"""
# collect happens after policy is updated
# save the updated policy to the buffer
self.update_policy("policy")
steps = 0
results = []
while s... |
def _train_epoch(self):
"""Train model one epoch."""
self.model.train()
if self.metric_fc is not None:
self.metric_fc.train()
for steps_per_epoch, batch in enumerate(self.data_loader["train"]):
# train one step
self._train_step(batch)
# ch... | This code executes a training loop for a machine learning model, iterating through epochs with progress tracking via tqdm. It trains for one epoch, validates periodically based on log intervals, checks save intervals for model checkpoints, and terminates training when completion conditions are met. The loop continues u... | def run(self):
"""Run training."""
self.tqdm = tqdm(
initial=self.epochs, total=self.config["train_max_epochs"], desc="[train]"
)
while True:
self._train_epoch()
if self.epochs % self.config["log_interval_epochs"] == 0:
self._valid_epoc... |
def get_motion_plan(self, goal: Goal) -> GetMotionPlanResponse:
req = self.get_motion_plan_req(goal)
resp = self.get_motion_plan_srv(req)
return resp.motion_plan_response.error_code.val, resp.motion_plan_response.trajectory
def retry_planning(
self, goal: Goal
) -> Tuple[int, Optiona... | This code plans a motion goal by attempting to generate a trajectory, retrying if an inverse kinematics solution is missing, checking joint configuration changes, and returning success/failure status along with configuration details. | def plan_goal_cb(self, req: PlanGoalRequest) -> PlanGoalResponse:
self.trajectory = None
error_code, trajectory = self.get_motion_plan(req.goal)
if error_code == MoveItErrorCodes.NO_IK_SOLUTION:
error_code, trajectory = self.retry_planning(req.goal)
if error_code == MoveItErr... |
def get_motion_sequence_plan(
self, goals: List[Goal], blends: List[float]
) -> GetMotionSequenceResponse:
msr = GetMotionSequenceRequest()
for i in range(len(goals)):
msi = MotionSequenceItem()
msi.req = self.get_motion_plan_req(goals[i])
msi.blend_radius... | This function plans a motion sequence for given goals and blends, checks for trajectory validity, retries on IK failures, verifies joint configuration changes, and returns a success/failure response with relevant data. | def plan_sequence_cb(self, req: PlanSequenceRequest) -> PlanSequenceResponse:
self.trajectory = None
error_code, trajectory = self.get_motion_sequence_plan(req.goals, req.blends)
if (len(trajectory)) > 1:
rospy.logerr("commander: multiple trajectories !!!!!!!")
if error_code ... |
def _is_finished(self, depth):
# has finished growing the tree if reached max_depth of num_samples in each split
if (depth >= self.max_depth
or self.n_class_labels == 1
or self.n_samples < self.min_samples_split):
return True
return False
def _best_split(sel... | This function recursively constructs a decision tree by selecting the best feature-threshold split, partitioning the data, and creating child nodes until stopping criteria are met. It handles termination by returning nodes with majority class labels or single-class values, then recursively builds left and right subtree... | def _build_tree(self, X, y, depth=0):
# builds tree recursively by getting the best split
self.n_samples, self.n_features = X.shape
self.n_class_labels = len(np.unique(y))
# stopping criteria
if self._is_finished(depth):
if len(np.unique(y)) == 1:
r... |
def select(self,env,node,turn):
# selects the node with the highest UCB until a leaf node is reached
current = node
spacials = []
non_spacials = []
turns = []
distributions = []
spatial_obs, non_spatial_obs, action_mask = node.spacials, node.non_spacials,... | This function performs a single iteration of Monte Carlo Tree Search (MCTS) in a BotBowl environment. It initializes or continues from a given root node, selects a path via tree traversal, expands unexplored nodes, simulates outcomes using a reward goal, and backpropagates results to update node values. The process tra... | def one_run(self,reward_goal,root=None):
reward = None
if root == None:
env_conf = EnvConf(size=5)
env = BotBowlEnv(env_conf,away_agent='human')
env.reset()
# env.render(feature_layers=True)
env = RewardWrapper(env, home_reward_func=A2C_Reward... |
def intro():
print('This Program simulates RACQUETBALL.')
print('Simulation is done on basis of probability of winning serves.')
print('For Simplicity of results, Player-A will always serve first.')
def getinputs():
prob_A = float(input('Enter Probability for A: '))
prob_B = float(input('Enter Proba... | The main task of the code is to simulate a game between two players (A and B) using specified probabilities and a given number of games. It begins by displaying an introduction, retrieves input values for probabilities and game count, simulates the games to determine outcomes for A and B, and finally generates a report... | def main(): # Main function for simulating the problem
intro()
prob_A, prob_B, no_of_game = getinputs()
A, B = sim_game(prob_A, prob_B, no_of_game)
report_card(A, B) |
def _fetch_html_eztv(self, full_url):
print("Fetching search results from eztv...")
html_doc = requests.get(full_url).text
print("Done fetching...")
return html_doc
def _fetch_html_pb(self, full_url, progress_bar):
progress_bar.update(1)
html_doc = requests.get(full_url).... | This code initializes a scraper to fetch and process TV show torrents from eztv.re and thepiratebay.asia. It constructs search URLs, retrieves HTML content, parses torrent data, rates/sorts episodes, and selects preferred results. The core task is to aggregate, filter, and organize torrent listings for user-specified T... | def __init__(self, user_show):
self.base_url_eztv = "https://eztv.re/search/"
self.base_url_pb = "https://thepiratebay.asia/s/?q="
if not user_show:
user_show = "game of thrones"
self.full_url_eztv = self.base_url_eztv + user_show
self.full_url_pb = self.base_url_pb +... |
def compute_layer_blocks_out(layer, ncc):
#blocks are computer on the output because the weight matrix is transposed
u, _, _ = layer_svd(layer)
blocks = -torch.ones(layer.out_features, dtype=torch.int) #pruned neurons will have value of -1
w = get_masked_weight(layer)
d1_inv_root = torch.diag(1/torc... | This code implements a forward pass with conditional dropout. During training, if `n_conn_comp` > 1, it applies block-wise dropout using predefined blocks (input/output-specific) and a given `do_rate`. Otherwise, standard dropout is used. In evaluation mode, input is returned unchanged. The dropout rate defaults to `se... | def forward(self, input, do_rate=0):
if do_rate == 0:
do_rate = self.p
if self.training:
if self.n_conn_comp > 1:
if self.apply_to=="out":
blocks = compute_layer_blocks_out(self.layer, self.n_conn_comp)
else:
... |
def getNeighbours(self, i, j):
result = []
neighbors = [[i-1,j],[i-1,j+1],[i,j-1],[i+1,j-1],[i+1,j],[i+1,j+1],[i,j+1],[i-1,j-1]]
for n in neighbors:
if 0 <= n[0] <= self.rows-1 and 0 <= n[1] <= self.cols-1:
result.append(n)
return result
def getCell(self, p):
return self.board[p[0]][p[... | This code populates a minefield by placing mines on random cells excluding the start position and its neighbors, then updates adjacent cells with the count of nearby mines. It ensures proper mine placement and updates cell values for a Minesweeper-like grid, ending with a verification check. | def populate(self, start=[]):
start_neighbours = self.getNeighbours(start[0], start[1])
start_neighbours.append(start)
board_coordinates = [[i, j] for i in range(self.rows) for j in range(self.cols) if not [i, j] in start_neighbours]
mine_coordinates = sample(board_coordinates, self.mines)
for mine... |
def populate(self, start=[]):
start_neighbours = self.getNeighbours(start[0], start[1])
start_neighbours.append(start)
board_coordinates = [[i, j] for i in range(self.rows) for j in range(self.cols) if not [i, j] in start_neighbours]
mine_coordinates = sample(board_coordinates, self.mines)
for mine... | This code reveals a cell in a game grid, unhidden it, and recursively reveals neighboring cells if the current cell has no remaining adjacent mines, based on flag placements. It initializes game setup if not already started, ensuring proper propagation of uncovered cells when safe. | def look(self, p):
if not self.started:
self.populate(p)
self.started = True
cell = self.getCell(p)
cell.hidden = False
flagsAround = self.getFlagNeighbors(p[0], p[1])
if not cell.mine and cell.value - len(flagsAround) == 0:
neighbours = self.getNeighbours(p[0], p[1])
for n i... |
def _anim_pose_to_deepwalker_pose(anim_pose, verbose = False) -> DWPose:
"""Converts a pose from an AnimReader into a deepwalker pose
Args:
anim_pose (dict<str: JointState>): The anim pose to convert. Anim joint names to their states.
Returns:
tuple of float with BulletJointState: The new... | This code converts an anim.xml file to a dwanim.xml format compatible with Deepwalker. It reads animation frames, interpolates poses between frames into finer timesteps, and writes the result as a structured XML file. The process involves pose conversion, timestep calculation, and XML tree construction with indentation... | def process_anim(anim_filepath):
"""Converts one anim.xml to dwanim.xml so Deepwalker can understand it
"""
anim_filename = os.path.basename(anim_filepath)
dwanim_save_filename = anim_filename.partition(".")[0] + ".dwanim.xml"
dwanim_save_filepath = join( common.DWANIMS_DIR, dwanim_save_filename )
... |
def get_style_image_features(image):
preprocessed_style_image = preprocess_image(image)
outputs = inception(preprocessed_style_image)
style_outputs = outputs[1:]
gram_style_features = [gram_matrix(style_layer) for style_layer in style_outputs]
return gram_style_features
def get_content_image_featu... | The code performs neural style transfer by generating an image that combines the style of a provided style image and the content of a content image. It initializes features from both images, iterates through epochs/steps, and updates a generated image using an optimizer to minimize style/content loss. The process outpu... | def fit_style_transfer(style_image, content_image, style_weight=1e-2, content_weight=1e-4,
optimizer='adam', epochs=1, steps_per_epoch=1):
images = []
step = 0
style_targets = get_style_image_features(style_image)
content_targets = get_content_image_features(content_i... |
def loadImages():
# Load all of the images. Display an error message and quit if the images
# are not loaded successfully.
try:
allImages = loadImage("ViperImages.gif")
except:
print("An error was encountered while trying to load the images from")
print("ViperImages.gif. Please ensure that it resi... | The code implements a multi-player snake game where a human player and AI-controlled snakes compete. It handles movement, collision detection (walls, self, others), scoring, and game state transitions. The player's snake grows, navigates obstacles, and competes against AI opponents. The game tracks scores, determines w... | def main():
# Only redraw the screen when specifically requested to do so
setAutoUpdate(False)
counter = 0 # Frame counter
speed = 100 # Snake speeds in pixels per second
max_length = 100 # Current maximum length for the snakes
time_since_increase = 0 # How much time has el... |
def isValidNode(self, root, node):
if root is None:
return False
if root == node:
return True
if node.val < root.val:
return self.isValidNode(root.left, node)
else:
return self.isValidNode(root.right, node)
def countNumberOfNodes(self, ro... | This function finds the lowest common ancestor (LCA) of two nodes p and q in a binary tree. It first validates inputs: p and q must be distinct, exist in the tree, and the tree must have 2-100,000 unique nodes. If valid, it recursively searches subtrees, returning the root if p/q are in opposite subtrees, or the non-nu... | def lowestCommonAncestor(self, root, p, q):
if p == q or not self.isValidNode(root, p) or not self.isValidNode(root, q) or \
not (2 <= self.countNumberOfNodes(root) <= 100000) or \
not self.nodeValueCheck(root) or not self.areAllValuesUnique(root):
raise ValueError("The conditi... |
def intra_block_MHA(inputs, n_blocks, n_heads, n_units, mask, dropout_rate, is_training, scope='intra_block_MHA'):
'''input shape = [N, T, C], mask shape = [N, T], where N = batch size, T = time steps, C = feature size'''
# Split
blocks_embed = tf.concat(tf.split(inputs, n_blocks, axis=1), axis=0) # [b*N, T... | The code implements an encoder-decoder model with multi-head attention for sequence processing. The encoder processes input sequences using self-attention, positional encoding, and layer-wise weighted aggregation, while predicting chord changes. The decoder incorporates self-attention, positional attention, and cross-a... | def HTv2(x, source_mask, target_mask, slope, dropout_rate, is_training, hyperparameters):
input = x
with tf.variable_scope("encoder_input_embedding"):
enc_input_embed = tf.layers.dense(input, hyperparameters.input_embed_size) # [n_batches, n_steps, input_embedding_size]
enc_input_embed = tf.laye... |
def load_dataset(resolution, vocabulary):
pieces = load_pieces(resolution=resolution) # {'no': {'pianoroll': 2d array, 'chromagram': 2d array, 'start_time': float}...}
chord_labels = load_chord_labels(vocabulary=vocabulary) # {'no': array}
corpus = get_framewise_labels(pieces, chord_labels, resolution=reso... | The main task of the code is to preprocess musical datasets by loading, augmenting, reshaping, and saving data for machine learning. It uses a specified vocabulary ('MIREX_Mm'), applies data augmentation (adding shifts and tonal features), reshapes arrays into 3D structures for model compatibility, and stores the proce... | def main():
vocabulary = 'MIREX_Mm'
corpus = load_dataset(resolution=4, vocabulary=vocabulary) # {'no': {'pianoroll': 2d array, 'chromagram': 2d array, 'start_time': float, 'label': array}, ...}
corpus_aug = augment_data(corpus) # {'shift_id': {'no': {'pianoroll': 2d array, 'chromagram': 2d array, tonal_ce... |
def _log(message: str) -> str:
print(message)
return message
def is_valid_filename(filename: str) -> bool:
return bool(fastq_utils.FASTQ_PATTERN.fullmatch(filename))
def _open_fastq_file(file: Path) -> TextIO:
return gzip.open(file, "rt") if file.name.endswith(".gz") else file.open()
def validate_fastq_... | This function validates a FASTQ file by checking its filename format, handling gzip compression, and verifying readable content. It logs errors for invalid filenames, file access issues, compression errors, or unexpected exceptions, while counting records in the file. | def validate_fastq_file(self, fastq_file: Path) -> None:
_log(f"Validating {fastq_file.name}...")
_log(f" → {fastq_file.absolute().as_posix()}")
if not is_valid_filename(fastq_file.name):
# If we don't like the filename, don't bother reading the contents.
self.errors.... |
def get_move(self, available_spaces):
while True:
try:
move = int(self.input_move(available_spaces))
if self.validate_input(move, available_spaces):
break
print(
"Invalid input - please make sure you have chosen ... | The code implements a game loop for a turn-based game. It repeatedly displays the board, retrieves available spaces, prompts the current player for a move, checks if the game is over, and switches players if the game continues. The loop terminates when the game ends, displaying the final board state. | def round_loop(self):
while True:
self.board.display_board()
spaces = self.board.get_available_spaces()
self.get_move(spaces)
if self.check_if_game_over():
self.board.display_board()
break
self.change_player() |
def round_loop(self):
while True:
self.board.display_board()
spaces = self.board.get_available_spaces()
self.get_move(spaces)
if self.check_if_game_over():
self.board.display_board()
break
self.change_player()
def displa... | The code defines a game loop that repeatedly initializes a new game board, processes rounds, displays scores, and checks if the player wants to continue. It runs until the player chooses to stop, then exits with a thank-you message. | def game_loop(self):
while True:
self.board = Board()
self.round_loop()
self.display_scoreboard()
if not self.play_again():
break
print("A new game shall begin!")
print("Thanks for playing :-)") |
def det(vector1, vector2):
return vector1[0] * vector2[1] - vector1[1] * vector2[0]
def abs(vector):
return math.sqrt(np.dot(vector, vector))
def normalize(vector):
norm = np.linalg.norm(vector)
if norm == 0:
raise Exception('normalizing vector of size 0')
return vector / norm
def linearProg... | This function performs a linear programming step to find a collision-free velocity for a moving object by iteratively checking line conflicts. It projects lines, calculates determinants to detect parallelism, and uses a helper function (linearProgram2) to adjust the result while avoiding obstacles. The process updates ... | def linearProgram3(lines, begin_line, radius, result):
distance = 0.0
for i in range(begin_line, len(lines)):
if det(lines[i].direction, lines[i].point - result) > distance:
proj_lines = []
for j in range(i):
line = Line()
determinant = det(line... |
def preprocess_data(threshold, window, horizon, priced, aggregated, chainlet_allowed, log_return, train_slide_length):
priced_bitcoin = pd.read_csv(PRICED_BITCOIN_FILE_NAME, sep=",")
if (ALL_YEAR_INPUT_ALLOWED):
pass
else:
priced_bitcoin = filter_data(priced_bitcoin, train_slide_length)
... | The function initializes and prepares data for a machine learning model by preprocessing input parameters, splitting data into training/test sets, excluding specific days, and separating input-output pairs. It returns scalers, input/target lists, and metadata for model training and evaluation, structuring financial tim... | def initialize_setting(threshold, window, horizon, priced, aggregated, chainlet_allowed, log_return, train_slide_length, test_slide_length):
scaler, data = preprocess_data(threshold, window, horizon, priced, aggregated, chainlet_allowed, log_return, train_slide_length)
train_list, test_list = train_test_split_... |
def get_data_file_path():
return os.path.join(up(up(up(up(up(up(__file__)))))), "data")
def filter_data(priced_bitcoin):
end_day_of_previous_year = max(priced_bitcoin[priced_bitcoin['year'] == START_YEAR-1]["day"].values)
start_index_of_previous_year = end_day_of_previous_year - SLIDING_BATCH_SIZE - window_... | The function preprocesses Bitcoin price data by generating a normalized occurrence matrix using sliding windows of specified size and prediction horizon. It filters data if needed, constructs daily occurrence matrices for each window, and concatenates them into a single array for machine learning input, considering pri... | def preprocess_data(window_size, prediction_horizon, is_price_of_previous_days_allowed, aggregation_of_previous_days_allowed):
data_file_path = get_data_file_path()
price_bitcoin_file_path = os.path.join(data_file_path, PRICED_BITCOIN_FILE_NAME)
priced_bitcoin = pd.read_csv(price_bitcoin_file_path, sep=",")... |
def preprocess_data(window_size, prediction_horizon, is_price_of_previous_days_allowed, aggregation_of_previous_days_allowed):
data_file_path = get_data_file_path()
price_bitcoin_file_path = os.path.join(data_file_path, PRICED_BITCOIN_FILE_NAME)
priced_bitcoin = pd.read_csv(price_bitcoin_file_path, sep=",")... | The main task of the code is to preprocess and split time-series data into training and testing sets for a predictive model. It processes input parameters to prepare data, divides it into training/test subsets, excludes specific days, and separates input features from target variables. The function returns structured l... | def initialize_setting(window_size, prediction_horizon, is_price_of_previous_days_allowed, aggregation_of_previous_days_allowed):
data = preprocess_data(window_size, prediction_horizon, is_price_of_previous_days_allowed, aggregation_of_previous_days_allowed)
train_list, test_list = train_test_split_(data)
x... |
def allNumbers(self):
numbers = []
for i in range(self._size):
numbers.append(1+i)
return numbers
def writeIn(self,n,x,y):
# print("Writing in",x,y,"at",n)
# if (self._status != Status.IN_PROGRESS):
# print("Dying here")
# return False
... | This code solves a puzzle group by identifying missing numbers and assigning them to empty positions. It checks each position in the group: if solved, it removes the number from available options; if empty, it tracks positions. Then, for each remaining number, it finds the first valid empty spot and assigns the number,... | def solveGroup(self,group):
numbers = self.allNumbers()
emptys = []
# Find out what numbers aren't accounted for
# Find out what available spaces there are
for pos in group:
if (self._solved[pos[0]][pos[1]]):
# print(pos[0],pos[1],self._possible[pos[0]... |
def focusGrid(ogimg):
rx = 500.0/ogimg.shape[0]
ry = 500.0/ogimg.shape[1]
r = max([rx,ry])
ogimg = cv2.resize(ogimg,(0,0),fx=r,fy=r)
img = cv2.cvtColor(ogimg, cv2.COLOR_BGR2GRAY)
# img = cv2.addWeighted(img, 1.5, np.zeros(img.shape, img.dtype), 0, 0)
img = cv2.adaptiveThreshold(img,255,cv... | The main task of the code is to extract a grid of digits from an input image. It processes the image by cleaning it, splitting it into individual cells, highlighting them, and then extracting the digits from each cell. If any step fails (e.g., invalid image, failed cleaning, or unreadable digits), it returns `None`. Th... | def extractGrid(img):
if img is None:
print("No such image found")
return None
clean = focusGrid(img)
if clean is None:
print("Failed")
return None
# cv2.imshow("clean",clean)
# cv2.waitKey(0)
cells = splitUp(clean)
cells = highlightCells(cells)
# prin... |
def clone(self):
newGrid = Grid(self._size,self._secW,self._secH,self._depth+1)
for i in range(0,self._size):
for j in range(0,self._size):
if (self._solved[i][j]):
newGrid.writeIn(self._possible[i][j][0],i,j)
# print("Clone:")
# newGrid.pr... | The code implements a guessing algorithm to solve a puzzle by iterating through cells with limited possibilities. It clones the grid, tests each possible value, and recursively solves. If a valid solution is found, it updates the grid and returns True. If multiple valid guesses exist, it selects one, applies it, and co... | def solveByGuess(self):
if (self._status != Status.IN_PROGRESS):
return False
changed = False
for i in range(0,self._size):
for j in range(0,self._size):
if (not self._solved[i][j] and len(self._possible[i][j]) <= 4):
works = -1
... |
def doQueue(self):
currentSolved = self._nSolved
while (len(self._queue) != 0):
self.writeIn(self._queue[0][0],self._queue[0][1],self._queue[0][2])
self._queue = self._queue[1:]
return (self._nSolved > currentSolved)
def solveByElimination(self):
if (self._status ... | The code repeatedly applies logical solving steps (doQueue, solveByElimination) until no further progress is made. If the puzzle remains unsolved, it initiates a guessing phase (solveByGuess) when the recursion depth is less than 2, indicating a need for heuristic-based solutions. | def solve(self):
progress = True
while progress:
# print("going")
progress = (self.doQueue() or self.solveByElimination())
if (self._status == Status.IN_PROGRESS):
print("Done all logical steps, moving onto guessing")
if (self._depth < 2):
... |
def get_genome(self, node: str):
return self.node2genome[node]
def extract_mutations(
self,
g1: np.ndarray, g2: np.ndarray,
name1: str, name2: str,
gene: str,
collect_freqs=True, context=False,
):
"""
Extract alterations of g... | This function traverses a tree structure using BFS to extract mutations between parent-child nodes, calculates mutspec metrics (12 and 192) for each mutation type, and aggregates nucleotide and context frequencies. It returns a concatenated DataFrame of all mutations with associated mutspec values and distances, enabli... | def extract_mutspec_from_tree(self, tree):
logger.info("Start extracting mutspec from tree")
discovered_nodes = set()
discovered_nodes.add(tree.name)
Q = Queue()
Q.put(tree)
edge_mutspec12 = defaultdict(list) # all, syn, ff
edge_mutspec192 = defaultdict(list)
... |
def read_data(path_to_tree, path_to_states, path_to_leaves, states_dtype=np.float16):
tree = PhyloTree(path_to_tree, format=1)
logger.info(f"tree loaded, number of leaf nodes: {len(tree)}, total number of nodes: {len(tree.get_cached_content())}")
dtypes = {
"p_A": states_dtype,
... | The main task of the code is to initialize a genetic analysis tool by loading phylogenetic tree data, codon tables, and mutation specifications. It processes nucleotide and codon information, extracts mutation spectra from the tree, and saves results like mutations, nucleotide frequencies, and edge-specific mutational ... | def __init__(
self,
path_to_tree,
path_to_states,
path_to_leaves,
out_dir,
gcode=2,
):
self.MUT_LABELS = ["all", "ff"] # TODO add syn
self.nucl_order = ["A", "C", "G", "T"]
self.gcode = gcode
self.codontabl... |
def readyModel_getPreds(imgDropped):
print("TRACE: readyModel_getPreds ...")
print("INFO: save raw tile ...")
strPth_tilRaw = save_tilRaw(imgDropped)
#--- ready the model
print("INFO: ready base model ...")
mdlBase = readyBaseModel()
print("INFO: ready model with weights ...")
m... | The function `showDiagnosis_horiz` processes a medical image to display diagnostic results, including the raw tile, model predictions, and GradCAM visualizations for background, whole tumor, and viable tumor regions. It organizes outputs into five Streamlit columns for side-by-side comparison, aiding in interpreting AI... | def showDiagnosis_horiz(imgDropped):
#--- copy the uploaded file to data/tiles/raw
st.write("#")
#--- ready the model, get predictions
print("TRACE2: ready model ...")
strPth_tilRaw, xai_pred, cam_img_bg, cam_img_wt, cam_img_vt = readyModel_getPreds(imgDropped)
#--- display the raw pr... |
def read_data(dirname):
raw_df = pd.DataFrame()
for file in os.listdir(dirname):
if file.endswith(".csv"):
data_from_this_csv = pd.read_csv(os.path.join(dirname, file), sep=';', encoding='UTF-8')
assert not data_from_this_csv.empty
raw_df = raw_df.append(data_from_thi... | The code processes experimental data by cleaning, filtering, and analyzing runtime statistics, timeouts, and call graph performance. It visualizes results, computes averages, identifies outliers, and exports detailed findings to CSV, focusing on seed behavior, error precision, and performance correlations in analysis t... | def main(dirname):
# Option to see the printed output more easily
pd.set_option('display.width', 250)
pd.set_option('display.max_columns', 6)
raw_data = read_data(dirname)
# Drop columns without useful information. Analysis always says "ideal" and there is an emtpy column
data = raw_data.drop(... |
def string_to_binary(self,s,sz):
res = ""
for i in s:
res += self.char_to_binary(i,sz)
arr = [int(i) for i in res]
return arr
def permutation(self,arr,box):
return [arr[i-1] for i in box]
def split_array(self,arr,x):
return [arr[i:i+x] for i in range(0,len(arr... | This code generates multiple cryptographic keys from an initial key using permutation and shifting operations. It truncates the input key, converts it to binary, applies optional masking, permutes bits via PC_1, splits the result, and iteratively applies left shifts and PC_2 permutations to produce a list of subkeys fo... | def generate_keys(self,key,no_of_keys,key_size):
keys = []
if(len(key) < key_size//8):
raise "Key length should be atleast "+str(key_size//8)
key = key[:key_size//8]
key_arr = self.string_to_binary(key,8)
if self.mask:
import random
random.seed... |
def split_array(self,arr,x):
return [arr[i:i+x] for i in range(0,len(arr),x)]
def string_to_binary(self,s,sz):
res = ""
for i in s:
res += self.char_to_binary(i,sz)
arr = [int(i) for i in res]
return arr
def permutation(self,arr,box):
return [arr[i-1] for i in... | The main task of the code is to implement a block cipher encryption algorithm (similar to DES) by applying multiple rounds of substitution-permutation operations on input text blocks. It performs initial permutation, key mixing, S-box substitution, and final permutation, storing intermediate results for each round. The... | def DEA(self,text,keys):
blocks = self.split_array(text,self.block_size//8)
cryp = []
#Stores the result after every round
cryp_inter = [[] for i in range(self.rounds)]
for block in blocks:
block = self.string_to_binary(block,8)
#Apply Intial Permuatat... |
def produce_dictionary(sentence, n, corpus):
n_test_result = n_test(sentence, n)
n_grams_result = n_grams(n, corpus)
n_grams_count_result = n_grams_count(n_grams_result)
n_grams_dic_result = n_grams_dic(n_grams_count_result, n_test_result)
return n_grams_dic_result
def back_off(dic, n, sentence, cor... | The function `finish_sentence` completes a given sentence by iteratively appending words from a corpus using either a randomized or deterministic selection method, based on n-gram probabilities. It continues until the sentence ends with a terminal punctuation (., ?, !) or reaches a maximum length of 10 words. | def finish_sentence(sentence, n, corpus, randomize=False):
while sentence[-1] not in [".", "?", "!"] and len(sentence) < 10:
produce_dictionary_result = produce_dictionary(sentence, n, corpus)
back_off_result = back_off(produce_dictionary_result, n, sentence, corpus)
if randomize == True:
... |
def DeleteAtFront(self):
if self.init is None:
print("List has no element")
return
self.init = self.init.then
def __len__(self, element=None, n=1):
if element is None:
element = self.init
if element:
if element.then is None:
... | This method deletes a node at a specified position in a linked list. It handles edge cases for front (pos=1) and end (pos=length) positions, using recursion for middle positions. If 'element' is None, it defaults to the head node. It adjusts pointers to skip the target node, with 'n' tracking recursive steps. If the po... | def DeleteAtPos(self, pos, element=None, n=1):
if pos == 1:
self.DeleteAtFront()
return
if pos == self.__len__():
self.DeleteAtEnd()
return
if element is None:
element = self.init
if pos < self.__len__():
if pos - 1... |
def DeleteAtFront(self):
if self.init is None:
print("List has no element")
return
self.init = self.init.then
def InsertAtFront(self, item):
Element = Node(item)
Element.then = self.init
self.init = Element
def __len__(self, element=None, n=1):
if ... | This function modifies the data of an element at a specified position in a linked list. It handles edge cases for the first and last positions by deleting and reinserting data. For other positions, it recursively traverses the list, updating the node's data when the position matches, using a recursive approach with a c... | def ChangeElementByPos(self, pos, data, element=None, n=1):
if pos == 1:
self.DeleteAtFront()
self.InsertAtFront(data)
return
if pos == self.__len__():
self.DeleteAtEnd()
self.InsertAtEnd(data)
return
if element is None:
... |
def DestroyChart(self):
print("Class Gui DestroyChart")
try:
self.top.destroy()
self.fig.clear()
if self.Status == True:
self.Table()
except AttributeError:
pass
def Table(self, Dataframe = None):
print("class Gui Table")
... | The main task of the code is to generate and display a bar chart using matplotlib within a Tkinter GUI, grouping data by date dimensions (year/month/day) or other attributes. It dynamically creates interactive plots, adjusts layouts, and includes a slider for large datasets. The function also prints aggregated data str... | def ShowChart(self):
print("Show Chart")
# try:
self.DestroyChart()
print(self.Agg_Dimensions)
print(self.Agg_DimensionsDate)
print(self.Agg_Measures)
if (len(self.Agg_Dimensions) > 0 or len(self.Agg_DimensionsDate) > 0) and len(self.Agg_Measures) > 0:
... |
def LabelFilter(self, word):
print("class Gui LableFilter")
if self.label:
self.label.destroy()
self.word = word
self.label = Label(self.root, text = word, bg = '#F0F8FF')
self.label.place(x=670, y=10)
def ShowChart(self):
print("Show Chart")
# try:
... | This method clears selected items from various listboxes based on user input, updates associated data structures, and triggers a chart refresh. It checks which listbox has a selection, removes items, clears filters, and calls ShowChart() to update the visualization. Error handling suppresses TclError exceptions from Tk... | def ClearCommand(self):
print("class Gui ClearCommand")
try:
if self.ListBox_Dimensions2.curselection():
self.ListBox_Dimensions2.delete(0, END)
self.ListBox_Filter.delete(0, END)
self.ListBox_Filter2.delete(0, END)
self.ListBox... |
def RemoveDimension2(self):
try:
Value = self.ListBox_Dimensions2.curselection()
StrValue = str(self.ListBox_Dimensions2.get(Value))
self.ListBox_Dimensions2.delete(Value)
for i in range(0,self.ListBox_Filter.size()):
if str(self.ListBox_Filter.get... | The main task of the code is to remove UI elements related to filters and dimensions in a GUI application. It deletes specific list boxes, clears filters, and updates the chart by removing selected filter entries from a list, handling potential errors gracefully. | def RemoveCommand(self):
print("class Gui RemoveCommand")
self.RemoveDimension2()
self.RemoveListBox(self.ListBox_Measures2, "Measures")
self.RemoveListBox(self.ListBox_DimensionsDate2, "DimensionsDate")
self.RemoveFilter()
try:
Value = self.ListBox_Filter3.cu... |
def update_gold_on_reserve(self, player):
if self.gold_in_bank > 0:
self.gold_in_bank -= 1
player.gold += 1
def update_cards_player_topdeck_reserve(self, player, tier):
if not self.decks[tier]:
raise IllegalMoveException(f'{player.name} tried to topdeck from empty dec... | The main task of the code is to process a player's action in a game, updating the game state accordingly. It handles three actions: 'reserve' (updating gold and cards), 'take' (transferring chips between player and bank after validation), and 'buy' (triggering a purchase process). The code modifies player resources, va... | def update_game(self, player, player_action):
if player_action.action == 'reserve':
self.update_gold_on_reserve(player)
if player_action.topdeck is not None:
self.update_cards_player_topdeck_reserve(player, player_action.topdeck)
else:
self.upd... |
def show_board(self, player):
print(Fore.WHITE+Back.BLACK)
print("")
print("****************************")
print(player.name, ", it is your turn.")
print("Here is the board: ")
def print_tier(tier):
tier_list = self.board[tier]
print(Fore.MAGENTA+... | The main task of the code is to simulate a turn-based game where players take turns performing actions, with optional board visualization. It checks after each round if the game has ended, returning the winner's name if so, or declaring a draw after all turns are exhausted. | def play_game(self, verbose=True):
for i in range(MAX_TURNS):
for player in self.players:
if verbose:
self.show_board(player)
self.player_turn(player, verbose)
self.assign_noble(player)
if self.check_ga... |
def _loadBodyLocations(self):
bodyLocations = self._diagnosisClient.loadBodyLocations()
self._writeRawOutput("loadBodyLocations", bodyLocations)
if not bodyLocations:
raise Exception("Empty body locations results")
self._writeHeaderMessage("Body locations:")... | The code simulates a diagnostic process by sequentially loading body locations, sublocations, associated symptoms, diagnosis, specializations, issue details, and proposed symptoms. It processes medical data to generate a structured diagnostic analysis, linking anatomical regions to symptoms, diagnoses, and treatment su... | def simulate(self):
# Load body locations
selectedLocationID = self._loadBodyLocations()
print("Selected location ID",selectedLocationID)
# Load body sublocations
selectedSublocationID = self._loadBodySublocations(selectedLocationID)
# Load body sublocations symptoms
... |
def deal_cards(hand_a, deck, hand_b=[], num=2):
for _ in range(num):
hand_a.append(deck.pop())
hand_b.append(deck.pop())
def count_hand(hand):
count = []
for card in hand:
card_arr = card.split()
if card_arr[0].isdigit():
count.append(int(card_arr[0]))
el... | The code simulates multiple blackjack games using a specified dealer card, varying the player's hit line (1-21) and recording win/loss percentages. It appends results to a CSV file, logging statistics like win/loss rates, dealer card, and hit line for analysis. | def card_run(card, ngames=1):
winner_list = []
data_dict = {}
with open("data.csv", "a") as csvfile:
fieldnames = ["win_percentage", "loss_percentage",
"player_hit_line", "dealer_card"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
for num in range(21):
... |
def random_DNA_sequence(min_length=10, max_length=10000):
DNA = ""
length = random.randint(min_length, max_length)
nucleotides = "atgc"
for n in range(length):
DNA += nucleotides[random.randint(0, 3)]
return DNA
def get_kmers(seq, k, randomized=True):
kmers = [seq[i:i+k] for i in range(l... | The main task of the code is to generate DNA sequences, extract 3-mers (including reverse complements) from each, and attempt to reconstruct the original sequences from these k-mers. It demonstrates sequence decomposition and reconstruction using k-mer analysis, testing how well the `construct_sequence` function can re... | def main():
seq_truths = ["aaaaaaaaaaa", "agcagctcagc", "agcagctcag", random_DNA_sequence(11, 15)]
for i in seq_truths:
print(i)
kmers = get_kmers(i,3,True)
print(kmers)
print(construct_sequence(kmers)) |
def random_DNA_sequence(min_length=10, max_length=10000):
DNA = ""
length = random.randint(min_length, max_length)
nucleotides = "atgc"
for n in range(length):
DNA += nucleotides[random.randint(0, 3)]
return DNA
def get_kmers(seq, k, randomized=True):
kmers = [seq[i:i+k] for i in range(l... | The code tests different de Bruijn graph construction methods (k-mer pairwise comparison, hashing, and hashing without deque) for DNA sequence assembly. It verifies if each method correctly identifies an Eulerian path, reconstructs the original sequence, and measures performance. The test uses predefined DNA sequences ... | def test_1(method):
print(f"Testing k-assembler by {method}")
seqs_truth = ["aaaaaaaaaaa","agcagctcagc","agcagctcagg",random_DNA_sequence(10000, 20000)]
ks = [5, 3, 3, 20]
for i in range(len(seqs_truth)):
print(f"\nExample {i}:")
curr = seqs_truth[i]
#print(curr)
k =... |
def random_DNA_sequence(min_length=10, max_length=10000):
DNA = ""
length = random.randint(min_length, max_length)
nucleotides = "atgc"
for n in range(length):
DNA += nucleotides[random.randint(0, 3)]
return DNA
def get_kmers(seq, k, randomized=True):
kmers = [seq[i:i+k] for i in range(l... | This code tests the accuracy of a sequence assembly method by generating a random DNA sequence, creating k-mers from it, and attempting to reconstruct the original sequence using the provided method. It compares the assembled sequence to the truth sequence and handles exceptions to validate the method's robustness. | def test_2(method):
seq_truth = random_DNA_sequence()
k = 10
kmers = get_kmers(seq_truth, k)
try:
seq = assemble_kmers(kmers, method)
test_and_print_message(seq, seq_truth, k, "Test 2")
except Exception as e:
print(e) |
def random_DNA_sequence(min_length=10, max_length=10000):
DNA = ""
length = random.randint(min_length, max_length)
nucleotides = "atgc"
for n in range(length):
DNA += nucleotides[random.randint(0, 3)]
return DNA
def get_kmers(seq, k, randomized=True):
kmers = [seq[i:i+k] for i in range(l... | The code tests a DNA sequence assembly method by generating a random DNA sequence, extracting 4-mers, and attempting to reconstruct the original sequence using the specified assembly method, then comparing the results and handling errors. | def test_3(method):
seq_truth = random_DNA_sequence(15, 15)
k = 4
print(f"Sequence: {seq_truth}")
kmers = get_kmers(seq_truth, k)
print("kmers:")
for kmer in kmers:
print(kmer)
try:
seq = assemble_kmers(kmers, method)
test_and_print_message(seq, seq_truth, k, "Test 3"... |
def test_1(method):
print(f"Testing k-assembler by {method}")
seqs_truth = ["aaaaaaaaaaa","agcagctcagc","agcagctcagg",random_DNA_sequence(10000, 20000)]
ks = [5, 3, 3, 20]
for i in range(len(seqs_truth)):
print(f"\nExample {i}:")
curr = seqs_truth[i]
#print(curr)
k =... | The main task of the code is to test and compare three sequence assembly methods—k-mer pairwise comparison, k-mer hashing, and k-mer hashing without deque—by executing test_1 and test_2 for each method, followed by a dedicated test_3 for the "k-mer hashing" approach. It evaluates their performance or outcomes in assemb... | def test_seq_assembly():
methods = [
"k-mer pairwise comparison",
"k-mer hashing",
"k-mer hashing without deque"
]
for method in methods:
print("-----------")
test_1(method)
print()
test_2(method)
print()
print("-----------")
test_3(... |
def count_words(self, raw = False):
"""counts how many times a word appears in the file"""
if self.__word_count == {}:
with open(self.__path, encoding="utf8") as file:
for line in file:
self.__count_line(self.__word_count, line, raw)
file.close()
... | The code counts character frequencies by iterating over words and their counts, accumulating character occurrences. If no prior character count exists, it calculates it using word frequencies, then returns an ordered dictionary of characters and their counts. | def count_characters(self, raw = False):
"""counts character frequency"""
self.count_words(raw)
if self.__character_count == {}:
for key in self.__word_count:
for character in key:
self.__count_char(self.__character_count, character, self.__word_coun... |
def clear_exits(self):
# Allows movement to next room when objectives are complete
if not self.clear:
if self.room_coins == self.total_coins and not len(self.enemy_list):
self.clear = 1
arcade.sound.play_sound(self.sound_all_coins)
for row in s... | This method updates the game state by clearing exits, checking the player's location, managing sword actions, and handling enemy movement. It tracks a game timer, triggering enemy movement every 30 ticks and ending the game when the timer reaches zero. | def update(self):
# Runs each time the window is updated
self.clear_exits()
self.check_player_location()
self.player.sword_ticker()
if self.player.draw_sword:
self.sword_collide()
if self.game_tick == 0:
if len(self.enemy_list):
... |
def _create_window(self) -> ttk.Window:
window = ttk.Window(
title=self.APP_NAME,
themename=self.THEME,
size=self.WINDOW_DEFAULT_SIZE,
minsize=self.WINDOW_MINSIZE,
iconphoto=str(resource_path(self.ICON_FILENAME)),
)
window.grid_rowconfi... | The code initializes a GUI application by creating a window, setting up UI elements like an image display timer and main menu, initializing variables for image handling and session tracking, customizing styles, binding hotkeys, and loading user settings to prepare the application for image viewing or processing tasks. | def __init__(self):
self.window = self._create_window()
self.image_show_time = tk.IntVar()
self.main_menu = MainMenu(self)
self.image_folder = ''
self.image_filepaths = []
self.timed_session = None
self.last_saved_window_size = self.window_size
self.last_i... |
def collinear(p1, p2, p3):
a = p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1])
return a == 0
def fillBottomFlatTriangle(self, v1, v2, v3, shade=u"\u2588"):
try:
invslope1 = (v2[0] - v1[0]) / (v2[1] - v1[1])
invslope2 = (v3[0] - v1[0]) / (v3[1] ... | This code draws a triangle by checking if its vertices are collinear. If not, it sorts vertices by y-coordinate and splits the triangle into flat-bottom or flat-top sub-triangles for rendering. If collinear, it draws a line between sorted points. The method uses interpolation to handle non-aligned vertices, ensuring ac... | def drawTriangle(self, triangle, shade=u"\u2588"):
if not self.collinear(*triangle):
triangle = sorted(triangle, key=lambda x: x[1])
v1, v2, v3 = triangle
if v2[1] == v3[1]:
self.fillBottomFlatTriangle(v1, v2, v3, shade)
elif v1[1] == v2[1]:
... |
def predict_viterbi(self, file_name, audio_path, cache_path, trans_prob_01=0.5, trans_prob_10=0.5,
p_state_weight=0.1, load_cache=False, multi_scaling=True):
y_pred_prob = self.predict_proba(file_name, audio_path, cache_path, load_cache=load_cache,
... | This function visualizes predicted annotations against ground truth for an audio file. It uses Viterbi or threshold methods to generate binary predictions and probability maps, loads reference annotations, and plots them alongside estimates using a visualizer. The output is saved to a specified path, comparing predicte... | def visualize_pred(self, file_name, audio_path, cache_test_path, save_path, annot_path, trans_prob_01=None,
trans_prob_10=None, p_state_weight=None, predict_type='viterbi_with_pstate',
load_cache=False, multi_scaling=True):
assert predict_type in ['viterbi_with_psta... |
def readData():
with open('queries.txt') as queriesFile:
queries = queriesFile.readlines()
queries = [q.strip() for q in queries]
budgetDicttemp = dict()
bidsDict = dict()
bidderData = pd.read_csv("bidder_dataset.csv")
for i in range(0, len(bidderData)):
advertiser = bi... | The code computes and prints the revenue and competitive ratio for a given algorithm input by reading data, calculating metrics using helper functions, and outputting the results. | def computeFinalOutput(algoInput):
budgetDict,bidsDict, queries = readData()
revenue = 0.0
competitiveRatio = 0.0
revenue = findRevenue(queries, budgetDict, bidsDict, algoInput)
competitiveRatio = findCompetitiveRatio(queries, budgetDict, bidsDict, algoInput)
print("revenue = " + str(revenue))
... |
def addrecord(RM, key: int, tag: int, hist: int, time: bool):
index = key
found = False
for i in range(HASHLENGTH):
hashtag = gettag(RM.planethash[index][0])
if(hashtag):
# index = keygen(index)
index += 1
if(index == HASHSIZE):
return
... | The function observes and records the time-of-day information on the next planet using RoboMemory (RM). If RM.highfreq is active, it either adds a new record or updates existing configurations based on RM.index, then adjusts frequency settings and stores the next planet ID in a masked format (nextPlanetID & 0xf). This ... | def observeAndRecordTimeofdayOnNextPlanet(RM: RoboMemory, nextPlanetID: int,
timeofDayOnNextPlanet: bool) -> None:
if(RM.highfreq):
if(RM.index == -1):
addrecord(RM, RM.key, RM.tag, RM.hist, timeofDayOnNextPlanet)
else:
updateconf(RM,... |
def day(self, is_alive: bool, players: list[mafia_pb2.Player], mafias: list[mafia_pb2.Player],
detective: mafia_pb2.Player | None):
print("The new ☀ day ☀ started.")
print(f"Other alive players:", *[f"{cf.blue}{player.name}{cf.reset}({player.id})" for player in players])
if mafias:
... | The code's main task is to handle a game loop for a mafia-style game, processing events from an RPC server. It displays a menu to choose between manual or auto gameplay, then iterates through game events (day/night phases) received via a stream. Depending on the event type, it updates the game state using corresponding... | def play_game(self):
menu = TerminalMenu(["Manual play", "Auto bot"])
ans = menu.show()
self.is_auto = ans == 1
for response in self.stub.GameProcess(mafia_pb2.GameProcessRequest(token=self.token)):
match response.WhichOneof("event"):
case "day":
... |
def set_name(self):
self.name = input("State your name: ")
while not self.name:
print("\033[F\033[K", end="")
self.name = input(f"{cf.red}Name cannot be empty!{cf.reset} State your name: ")
def connect_to_server(self):
while self.stub is None:
try:
... | The code initializes and starts a Mafia online game by setting the player's name, connecting to a server, creating or joining a game, waiting for other players, assigning roles, and initiating gameplay. | def start(self):
tprint("Mafia online")
print("Greetings! ✌(◕‿-)✌")
self.set_name()
print()
self.connect_to_server()
print()
self.create_or_join_game()
print()
self.wait_players()
print()
self.get_role()
print()
self... |
def clearWindow(list):
#Resets the results playlist data
for i in range(len(list)):
list.pop()
#Deletes the text on screen
searchedLabels.clear()
def convertResults(data):
return Song(data["name"], data['album']['artists'][0]['name'], data['album']['name'], data['uri'],
... | This code generates a music playlist by searching for a song, using it to fetch Spotify recommendations, and displaying the results. It clears previous results, extracts song/artist data, requests recommendations via Spotify's API, converts tracks into displayable format, and updates the UI with the new playlist. | def recomendPlaylist():
clearWindow(recommendResults.songs)
#Gets the first song that the search comes up with
results = sp.search(q=recommend.get())['tracks']['items'][0]
givenSong = convertResults(results)
#Sets results to lists bc the function parameters need lists
listArtists = []
listA... |
def debug(record):
if debugging:
print(record)
def draw_histogram(self, pil_image, image_path):
'''Given a PIL image, render the histogram for it'''
# We need a greyscale version which has 256 values
mono = pil_image.convert('L')
histogram = mono.histogram()
# Fix t... | This code loads an image from a list, handles errors by skipping invalid images, resizes the image to fit the window, and displays it on a canvas. It updates the window title with image dimensions, manages image references to prevent garbage collection, and optionally draws a histogram. If loading fails, it logs the er... | def load_image(self):
'''Load the image with the current image index'''
if self.image_index == None: return
# Get PIL to load the image
path = self.images[self.image_index]
try:
pil_image = Image.open(path, 'r')
pil_image.load()
except (PIL.Uniden... |
def debug(record):
if debugging:
print(record)
def treewalk(rootpath: str, wanted_types: List[str]) -> List[str]:
def wanted(p: str):
return any([p.endswith(suffix) for suffix in wanted_types])
result: List[str] = []
for root, dirs, files in os.walk(rootpath):
wanted_files: List... | (The updater function periodically checks a directory for new .jpg/.jpeg images, adds them to the list, displays the first new one, and manages slideshow functionality. It rescan on request, ignores corrupt files, and triggers updates. It also schedules itself to run again.) | def updater(self):
'''Called regularly to see if new images have appeared on disk'''
if not self.update: return
if self.rescan:
debug('rescan')
# We've been asked to rescan the directory - perhaps a file disappeared
self.images = []
self.image_in... |
def go_to_joint_state(self):
group = self.group
joint_goal = group.get_current_joint_values()
joint_goal[0] = pi/2
joint_goal[1] = 0
joint_goal[2] = 0
joint_goal[3] = 0
joint_goal[4] = 0
group.go(joint_goal, wait=True)
group.stop()
current_joints = self.group.get_current... | The code initializes a MoveIt interface for a robotic arm and gripper, sets up planning scene components, and executes a sequence of motions: moving the arm to a target pose, opening the gripper, lowering it to grasp an object, then closing the gripper. It also configures tolerances, publishes trajectories for visualiz... | def __init__(self):
super(MoveGroupPythonIntefaceTutorial, self).__init__()
## First initialize `moveit_commander`_ and a `rospy`_ node:
moveit_commander.roscpp_initialize(sys.argv)
rospy.init_node('move_group_python_interface_tutorial',
anonymous=True)
## Instantiate a `Ro... |
def get_height_patch_num(self, input_img_shape):
b, c, h, w = input_img_shape
patch_size = self.get_patch_size()
return h // patch_size
def get_width_patch_num(self, input_img_shape):
b, c, h, w = input_img_shape
patch_size = self.get_patch_size()
return w // patch_size
d... | This code extracts and normalizes attention-based features and saliency maps from a Vision Transformer model's outputs. It processes input images to capture class attention maps, computes normalized key features from QKV matrices, and returns these as features and saliency maps for downstream tasks like visualization o... | def extract_feat(self, inputs):
features = []
cls_tokens = []
saliency_maps = []
with torch.no_grad():
for img in inputs:
height = self.get_height_patch_num(img.shape)
width = self.get_width_patch_num(img.shape)
t = self... |
def get_uvs_and_faces(self, lev=1, gitter=True):
uvs = self.meshes[lev].verts.clone()
faces = self.meshes[lev].faces.clone()
if gitter:
uvs += torch.randn_like(uvs)*1e-2 / (2**lev)
return uvs, faces
def update_bone_rot_rest(self):
with torch.no_grad():
mea... | This function optimizes mesh deformation parameters using an Adam optimizer. It iteratively computes forward passes, calculates weighted losses (including pose priors if enabled), backpropagates gradients, freezes specified mesh parts, and updates vertex features. The process refines 3D mesh deformations to align with ... | def optimize(self, variables, inputs, params, weights):
sigma = 5e-3
uvs, _ = self.get_uvs_and_faces(params['mesh_lev'], True)
if 'pose_prior' in weights:
self.update_bone_rot_rest()
losses = {}
optimizer = torch.optim.Adam(variables, lr=params['lr'])
loop = ... |
def get_uvs_and_faces(self, lev=1, gitter=True):
uvs = self.meshes[lev].verts.clone()
faces = self.meshes[lev].faces.clone()
if gitter:
uvs += torch.randn_like(uvs)*1e-2 / (2**lev)
return uvs, faces
def forward(self, inputs, uvs, deform=True, use_ellipsoid=False, view=None, s... | The code saves rendered 3D results (part and texture) for each input image. It generates PNGs of per-image renderings and GIFs across 37 views, using part_renderer and text_renderer. Texture maps are computed from vertex positions, and outputs are saved in the specified output directory. | def save_results(self, inputs, params, losses=None):
uvs, faces = self.get_uvs_and_faces(4, False)
outputs = self.forward(inputs, uvs, deform=True)
texture = self.get_texture(uvs, inputs['images'], outputs['verts'], outputs['verts_2d'])
self.save_pred_masks(inputs['images'], outputs['ver... |
def init_feat_verts(self, feat_part, part_mapping):
self.feat_verts = feat_part[part_mapping]
def optimize(self, variables, inputs, params, weights):
sigma = 5e-3
uvs, _ = self.get_uvs_and_faces(params['mesh_lev'], True)
if 'pose_prior' in weights:
self.update_bone_rot_rest()... | The code performs multi-stage optimization of a 3D mesh's global and hierarchical pose, base part shape, and full shape through iterative refinement. It optimizes parameters like global transformations, bone rotations, and part codes using weighted loss terms (feature alignment, pose priors, silhouette, etc.) across in... | def train(self, inputs):
self.skeleton.init_part_mapping(inputs['part_cent'])
self.init_feat_verts(inputs['feat_part'], self.skeleton.part_mapping)
print("========== Optimizing global pose... ========== ")
var = [self.global_scale, self.global_trans, self.global_rot]
params = {'... |
def split_text_into_AIDA(input_file):
remove_lds_dfile()
remove_ldv_dfile()
current_directory = os.path.dirname(os.path.abspath(__file__))
with open(input_file, 'r') as file:
code_content = file.read()
code_content=code_content.replace("valore Fal /*67,*/","valore False /*67,*/"... | The function processes .txt files from a source directory by cleaning AIDA input folders (LdS/LdV), running a code generator, and moving generated LNC files to output folders based on report success status. It deletes existing files in AIDA input folders, executes the generator, checks the report for "SUCCESS," and rel... | def create_LNC_Files_into_AIDAFolder():
source_dir = Path('D://Milan/RFI/ToolsForLNCGenarator/rmutt.js/LNCGram/tempout')
files = source_dir.iterdir()
files = source_dir.glob('*.txt')
for file in files:
# remove previous files to... |
def show_lunch():
print("SERIAL FOOD ITEM PRICE")
for i in range(len(lunch_name)):
print("No." + str(i + 1) + " " + str(lunch_name[i]) + " " * (20 - len(lunch_name[i])) + "Tk. " + str(
lunch_price[i]))
total_bill = 0
while True:
food_item = input("Please Sele... | The main task of the code is to display a menu with meal options (BREAKFAST, LUNCH, DINNER) and direct user input to corresponding functions (show_breakfast, show_lunch, show_dinner). It validates input case-insensitively and handles invalid entries by displaying an error message. | def main_menu():
print("*" * 31 + " MAIN MENU " + "*" * 31 + "\n"
"\t(B) BREAKFAST\n"
"\t(L) LUNCH\n"
"\t(D) DINNER\n" +
"_" * 72)
input_1 = str(input("Pleas... |
def __infoLogger(self, string):
self.__logger.info(string)
def __shift_edge(self, pr, pk, edge, triangles):
self.__infoLogger("Shifting Edge " + str(edge) + " to " + str(Vector(pr, pk)))
for triangle in triangles:
self.__remove_triangle(triangle)
nodes = [self.__... | This function fixes an edge in a triangulation by checking if the edge exists in the structure. If not, it identifies adjacent triangles, selects a reference point, and ensures proper connectivity. It handles cases with negative point IDs and uses circle containment checks to determine if a point lies within a triangle... | def __fix_edge(self, pr, edge):
self.__infoLogger("Fix Edge(pr = " + str(pr) + ", edge = " + str(edge) + ")")
if self.__dtree.triangle.hasEdge(edge.pointA, edge.pointB):
return
else:
triangles_with_edge = [i for i in self.__triangles if i.hasEdge(edge.pointA, edge.pointB)... |
def __get_initial_point(self):
row_ids = np.where(self.__points[:,1] == np.max(self.__points, axis=0)[1])[0]
sel_row = np.argmax(self.__points[row_ids, :], axis=0)[0]
p0 = self.__points[row_ids[sel_row], :]
self.__infoLogger("Lexicographically Distant Point : %s"%(str(p0)))
retur... | The code performs Delaunay triangulation by incrementally inserting points into an initial triangle structure. It handles each new point by locating it within or on an edge of existing triangles, splitting them into new triangles, and updating the data tree. The process ensures proper triangulation, edge fixing, and st... | def execute(self):
p0, ind = self.__get_initial_point()
p0 = Point(p0[0], p0[1], 0)
pm1 = Point(-1, -1, -1)
pm2 = Point(-2, -2, -2)
firstTriangle = Triangle(p0, pm1, pm2)
self.__dtree = Dtree(firstTriangle, None, step = self.__step)
self.__step = self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.