dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def getModel(self, settings, bow_corpus, dictionary, processed_corpus):
"""Will create and optimize a model, or create a model from given parameters."""
if 'optimize_model' in settings and settings['optimize_model']:
model = self.optimizeModel(dictionary, bow_corpus, processed_corpus)
... | The code's main task is to train a topic model by either loading existing model/dataframes or retraining them if files are missing or reload is requested. It generates topic distributions and word-topic associations, saving results to dataframes for analysis. | def train(self):
"""Will attempt to load the model and its associated data, will train and create if they cannot be found or retrainModel is True."""
print('Attempting to load Dataframes...')
settings = self.settings
try:
self.model = loadModel(settings, self.MODEL_FILE)
... |
def char2array(self,s):
m = [int(c) for c in s if int(c) in [0,1]]
x= np.array(m)
return x*2-1
def AR_model(self,x,r):
x1,x2 = self.build_time_matrices(x,r)
p,res,rnk,s = np.linalg.lstsq(x1.T,x2,rcond=None)
return x1,x2,p
def error_rate(self,x_test,p):
x1,x2 = sel... | The main task of the code is to prepare and process input data for training and testing an AR model with varying r-values. It splits input and random binary data into train/test sets, converts them into arrays, fits the model for each r-value, calculates train/test errors, and compiles results into a structured diction... | def main(self):
result_final = {}
r = np.arange(1, self.r_num)
x_input = self.random_number
result_final['input_original'] = [int(c) for c in x_input if c in ['0','1']]
result_final['input_length'] = len(x_input)
test_range = len(x_input) - (len(x_input)//self.part if len... |
def adjacent_squares(i, j):
return [(i - 1, j - 1), (i - 1, j), (i - 1, j + 1), (i, j + 1), (i + 1, j + 1), (i + 1, j), (i + 1, j - 1),
(i, j - 1)]
def add_if_legal(self, moves, move, check, pin):
if move is None:
return
if move.piece is None or move.piece.color != se... | The main task of the code is to generate all legal moves for a chess piece by examining adjacent squares, checking their validity with `add_if_legal`, and including castling options. It returns a list of possible moves considering the current board state and check status. | def possible_moves(self, check):
moves = []
squares = self.adjacent_squares(self.square.row, self.square.column)
for r, c in squares:
move = self.board.get_square(r, c)
self.add_if_legal(moves, move, check, None)
self.castle_available(moves)
return mov... |
def _split_valid(split):
return split == "train" or split == "val" or split == "test"
def load_vocab_pickle(split="train"):
assert(_split_valid(split))
vocab_pickle_path = load_vocab_pickle_path(split)
if os.path.exists(vocab_pickle_path):
with open(vocab_pickle_path, "rb") as f:
vo... | The main task of the code is to load a precomputed vocabulary for a given dataset split (e.g., "train") from a pickle file if available. If not, it constructs the vocabulary from the dataset's text data, either word-based or character-based depending on settings, then saves the newly built vocabulary to a pickle file f... | def load_vocab(split="train"):
assert(_split_valid(split))
# attempt to load pickled version, otherwise, re-build
vocab = load_vocab_pickle(split)
if vocab is not None:
return vocab
# otherwise build the vocab
sis_path = load_sis_path(split)
if settings.USE_WORD_VOCAB:
voca... |
def process_dataframe(language, country):
jdf = urllib.request.urlopen(
f"http://data_processing:5001/get_headlines?language={language}&country={country}"
).read()
df = pd.read_json(json.loads(jdf.decode("utf-8")))
df["lower_entities"] = df.entities.apply(
lambda entities_set: set([i.low... | The function builds a recommendation tree for a specified language and country by processing a dataframe, selecting frequent entities, and recursively constructing subtrees while avoiding invalid or blacklisted entries. It returns a structured tree with "Source" as the root, containing child nodes representing recommen... | def get_recommendations_with_article(language: str, country: str):
"""
Build a recommendation tree for the specified language and country
:return: recommendation tree for the specified language and country
"""
df = process_dataframe(language, country)
article_entity_counter, text_entity_counter... |
def matchPreviousBet(index, balanceLIst):
#betList[index] += match(index)
bet(index,match(index),betList,balanceLIst)
print("before")
#print(balanceLIst[index])
balanceLIst[index] -= match(index)
print("after")
def bet(index:int, bet:int,betList,balanceLIst) -> bool:
print("be... | This function determines a player's betting action in a game based on their hand strength (`chance`), pot odds, and balance. It matches previous bets, places randomized bets within specific ranges, or folds, adjusting thresholds and bet sizes according to `chance` values. Higher `chance` requires lower odds and allows ... | def actionBasedOnHand(chance, index, odds,balanceList):
if chance == 10:
if odds >=0:
matchPreviousBet(index,balanceList)
bet(index, random.randint(0,20),betList,balanceList)
elif chance == 9:
if odds >=1:
matchPreviousBet(index,bal... |
def checkStraight(allCards:list)->list:
sortedValues = sortValuesandNumerize(allCards)
final = []
maxCountinaRow = 0
indexs = []
sortedValuesTEMP = list(dict.fromkeys(sortedValues))
sortedValues = []
for i in sortedValuesTEMP:
sortedValues.append(int(i))
sortedValu... | The function `checkChances` evaluates the strength of a poker hand by combining the player's hand and community table cards. It checks for poker hand rankings (from highest to lowest: royal flush, straight flush, four of a kind, full house, flush, straight, three of a kind, two pair, pair, high card) using helper funct... | def checkChances(hand:list, table:list)->int:
totalChance = 0
#highcard is 1
#pair is 2
#two pair is 3
#three of a kind is 4
#straight is 5
#flush is 6
#full house is 7
#four of a kind is 8
#straight flush is 9
#royal flush is 10
cardsInPlay = [hand[0], hand[1]]
... |
def make_shit_happen(Year="2022",Month="5",Day="4",Test_Length="3",NOC=2,Bullish_Bearish="1",SS=2,Number_of_Stocks=3):
date = Year + '-' + Month + '-' + Day
year = int(Year)
month = int(Month)
day = int(Day)
c = wall_street_bet_get_stock_from_previous_days(date, year, month, day, Test_Length)
re... | The main task of the code is to test stock data retrieval for a specific time frame, fetch historical stock information from Wall Street Bet, set up a database connection, and generate visualizations using graph functions. It includes commented-out sections for potential additional tasks like sentiment analysis, table ... | def main():
print('Test stocks of given time frame')
make_shit_happen()
#Test not past stock
# print('Trending stocks for today')
# get_stocks_good_setiment(.5, 5)
#Test past stock
wall_street_bet_get_stock_from_previous_days()
#DataBase Set Up
cur, conn = setUpDatabase('WSBs... |
def scrape_terminals(self, terminals):
all_trains = []
for name in terminals:
terminal = self.terminals[name]
trains = self.get_departures(terminal['abbrev'])
#TODO: get unique
self.terminals[name]['t_scrape'] = terminal['t_scrape'] + timedelta(seconds = terminal['freq'])
all_trains = all_trains + tr... | The code continuously monitors and processes train data by scraping terminals at scheduled intervals, tracking train progress, and managing completed trains. It resets daily data, identifies terminals to scrape, updates train statuses, writes completed trains to files, and periodically logs loop counts. The loop runs e... | def run(self):
loop_count = 1
while True:
now = datetime.now()
if now.day != self.time.day:
self.completed_trains = {}
self.time = now
#identify terminals to scrape
scrape_terms = []
for term, info in self.terminals.iteritems():
if (info['t_scrape'] <= self.time):
scrape_terms.append... |
def get_last_page_with_time_estimate(self, line_idx):
time_in_line = False
i = 0
while not time_in_line and i < len(self.data['data']):
i = i + 1
try:
line = self.data['data'][-i][1][line_idx]
time_in_line = ":" in line
except IndexError:
pass
return -i
def parse_status_line_not_departed(se... | The main task of the code is to estimate the departure time for a specific line by parsing the status from the last available page data, approximating the time using scraped data, and returning the estimated time and status if successful. If the approximation fails, it returns None. | def estimate_departure(self, line_idx):
last_page = self.get_last_page_with_time_estimate(line_idx)
time_scraped = self.data['data'][last_page][0]
missing_line = self.data['data'][last_page][1][line_idx]
estimated_stop = self.parse_status_line_not_departed(missing_line)
approx_time = self.approximate_time(est... |
def get_number_status_lines(self):
num_status_lines = 0
i = 1
while num_status_lines <= 1 and i <= len(self.data['data']):
num_status_lines = len(self.data['data'][-i][1]) - 1
i = i + 1
return num_status_lines
def estimate_departure(self, line_idx):
last_page = self.get_last_page_with_time_estimate(line... | The function fills missing departures by estimating them based on the difference between existing departures and the total number of status lines. It iterates from the current departure count to the total status lines, estimates each missing departure, and appends or updates it if the estimate is valid. | def fill_missing_departures_with_estimates(self):
num_status_lines = self.get_number_status_lines()
num_departures = len(self.departures)
for i in range(num_departures, num_status_lines):
estimated_departure = self.estimate_departure(i)
if estimated_departure is not None:
self.append_or_update_departure... |
def get_number_status_lines(self):
num_status_lines = 0
i = 1
while num_status_lines <= 1 and i <= len(self.data['data']):
num_status_lines = len(self.data['data'][-i][1]) - 1
i = i + 1
return num_status_lines
def estimate_departure(self, line_idx):
last_page = self.get_last_page_with_time_estimate(line... | The function estimates the last departure using the number of status lines, checks if the departure station is already recorded, and either updates the existing departure or appends a new one if it's a new station. | def estimate_last_departure(self):
num_status_lines = self.get_number_status_lines()
estimated_departure = self.estimate_departure(num_status_lines-1)
if estimated_departure is not None:
if estimated_departure['station'] in self.departed_stations:
self.replace_departure(estimated_departure)
else:
se... |
def parse_departures_from_status_page(self, page):
time_scraped = page[0]
page_lines = page[1]
if not self.check_page_valid(page_lines):
return
page_lines = self.get_relevant_stations(page_lines)
#update SM
try:
for idx, line in enumerate(page_lines):
if self.num_lines_parsed <= idx:
break... | This function processes stop time data by iterating through pages, parsing departures, checking for corruption (e.g., no departures), and handling NJ Transit-specific logic to estimate missing departures. It updates parsed pages, marks corruption if needed, and clears departures if corruption is detected. | def get_stop_times(self):
for page in self.data['data']:
self.parse_departures_from_status_page(page)
self.pages_parsed = self.pages_parsed + 1
if self.corrupted:
break
if not len(self.departures):
self.corrupted = True
self.corrupted_reason = "no departures"
# print(self.filename, "corrupted ... |
def get_stop_times(self):
for page in self.data['data']:
self.parse_departures_from_status_page(page)
self.pages_parsed = self.pages_parsed + 1
if self.corrupted:
break
if not len(self.departures):
self.corrupted = True
self.corrupted_reason = "no departures"
# print(self.filename, "corrupted ... | The main task of the code is to parse data from a file into a structured DataFrame. It achieves this by first retrieving stop times, then fetching rows of data, and finally converting those rows into a pandas DataFrame using the `get_df` method. This process facilitates structured data analysis and manipulation. | def parse_file_to_df(self):
self.get_stop_times()
rows = self.get_rows()
return self.get_df(rows) |
def clear_notifications(self):
self.notification_container.clear_widgets()
self.notifications_list = []
def test_notifications(self):
self.emit_notification({
"type": NotificationEnum.INFO,
"title": "Test Notification (Info 1)",
"message": "This is a test info... | The code initializes a `NotificationsTab` UI component with a dropdown filter for notification types (all, info, success, warning, error), buttons to clear or test notifications, and a scrollable area to display notifications. It sets up layouts, binds event handlers, and prepares structures to manage and filter notifi... | def __init__(self, **kwargs):
super(NotificationsTab, self).__init__(**kwargs)
self.text = "Notifications"
# self.temporary_label = Label(
# text="[size=20]Notifications Tab is not implemented yet.[/size]",
# markup=True
# )
# self.add_widget(self.tempora... |
def align_helper(self, X, Y, local=False):
"""
Divide and conquer alignment algorithm
Parameters
----------
X : string
first string to align
Y : string
second string to align
local : bool, optional
set to True for local alignme... | The code performs sequence alignment (global or local) by generating distinct alignments between two strings. For global alignment, it uses a helper to find and deduplicate alignments. For local alignment, it identifies optimal start/end positions via scoring, trims sequences, and recursively finds alignments. Results ... | def align(self):
"""
Run the recursive alignment algorithm and return distinct alignments
Returns
-------
list
a list of tuples with the string representations of the alignments between s1 and s2
"""
#
# global
#
if not self.lo... |
def _ValidateSourcePaths(source_paths):
if source_paths is None:
return
for x in source_paths:
assert os.path.exists(x)
assert os.path.isdir(x)
assert os.path.isabs(x)
def _EscapeJsString(s):
assert isinstance(s, str)
return json.dumps(s)
def _GetBootStrapJsContent(source_paths):
assert isinst... | (Runs a JavaScript or HTML file using a temporary bootstrap script that loads the file via HTMLImportsLoader, then executes it with D8/V8 engine, returning the output. Validates input, handles file types, and cleans up temporary files.) | def RunFile(file_path, source_paths=None, js_args=None, v8_args=None,
stdout=subprocess.PIPE, stdin=subprocess.PIPE):
"""Runs JavaScript program in |file_path|.
Args are same as ExecuteFile.
Returns:
A RunResult containing the program's output.
"""
assert os.path.isfile(file_path)
_Valida... |
def handle_pin_button(event):
'''Function to add the number of the button clicked to the PIN number entry via its associated variable.'''
global pin_number_var
if len(pin_number_var.get()) <4:
number = pin_number_var.get() + str(event)
pin_number_var.set(number)
def clear_pin_entry(even... | Your return
The code creates a login screen GUI with a red background, displaying "FedUni Banking" in large font. It includes fields for entering an account number and PIN, along with numeric buttons (1–9, 0) and actions for "Cancel/Clear" (red) and "Login" (green). Buttons trigger `handle_pin_button` for digit input... | def create_login_screen():
'''Function to create the login screen.'''
mainFrame = tk.Frame(win,bg='red')
mainFrame.pack(fill='both', expand = True)
verticalFrame = tk.Frame(mainFrame)
verticalFrame.pack(fill='both')
# ----- Row 0 -----
# 'FedUni Banking' label here. Font size is 3... |
def is_inverse_included(self, name: Graph_names):
return len(self.graphs[name]) > self.num_relation
def inverse_rel(self, rel):
return self.inv_to_rel(rel) if self.is_inverse(rel) else self.rel_to_inv(rel)
def get_heads_corrupted_for_rel_tail(self, graph_name: Graph_names, rel: int, tail: int):
... | This function retrieves non-existing (corrupted) head entities for a given relation and entity in a knowledge graph, considering inverse relations. It adjusts the relation based on the 'reverse' flag and graph configuration, then delegates to 'get_heads_corrupted_for_rel_tail' to fetch results. The output is an array o... | def get_heads_corrupted_for_rel_entity(self, graph: Graph_names, rel: int, entity: int, reverse=False) -> NDArray[
np.intp]:
"""Same as 'get_heads_for_rel_entity' but only not existing facts are returned"""
result = None
if self.is_inverse_included(graph):
if reverse:
... |
def _init_base_problem(self, rel: int, graph: Graph_names):
base_problem = pl.LpProblem(f'Problem_{rel}', pl.LpMinimize)
penalties = []
weights_rules = [(pl.LpVariable(f'w_{i}', lowBound=0.0, upBound=1.0), rule) for i, rule in
enumerate(self.get_rules_for_rel(rel))]
... | This code solves a linear programming problem to find optimal rule combinations for maximizing MRR (Mean Reciprocal Rank) under varying complexity constraints. It iterates through tradeoff parameters, solves LP problems, tracks non-zero weights, avoids duplicate rule combinations, and returns the combination with the h... | def solve_lps(self, solver: pl.LpSolver, rel: int, k: int, max_complexity: int, graph_lp: Graph_names,
graph_mrr: Graph_names):
base_problem, weights_rules, penalty = self._init_base_problem(rel, graph_lp)
result = []
# MRR -1 so first combination of weihts is returned even if ... |
def init_custom_problem(self, rel: int, rules, graph: Graph_names, t, complexity):
problem = pl.LpProblem(f'Problem_{rel}', pl.LpMinimize)
constraints = {}
penalties = []
weights_rules = [(pl.LpVariable(f'w_{i}', lowBound=0.0, upBound=1.0), rule) for i, rule in enumerate(rules)]
... | The function `get_rules_for_rel_column` generates optimized rules for a specific relation in a graph by iteratively solving a constraint problem, exploring paths, and selecting rules based on dual variables and evaluation metrics like `red_k` and frequency. It refines the problem in each iteration, adding newly discove... | def get_rules_for_rel_column(self, rel, graph, solver, iterations=15, max_per_iter=10):
min_t = min(self.tradeoff)
min_k = 4
found_paths = set()
problem, weights_rules, constraints = self.init_custom_problem(rel, [], graph, min_t, min_k)
problem.solve(solver)
dual_comple... |
def calculate_neg_freq(self, graph, rule):
right_k, freq_r = self.get_neg_freq(graph, rule, True)
left_k, freq_l = self.get_neg_freq(graph, rule)
return right_k + left_k, freq_r + freq_l
def get_rule_antecedent(self, rule: NDArray):
return rule['antecedent'][:rule['length']]
def create_... | (The function filters rules with a specific consequent relation, computes their negative frequency and overall frequency using `calculate_neg_freq`, and constructs a structured NumPy array of rules containing consequents, antecedents, and computed values, returning it as the output.) | def get_rules_with_updated_neg_freq(self, rel) -> NDArray:
rules_data = []
for rule in self.rules[np.where(self.rules['consequent'] == rel)]:
neg, freq = self.calculate_neg_freq(Graph_names.Train, rule)
rules_data.append((rule['consequent'], self.get_rule_antecedent(rule), neg, f... |
def _get_rules_h1(self, graph_name: Graph_names, rel: int) -> set[tuple[int]]:
rel_paths = set()
for tail, heads in self.data.get_facts_for_rel(graph_name, rel):
for head in heads:
paths = []
fact = (tail, rel, head)
for r, entities_for_r in se... | The function generates rules for a specific relation by combining two sets of rules (rules_h1 and rules_h2), converting them into a NumPy array of rule objects, and returning the array. It uses helper methods to retrieve rules, applies a union operation, and constructs each rule with the `create_rule` method, finalizin... | def generate_rules_for_rel(self, graph_name: Graph_names, rel: int) -> NDArray:
rules_h1 = self._get_rules_h1(graph_name, rel)
rules_h2 = self.get_rules_h2(graph_name, rel)
rules_for_rel = rules_h1.union(rules_h2)
rules = np.array([self.create_rule(rel, rel_path) for rel_path in rules_f... |
def param_interp(df,tenor,date,expire):
assert isinstance(df,pd.DataFrame)
if date<expire[0]:
new_p1=df[str(tenor)+'Y'][str(expire[0])+'Y']-\
(expire[0]-date)/expire[0]*df[str(tenor)+'Y'][str(expire[0])+'Y']
return new_p1
else:
for i in range(len(expire)):
... | The code calculates the present value of a Constant Maturity Swap (CMS) leg by discounting CMS cash flows. It uses SABR model parameters (alpha, rho, nu) and swap rates (F) interpolated from given dataframes. For semi-annual or quarterly frequencies, it constructs time points (T), retrieves discount factors, and comput... | def CMS_leg(tenor,year,DFLibor,DFOIS,dfidx,freq='semi-annually'):
CMS=[]
DiscountF=[]
if freq=='semi-annually':
T=[0.5+i*0.5 for i in range(year*2)]
for t in T:
# locate the correponding discount factors
DiscountF.append(OISDarray[dfidx.index(t)])
# use param_in... |
def set_last(self, last):
self.last = last[0].upper() + last[1:].lower()
return
def set_first(self, first):
self.first = first[0].upper() + first[1:].lower()
return
def set_mi(self, mi):
if not mi:
self.mi = 'X'
else:
self.mi = mi[0].upper()
... | The main task of the code is to populate an object's fields with data from the `entry` tuple and `id_dict`. It unpacks the `entry` into last name, first name, middle initial, ID, and phone, then calls corresponding setter methods (`set_last`, `set_first`, etc.) to assign these values to the object's attributes. The `se... | def set_fields(self, entry, id_dict):
last, first, mi, my_id, phone = entry
self.set_last(last)
self.set_first(first)
self.set_mi(mi)
self.set_id(my_id, id_dict)
self.set_phone(phone)
return |
def test_strictly_increasing(sample_path, asm_file, tests_file, generate_num=10):
"""Test that strictly increasing linked lists return 3."""
generic_test(sample_path=sample_path,
asm_file=asm_file,
tests_file=tests_file,
test_name="Strictly Increasing",
... | The function `run_all_tests` executes five distinct test cases on sequences generated from given files, validating properties like strictly increasing, increasing, semi-increasing, decreasing, and multiple bad cases, using parameters such as input paths and generation count. | def run_all_tests(sample_path, asm_file, tests_file, generate_num=10):
test_strictly_increasing(sample_path, asm_file, tests_file, generate_num)
test_increasing(sample_path, asm_file, tests_file, generate_num)
test_semi_increasing(sample_path, asm_file, tests_file, generate_num)
test_decreasing(sample_p... |
def basic_good_binary():
return ["0b10"]
def basic_bad_binary():
return ["0b2"]
def run_tests(asm_file,
tests_file,
test_name,
good_basic_lis,
bad_basic_lis,
good_random_lis,
bad_random_lis):
"""Runs a single test."""
tr... | The code generates and runs test cases for parsing/validating numbers in different bases (binary, octal, decimal, hexadecimal). It creates valid and invalid examples for each base, then executes tests using `run_tests`, comparing expected outcomes against actual processing in an assembly file. The goal is to verify cor... | def run_all(asm_file, tests_file, generate_num: int = 10):
# Binary
good_basic_bin_lis, bad_basic_bin_lis = basic_good_binary(), basic_bad_binary()
good_random_bin_lis = generate_valid_bin()
bad_random_bin_lis = generic_generate_invalid(good_chars="01", generate_num=generate_num, prefix="0b")
run_te... |
def read_process_image(path):
orig_img = cv2.imread(path)
img = cv2.cvtColor(orig_img, cv2.COLOR_BGR2GRAY)
# gaussian blurring
# Tried other values but found (9,9)is the best kernel size.
kernel_size = (9, 9)
img = cv2.GaussianBlur(img, kernel_size, 0)
# thresholding
img = cv2.adaptive... | The main task of the code is to process a Sudoku image by detecting its grid, correcting perspective, segmenting individual cells, and classifying digits. It reads an image, identifies contours and corners, warps the grid, splits it into cells, recognizes digits, and returns labels (digits), corners, and processed imag... | def get_sudoku(path, show_contours=False, show_corners=False, show_grid=False):
orig_img, img = read_process_image(path)
ext_contours = get_contours(img, show_contours)
corners = get_corners(img, ext_contours, show_corners)
image, orig_warped_img, matrix = get_cropimage(img, orig_img, corners)
num_i... |
def get_artist_uri_from_name(self, artist_name):
results = self.sp.search(q='artist:' + artist_name, type='artist')
artist_uri = results['artists']['items'][0]['uri']
return artist_uri
def create_children(self):
self.current_results.clear()
# artist_uri = self.get_artist_uri_from... | This code implements a game loop handling user input (keyboard/mouse), updating artist animations, managing selection/interaction, and rendering graphics. It supports pausing/resuming animations, searching for artists via keyboard, double-click detection, object movement, and timed auto-animations using Pygame. | def run_loop(self):
# Game loop.
while True:
self.screen.fill(BLACK)
self.artist_collection.draw(self.screen)
self.artist_collection.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
... |
def checkConfig():
global repo_local_path
global hal_dest_path
global cmsis_dest_path
global md_HAL_path
global md_CMSIS_path
if os.path.isfile(os.path.join(script_path, path_config_filename)):
try:
path_config_file = open(
os.path.join(script_path, path_confi... | The main task of the code is to execute a series of operations for STM32 device management: check configuration, update core repository, generate an STM32 device list, update ST repository, and conditionally print version info or perform a core update based on the 'check' flag in upargs. The global 'stm32_list' is popu... | def main():
global stm32_list
# check config have to be done first
checkConfig()
updateCoreRepo()
stm32_list = genSTM32List(hal_dest_path, upargs.serie)
updateSTRepo()
if upargs.check:
printVersion()
else:
updateCore() |
def _subdirs(root_dir, _sort=True):
"""
Returns a list of the sub-directories found in root_dir.
Raises:
NotADirectoryError: root_dir is not a directory
:param root_dir: [str] root directory
:param _sort: [bool] if True returns sorted list
:return: [list of strings] sub-directories (abso... | This code initializes a GUI viewer for multi-view annotations, setting up a window to display synchronized camera frames and navigation controls. It loads annotation files, verifies input directories, arranges frames in a grid layout, and enables frame navigation via buttons. The viewer handles errors for missing direc... | def __init__(self, _gui, _opt, _verbose=True):
"""
Initializes a GUI viewer of the annotations.
Attributes:
_verbose: [bool] if True navigating actions will printout info
_fr_sub_dirs: [list of str] where each str is an absolute path to the subdir for a camera
... |
def compute_ODS(bidders):
mod = compute_mods(bidders)
od = mod
while len(mod) > 0:
for b in bidders:
b.demand_set = b.demand_set - mod
mod = compute_mods(bidders)
od = od | mod
return od
def compute_maximum_matching(bidders, n):
room_edges = {}
bidder_edges = {}
for i in range(n):
room_edges[i] = set(... | This code conducts a discrete price auction by iteratively adjusting prices based on overdemanded items (ODS) until no ODS remains. It initializes prices evenly, updates bidders' demand sets, computes ODS, and adjusts prices proportionally to ODS size. The process repeats until ODS is empty, then returns the maximum ma... | def conduct_discrete_price_auction(bidders, C):
n = len(bidders)
prices = [C/n] * n
count = 0
while True:
count+=1
print("Price on iteration", str(count)+ ":")
print(prices)
for bidder in bidders:
bidder.recompute_demand_set(prices)
od = compute_ODS(bidders)
print("FODS on iteration", str(count)+ ":"... |
def sort_sq(self,game_sq,num='ALL'):
list_0 = []
list_1 = []
list_2 = []
list_3 =[]
for i in range(self.size):
for j in range(self.size):
if num == 'ALL':
if type(game_sq[i][j]) is Square and game_sq[i][j].numbers_of_occupied_walls... | The function determines the computer's next move by selecting squares via A* algorithm if no zero-wall squares exist, or using a custom algorithm on sorted squares. It then extracts their positions and sends an update to the GUI with computer ownership. | def computer_turn(self):
sq_to_play0,sq_to_play1,sq_to_play2,sq_to_play3 = self.sort_sq(self.game_module)
if len(sq_to_play0) == 0:
# if no squares with 0 wall, need to use AI in aim to choose the next stage
sq_walls_to_play = self.A_start()
self.update_computer_step... |
def update_square_affected(game_board,place,color):
list_of_sq_to_colored=[]
for sq in game_board[place[0]][place[1]].square_affected:
if (sq.update_square_state(color)):
list_of_sq_to_colored.append(sq)
return list_of_sq_to_colored
def check_if_someone_win(self):
... | The function updates a user's ownership of a wall module by checking if the target is unoccupied and a wall. If valid, it marks the wall as user-owned, updates affected squares, increments user-occupied count, notifies the GUI, checks for a win, and grants another turn if squares were closed. Otherwise, it proceeds to ... | def update_user_step_in_module(self,place,color):
if self.game_module[place[0]][place[1]].owned != 0:
print("Module Error: trying to update occupied place ", place,self.game_module[place[0]][place[1]].owned)
return
if type(self.game_module[place[0]][place[1]]) != Wall:
... |
def display_board(self) -> None:
# lining it up well only for 1-100
print(self.cell_sep, end = '')
for col_name in self.col_inputs:
if col_name < 10:
print(f'{col_name}{self.cell_sep}', end='')
else:
print(f'{col_name}{self.cell_sep[0:-1]}... | The code runs a game loop where players take turns making moves. After each move, it checks for a win or tie. If a player wins, the board is displayed, the winner is announced, and the loop exits. If the game ties, a tie message is shown. The player alternates using a generator, ensuring continuous gameplay until a ter... | def game_loop(self) -> None:
while True:
self.display_board()
self.move()
if self.check_win():
self.display_board()
print(f"{self.player.name} wins!")
print(f"{self.player.name}: {self.player.win_message}")
retur... |
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def setup(args):
# Prepare model
config = CONFIGS[args.model_type]
in_channels = 3
num_classes = 8
model = VisionTr... | The main task of the code is to configure and execute machine learning model training for image classification tasks, supporting datasets like CIFAR, MRI variants, and FFR. It parses parameters for model architecture (e.g., ViT, ResNet), training settings (optimizer, batch sizes), data modalities (T1/T2/EarlyFusion), c... | def main():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument("--name", required=True,
help="Name of this run. Used for monitoring.")
parser.add_argument("--dataset", choices=["cifar10", "cifar100", 'MRI', 'MRI-BALANCED', 'MRI-BALANCED-3Classes', 'MRI-B... |
def getFSM(self):
with open(f"{self.folder}/mission-folder/fsm.txt",'r') as f:
line = f.readline()
PFSM = FSM.parse_from_commandline_args(line.split(" "))
return PFSM
def computeMu(self, exp=10):
phi_list = []
for _ in range(exp):
phi = self.computePhi... | The main task of the code is to generate and iteratively improve a Policy Function State Machine (PFSM) by computing its parameters (mu, phi, margin, SVM coefficients), tracking historical data, and saving results to JSON and text files for analysis. It updates the PFSM based on margin improvement, logs iteration detai... | def computePFSM(self):
"""Perform the algorithm to generate the desirable PFSM"""
self.PFSM = self.getFSM()
self.mu, phi_list = self.computeMu()
self.muHistory.append(self.mu)
self.labelHistory.append(-1)
w, t, svm, SVs, improved, previous_best = self.computeMargin(... |
def computeMuE(self):
phi_list = []
for img_name in self.img_path_names:
if img_name.endswith(".png"):
img = cv2.imread(f"{self.folder}/mission-folder/demos/{img_name}")
_, phi = self.histogram_comparision(img, self.img_base, d_kernel=self.d_kernel, s... | The code initializes an object to process mission data by parsing an experience string, setting up file paths, loading base images, configuring parameters for image comparison, computing initial metrics (muE), generating a random PFSM (Probabilistic Finite State Machine), and initializing history files to track mu valu... | def __init__(self, experience):
self.experience = experience
self.mission = self.experience.split("_")[0]
self.folder = f"/home/jpmedina/autodemo/irace/{experience}"
self.demoFile = f"{self.folder}/mission-folder/{self.mission}.argos"
self.arenaD = 3
# self.demos = self.c... |
def enter_book():
# get title info from title() function
title_add = title()
# get author info from author() function
author_add = author()
# get quantity info from the quantity() function
qty_add = quantity()
# Once the relevant data is captured for a new book,
# it will send the infor... | The code defines a menu function that displays a menu and processes user input to perform book-related operations. It uses a while loop to repeatedly prompt the user until they enter '0' to exit. Valid inputs (1-5) trigger specific functions: entering, updating, deleting, searching, or viewing books. Invalid inputs tri... | def menu():
# While loop to keep the program running whilst the response is not '0'
while (menu_input := input(menu_text)) != '0':
if menu_input == '1':
enter_book()
elif menu_input == '2':
update_book()
elif menu_input == '3':
delete_book()
elif m... |
def read_data_words():
x_train, y_train, x_test, y_test = [], [], [], []
cop = re.compile("[^a-z^A-Z^0-9^,^.^' ']")
train_file = os.path.join(dir, 'train_medium_trojan.csv')
with open(str(train_file), encoding='utf-8') as filex:
reader = csv.reader(filex)
for row in reader:
d... | The code trains an LSTM/GRU model for NLP tasks, using TensorFlow datasets for batching and shuffling. It builds, trains, evaluates, and saves the model, then loads it for predictions. If enabled, it also trains a robust version and tests it. Key steps include data loading, model construction with dropout, training wit... | def main():
CLIPPING = True
model_type = "LSTM"
dropout=True
x_train, y_train, x_test, y_test, vocab_size = read_data_words()
# Use `tf.data` to batch and shuffle the dataset:
train_ds = tf.data.Dataset.from_tensor_slices(
(x_train, y_train)).shuffle(10000).batch(batch_size)
test_ds ... |
def lr_schedule(epoch):
lr = 1e-3
if epoch > 180:
lr *= 0.5e-3
elif epoch > 160:
lr *= 1e-3
elif epoch > 120:
lr *= 1e-2
elif epoch > 80:
lr *= 1e-1
print('Learning rate: ', lr)
return lr
def build_pretrained_resnet(resnet_type):
model = keras.models.Seque... | The main task of the code is to train a ResNet model (pretrained or from scratch) with configurable optimizers, learning rate scheduling, and checkpoint resuming. It compiles the model, loads saved weights if specified, and trains it on provided data, returning the trained model and training history. | def train_model(cp_callback, optimizer_ , x_train, x_test, y_train, y_test, saved_weights, fine_tuning):
with tf.device(str(device_name)):
initial_epoch = 0
if optimizer_ == 'SGD':
optimizer = keras.optimizers.SGD(learning_rate=lr_schedule(0), momentum=MOM,nesterov=False)
elif op... |
def load_and_process_data():
data = pd.read_csv('merged_books_data.csv')
# Replace NaN in 'Most Common Words' with an empty list
data['Most Common Words'] = data['Most Common Words'].fillna("[]")
# Convert the 'Most Common Words' column from string to list of tuples
data['Most Common Words'] =... | The main task of the code is to create a Streamlit-based web dashboard for book analysis. It loads and processes book data, provides a search feature, and allows users to navigate between pages: Home (welcome message), Trend Analysis (visualizing trends), and Random Book Suggestion (generating random recommendations). ... | def main():
data = load_and_process_data()
st.title("Book Analysis Dashboard")
# Search functionality
search_query = st.text_input("Search for a book title")
if search_query:
search_results(data, search_query)
page = st.sidebar.selectbox("Choose a function", ["Home", "Trend Analy... |
def get_user_key():
while True:
user_key = input("Enter a 4-digit secret key: ")
if len(user_key) == 4 and user_key.isdigit():
return user_key.encode('utf-8')
else:
print("Invalid key. Please enter a 4-digit numeric key.")
def encrypt_message(key, message):
key = ... | The main task of the code is to encode a user-provided message into an image by encrypting it with a secret key, embedding the encrypted data into the image, and saving the modified image with optimization settings. It involves reading an input image, encrypting the message using AES, embedding the encrypted data, resi... | def encode():
img_name = input("\nEnter image name: ")
image = cv2.imread(img_name)
img = Image.open(img_name, 'r')
w, h = img.size
data = input("Enter message: ")
if len(data) == 0:
raise ValueError("Empty data")
enc_img = input("Enter encoded image name: ")
# Get the user'... |
def snell(theta1):
'''
snells(theta1)
Calculates theta2 from snells law in radians.
Parameters
----------
theta1: float
Angle in to refracting surface.
Returns
-------
theta2: float
Angle out of refracting surface.
inputut Script Parameters
------------... | The code calculates and visualizes the scattering force components (Fx and Fy) along x- and y-axes by iterating over incident angles, applying Snell's law, and using reflection/transmission coefficients (R1, T1). It computes Q_s (Fx) and Q_g (Fy) with complex optical formulas, then plots them against the incident angle... | def F():
'''
Calculate the scattering force.
:return total_forcr: list
The total_foce contains two element, the first one is the force along x-aixs, and the second one is the force along y-axis.
'''
plt.figure(1)
maxtheta = np.pi/2
theta = np.linspace(0, maxtheta, 1000)
for i in... |
def backprop(self, x, y_true, learning_rate):
y_pred = self.forward(x)
loss = self.compute_loss(y_pred, y_true)
d_loss = 2 * (y_pred - y_true) / y_true.size
d_w3 = np.dot(self.a2.T, d_loss)
d_loss = np.dot(d_loss, self.w3.T) * self.relu_derivative(self.z2)
d_w2 = np.dot(... | This code trains a neural network model over multiple epochs using batch processing. It computes training and validation losses for each epoch, performs backpropagation on training batches, evaluates the model on validation data, and returns lists of training and validation losses. The function iterates through epochs,... | def train(self, x_train, y_train, x_val, y_val, epochs, learning_rate, batch_size):
training_losses = []
validation_losses = []
for epoch in range(epochs):
epoch_loss = 0
for i in range(0, len(x_train), batch_size):
x_batch = x_train[i:i + batch_size]
... |
def true_zeta(z, k=100):
res = np.zeros_like(z)
for i in range(1, k):
res += inv(exp(z * np.log(i)))
return res
def exp(z):
return np.exp(z)
def sin(z):
return np.sin(z)
def gamma(z):
return sp.gamma(z) | The code computes the Riemann zeta function for complex inputs. It evaluates the zeta function directly for real parts greater than 1 using `true_zeta`, and applies analytic continuation via the functional equation for real parts ≤ 1, involving exponential, logarithmic, trigonometric, and gamma functions to extend the ... | def zeta(z):
res = np.zeros_like(z)
# Main part
res[z.real > 1] = true_zeta(z[z.real > 1])
# Analytic continuation
res[z.real <= 1] = exp(z[z.real <= 1] * np.log(2)) * exp((z[z.real <= 1] - 1) * np.log(PI)) * sin(PI * z[z.real <= 1] / 2) * gamma(1 - z[z.real <= 1]) * true_zeta(1 - z[z.real <= 1])
... |
def cliArgumentParser():
"""`Returns` a ArgumentParser instance with specific arguments necessary for the program."""
argParser = argparse.ArgumentParser(description='A parser to collect weather data and converts it into a XML schema.')
argParser.add_argument("-t", "--time-intervall", type=str, choices=["h... | The main task of the code is to process command-line arguments for time interval, year, and location, validate them, construct a URL to download a file, execute the download, and insert the retrieved data into an XML template using predefined mappings. The script handles parameter validation, URL generation, file retri... | def main():
"""Main function to be called by a script or terminal which gets the `intervall`, `year` and `location` values by cli arguments."""
args = cliArgumentParser()
try:
validateRequestParams(args.time_intervall, args.year, args.location)
except Exception as err:
raise Exception(... |
def setTimeIntervall(timeIntervall: str):
"""Sets the global `INTERVALL_PATH` depending on the given `timeIntervall`."""
global INTERVALL_PATH
match timeIntervall:
case "hourly": INTERVALL_PATH = HOURLY_PATH
case "daily": INTERVALL_PATH = DAILY_PATH
case "monthly": INTERVALL_PATH = ... | The main task of the code is to download and process data based on specified parameters. It sets a time interval, constructs a URL, retrieves a file, and populates an XML template with the downloaded data, returning the filled XML as a string. | def apiMain(intervall: str, year: int, location: str):
"""Main function to be called by an api service with given `intervall`, `year` and `location`"""
setTimeIntervall(intervall)
finalUrl = getUrl(intervall, year, location, '.txt', CREDENTIALS)
print("Following file was found: '" + finalUrl + "'\n\n... |
def verify_ffmpeg_still_running(root):
ffmpeg_window = tk.Toplevel(root)
ffmpeg_window.resizable(False, False)
ffmpeg_window.geometry("400x150")
ffmpeg_window.title("Verify ffmpeg Status")
output = ''
cpu_usage = ''
if isMacOs():
proc = subprocess.Popen("ps -Ao comm,pcpu -r | head -... | The main task of the code is to initialize a GUI interface for video processing, destroy initial UI elements, create progress tracking components (labels, progress bar), and launch a background thread to inspect and process video files in a specified directory. It also sets up OS-specific quit buttons and error logging... | def start_program(directory, root, index_start, log_file, label_chosen_directory, label_chosen_directory_var, label_video_count, label_video_count_var, label_index_start, entry_index_input, label_explanation, button_start, listbox_completed_videos):
try:
label_chosen_directory.destroy()
label_chosen... |
def countAllVideoFiles(dir):
total = 0
for root, dirs, files in os.walk(dir):
for file in files:
if file.lower().endswith(tuple(VIDEO_EXTENSIONS)):
total += 1
return total
def getAllVideoFiles(dir):
index = 1
videos_found_list = []
for root, dirs, files in os.... | The main task of the code is to initialize a GUI interface for a video inspection tool after a directory is selected. It creates a log file, displays the chosen directory and video count, lists all video files in a listbox, and provides input for a starting index. If videos exist, it enables a "Start Inspecting" button... | def afterDirectoryChosen(root, directory):
# Log file
log_file_path = os.path.join(directory, '_Logs.log')
log_file_exists = os.path.isfile(log_file_path)
if log_file_exists:
os.remove(log_file_path)
log_file = open(log_file_path, 'a', encoding="utf8")
# Logging
print('CORRUPT VIDEO... |
def recolor(k, data):
# Pick random centers from the data list to start
centers = cc.random_picks(k, data)
# RSS is the residual sum of squares (total error squared of each point's dist to its cluster center)
old_RSS, RSS = 0, 0
centers_changed = True
while centers_changed:
# Create di... | The code performs image colorization using a machine learning model trained on clustered color data. It splits an image into training and testing halves, applies k-means clustering (k=10) to the training data, combines recolored pixels with grayscale patches, trains a model on this dataset, and applies it to the test i... | def start():
# Relative path
original = Image.open("C:Nature\\small_nature.jpeg")
# original = Image.open("C:Images\\EvenSmaller.png")
k = 10 # Adjusted number of clusters
img = original.convert("L") # grayscale copy
width, height = img.size
# Create left (training) and right (testing) i... |
def downsample(self, x, f):
"""Average every f samples in x"""
x = np.asarray(x)
xp = np.r_[x, np.nan + np.zeros((-len(x) % f))]
return np.nanmean(xp.reshape(-1, f), axis=-1)
def indicator_transform(self, df):
"""Transform var to indicators based on thresholds"""
ind_cols... | The main task of the code is to initialize and preprocess data for each drillhole (dh) by storing original and downsampled data, applying indicator and normal score transformations, simulating realizations, calculating run frequencies, and analyzing scale sensitivity. This prepares structured data for subsequent tests,... | def _initialize_dict(self):
"""Initialize data for subsequent tests and measures"""
self.dh_dict = {dh: {} for dh in self.dhids}
for dh in self.dhids:
x = self.data.loc[self.data[self.dhid] == dh][[self.var]].copy()
self.dh_dict[dh]["x_numpy"] = x.values.flatten()
... |
def _ng_scale_continuous(self):
"""Scale based measure of non-Gaussianity from continuous values"""
df = pd.DataFrame(columns=[f"Scale Factor {f}" for f in self.scale_factors])
df.index.name = self.dhid
for f in self.scale_factors:
for dh in self.dhids:
df.loc... | The function calculates a specified non-Gaussianity measure based on the provided metric. It validates the metric, selects the corresponding internal computation method (e.g., scale_continuous, total_runs, etc.), executes it with optional parameters like max_runs or nstep, and returns the resulting DataFrame containing... | def nongauss_measure(self, metric, max_runs=None, nstep=None):
"""Calculate measures of non-Gaussianity.
Metrics: scale_continuous, total_runs, run_length_freqs, n_pt_connectivity
"""
if metric not in self.metrics:
raise ValueError(f"metric must be one of {self.metrics}")
... |
def _plot_variance(self, dh, figsize, **kwargs):
"""Plot variance vs scale factor"""
fig, ax = plt.subplots()
dh_var = self.dh_dict[dh]["cont_var"]
sim_var = self.dh_dict[dh]["sim_cont_var"]
ax.plot(
list(dh_var.keys()), list(dh_var.values()), marker=".", label="Drill... | The function generates diagnostic plots to visualize measures of non-Gaussianity, such as variance scaling, run statistics, and connectivity patterns. It selects a plotting method based on the specified metric, validates inputs, and returns a matplotlib figure and axes object for visualization. | def diagnostic_plot(
self,
metric,
dh,
q=None,
f=None,
max_runs=None,
nstep=None,
figsize=None,
**kwargs,
):
"""Plot measures of non-Gaussianity.
Metrics: scale_continuous, total_runs, run_length_freqs, n_pt_connectivity
... |
def usage( sname ):
""" Define input and output """
os.sys.stderr.write("\nPCA-based rigid registration of image sequences\n")
os.sys.stderr.write("\nUsage: {0} -target_path <path_to_target_seq> "\
"-source_path <path_to_source_seq> -dofout <dof_file> -out_path"\
" <out_path> -out_time <otim... | The code processes target and source medical image sequences by resampling them into isotropic volumes, optimizing degrees of freedom (DOF) for registration, and outputting registered images and DOF parameters. It handles metadata and raw image pairs, applies smoothing, and writes results to specified directories with ... | def main(argv):
""" Check input arguments """
argc = len(argv)
if argc < 11:
return usage(argv[0])
else:
target_dir, source_dir, doffile, out_path, otime, verbose = read_inputs(argv, argc)
#==============================================================================
# Read names of i... |
def load_audio(filepath, offset):
off_set = OFFSET + offset - seconds_per_buffer
audio, _ = lb.load(filepath, offset=off_set, duration=DURATION)
audio = butter_bandpass_filter(audio, LOWCUT, HIGHCUT, SR)
# audio = nr.reduce_noise(y=audio, sr=SR)
return audio
def extract_logmel_spectrogram(audio):
... | The main task of the code is to preprocess an audio file by loading it, applying preemphasis, extracting a log-mel spectrogram, and saving the result. The function takes a WAV file path, event time, and minute as inputs, processes the audio to enhance features, converts it into a log-mel spectrogram for analysis, and s... | def preprocess_and_save_spectrogram(wavfile_path, time_of_event, minute):
audio = load_audio(wavfile_path, time_of_event)
audio = lb.effects.preemphasis(audio)
# if np.max(audio) < 0.5 and np.max(audio) > 0.012: # delete this for the original code
logmel_spec = extract_logmel_spectrogram(audio)
sav... |
def set_measure_param(self, param, value):
_PARAMS = ["P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8"]
assert param in _PARAMS, f'In method {inspect.currentframe().f_code.co_name}() param: {param}" not allowed\nAllowed channels are: {_PARAMS}'
_VALUES = ["100BTfall", "100BTrise", "100BTTIE", "10... | The function `get_measurement` configures measurement parameters and sources, initiates data acquisition, and returns the result. It sets the measurement parameters using `set_measure_param`, assigns input sources via `set_measure_source`, triggers acquisition with `acquire(1)`, and retrieves the result via `get_measur... | def get_measurement(self, param, paramengine, source1, source2=None):
self.set_measure_param(param, paramengine)
self.set_measure_source(param, source1, source2)
self.acquire(1)
return self.get_measure_result(param) |
def createobjects(self):
# Set the name of the folders in which to store the current analysis based on the length of reads
reads = '{}_{}'.format(self.forwardlength, self.reverselength)
# Update the necessary variables to allow for the custom naming of folders based on the length forward and
... | The main task of the code is to execute an analysis pipeline for sequencing data, handling forward and reverse read lengths. It iteratively runs quality checks and analyses on strains until all pass thresholds or the sequencing completes. The code creates objects, performs gene sipping analyses, generates reports, and ... | def main(self):
"""
Run the analyses using the inputted values for forward and reverse read length. However, if not all strains
pass the quality thresholds, continue to periodically run the analyses on these incomplete strains until either
all strains are complete, or the sequencing run ... |
def generate_doxygen_xml(input_directory, output_directory):
print("Generating Doxygen XML...")
doxygen_config = {
"DOXYFILE_ENCODING" : "UTF-8",
"FILE_PATTERNS" : "*.h",
"GENERATE_BUGLIST" : "NO",
"GENERATE_DEPRECATEDLIST" : "NO",
"GENERATE_HTML" : "NO",
"GENERAT... | The main task of the code is to generate C++ reflection code (RegisterTypes.h) from header files in an input directory, using Doxygen XML parsing. It ensures the output is only regenerated if input headers are newer than the existing output, avoiding redundant work. The code creates necessary directories, checks modifi... | def action(input_directory, output_directory, namespace):
print("Generating '{}' types...".format(namespace))
if not os.path.exists(output_directory):
os.makedirs(output_directory)
if not os.path.exists(os.path.join(output_directory, "xml")):
os.makedirs(os.path.join(output_directory, "xml... |
def _check_events_down(self, event):
""" check down events """
if event.key == pygame.K_RIGHT:
self.ship.move_right = True
elif event.key == pygame.K_LEFT:
self.ship.move_left = True
elif event.key == pygame.K_SPACE:
self._fire_bullet()
elif ev... | This function processes user input events in a Pygame application. It iterates through all detected events, handling window close requests, keyboard key presses/releases, and mouse button clicks by delegating to specific methods. The primary task is to detect and respond to user interactions, triggering appropriate gam... | def _check_events(self):
""" dealwith user click event """
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_events_down(event)
elif event.type == pygame.KEYUP:
... |
def _check_eliens_bottom(self):
""" elien move bottmon """
for elien in self.aliens.sprites():
if elien.rect.bottom >= self.screen_rect.bottom:
return True
return False
def _ship_hit(self):
""" ship hit """
self.stats.ships_left -= 1
if self.... | This method updates alien movement by checking collisions between the ship and aliens or if aliens reach the screen bottom, triggering a ship hit response. It also checks for aliens hitting screen edges, updates their positions, and redraws them on the screen. | def _update_alien(self):
""" update alien move """
if pygame.sprite.spritecollideany(self.ship, self.aliens) or self._check_eliens_bottom():
self._ship_hit()
self._check_elien_edge()
self.aliens.update()
self.aliens.draw(self.screen) |
def _check_events(self):
""" dealwith user click event """
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_events_down(event)
elif event.type == pygame.KEYUP:
... | The code runs a game loop that continuously checks for events, updates game elements (ship, bullets, aliens, score) when the game is active, and refreshes the display to render the current game state. | def run_game(self):
""" play game """
while True:
self._check_events()
self._update_screen()
if self.settings.game_active:
self._update_ship()
self._update_bullet()
self._update_alien()
self._update_scor... |
def next(self):
self.__turn *= -1
def generate_legal_moves(self):
for i in range(self.__board.DIMENS):
for j in range(self.__board.DIMENS):
if self.at(i, j) != self.__board.FREE:
piece, legal_moves = self.at(i, j), []
if piece.get_type(... | This method attempts to move a chess piece from coordinates 'old' to 'new' if valid. It checks if the source piece belongs to the current player, the destination is unoccupied or enemy-occupied, and the move is legal. If valid, it updates the board, switches turns, and checks if the move leaves the player in check. If ... | def move(self, old, new):
if self.__state == self.ONGOING:
src, dest = self.__board.at(old[0], old[1]), self.__board.at(new[0], new[1])
if src != self.__board.FREE: # not a free space
src_color, dest_color = src.get_color(), self.__board.FREE if dest == self.__board.FREE ... |
def freeform_answer(self, number, mentoring, controls, text_input, result, saved_value="", last=False):
self.expect_question_visible(number, mentoring)
self.assert_persistent_elements_present(mentoring)
answer = mentoring.find_element_by_css_selector("textarea.answer.editable")
self.as... | The code tests an assessment system by simulating user interactions with various question types (freeform, single-choice, rating, multiple-response), verifying correctness, partial/incorrect responses, and feedback. It checks if the system tracks attempts, displays appropriate messages (e.g., "used all attempts"), enab... | def test_assessment(self, params):
mentoring, controls = self.load_assessment_scenario("assessment.xml", params)
max_attempts = params['max_attempts']
extended_feedback = params['extended_feedback']
self.freeform_answer(1, mentoring, controls, 'This is the answer', CORRECT)
self... |
def check_valid_file(file_name):
directory = os.getcwd()
listed_directory = os.listdir(directory)
while file_name not in listed_directory:
print("File not found, please try again.")
file_name = input("Please enter file name with extension: ")
return file_name
def load_file(file_name: str... | The main task of the code is to create a GUI application for scheduling using Tkinter. It loads data from an Excel file, generates a schedule via a genetic algorithm, sorts it by time, and displays the schedule in a window. Key steps include file validation, data loading, genetic algorithm hypothesis generation, sortin... | def main():
root = tk.Tk()
root.title("Schedule")
# Set a reasonable size for the initial window
root.geometry('800x600')
file_name = "Simulated Data.xlsx"
file_name = check_valid_file(file_name)
sim_course_sections, classrooms, time_slot_descriptions, teacher_satisfaction = load_file(file_... |
def initialize_hypotheses(number_hypotheses):
# Empty list
hypotheses = []
# Generate hypotheses
for _ in range(number_hypotheses):
hypothesis = generate_hypothesis()
hypotheses.append(hypothesis)
return hypotheses
def get_next_filename(base_name="Generation", extension=".csv"):
i = 1
while ... | The code implements a genetic algorithm to optimize hypotheses by iteratively applying selection, crossover, mutation, and injection operations. It tracks the best hypothesis, records fitness data in a file, and terminates when no improvement is observed for a specified number of generations (plateau_generations). | def genetic_algorithm(num_hypotheses, cross_rate, mutate_rate, injection_rate, plateau_generations):
print(f"Initializing {num_hypotheses} hypotheses ...")
hypotheses = initialize_hypotheses(num_hypotheses)
generation = 1
best = 0
gen_num = 0
best_hypothesis = hypotheses[0]
# Repeat below until threshold ... |
def format_time():
global time_slots
time_slots = add_am_pm()
# Add a new columns to the existing array representing time slots in minutes
time_slots = np.column_stack(
(time_slots, [convert_to_minutes(slot) for slot in time_slots]))
remove_time_slot()
return time_slots
def generate_conflict_lists():
... | The main task of the code is to retrieve and return three data sets: formatted time slots, generated time conflicts, and credit information. The function `get_values()` calls three helper functions to obtain these values and packages them as a tuple for further processing, likely in scheduling or planning applications. | def get_values():
time_slots = format_time()
time_conflicts = generate_conflict_lists()
credits = generate_credits()
return time_slots, time_conflicts, credits |
def log(text, *args, **kwargs):
"""Log technical details to LOG_PATH."""
caller = inspect.stack()[1][3] # Get the caller function name
log_text = text.format(*args, **kwargs)
lines = (log_text + '\n').splitlines()
install_log.extend(lines)
write_lines = '\n'.join(
"{}: {}".format(calle... | The code generates a structured report containing system information (CPU, OS), elapsed time, status, and other metadata, formatting it into a JSON string within a dictionary for transmission. It calculates total runtime, logs details, and includes a token from settings to authenticate or identify the report. | def build_report(status, reason=None):
"""Generate report data for `send_report`."""
log('{} ({})', status, reason)
# Get total time to this point (in seconds)
elapsed = int(time.time() - start_time)
log('{}s elapsed (total)', elapsed)
data = {
"cpu": get_cpu_info(),
"elapsed"... |
def log(text, *args, **kwargs):
"""Log technical details to LOG_PATH."""
caller = inspect.stack()[1][3] # Get the caller function name
log_text = text.format(*args, **kwargs)
lines = (log_text + '\n').splitlines()
install_log.extend(lines)
write_lines = '\n'.join(
"{}: {}".format(calle... | The code registers a device with a server by sending its serial number, name, and token via a POST request. It handles server responses, updates registration details if the device is new, or alerts about existing devices. On success, it returns the device URL; on failure, it aborts installation with an error message. | def register_device(urlopen=None):
"""
Register device with the server.
Returns a URL to the device on success.
"""
serial = None
if os.path.isfile(SERIAL_PATH):
with open(SERIAL_PATH, 'rb') as serial_file:
serial = serial_file.read().strip().decode('utf-8')
log('se... |
def log(text, *args, **kwargs):
"""Log technical details to LOG_PATH."""
caller = inspect.stack()[1][3] # Get the caller function name
log_text = text.format(*args, **kwargs)
lines = (log_text + '\n').splitlines()
install_log.extend(lines)
write_lines = '\n'.join(
"{}: {}".format(calle... | The code defines a function `report` that logs installation status and reason, constructs a report using `build_report`, logs the generated report, and sends it to a server via `send_report`, primarily to transmit installation results for tracking or monitoring purposes. | def report(status, reason=None):
"""Report install result to server."""
log('status={!r} reason={!r}', status, reason)
_report = build_report(status, reason=reason)
log("{!r}", _report)
send_report(_report) |
def get_A(self, A : Fxp):
self._A.equal(A)
def init_V(self):
self._V.set_val(np.eye(self._N))
def do_one_sweep(self):
self.init_round_state()
for i in range(self._N-1):
self.do_one_round() | The code performs multiple iterative sweeps on input matrix A, initializing vector V each time. It executes `do_one_sweep()` repeatedly, updating A and V through each iteration. The main task is to process A through a series of transformations defined in `do_one_sweep()`, returning the final state of A and V after all ... | def run(self, A):
self.get_A(A)
self.init_V()
for i in range(self._n_sweeps):
print("Sweep {n}/{N}".format(n = i+1, N = self._n_sweeps), end = '\r')
self.do_one_sweep()
return self._A, self._V |
def move(position):
print("Moving spaces: ", position[0], position[1])
x, y = 420 + 25 * position[0], 425 - 20 * position[1]
# add a random offset in px
x += random.randrange(-3, 3)
y += random.randrange(-3, 3)
b = random.uniform(0.2, 0.7)
pyautogui.moveTo([x, y], duration=b)
antiafk.ran... | The main task of the code is to automate a banking process in a game. It moves the character to a bank, detects and interacts with the bank interface (dropping specified items), handles retries if the bank HUD isn't detected, and performs anti-AFK actions to avoid detection. The function also includes pre- and post-ban... | def do_banking(item_ids):
for movement in options_yaml['general']['walk_before_bank']:
move(movement)
num_tries = 0
while not imgdetection.contains_item_on_screen('bank_hud') and num_tries < 3:
imgdetection.object_rec_click_closest_single('bank_highlight')
wait_until_idle()
... |
def preprocess_input_data(input_data_list: List, target_house_type: str):
not_num_feat = 6
input_mean_list = get_input_means(input_data_list, not_num_feat)
input_data = []
label_data = []
for data in input_data_list:
if data[1] == target_house_type:
label = 1
else:
... | The main task of the code is to train a logistic regression model for each Hogwarts house (Gryffindor, Hufflepuff, Ravenclaw, Slytherin) using the provided training data. It processes input data by normalizing features, trains separate models for each house, and saves the learned parameters, normalization statistics, a... | def train(train_data_path: str, output_param_path: str):
with open(train_data_path) as f:
reader = csv.reader(f, delimiter=",")
input_data_list = [row for row in reader][1:]
house_list = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]
param_list = []
remv_num = 1
for i in ran... |
def _get_bert_features(self, input_ids,
attention_mask,
token_type_ids,
position_ids,
head_mask,
inputs_embeds,
output_attentions,
... | This code processes input text through a BERT model to extract features, decodes them using the Viterbi algorithm for sequence labeling, and computes negative log likelihood loss during training. In inference mode, it returns predicted labels without loss. The method combines BERT embeddings with a CRF layer for token ... | def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
... |
def move_wheels(self, parameters):
lspeed = int(parameters["lspeed"])
rspeed = int(parameters["rspeed"])
time = float(parameters["time"])
self.sim_plugin.moveWheelsByTime(rspeed, lspeed, time)
wheels_message = self.read_wheels()
self.outgoing.put_nowait(wheels_message)
de... | The code's main task is to move wheels using provided parameters, unlock a specified block with an "UNLOCK-MOVE" command, read the updated wheel status, and asynchronously send the wheel data via the outgoing message queue. | def move_wheels_blocking(self, parameters):
self.move_wheels(parameters)
blockid = parameters["blockid"]
self.unlock(blockid, "UNLOCK-MOVE")
wheels_message = self.read_wheels()
self.outgoing.put_nowait(wheels_message) |
def move_pan(self, parameters):
pos = int(parameters["pos"])
speed = int(parameters["speed"])
self.sim_plugin.movePanTo(pos, speed)
pan_message = self.read_pan_position()
self.outgoing.put_nowait(pan_message)
def unlock(self, blockid, command):
self.sim_plugin.block()
... | The function `move_pan_blocking` executes a sequence of operations to control a pan mechanism: it initiates a pan movement, unlocks a specified block using a predefined reason, reads the updated pan position, and asynchronously sends the position data via a message queue. The process is blocking, ensuring each step com... | def move_pan_blocking(self, parameters):
self.move_pan(parameters)
blockid = parameters["blockid"]
self.unlock(blockid, "UNLOCK-PAN")
pan_message = self.read_pan_position()
self.outgoing.put_nowait(pan_message) |
def move_tilt(self, parameters):
pos = int(parameters["pos"])
speed = int(parameters["speed"])
self.sim_plugin.moveTiltTo(pos, speed)
tilt_message = self.read_tilt_position()
self.outgoing.put_nowait(tilt_message)
def unlock(self, blockid, command):
self.sim_plugin.block(... | The code executes a tilt movement using provided parameters, unlocks a specified block with "UNLOCK-TILT", reads the resulting tilt position, and sends the position data to an outgoing queue for further processing. | def move_tilt_blocking(self, parameters):
self.move_tilt(parameters)
blockid = parameters["blockid"]
self.unlock(blockid, "UNLOCK-TILT")
tilt_message = self.read_tilt_position()
self.outgoing.put_nowait(tilt_message) |
def get_all_cat(categories):
'''
find the list of all category tuples.
Inputs:
categories (list): a list of categories - low, medium and high.
Outputs:
cat_lst (list): the list of all category tuples (in this pa, 27).
'''
cat_lst = []
for cat1 in categories:
for cat2 in c... | The function `find_matches` performs record linkage to classify potential matches between Zagat and Fodors restaurant datasets. It reads input data, computes probabilities for matches/non-matches using known links/unmatch pairs, and categorizes pairs into "high," "medium," or "low" match likelihood based on thresholds ... | def find_matches(output_filename, mu, lambda_, block_on_city=False):
'''
Put it all together: read the data and apply the record linkage
algorithm to classify the potential matches.
Inputs:
output_filename (string): the name of the output file,
mu (float) : the maximum false positive rate,
... |
def exists(self, user:str):
"""Search the database for a selected user. Return boolean"""
exists = False
for player in self._read():
if player[0] == user and not(exists):
exists = True
elif player[0] == user and exists:
raise InternalExcept... | This code implements a server-side function to handle client requests for account creation and login. It continuously accepts connections, processes received messages to check if the request is for account creation (msg[0] = "\x00") or login (msg[0] = "\x01"), validates credentials, and sends appropriate responses. It ... | def start(self):
while True:
addr, info = self.skt.accept()
msg = addr.recv(1024).decode().split("-")
if msg[0] == "\x00":
#Account creation
if self.exists(msg[1]):
addr.send(b"\x00-0-This username is already taken !", 1024)... |
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Font"))
self.groupBox.setTitle(_translate("Form", "Exampke"))
self.label.setText(_translate("Form", "A B C D E F G H"))
self.label_2.setText(_translate("Form", "a... | This code sets up a GUI with a font selector, size input, labeled group box, and save/cancel buttons. It initializes UI components, links signals to update an example display, and connects font/size changes to dynamically refresh the example. | def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(287, 206)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setObjectName("gridLayout")
self.Font_Box = QtWidgets.QFontComboBox(Form)
self.Font_Box.setObjectName("Font_Box")
self.gridLayou... |
def _getHash(self, key):
hasher = hmac.HMAC(self._getKey(key), hashes.SHA256(), default_backend())
hasher.update(key)
return hasher.finalize()
def _random(self):
digest = hashes.Hash(hashes.SHA256(), default_backend())
digest.update(self._SEED)
self._SEED = digest.finalize()
return self._SEE... | The main task of the code is to generate a secure, random alphanumeric password of a specified length for a given domain, ensuring no existing password for that domain and adhering to maximum length constraints. The password is then stored in a password manager and returned. | def generate_new(self, domain, desired_len):
"""Generates a password for a particular domain. The password
is a random string with characters drawn from [A-Za-z0-9].
The password is automatically added to the password manager for
the associated domain.
Args:
domain (str)... |
def matrixify(grid, separator='\n'):
return grid.split(separator)
def find_base_match(char, matrix):
base_matches = [(row_index, column_index)
for row_index, row in enumerate(matrix)
for column_index, column in enumerate(row)
if char == column]
re... | The code searches for all possible matches of a given word in a grid. It first identifies starting positions with the word's first character, checks grid dimensions for feasibility, and then explores paths to complete the word match, returning coordinates of valid matches. | def find_matches(word, grid, separator='\n'):
word_len = len(word)
matrix = matrixify(grid, separator)
row_len, column_len = len(matrix), len(matrix[0])
base_matches = find_base_match(word[0], matrix)
if column_len < word_len > row_len or not base_matches:
return []
elif word_len == 1:
... |
def get_data(folder: str, n_patients: Optional[int] = N_PATIENTS) -> List[dict]:
"get data from a folder"
data = []
path = os.path.join("data", folder)
for file in os.listdir(path):
if file.endswith(".json"):
filepath = os.path.join("data", folder, file)
with open(filepa... | The function `get_version_stats` computes and returns statistical information about medical resources in a specified dataset version. It processes data grouped by resource type, calculating the number of resources, their structural shapes, and depth metrics. The result is a structured dictionary containing version deta... | def get_version_stats(version: str, n_patients: int = N_PATIENTS) -> Dict[str, tuple]:
"get shapes of resources"
data = get_data(version, n_patients)
grouped = group_by_resource_type(data)
shapes, depths = get_shapes_and_depths(grouped)
version_stats = VersionStats(
version=version,
... |
def buildMinHeap(arr):
heapSize = len(arr)
for i in range((heapSize - 2) // 2, -1, -1):
minHeapify(arr, heapSize, i)
return arr
def extractMin(heap):
minElement = heap.pop(0)
if heap:
last_elem = heap.pop()
heap.insert(0, last_elem)
minHeapify(heap, len(heap), 0)
... | The code constructs a Huffman tree by repeatedly extracting the two smallest frequency nodes from a min-heap, merging them into a new node with combined frequency, and reinserting the new node into the heap. This process continues until one node remains, which becomes the root of the Huffman tree for optimal prefix-fre... | def huffman(C):
heap = C[:]
buildMinHeap(heap)
n = len(heap)
for i in range(n - 1):
z = Node()
z.left = extractMin(heap)
z.right = extractMin(heap)
z.freq = z.left.freq + z.right.freq
insertMinHeap(heap, z)
return extractMin(heap) |
def createCharFreqFromFile(filePath):
with open(filePath, 'r') as file:
text = file.read()
charFreq = {}
for char in text:
if char in charFreq:
charFreq[char] += 1
else:
charFreq[char] = 1
chars = list(charFreq.keys())
freqs = list(charFreq.values())... | The main task of the code is to provide a user interface for Huffman encoding/decoding files. It allows users to select options: encode a file (generating Huffman codes and saving them), decode a file using stored codes, or exit. The program handles file input/output, constructs Huffman trees, and implements compressio... | def main():
while True:
print("1. Encode File")
print("2. Decode File")
print("3. Exit")
choice = input("Choose option: ")
if choice == "1":
inputFilePath = input(f"Enter the path to the file you want to encode (default: {DEFAULT_ENCODE_INPUT_PATH}): ") or DEFAUL... |
def get_midway_point_of_hdist(p, q, hdist, A, B):
"""
A--p--q--B
Will find point on line between p and q, which is hdist from q. Searches line in binary search. Maybe there's a
better way? I can't tell. Please let me know ;)
:param p: np.array(coordinates)
:param q: np.array(coordinates)
:param hdi... | The code computes and returns the midpoint of a segment by calculating it once if not already stored. It uses a helper function with parameters including endpoints, half the distance, and boundary intersections to determine the midpoint, ensuring efficient retrieval on subsequent calls. | def get_midpoint(self):
if self.midpoint is None:
self.midpoint = get_midway_point_of_hdist(self.p, self.q, self.get_hdist() / 2, *self.get_boundary_intersections())
return self.midpoint |
def genus_2_cover_security(curve):
r""" Return whether the given `curve` is resistant to genus 2 cover attacks.
INPUT:
- ``curve`` -- the elliptic curve
OUTPUT: a boolean indicating whether the given `curve` is resistant to genus 2 cover attacks.
"""
n = curve.count_points()
# We don't p... | The function `sextic_extension_specific_security` checks if an elliptic curve is resistant to extension-specific attacks (genus 2/3 hyperelliptic/non-hyperelliptic covers and GHS attacks). It evaluates four security conditions using specialized functions and returns `True` only if all checks pass. Inputs include the cu... | def sextic_extension_specific_security(curve, curve_coeff_a, curve_coeff_b, field_characteristic, number_points=0):
r""" Return whether the given `curve` is resistant to extension specific attacks, namely:
- genus 2 cover attacks
- genus 3 hyperelliptic cover attacks
- genus 3 non-hyperelli... |
def plurality_value(a):
# Plurality function for selecting most common output value
return max(set([x[-1] for x in a]), key=a.count)
def argmax(examples, attributes, rand):
if rand: # Choosing the attribute randomly
return random.choice(attributes)
else: # Choosing the attribute using i... | The code constructs a decision tree recursively. It selects the best attribute to split data, creates tree nodes, and handles base cases like empty examples or uniform outputs by returning majority-voted nodes. Subtrees are built for each attribute value, using remaining attributes and filtered examples. Your return | def decision_tree_learning(examples, attributes, parent_examples, rand):
# Creating a list to use with plurality function
output = []
for example in examples:
output.append(example[-1])
if not examples:
return Node(plurality_value(parent_examples), True)
elif len(set(output)) == 1:
... |
def readfile(filename):
# Reading the training set and creating a list
with open(filename, "r") as f:
data = f.readlines()
datalist = []
for line in data:
datalist.append([int(i) for i in line.split()])
return datalist
def decision_tree_learning(examples, attributes, parent_examples,... | The code trains a decision tree on a training dataset, evaluates its accuracy on a test dataset by comparing predicted and actual labels, and visualizes the learned decision tree as an SVG file. | def main():
# Loading the training set
examples = readfile("data/training.txt")
attributes = [x for x in range(len(examples[0])-1)]
# Training the decision tree
tree = decision_tree_learning(examples, attributes, None, False)
# Loading the test file
test = readfile("data/test.txt")
count... |
def subset_json_detector_output_by_query(data, options):
"""
Subset to images whose filename matches options.query; replace all instances of
options.query with options.replacement.
"""
images_in = data['images']
images_out = []
print('Subsetting by query {}, replacement {}...'... | This function processes a JSON dataset of images, optionally filtering by query, confidence, or removing failed images. If enabled, it splits the dataset into separate JSON files per folder, adjusting file paths to be relative. The processed data is saved to the specified output, either as a single file or multiple fil... | def subset_json_detector_output(input_filename, output_filename, options, data=None):
"""
Main internal entry point
Makes a copy of [data] before modifying if a data dictionary is supplied.
"""
if options is None:
options = SubsetJsonDetectorOutputOptions()
... |
def get_Intermediate_Points(slope1, slope2, X1, X2, Y1, Y2):
global track_width
global ratio
int1 = np.zeros(2)
int2 = np.zeros(2)
d = distancecalcy(Y2,Y1,X2,X1)
ratio = 0.4 - 0.06*(d/(track_width+d))
# if(d>track_width):
# d = track_width
int1[0] = X1 + ratio*m.cos(slope1*DEG2RAD)*d
int1[1] = Y1 + ratio*m.s... | The function calculates the maximum curvature, its first and second derivatives, arc length, and intermediate curvature values for a path between two points with specified slopes, returning these metrics along with the time taken for the section. | def s_k(X, Y, slope1, destX, destY, slope2):
int1,int2 = get_Intermediate_Points( slope1, slope2, X, destX, Y, destY)
t = get_T(X, Y, int1[0], int1[1], int2[0], int2[1], destX, destY)
Curvature,dk,d2K,section_time = get_Curvature(X, Y, int1[0], int1[1], int2[0], int2[1], destX, destY, t)
k_st = Curvature[2]
k_en =... |
def findFiles(self):
with open("filelist.txt", 'w') as f:
for current_path, directories, files in os.walk(self.rootDir):
if "node_modules" in current_path:
continue
for file in files:
if os.path.splitext(file)[1] == ".js" or os.... | The main task of the code is to find and process environment files by searching for files, reading their contents, generating an environment file, and then deleting a temporary filelist.txt. It prints the count of found ENV files and cleans up the filelist after processing. | def generateEnvSnippet(self):
self.findFiles()
self.readFiles()
print("ENV Found : " + str(self.envFound))
self.generateEnvFile()
os.remove("filelist.txt") |
def setProjectName(self):
pn = self.rootDir.split('\\')
if pn[-1] == '':
self.projectName = pn[-2]
else:
self.projectName = pn[-1]
def generateEnvSnippet(self):
self.findFiles()
self.readFiles()
print("ENV Found : " + str(self.envFound))
se... | The main task of the code is to generate deployment configuration snippets for environment variables and optionally Azure Key Vault (AKV) objects. It initializes with a root directory, sets a project name, creates an environment variables YAML file, and prompts the user to generate AKV configuration files if requested.... | def __init__(self, rootDir):
self.rootDir = rootDir
self.setProjectName()
print("Generating deployment snippet for env variables.")
self.generateEnvSnippet()
print("Generated Snippets, Saved in file: " + self.projectName + ".yml")
print("Do you want to generate akvs objec... |
def _parse_list(self, varname: str, varvalue: str, vartype: VarType) -> VarType:
if not varvalue:
return tuple()
if hasattr(vartype, "__args__") and vartype.__args__:
return tuple(
self._parse_item(varname, item, vartype.__args__[0])
for item in va... | This function determines the type of a collection (list, tuple, set, frozenset, or dict) from the given variable type and delegates parsing of the variable value to the corresponding helper method, returning the parsed result. | def _parse_collection(
self, varname: str, varvalue: str, vartype: VarType
) -> VarType:
origin = getattr(vartype, "__origin__", vartype)
if origin in (list, tuple):
return self._parse_list(varname, varvalue, vartype)
if origin in (set, frozenset):
return self... |
def get_closest_waypoint(self, position_x, position_y):
"""Identifies the closest path waypoint to the given position
https://en.wikipedia.org/wiki/Closest_pair_of_points_problem
Args:
pose (Pose): position to match a waypoint to
Returns:
int: index of the cl... | The main task of the code is to identify the closest visible traffic light to the vehicle, determine its color/state, and return the index of the nearest waypoint and the traffic light's state (or -1 and UNKNOWN if none exists). It uses position comparisons and optionally a classifier to assess the light's state, ensur... | def process_traffic_lights(self):
"""Finds closest visible traffic light, if one exists, and determines its
location and color
Returns:
int: index of waypoint closes to the upcoming traffic light (-1 if none exists)
int: ID of traffic light color (specified in styx_m... |
def _request(self, url_key, data, headers, queryParam=False):
url = self._generate_url(url_key, queryParam)
print("### ", url, data, headers, queryParam)
try:
r = requests.post(url, data, headers)
except Exception as e:
raise e
return r
def getCommo... | The code authenticates a user by sending login credentials (client_id and password) to the "auth.login" endpoint, retrieves a request token from the response, and prompts the user to input a TOTP (Time-based One-Time Password) for 2FA validation. The token is stored in `self.requestToken` for subsequent API requests. | def _getRequestToken(self):
params = {
"platform": "api",
"data": {
"client_id": self.userId,
"password": self.password
}
}
resp = self._request("auth.login", json.dumps(params), self.getCommonHeader(), True)
da... |
def remove_piece(self, row, col):
self.board.remove(row, col)
def king_in_check(self, king):
king_position = (king.row, king.col)
king_moves = self.get_valid_moves(king)
for row in range(ROWS):
for col in range(COLS):
piece = self.board.get_piece(row, col)
... | This function handles moving a selected chess piece to a specified position if valid. It removes captured pieces, updates the board, checks for king safety, switches turns, and plays a sound effect. | def move_piece(self, row, col):
if self.selected is not None:
piece = self.board.get_piece(row, col)
position = (row, col)
if self.valid_moves is not None and position in self.valid_moves:
if piece != 0 and piece.color != self.turn:
self.r... |
def parse_vertex(s):
x, y = s.split(',')
return (int(x), int(y))
def pairwise(iterable):
# pairwise('ABCDEFG') --> AB BC CD DE EF FG
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def draw_line(grid, start, end):
direction = signvec(subvec(end, start))
curr = start
while curr !=... | The code simulates particle movement on a grid generated from path data in a file. It initializes a grid, draws lines based on input coordinates, tracks an active particle's motion, and stops when the particle exceeds the grid's maximum y-coordinate. Finally, it counts the number of 'o' markers (particles) remaining in... | def main(path):
global grid, active_particle
grid = {}
active_particle = SOURCE
grid[active_particle] = 'o'
for line in open(path).read().splitlines():
vertices = [parse_vertex(each) for each in line.split(' -> ')]
for v, w in pairwise(vertices):
draw_line(grid, v, w)
... |
def parse(text):
room_grid_2d = [list(line) for line in text.splitlines()]
exit_pos = (-1, -2)
assert getindex(room_grid_2d, exit_pos) == '.'
setindex(room_grid_2d, exit_pos, 'X')
blizzards = collections.defaultdict(list)
for r, row in enumerate(room_grid_2d):
for c, ch in enumerate(r... | The code solves a maze with moving blizzards by simulating their repeating patterns over time, creating a 3D grid (time as the third dimension), and using BFS to find the shortest path from a start point to the exit. It calculates the loop duration of blizzard movements, constructs a 3D maze, and applies BFS on this st... | def main(path):
# Parse
text = open(path).read()
room_grid_2d, blizzards = parse(text)
# Find the "loop duration" (After enough steps, the blizzard pattern repeats)
inner_height = len(room_grid_2d) - 2
inner_width = len(room_grid_2d[0]) - 2
loop_duration = math.lcm(inner_height, inner_width... |
def display_menu(self):
Utils.clear_screen()
print(f"\n=== Weed Growing Simulator ===\nLevel: {self.level['player']} | Cash: ${self.cash} | Items: {self.inventory}")
print("1. Buy items\n2. Buy seeds\n3. Plant seeds\n4. Harvest plants\n5. Sell plants\n6. Display Plants\n7. Upgrades\n8. Save game... | The main task of the code is to run a game loop that displays a menu, processes user choices for actions like buying items, growing plants, harvesting, and selling, and exits when the user selects option 10. It uses milestone thresholds to trigger skill upgrades at specific levels and handles invalid inputs with error ... | def main_loop(self):
milestones = {
5: "You've reached level 5! Your negotiation skill has increased.",
10: "You've reached level 10! Your charisma skill has increased.",
20: "You've reached level 20! Your trimming skill has increased."
}
while True:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.