dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def cmd_guard():
pwd = get_pwd()
state = read_state(pwd)
# if it's after 22:00 block yt and kill all minecraft processes
now = datetime.datetime.now()
if now.hour >= 21:
print("after 21:00 blocking....")
block_yt()
kill_mc()
return
# if date is not today, set t... | The main task of the code is to execute different functions based on the first command-line argument. If the argument is "g" or "guard", it runs `cmd_guard()`. If "r" or "request", it runs `cmd_request()`. If "i" or "info", it runs `cmd_info()`. If "s" or "starter", it runs `cmd_starter()`. If none match, it prints "un... | def main():
if sys.argv[1] == "g" or sys.argv[1] == "guard":
cmd_guard()
return
if sys.argv[1] == "r" or sys.argv[1] == "request":
cmd_request()
return
if sys.argv[1] == "i" or sys.argv[1] == "info":
cmd_info()
return
if sys.argv[1] == "s" or sys.argv[1... |
def renpy_log_and_print(msg: str):
renpy_log(msg)
print(msg)
return
def log_filename_line(filename_line=None):
if filename_line:
renpy_log_and_print("filename_line: " + str(filename_line))
return
def renpy_log(msg: str):
renpy.log(msg)
return | The function logs an error message using Ren'Py's logging system, prepends "Error: " to the input message, records the provided filename/line context, and adds a blank line separator. It handles error reporting in Ren'Py games by combining immediate console output with persistent log entries. | def log_error(msg: str, filename_line=None):
renpy_log_and_print("Error: " + msg)
log_filename_line(filename_line)
renpy_log("")
return |
def renpy_log_and_print(msg: str):
renpy_log(msg)
print(msg)
return
def log_filename_line(filename_line=None):
if filename_line:
renpy_log_and_print("filename_line: " + str(filename_line))
return
def renpy_log(msg: str):
renpy.log(msg)
return | The function `log_warn` logs a warning message by printing it with "Warn: " prefix, records the provided filename and line number (if any), and adds an empty line for separation in logs. | def log_warn(msg: str, filename_line=None):
renpy_log_and_print("Warn: " + msg)
log_filename_line(filename_line)
renpy_log("")
return |
def renpy_log_and_print(msg: str):
renpy_log(msg)
print(msg)
return
def log_filename_line(filename_line=None):
if filename_line:
renpy_log_and_print("filename_line: " + str(filename_line))
return
def renpy_log(msg: str):
renpy.log(msg)
return | The function logs an info message using Ren'Py's logging system, prepending "Info: " to the input message. It optionally logs a filename/line number via `log_filename_line` and adds a blank log entry with `renpy_log("")`, likely for formatting or separation in logs. | def log_info(msg: str, filename_line=None):
renpy_log_and_print("Info: " + msg)
log_filename_line(filename_line)
renpy_log("")
return |
def fit(x,y):
matrix_a = []
for i in range(len(x.columns)+1):
line = []
if i == 0:
for j in range(len(x.columns)+1):
if j == 0:
line.append(len(x))
else:
line.append(sum(x.iloc[:,j-1]))
else:
... | The code's main task is to print regression statistics for given variables x and y, including the constant term, individual coefficients, Multiple R (correlation coefficient), and R Squared (coefficient of determination) by calling fit(), r(), and rsquare() functions. It iterates through coefficients to display each wi... | def info(x,y):
print('Constant : ',fit(x,y)[0])
for i in range(len(fit(x,y)[1])):
print(f'Coefficient_{i+1} : {fit(x,y)[1][i]}')
print('Multiple R : ',r(x,y))
print('R Squared : ',rsquare(x,y)) |
def makePath(im):
npimg = np.array(im)
h = im.shape[0]
w = im.shape[1]
path = a_star(npimg, (0, int(w/2)), (h-1, int(w/2)))
return path
def makeCut(orig, path):
w = orig.shape[1]
im1 = orig.copy()
im2 = orig.copy()
## Fill remaining pixels with WHITE for both segments based on path coordinates
for... | The code refines image segments by splitting wide segments (width > 60) using either a detected path or a bigram method if no path is found. It ensures splits produce segments larger than 25% of the original width, appending valid splits to a new list. If splitting fails or segments are narrow, they are retained. The f... | def refineSegm(segm, h):
new = []
## Keep track of newly added segments to re-address these later on
newSegm = 0
for s in segm:
width = s.shape[1]
if width > 60:
path = makePath(s)
## path returns 0 when no path has been found
if(path != 0):
im1, im2 = makeCut(s,path)
... |
def pers(im, width):
profile = np.zeros((width))
for w in range(width):
profile[w] = (im[:,w] == 0).sum()
removed_zeros = profile[~np.all(profile == 0)]
THRESHOLD = abs(np.mean(removed_zeros))
extrema_persistence = RunPersistence(profile)
extrema_persistence = [t[0] for t in extrema_persistence if t... | This function segments characters from a line image by binarizing it, performing initial segmentation, refining segments iteratively, and cleaning up whitespace and borders to isolate individual characters for OCR processing. | def segmChars(line):
h = line.shape[0]
w = line.shape[1]
## Binarize image
(thresh, line) = cv2.threshold(line, 127, 255, cv2.THRESH_BINARY)
ext_pers = pers(line,w)
## Initial rough cut
segm = cutSegments(line,ext_pers,h)
segm = cleanSegm(segm)
newSegm = -1
maxSegmenting = 0
## Refining
wh... |
def avgSpeed(tup1, tup2):
return round( (speed(tup1) + speed(tup2))/2, 2)
def distance(*points):
dist = 0
p1 = points[0]
for point in points:
p2 = point
dist = dist + geopy.distance.distance(p1, p2).miles
p1 = p2
return dist
def timeBetween(p1, p2, speed):
distance = geop... | The code calculates the maximum distance saved by merging two trips (`t1` and `t2`) into optimized sequences, considering time constraints and passenger limits. It checks four possible merged sequences, computes merged distances, and compares them to individual trip distances. If a merged sequence reduces total distanc... | def distanceSaved(t1, t2):
#check passengers here
(id1,_,_,t1_passengers,*theRest) = t1
(id2,_,_,t2_passengers,*theRest) = t2
if((t1_passengers + t2_passengers) > 3):
return ("0","0","0","0",0)
(_,startTime1,endTime1,*therest1,startLong1,startLat1,endLong1,endLat1) = t1
startPoint1... |
def macos_dump():
logging.debug(MACOS_DETECTED)
files = []
try:
for drive in listdir('/Volumes/'):
logging.debug("Beginning File Dumping of: %s" % drive)
files.extend(get_files('/Volumes/' + drive))
return files
except Exception as e:
logging.critical("... | The function `dump_files` identifies the operating system and executes the corresponding OS-specific dumping function (macos_dump, linux_dump, or windows_dump). If the OS is unrecognized, it logs a critical error and returns None. | def dump_files():
if MAC_OS in system:
return macos_dump()
elif LINUX in system:
return linux_dump()
elif WINDOWS in system:
return windows_dump()
else:
logging.critical(INDIE_CRITICAL)
return None |
def macos_dump(type=ALL):
logging.debug(MACOS_DETECTED)
file_types = []
try:
for drive in listdir('/Volumes/'):
logging.debug("Beginning File Type Dumping of: %s" % drive)
file_types.append(get_file_types_and_size(('/Volumes/' + drive), type))
return file_types
e... | The main task of the code is to determine the operating system and execute the corresponding file-dumping function (macos_dump, linux_dump, or windows_dump) based on the detected OS. If the OS is unrecognized, it logs an error and returns None. | def dump_file_types(type=ALL):
if MAC_OS in system:
return macos_dump(type)
elif LINUX in system:
return linux_dump(type)
elif WINDOWS in system:
return windows_dump(type)
else:
logging.critical(INDIE_CRITICAL)
return None |
def macos_dump():
logging.debug(MACOS_DETECTED)
drive_info = []
try:
for drive in listdir('/Volumes'):
logging.debug("Beginning Info Dumping of: %s" % drive)
drive_info.append((drive, get_folder_and_files_total('/Volumes/' + drive), get_disk_info('/Volumes/' + drive)))
... | The main task of the code is to determine the operating system and execute the corresponding disk dump function (macos_dump, linux_dump, or windows_dump). If the system is unsupported, it logs a critical error and returns None. The function acts as a dispatcher for OS-specific data extraction routines. | def dump_drives():
if MAC_OS in system:
return macos_dump()
elif LINUX in system:
return linux_dump()
elif WINDOWS in system:
return windows_dump()
else:
logging.critical(INDIE_CRITICAL)
return None |
def dictionary_to_vector(parameters):
"""
Roll all our parameters dictionary into a single vector satisfying our specific required shape.
"""
keys = []
count = 0
for key in ["W1", "b1", "W2", "b2", "W3", "b3"]:
# flatten parameter
new_vector = np.reshape(parameters[key], (-1, 1)... | The function `gradient_check_n` verifies the correctness of backward propagation in a neural network by comparing analytical gradients (from backprop) with numerical gradients (via finite differences). It perturbs each parameter slightly, computes the cost for each perturbation, and approximates gradients. It then calc... | def gradient_check_n(parameters, gradients, X, Y, epsilon=1e-7):
# Set-up variables
parameters_values, _ = dictionary_to_vector(parameters)
grad = gradients_to_vector(gradients)
num_parameters = parameters_values.shape[0]
J_plus = np.zeros((num_parameters, 1))
J_minus = np.zeros((num_parameters,... |
def initialize_with_zeros(dim):
# initialize weights and bias to be zero
w = np.zeros(shape=(dim, 1))
b = 0.0
return w, b
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost=False):
costs = []
for i in range(num_iterations):
grads, cost = propagate(w, b, X, Y)
dw ... | The code trains a logistic regression model using gradient descent by initializing parameters, optimizing them with given iterations and learning rate, predicting on training/test data, calculating accuracy, and returning results including costs, parameters, and predictions. | def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=True):
w, b = initialize_with_zeros(X_train.shape[0])
params, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)
w = params["w"]
b = params["b"]
Y_prediction_trai... |
def L_model_forward_with_dropout(X, parameters, keep_prob=1):
# number of layers in the network
L = len(parameters) // 2
caches = []
A = X
# L-1 times RELU
for l in range(1, L):
A_prev = A
A, cache = linear_activation_forward_with_dropout(A_prev, parameters["W" + str(l)], parame... | The code implements a three-layer neural network (LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID) with dropout and L2 regularization. It trains the model using gradient descent over specified iterations, updating parameters to minimize a cost function that combines cross-entropy loss with regularization terms. The model l... | def model(X, Y, learning_rate=0.3, num_iterations=30000, print_cost=True, lambd=0.0, keep_prob=1):
'''
Implements a three layer NN: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID
:param keep_prob: the probability of keeping neurons in a drop out regularization scheme.
:param lambd: the hyperparameter for L... |
def regularize_ld(LD):
LD = (LD + LD.T)/2
s, w = np.linalg.eig(cpu(LD).data.numpy())
s = np.real(s)
s_new = torch.zeros(len(s))
if min(s)<10**-3:
s_new = torch.ones(len(s))*(min(s)-10**-3)
print("\n Adding a constant {} to regularize LD".format(-min(s)+10**-3))
LD = LD - gpu(t... | The main task of the code is to identify credible sets of causal variants using Bayesian inference on genetic data. It processes input matrices (Z, LD), computes posterior inclusion probabilities (PIP), applies thresholding, and iteratively refines credible sets via conditional sampling. Results are saved as text files... | def main(options):
########################################################################################################################################################
Z = gpu_t(pd.read_table(options['z'], sep=' ', header=None).to_numpy()[:,1].astype(float))
LD = gpu_t(pd.read_table(options['LD']... |
def getLocations(fil, start):
locations = []
with open(fil, "r") as f:
lines = f.readlines()
for i, line in enumerate(lines):
if start in line:
locations.append(i)
string = copy_lines(fil, locations[0], locations[1])
return string
def sessionReplace(string, re... | The code generates a LaTeX table of contents by replacing placeholders in a `.tex` file with session and talk entries from provided links. It processes each link to determine if it represents a session header or a talk entry, constructs the appropriate TeX strings, and updates the document structure by inserting these ... | def createContentTable(true_links, sessions):
# open and find line to replace
toc_name = "../t-general_conference--notepad.tex"
session_lines = getLocations(toc_name, "PART HEADER START>")
session_end_lines = getLocations(toc_name, "PART HEADER END>")
talk_lines = getLocations(toc_name, "CHAPTER ENT... |
def _get_icons_to_transform(self, source_directory):
"""
Returns the paths for the icons to generate sprites from
"""
all_paths = list_files_with_extensions(source_directory,
SpriteGenerator.SUPPORTED_ICON_FORMATS)
return [p for p in al... | The code processes icons from a source directory by generating transformed sprite icons (with and without colorblind adjustments), saving individual icon outputs and sprite sheets to an artifacts directory, and storing sprite coordinate mappings in a JSON file for reference. | def generate_from_directory(self, source_directory, artifacts_dir):
"""
Apply the transformation on all icons
"""
source_icon_paths = self._get_icons_to_transform(source_directory)
all_sprites_directory = path_join(artifacts_dir, "sprites")
sprite_coordinate_index = None
... |
def garbage_collect(self, df: pd.DataFrame):
del df
gc.collect()
self.import_data()
def deweese_schema(self, df: pd.DataFrame) -> pd.DataFrame:
try:
df = df.rename(columns=lambda x: x - 1)
first_row_ix = df.index[0]
ix_label = first_row_ix.rsplit('/', ... | The code checks if a checkbox is selected. If checked, it performs garbage collection on the DataFrame if modified, applies a schema transformation, and updates the UI with the processed data. If unchecked, it only garbage collects the DataFrame. The main task is conditionally processing and updating data based on chec... | def if_button_checked(self):
if self.checkBox.isChecked():
if self.is_modified:
self.garbage_collect(self.df)
self.df = self.deweese_schema(self.df)
self.insert_to_window(self.df)
if not self.checkBox.isChecked():
self.garbage_collect(self.... |
def conv_relu3x3(x, scope, num_filters, padding='VALID', train=True):
with tf.variable_scope(scope):
h1 = tf.layers.conv2d(x, filters=num_filters, kernel_size=(3, 3), strides=(1, 1), padding=padding, name='conv',
kernel_initializer=tf.contrib.layers.xavier_initializer())
... | This code defines a basic Convolutional Neural Network (CNN) for classification tasks. It processes input data through multiple convolutional layers with ReLU activation, max-pooling, batch normalization, and dense layers, ultimately outputting logits for 4-class classification. The network progressively reduces spatia... | def basic_CNN(x, training):
l0 = tf.layers.batch_normalization(x, scale=True, center=True, name='bn', training=training, momentum=0.9)
l1 = conv_relu3x3(l0, 'conv1', 16, train=training)
l2 = max_pool3x3(l1)
l3 = conv_relu3x3(l2, 'conv2', 32, train=training)
l4 = max_pool2x2(l3)
l5 = conv_relu3x3... |
def program_counter(self):
return self.internal_memory[0]
def load_word(self):
self.increment()
register_index = self.current_value()
self.increment()
self.internal_memory[register_index] = self.current_value()
def store_word(self):
self.increment()
register_value... | This code executes instructions from memory by fetching the current instruction at the program counter, then branching to handle specific operations like loading, storing, adding, or subtracting based on the instruction's value. It acts as a simple CPU instruction decoder, routing each opcode to the corresponding metho... | def run_instruction(self):
instruction = self.memory[self.program_counter()]
if instruction == 0x01:
self.load_word()
elif instruction == 0x02:
self.store_word()
elif instruction == 0x03:
self.add()
elif instruction == 0x04:
self.s... |
def program_counter(self):
return self.internal_memory[0]
def instructions(self):
return self.memory[:12]
def run_instruction(self):
instruction = self.memory[self.program_counter()]
if instruction == 0x01:
self.load_word()
elif instruction == 0x02:
self.... | The code executes instructions sequentially by looping through each instruction, running it, and incrementing the program counter until all instructions are processed. | def run(self):
while self.program_counter() < len(self.instructions()):
self.run_instruction()
self.increment() |
def identify_robust_merge(self, model, X, n_average = 10, score_threshold = 0.5):
"""Starting from the root, goes down the tree and evaluates which clustering node are robust
It returns a list of the nodes for which their corresponding clusters are well defined according to
a logistic regressio... | The main task of the code is to relabel data points based on statistically significant merges identified through cross-validation, using a score threshold. It updates the tree object with new cluster labels, centers, and mappings, ensuring robust terminal nodes are assigned labels based on classification scores. The fu... | def find_robust_labelling(self, model, X, n_average = 10, score_threshold = 0.5):
""" Finds the merges that are statistically significant (i.e. greater than the score_threshold)
and relabels the data accordingly
Trick here: first use a low threshold (will compute the tree down to it's l... |
def prediction_model_3D(self):
model3D= get_3DAda(h=self.patch_size[0], w=self.patch_size[1] , p=self.gene3D[0],k1=self.gene3D[1],
k2=self.gene3D[2], k3=self.gene3D[3], nfilter=self.gene3D[4],actvfc=self.gene3D[5],
blocks=self.gene3D[7], slices=self.patch_size[2],... | The code evaluates 2D and 3D prediction models by calculating metrics (Dice, recall, surface distance) on test data, compares results, and saves them in CSV files. It also combines predictions, applies connected components, and stores final performance metrics for analysis. | def evaluate(self):
# Training logs
location="EvalLogs"
if not os.path.exists(location):
os.makedirs(location)
_, self.height, self.width, _, self.channels=self.X_test3D.shape
print(np.max(self.X_test3D),np.min(self.X_test3D))
print(np.u... |
def search_artist(artist_name):
# actual GET request with proper header
search_result = requests.get(BASE_URL + 'search?' + f'q=%20artist:{artist_name}&type=artist&limit=5', headers=authorization.get_headers())
search_result = search_result.json()
data_searched = {'id_artist':[],'Name_artist':[],'genre... | This function retrieves and compiles artist, album, and track data based on an input artist name. It first searches for the artist, filters their data, then fetches and aggregates their albums and tracks. The output includes three dataframes: filtered artist info, their albums, and associated tracks. | def get_tracks_artist_by_albums(search_artist_name):
df_artists = search_artist(artist_name=search_artist_name)
df_artists = choose_kept_data(df_artists)
print_data_frame(df_artists)
list_df_albums = []
for id_art in df_artists['id_artist']:
df_albums = get_all_albums(artist_id=id_art)
... |
def logtext(level, text, colorf=None):
obj = {
'time' : datetime.now(),
'symbol' : SYMBOL,
'level' : level,
'text' : text,
}
if VERBOSE:
text = colorf(str(obj)) if colorf is not None else str(obj)
print(text)
DB.logging.insert_one(obj)
def get_bid_ask... | The main task of the code is to configure and log trading parameters for a strategy involving bid/ask price retrieval and database updates. It initializes dictionaries (`dipseeker`, `buyer`, `seller`) with hardcoded values for trading settings like intervals, budgets, order quantities, and timeouts, then logs the resul... | def maestro(s):
log = lambda text: logtext('info', text, cyan)
bid_price, ask_price = get_bid_ask_price(s)
## hardcoded values for testing on BTCUSDT
dipseeker = {
'symbol' : SYMBOL,
'name' : DIPSEEKER,
'INTERVAL' : '1m',
'LIMIT' : 5,
... |
def logtext(level, text, colorf=None):
obj = {
'time' : datetime.now(),
'symbol' : SYMBOL,
'level' : level,
'text' : text,
}
if VERBOSE:
text = colorf(str(obj)) if colorf is not None else str(obj)
print(text)
DB.logging.insert_one(obj)
def get_order(s... | The main task of the code is to manage open buy orders by checking their status, handling timeouts, and creating sell orders when filled or timed out. It retrieves buy orders, verifies their execution status, updates records, and triggers sell orders with calculated prices while logging actions and handling exceptions ... | def buyer(s):
log = lambda text: logtext('info', text, magenta)
M = DB.meta.find_one({'symbol': SYMBOL, 'name': BUYER})
if M is None: raise MetaNotFound
for buy in DB.buy.find({'symbol': SYMBOL, 'status':'OPENED'}):
buy_id = buy['buy_id']
## TODO create new status so that I don't have to... |
def logtext(level, text, colorf=None):
obj = {
'time' : datetime.now(),
'symbol' : SYMBOL,
'level' : level,
'text' : text,
}
if VERBOSE:
text = colorf(str(obj)) if colorf is not None else str(obj)
print(text)
DB.logging.insert_one(obj)
def get_order(s... | This function manages sell orders by checking their status, updating prices if the bid price increases, closing filled orders, and handling timeouts. It queries open sell orders, adjusts or cancels orders based on execution status, logs actions, and updates the database with new prices, quantities, or closure details. | def seller(s):
log = lambda text: logtext('info', text, green)
M = DB.meta.find_one({'symbol': SYMBOL, 'name': SELLER})
if M is None: raise MetaNotFound
for sell in DB.sell.find({'symbol': SYMBOL, 'status':'OPENED'}):
sell_id, buy_id = sell['sell_id'], sell['buy_id']
r = get_order(s, sel... |
def logtext(level, text, colorf=None):
obj = {
'time' : datetime.now(),
'symbol' : SYMBOL,
'level' : level,
'text' : text,
}
if VERBOSE:
text = colorf(str(obj)) if colorf is not None else str(obj)
print(text)
DB.logging.insert_one(obj)
def get_mrkt_di... | The main task of the code is to monitor market price dips relative to a predefined threshold (DTHR) and execute conditional buy orders. It queries market data, checks balance sufficiency, and logs actions. If the dip exceeds DTHR and sufficient funds exist, it generates a buy order with a unique ID, using the ask price... | def dipseeker(s):
log = lambda text: logtext('info', text, blue)
M = DB.meta.find_one({'symbol': SYMBOL, 'name': DIPSEEKER})
if M is None: raise MetaNotFound
dip = get_mrkt_dip(s, M['INTERVAL'], M['LIMIT'])
exps, blnc = get_mrkt_info(s)
bid_price, ask_price = get_bid_ask_price(s)
log(db_inse... |
def loginfo(text):
logtext('info', text)
def maestro(s):
log = lambda text: logtext('info', text, cyan)
bid_price, ask_price = get_bid_ask_price(s)
## hardcoded values for testing on BTCUSDT
dipseeker = {
'symbol' : SYMBOL,
'name' : DIPSEEKER,
'INTERVAL' ... | This code defines a multithreaded worker function that periodically executes task-specific functions (e.g., maestro, buyer) at intervals defined by 'period'. It maintains a request session, handles connection errors by restarting the session, and respects a stop_event to terminate gracefully. The thread logs its start/... | def thread_entry(stop_event, name, period):
try:
cnter = -1
s = None
loginfo(f'thread {name} started')
while not stop_event.is_set():
try:
if s is None:
s = requests.Session()
s.headers.update(DFT_API_HDRS)
... |
def read(fname, labeled):
dtype = {
"id": str,
"text": str,
#"keyword": str,
#"location": str,
}
if labeled:
dtype["target"] = np.int32
p = os.path.join(os.pardir, "input", fname)
return pd.read_csv(p, dtype=dtype)
def bert_encode_text(df, tokenizer):
rows... | The code performs text classification using BERT, splitting labeled data into train/val sets, tokenizing text, pretraining a model, fine-tuning it, and generating predictions for submission. It handles data preparation, model building, training, and outputting results in CSV format for a competition. | def main():
timestamp = time.strftime("%Y%m%d-%H%M")
shutil.copyfile(sys.argv[0], timestamp + ".py")
log_dir = os.path.join(os.pardir, "logs", timestamp)
labeled_df = read("train.csv", labeled=True)
test_df = read("test.csv", labeled=False) if submit else None
train_size = int(len(labeled_df) *... |
def gradient_pi(phi_s,theta,a):
return pi(phi_s,theta,a)*gradient_log_pi(phi_s,theta,a)
def gradient_log_pi(phi_s,theta,a):
result=phi_s[a].reshape(-1,1)
temp=np.zeros((4,1))
for i in [0,1,2]:
temp+=pi(phi_s,theta,i)*phi_s[i].reshape(-1,1)
return result-temp
def pi(phi_s,theta,a):
num=ma... | This code computes the Hessian matrix of a policy function in reinforcement learning. It calculates second-order derivatives by combining gradients of the policy and log-policy, subtracting a term involving the policy's gradient and state features. The result is a matrix representing curvature information for optimizat... | def hessian(phi_s,theta,a):
hess=np.zeros((len(theta),len(theta)))
for i in range(len(theta)):
for j in range(len(theta)):
temp=gradient_pi(phi_s,theta,a)[i]*(gradient_log_pi(phi_s,theta,a)[j][0])
temp2=0
for k in [0,1,2]:
temp2+=gradient_pi(phi_s,thet... |
def get_path_length(self, graph, solution):
"""
Calculates the length of the path based on each node's position. Returns length.
:param graph: NetworkX Graph object containing each node's position
:param solution: the solution path to be checked
:return: length -- the length of ... | The function smooths a path by iteratively connecting non-colliding points k_max steps apart, removing intermediate nodes, and halting when variance falls below a threshold or iterations exceed a limit, returning the optimized path as a NetworkX Graph. | def smooth_solution(self, k_max, eps, variance_steps, min_variance, debug=False):
"""
Smooths the path solution over a range of iterations, breaking if the range count is exceeded, or if the path
variance is smaller than a minimum value.
Selects a random point (P) on the path, then atte... |
def laptop_map_to_output():
# see touchscreen.sh
run('bash /home/poleguy/flippy-data/bin/yoga/touchscreen.sh')
def all_ids():
# get all laptop control devices
device_ids = [get_keyboard(), get_touchpad(), get_trackpoint()]
return device_ids
def enable(device: str):
new_state = 1
set_state(de... | The code configures devices into laptop mode by iterating through all device IDs, printing each with "laptop" prefix, and enabling them. It initially maps output settings and may log actions to a file, though logging is currently disabled. | def laptop() -> None:
# sets yoga to laptop mode
laptop_map_to_output()
for id in all_ids():
print(f"laptop {id}")
# with open('/tmp/log.txt','a') as f:
# print(f"laptop {id}", file=f)
enable(id) |
def tablet_map_to_output():
# see touchscreen.sh
run('bash /home/poleguy/flippy-data/bin/yoga/touchscreen-no-fingers.sh')
def all_ids():
# get all laptop control devices
device_ids = [get_keyboard(), get_touchpad(), get_trackpoint()]
return device_ids
def disable(device: str):
new_state = 0
... | The main task of the code is to switch a device into tablet mode by mapping outputs and disabling specific functions for each device ID. It iterates through all device IDs, logs tablet mode activation, and applies disable settings to transition the device into tablet mode. | def tablet() -> None:
# sets yoga to laptop mode
tablet_map_to_output()
for id in all_ids():
print(f"tablet {id}")
# with open('/tmp/log.txt','a') as f:
# print(f"tablet {id}", file=f)
disable(id) |
def _parse_types(self) -> dict[str, str]:
types = set()
# prefabs does not contain all types so iterate over items
for item_data in self.items_game["items"].values():
try:
top_prefab = self._find_top_level_prefab(item_data, "item_type_name")
types.add(... | The main task of the code is to parse multiple data components into indexed formats. It separates fields like types, qualities, rarities, definitions, paints, musics, and tints using private methods, creates a reverse mapping for types, and aggregates all parsed data into a tuple for return. This structured output orga... | def __call__(self) -> tuple[dict, ...]:
"""Parse all data to indexed format"""
# separate fields
types = self._parse_types()
self._types_mapping = invert_dict(types)
qualities = self._parse_qualities()
rarities = self._parse_rarities()
definitions = self._parse... |
def create_table(df):
df = df[df["comparison"] == "ground truth"]
dataset_groups = df.groupby("dataset")
methods = ["Vamana", "fastdp", "BruteForce", "kmeans", "DBSCAN"]
for dataset_name, dataset_group in dataset_groups:
dataset_name = dataset_name_map[dataset_name]
print("\midrule")
... | The main task of the code is to generate a Pareto frontier comparing total time vs. ARI by aggregating data from multiple CSV files in a specified folder. It processes "pareto" and "brute" method files, merges them with DBSCAN results (renamed and annotated), and creates visualizations (plots, tables) to analyze trade-... | def main():
parser = argparse.ArgumentParser(
description="Plot a pareto frontier of total time vs. ARI"
)
parser.add_argument("folder", type=str, help="Folder to read csv files from.")
args = parser.parse_args()
# Use glob to find files matching the pattern
csv_files = glob.glob(args.f... |
def getWH(self):
'''get width and height'''
if self.w is None or self.h is None:
res, image = self.vc.read()
self.w = image.shape[1]
self.h = image.shape[0]
return (self.w, self.h)
def calcFPS(self):
self.fps = self.vc.get(cv2.CAP_PROP_FPS)
def calcLen... | This code initializes a video reader by validating the input video path, setting up a frame buffer, and configuring video properties like resolution, FPS, and duration. It also prepares a list of specific frames if provided, enabling selective frame processing. | def __init__(self, config, setOfFrames=None):
videoPath = config["inputPath"]
self.videoPath = videoPath
if videoPath is None:
raise Exception("VideoReader:: Video reader needs a videoPath!")
if not os.path.exists(videoPath):
raise Exception("VideoReader:... |
def print_initial(options, message="\nSelect option to continue:"):
print_message(message)
for item in options:
print(f"{Colors.WHITE}%s" % item)
def get_category_ranking(self):
self.controller.get_category_ranking()
def get_categories_menu(self, callback):
categories = self.controller.g... | The main task of the code is to provide a menu-driven interface for analyzing sales data. It allows users to select options for retrieving category rankings by sales, average prices per category, or price predictions, with a "back" option to exit. The loop continuously displays the menu, processes user input, and invok... | def start_analysis(self):
menu = [
'1. get category ranking by sales',
'2. get average prices for category',
'3. get price prediction',
'0. back'
]
while True:
print_initial(menu, 'Select analysis option')
option = int(inpu... |
def print_initial(options, message="\nSelect option to continue:"):
print_message(message)
for item in options:
print(f"{Colors.WHITE}%s" % item)
def get_categories_menu(self, callback):
categories = self.controller.get_parent_categories()
while True:
print_message('Select ca... | The code displays a menu, processes user input, and executes corresponding actions: generating data, retrieving products, starting analysis, or exiting. It runs in a loop until the user selects the 'BACK' option, which breaks the loop and exits the menu. | def show(self):
while True:
print_initial(menu_option)
option = int(input("----> "))
if option == GENERATE_DATA:
run()
if option == GET_PRODUCTS:
self.get_categories_menu(self.get_products)
if option == START_ANALYSIS... |
def format_lines(color_only=False, include_done=False):
"""Take in a list of lines to do, return them formatted with the
TERM_COLORS and organized based upon priority."""
plain = CONFIG["PLAIN"]
no_priority = CONFIG["NO_PRI"]
default = CONFIG.get("DEFAULT", "default")
default = TERM_COLORS[defau... | The main task of the code is to print a prioritized list of todo items (ordered by priority levels) and subsequently display the contents of the 'done.txt' file. The function formats todo items, groups them by priority, concatenates them for output, and prints them. It then calls a helper function to print the 'x of y'... | def list_all():
"""Print the list of todo items in order of priority and then print the
done.txt file."""
formatted = format_lines(include_done=True)
lines = []
for p in PRIORITIES:
lines.extend(formatted[p])
if lines:
print(concat(lines)[:-1])
print_x_of_y(lines, lines) |
def _list_(by, regexp):
"""Master list_*() function."""
nonetype = concat(["no", by])
todo = {nonetype: []}
by_list = []
sorted = []
if by in ["date", "project", "context"]:
lines = format_lines(color_only=True)
regexp = re.compile(regexp)
for line in lines:
... | The main task of the code is to list and display todo items sorted by date (yyyy-mm-dd) using a regex pattern to filter and process date-formatted entries, then print the sorted results with pagination or subset handling via the print_x_of_y function. | def list_date():
"""List todo items by date #{yyyy-mm-dd}."""
lines, sorted = _list_("date", "#\{(\d{4})-(\d{1,2})-(\d{1,2})\}")
print(concat(sorted)[:-1])
print_x_of_y(sorted, lines) |
def _list_(by, regexp):
"""Master list_*() function."""
nonetype = concat(["no", by])
todo = {nonetype: []}
by_list = []
sorted = []
if by in ["date", "project", "context"]:
lines = format_lines(color_only=True)
regexp = re.compile(regexp)
for line in lines:
... | The main task of the code is to organize items by their associated project tags (e.g., +prj), sort them, and display the results. It retrieves data using `_list_`, processes it to group items under their projects, trims unnecessary characters from the output, and formats the display with `print_x_of_y` to show items in... | def list_project():
"""Organizes items by project +prj they belong to."""
lines, sorted = _list_("project", "\+(\w+)")
print(concat(sorted)[:-1])
print_x_of_y(sorted, lines) |
def _list_(by, regexp):
"""Master list_*() function."""
nonetype = concat(["no", by])
todo = {nonetype: []}
by_list = []
sorted = []
if by in ["date", "project", "context"]:
lines = format_lines(color_only=True)
regexp = re.compile(regexp)
for line in lines:
... | The code organizes items by extracting and grouping them based on "@context" tags using a regex pattern. It sorts the items, concatenates them, trims the last character, and prints the count of items along with the processed list. | def list_context():
"""Organizes items by context @context associated with them."""
lines, sorted = _list_("context", "@(\w+)")
print(concat(sorted)[:-1])
print_x_of_y(sorted, lines) |
def _list_(by, regexp):
"""Master list_*() function."""
nonetype = concat(["no", by])
todo = {nonetype: []}
by_list = []
sorted = []
if by in ["date", "project", "context"]:
lines = format_lines(color_only=True)
regexp = re.compile(regexp)
for line in lines:
... | The function `list_todo` prints a prioritized list of todo items from a file, ordered by priority and their position in the file. When no arguments are provided, it retrieves and displays all items sorted by priority, using helper functions to format and print the list. If arguments are given, it filters or processes t... | def list_todo(args=None, plain=False, no_priority=False):
"""Print the list of todo items in order of priority and position in the
todo.txt file."""
if not args:
lines, sorted = _list_("pri", "")
print(concat(sorted)[:-1])
print_x_of_y(sorted, sorted)
else:
_list_by_(*arg... |
def separate_line(number):
"""Takes an integer and returns a string and a list. The string is
the item at that position in the list. The list is the rest of the todos.
If the todo.txt file is empty, separate = lines = None. If the number is
invalid separate = None, lines != None."""
lines = [line f... | The function appends user-provided text to a specific line in a file or data structure. It validates the line number, modifies the target line by concatenating input arguments, inserts the updated line, and triggers a rewrite/update process. If the first argument isn't a number, it reports an error expecting a numeric ... | def append_todo(args):
"""Append text to the item specified."""
if args[0].isdigit():
line_no = int(args.pop(0))
old_line, lines = separate_line(line_no)
if test_separated(old_line, lines, line_no):
return
new_line = concat([concat([old_line[:-1],
concat(... |
def separate_line(number):
"""Takes an integer and returns a string and a list. The string is
the item at that position in the list. The list is the rest of the todos.
If the todo.txt file is empty, separate = lines = None. If the number is
invalid separate = None, lines != None."""
lines = [line f... | The function `prioritize_todo` modifies or adds a priority to a specified line in a todo list. It accepts arguments (line number and a capital letter priority) to update the line's priority. It checks if the line exists, formats the new priority, replaces or appends it, and updates the list. Errors occur if inputs don'... | def prioritize_todo(args):
"""Add or modify the priority of the specified item."""
args = [arg.upper() for arg in args]
if args[1:] and args[0].isdigit()\
and len(args[1]) == 1 and args[1] in PRIORITIES:
line_no = int(args.pop(0))
old_line, lines = separate_line(line_no)
... |
def separate_line(number):
"""Takes an integer and returns a string and a list. The string is
the item at that position in the list. The list is the rest of the todos.
If the todo.txt file is empty, separate = lines = None. If the number is
invalid separate = None, lines != None."""
lines = [line f... | The function `de_prioritize_todo` removes priority markings (e.g., `(A)`, `(X)`) from the beginning of a specified line in a list, if present. It takes a line number, checks if it is valid, and uses regex to strip priority tags before reinserting the modified line. If the number is invalid, it triggers an error. The co... | def de_prioritize_todo(number):
"""Remove priority markings from the beginning of the line if they're
there. Don't complain otherwise."""
if number.isdigit():
number = int(number)
old_line, lines = separate_line(number)
if test_separated(old_line, lines, number):
return
... |
def separate_line(number):
"""Takes an integer and returns a string and a list. The string is
the item at that position in the list. The list is the rest of the todos.
If the todo.txt file is empty, separate = lines = None. If the number is
invalid separate = None, lines != None."""
lines = [line f... | The function `prepend_todo` takes a line number and a list of arguments, then prepends the concatenated arguments to the specified line in a file. It handles priority markers (e.g., `(A)`) by either inserting the prepended text before the marker or combining it with the marker if present. The modified line is inserted ... | def prepend_todo(args):
"""Take in the line number and prepend the rest of the arguments to the
item specified by the line number."""
if args[0].isdigit():
line_no = int(args.pop(0))
prepend_str = concat(args, " ") + " "
old_line, lines = separate_line(line_no)
if test_separa... |
def config_model():
model = keras.Sequential()
model.add(keras.layers.Input(shape=(2 * COORDINATES + 1, )))
model.add(keras.layers.Dense(128, activation="relu"))
model.add(keras.layers.Dense(64, activation="relu"))
model.add(keras.layers.Dense(32, activation='relu'))
model.add(keras.layers.Dense... | The main task of the code is to train a machine learning model using a custom loss function (sigma_loss_alt), evaluate its performance on test data, and save the model architecture, training loss, validation loss, and evaluation metrics with timestamped filenames. It configures the model, generates synthetic training/v... | def main(epochs=3, batch_size=32, sample_size=28, no_of_samples = 10000):
model = config_model()
model.compile(optimizer = keras.optimizers.Adagrad(learning_rate=LEARNING_RATE), metrics=['accuracy'])
train_dataset = feature_dataset(no_of_samples, batch_size)
val_dataset = feature_dataset(no_of_samples,... |
def read_config():
global mailfolder_junk
global mailfolder_normal
global keywordfile_junk
global keywordfile_normal
global file_studied_mail_junk
global file_studied_mail_normal
global unknown_mail_list
global unknown_mail_check_result
global junklevel
global CheckedWords
with open("config.ini") as f:
for... | The code analyzes emails from a specified list, classifying each as junk or normal using predefined configurations and analysis functions. It counts classifications, calculates percentages, generates a summary report, and saves results to a file. The process involves reading settings, processing each email, appending c... | def main():
junkcount = 0
normalcount = 0;
allmail = 0
listresult = []
read_config()
print("=========")
print(mailfolder_junk)
print(mailfolder_normal)
print(keywordfile_junk)
print(keywordfile_normal)
print(file_studied_mail_junk)
print(file_studied_mail_normal)
print(unknown_mail_list)
print(unknown_mai... |
def read_config():
global mailfolder_junk
global mailfolder_normal
global keywordfile_junk
global keywordfile_normal
global file_studied_mail_junk
global file_studied_mail_normal
with open("config.ini") as f:
for line in f:
strall = line.strip()
if strall.find("mailfolder_junk") != -1:
mailfolder_jun... | The main task of the code is to configure mail processing parameters, analyze junk and normal mail folders to count studied emails, generate data files, and output summary statistics. It initializes global counters, reads configurations, processes mail data, and prints results including studied mail counts. | def main():
global junk_mail_count
global normal_mail_count
read_config()
print("=========")
print(mailfolder_junk)
print(mailfolder_normal)
print(keywordfile_junk)
print(keywordfile_normal)
print(file_studied_mail_junk)
print(file_studied_mail_normal)
junk_mail_count = study_junk_mail(mailfolder_junk)
no... |
def ReadCosts() :
U=[]
V=[]
costs = {}
c = open(COSTS_FILE, 'r')
lines = c.readlines()
i = 1
for line in lines :
U.append((i,0))
j = 1
for col in line.split() :
if i == 1 :
V.append((0,j))
costs[i,j] = int(col)
j += ... | The code solves an assignment problem using the Hungarian algorithm. It reads cost data, constructs a bipartite graph, adjusts costs if maximizing, and computes optimal matches. It then prints matched indices and the total cost sum, handling both maximization and minimization scenarios. | def Examples() :
final = False
U,V,costs = ReadCosts()
g = CreateGraph(U,V)
if MAXIMIZE :
new_costs = AdjustCosts(costs)
result = Hungarian(g,new_costs,final,U)
else :
result = Hungarian(g,costs,final,U)
sum = 0
c = 1
for i in result :
if i in U :
... |
def CreateGraph(input_filename):
g = {}
with open(input_filename) as graph_input:
for line in graph_input:
nodes = [int(x) for x in line.split()]
if nodes[0] not in g:
g[nodes[0]] = []
if nodes[1] not in g:
g[nodes[1]] = []
... | This code implements an iterative algorithm to identify and remove the most influential node in a graph. It calculates node influences based on adjacency sums, repeatedly selects the node with maximum influence, updates the graph by removing it, and adjusts influence values for affected nodes until all nodes are proces... | def Algorith_B():
# Graph for the algorithm.
g = CreateGraph(input_filename)
# Compute the grades and then the influences.
nodes_sum = ComputeAdjencieSum(g)
nodes_influence = NodesInfluence(nodes_sum,g)
for n in range (num_nodes):
# Find the node to be removed.
max_node = FindMa... |
def fullScan(self):
self.showScanTool(True)
drives = win32api.GetLogicalDriveStrings()
print(drives)
drives = drives.split('\000')[:-1]
for drive in drives:
self.specificScan(drive)
while self.scanThread.isRunning():
time.sleep()
def checkP... | The scanning method performs a full scan if enabled, otherwise validates the specified folder path and initiates a targeted scan after clearing previous logs. It handles errors by displaying warnings for invalid inputs and printing exceptions. | def scanning(self):
try:
if self.optionFullScan.isChecked():
self.fullScan()
else:
if self.folderPath.text() == "":
QMessageBox.warning(
self, 'Alert', "Please choose your folder", QMessageBox.Yes, QMessageBox.Ye... |
def scanControl(self):
if self.btnControl.isChecked():
print('pausing')
self.scanThread.pause = True
self.btnControl.setText('Resume')
else:
print('resuming')
self.scanThread.pause = False
self.btnControl.setText('Pause')
def clearS... | This code defines the setup for a graphical user interface (GUI) of a quick scan feature in an antivirus application. It creates and configures UI elements such as buttons, labels, progress bars, tabs, and layouts to allow users to initiate scans, monitor progress, pause/resume scans, clear logs, select scan folders, a... | def setupUi(self, QuickScanLayout):
QuickScanLayout.setObjectName("QuickScanLayout")
QuickScanLayout.resize(900, 600)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.se... |
def initialize_pinion_tooth_width(self):
""" From http://www.csparks.com/watchmaking/CycloidalGears/index.jhtml:
The nominal width of a tooth or a space when they are equally spaced is just pi/2, or about 1.57.
For pinions, we will reduce the width of the tooth a bit. For pinions with 6-10 leave... | This code constructs a pinion gear by calculating its pitch diameter, dedendum, and initializing tooth width, addendum, and sketch lines. It uses either a custom slope value or a default formula based on the gear module and addendum factors to define the pinion's geometric dimensions, ensuring compatibility with mating... | def build_pinion(self):
self.pinion_pitch_diameter = self.module * self.pinion_count
if self.custom_slop_enabled:
self.pinion_dedendum = self.wheel_addendum + self.custom_slop
else:
self.pinion_dedendum = self.module * (self.wheel_practical_addendum_factor + 0.4)
... |
def compute_wheel(self):
"""Computes values for critical dimensions of the wheel"""
self.wheel_add_factor = self.addendum_factor()
self.wheel_practical_addendum_factor = self.wheel_add_factor * 0.95
self.gear_ratio = self.wheel_count / self.pinion_count
self.wheel_circular_pitch ... | The main task of the code is to construct a gear set by first computing wheel parameters and conditionally building the wheel or pinion components based on the `draw_wheel` and `draw_pinion` flags. This function orchestrates the assembly of gear elements, ensuring only required parts are generated according to specifie... | def build_gear_set(self):
self.compute_wheel()
if self.draw_wheel:
self.build_wheel()
if self.draw_pinion:
self.build_pinion() |
def get_Q_value(self, moveable_node):
mu = self.s2v_dqn.embedding()
Q = self.s2v_dqn.evaluate(moveable_node, mu).numpy()
return Q
def update_model(self):
loss = []
for e in range(self.train_epoch):
batch_G_idx, batch_S, batch_v, batch_R, batch_W = self.graph_handler... | The code trains a DQN agent on a graph-based task by generating graph instances, using epsilon-greedy exploration to select node moves, updating the model with experience replay, tracking episode losses, and periodically saving model weights and loss plots for training progress. | def run_train(self):
print('[Task] Start Train')
for ep in range(self.train_eps):
G = self.graph_handler.generate_graph_instance()
self.s2v_dqn.import_instance(G)
e = 1. / ((ep / 10) + 1)
done = False
step = 0
ep_loss = []
... |
def info(msg):
print(msg)
logging.info(msg)
def _train_one_epoch(self, epoch, **kwargs):
self.model.train()
def print_log():
msg = 'Epoch {}, Batch {}, lr = {:.5f}, '.format(epoch, bid, curr_lr)
for k, v in loss_meter.items():
msg += '{} = {:.4f}, '.forma... | The code trains a model over multiple epochs, saving the best-performing model based on evaluation metrics (e.g., mIoU). It iteratively trains, evaluates, and updates the best results, copying the optimal model to a dedicated file. The main task is to optimize model performance by tracking and preserving the highest ev... | def train(self):
best_results = None
for epoch in range(self.args['train']['max_num_epochs']):
info('Start Epoch {}'.format(epoch))
self.model_saved_path = self.args['train']['model_saved_path']
os.makedirs(self.model_saved_path, mode=0o755, exist_ok=True)
... |
def checking(deck):
for cards in deck:
if len(cards) == 2:
shapes[cards[0]] += 1
values[cards[1]] += 1
elif len(cards) == 3:
shapes[cards[0]] += 1
values[cards[1:]] += 1
def royalFlush(deck):
fp = flush()
sp = royal(deck)
if fp and sp:
... | The code evaluates a poker hand's rank by checking for specific combinations (e.g., royal flush, straight, pairs) in descending order of priority. If none are found, it converts face cards to numerical values, identifies the highest card, and returns a score of 1 along with the highest card's name. The function priorit... | def checks(deck):
deck = deck[:-1]
deck = deck.split()
score = 0
checking(deck)
if royalFlush(deck):
score = 10
return score
elif straightFlush(deck):
score = 9
return score
elif fourOfKind(deck):
score = 8
return score
elif ful... |
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def append_z_term(qc, q_i, gamma, constant_term):
... | The function constructs a quantum circuit representing a cost Hamiltonian for a given graph $ G $, using parameters $ \gamma $ and $ \lambda $. It initializes a quantum circuit with $ N^2 $ qubits, applies Z and ZZ gates based on simplified classical Hamiltonian terms derived from $ G $, and returns the resulting circu... | def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
... |
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, _LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def inver... | The code evaluates and prints TSP-related energy metrics using inverted counts. It calculates the mean energy, minimum energy value, total evaluations, and the minimum vector from the given graph `G`. The function `invert_counts` preprocesses input counts, while `compute_tsp_energy_2` and `compute_tsp_min_energy_2` der... | def test_counts_2(counts, G):
mean_energy2 = compute_tsp_energy_2(invert_counts(counts),G)
cantidad, min, min_meas = compute_tsp_min_energy_2(invert_counts(counts),G)
print("*************************")
print("En el algoritmo 2 (Marina) el valor esperado como resultado es " + str(mean_energy2))
prin... |
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def append_z_term(qc, q_i, gamma, constant_term):
... | The code constructs a quantum circuit representing a Hamiltonian for a graph-based optimization problem. It initializes a quantum circuit with $N^2$ qubits, where $N$ is the graph's node count. The function adds Z and ZZ terms to the circuit based on classical simplified Hamiltonian components retrieved from `get_class... | def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
... |
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
q... | This function evaluates the expected value of a Traveling Salesman Problem (TSP) solution using a Quantum Approximate Optimization Algorithm (QAOA) circuit. It splits input parameters into beta and gamma, constructs a quantum circuit, simulates it to obtain probabilities, calculates the expected cost based on TSP objec... | def f(theta):
beta = theta[:p]
gamma = theta[p:]
#print(beta)
_lambda = _LAMBDA # get global _lambda
qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
#print(beta)
result = execute(qc, backend, seed_simulator=10, shots=_SHOTS).result()
final_state_v... |
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
def f(theta):
beta = theta[:p]
gamma = theta[p:]
#print(beta)
_lambda = _LAMBDA # get global _lambda
qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
... | The code performs a quantum optimization task using the QAOA (Quantum Approximate Optimization Algorithm) on a graph. It generates a random graph if none is provided, initializes parameters (beta, gamma) for quantum circuit angles, optimizes these parameters via COBYLA, constructs a quantum circuit, simulates it, and e... | def test_solution(grafo=None, p=7):
global _UNIFORM_CONVERGENCE_SAMPLE
_UNIFORM_CONVERGENCE_SAMPLE = []
if grafo == None:
cantidad_ciudades = 2
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciud... |
def get_black_box_objective(G,p):
backend = Aer.get_backend('qasm_simulator')
def f(theta):
beta = theta[:p]
gamma = theta[p:]
_lambda = _LAMBDA # get global _lambda
qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA)
counts = execute(qc, backend, seed_simulator=10, shots=_SH... | The code generates a random graph with 2 cities, computes the optimal Hamiltonian path classically, maps the graph, and uses QAOA (Quantum Approximate Optimization Algorithm) with optimized parameters to simulate quantum circuits. It compares results from two parameter sets, visualizes quantum state distributions via h... | def defult_init():
cantidad_ciudades = 2
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
print(m... |
def compute_tsp_energy(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj(meas, G)
energy += obj_for_meas*meas_count
total_counts += meas_count
return energy/total_counts
def invert_counts(counts):
return ... | The code computes and prints the average energy and minimum energy values for a Traveling Salesman Problem (TSP) using given counts and a graph G. It inverts the counts, evaluates the energy, and reports the mean energy, minimum energy found, total evaluations, and the corresponding minimum solution vector. | def test_counts_1(counts, G):
mean_energy1 = compute_tsp_energy(invert_counts(counts),G)
cantidad, min, min_meas = compute_tsp_min_energy_1(invert_counts(counts),G)
print("*************************")
print("En el algoritmo 1 (Pablo) el valor esperado como resultado es " + str(mean_energy1))
print("... |
def helper_hinge():
mnist = fetch_openml('mnist_784')
data = mnist['data']
labels = mnist['target']
neg, pos = "0", "8"
train_idx = numpy.random.RandomState(0).permutation(np.where((labels[:60000] == neg) | (labels[:60000] == pos))[0])
test_idx = numpy.random.RandomState(0).permutation(np.where((labels[60000:] =... | The code performs hyperparameter tuning for Support Vector Machine (SVM) models using Stochastic Gradient Descent (SGD) with hinge loss and cross-entropy loss. It identifies optimal learning rates (eta) and regularization parameters (C), trains models, evaluates accuracy on test data, and visualizes learned weights. Th... | def main():
# q1
train_data, train_labels, validation_data, validation_labels, test_data, test_labels = helper_hinge()
# q1.a
best_eta = find_best_eta(train_data, train_labels, validation_data, validation_labels, 1, 1000)
print(best_eta)
# q1.b
best_c = find_best_C(train_data, train_labels, ... |
def load_data():
'''The method loads the data.'''
mnist = fetch_openml("mnist_784")
data = mnist["data"]
labels = mnist["target"]
return (data, labels)
def divide_data(data, labels):
''' The method divides the data and its corresponding labels
into train and test.'''
idx = numpy.r... | The main task of the code is to evaluate and optimize a machine learning model's accuracy by testing different parameter values (k and n) on a dataset. It loads data, splits it into training and test sets, calculates prediction accuracy for a fixed k=10, identifies the optimal k value through variable analysis, and det... | def main():
(data, labels) = load_data()
(train, train_labels, test, test_labels) = divide_data(data, labels)
# q.2
false_prediction_p = compare(train, train_labels, test, test_labels, 10, 1000)
print("The accuracy of the prediction using the first 1000 training "+
"images, on each of the ... |
def send_lobby_message(self):
data = {"players": {}, "map": GlobalData.map_used}
timeDelta = datetime.now() - GlobalData.startedTimerMoment
if timeDelta < timedelta(seconds=5):
data["timer"] = timeDelta.total_seconds()
for i in GlobalData.ws_connections:
# logger.... | This function processes incoming client messages by decoding data, logging it, and handling different message types (0-5) to update lobby status, game timers, loading states, velocity data, and game over conditions. It coordinates client interactions by modifying global game data, checking readiness, and broadcasting u... | def on_message(self, message):
if type(message) == bytes:
message = message.decode('UTF-8')
logger.debug("Got Data from client: "+self.id+", "+str(message))
if self.first_message:
data = json.loads(message)
self.name = data["name"]
if len(GlobalDat... |
def close_open_orders(self):
self.exchange.private_post_v1_order_cancel_all()
def send_limit_order(self, trade_type):
for lp in range(self.attempts):
try:
amount, price = self.get_max_amount(trade_type)
print(amount,price)
if amount == 0:
... | The main task of the code is to continuously monitor and adjust a limit order for a given trade type. It closes existing orders, sends a new limit order, and checks the order status every 0.5 seconds. If the best bid price exceeds the limit price, it cancels the current order and sends a new one. The loop exits once th... | def fill_order(self, trade_type):
self.close_open_orders()
order, limit_price = self.send_limit_order(trade_type)
while True:
time.sleep(.5)
order = self.exchange.fetch_order(order['info']['id'])
print(order)
if order['status'].lower() !... |
def aggregate_elements_back_into_sequence(sequence_lengths, elements):
final_results = []
count = 0
for seq_i in range(len(sequence_lengths)):
seq = {"num_error": 0, "undetected_tokens": 0, "masked_tokens": 0, "total_logkey": 0, 'deepSVDD_label': 0,
'element_anomaly_score': 0}
... | The function `analyse_predictions` loads test results from pickle files, aggregates them into sequences (if enabled), evaluates element-level and sequence-level anomaly detection by computing optimal thresholds, and returns the best thresholds for sequence-level and element-level (if enabled) anomaly scoring. | def analyse_predictions(self):
print("Loading test results from pickle files")
test_normal_results = pickle.load(open(self.model_dir + "test_normal_results.pkl", "rb"))
test_abnormal_results = pickle.load(open(self.model_dir + "test_abnormal_results.pkl", "rb"))
# print(test_normal_resul... |
def get_sensor_reading(self):
"""
Set sonar reading to objcts infront of sonar sensor\n
Returns value in range 0-255 cm
"""
try:
sensor_readings = []
for i in range (0,5):
r = self.BP.get_sensor(self.sonar)
sensor_readings.a... | This function updates particles in a particle filter by calculating their likelihood based on sensor readings, normalizing weights to sum to 1, and resampling particles to focus on high-weight states, improving estimation accuracy in probabilistic tracking systems. | def updateParticles(self,particles):
ioInterface.drawParticles(particles)
z = self.get_sensor_reading() #step 2
for i in range(len(particles)):
((x,y,theta),weight) = particles[i]
particles[i] = ((x,y,theta), weight * self.calculate_likelihood(x,y,theta,z))
#nor... |
def stop(self):
"""
Stops both motors turning
"""
self.BP.set_motor_dps(self.L, 0)
self.BP.set_motor_dps(self.R, 0)
return
def moveParticleForward(self, particle, distance):
"""
Update particle prediction for forward movement of distance cm
particl... | The code drives a robot forward a specified distance by setting motor speeds, pausing for calculated time, then stops. It updates particle positions using a movement function for localization, essential in particle filter-based navigation systems. | def forward(self, distance):
"""
Drives straight forward 'distance' cm
"""
direction = 1 if distance >=0 else -1
t = abs(distance) / self.wheel_speed + self.forward_tuning
self.BP.set_motor_dps(self.L, direction * self.dps)
self.BP.set_motor_dps(self.R, direction ... |
def stop(self):
"""
Stops both motors turning
"""
self.BP.set_motor_dps(self.L, 0)
self.BP.set_motor_dps(self.R, 0)
return
def moveParticleSpin(self, particle, radians):
"""
Update particle prediction for left spin radians radians
particle :: tuple... | The code spins a robot in place by a specified angle (radians), adjusting motor directions for clockwise/counter-clockwise rotation. It calculates required time based on robot width and wheel speed, updates motor speeds, pauses, stops motors, and updates particle positions via a spin transformation. | def spin(self, radians):
"""
Spins 'radians' radians in place\n
A positive value for radians is a counter-clockwise (left) spin\n
A negative value for radians is a clockwise (right) spin
"""
# direction = 1 for spin left, -1 for spin right
direction = 1 if radian... |
def metrics(self):
"""
Reports mean and standard deviation of particles position array
particles :: list of tuples [((x,y,theta),weight)]
Return ((mu_X, mu_y, mu_theta), (sigma_x, sigma_y, sigma_theta))
"""
xs = list(map(self.getX, self.particles))
ys = list(map(... | The main task of the code is to navigate a robot to a specified waypoint (Wx, Wy) in world coordinates. It calculates the angular difference (beta) between the robot's current orientation and the direction to the target, rotates the robot to align with the target (spin(beta)), then moves forward by the Euclidean distan... | def navigateToWaypoint(self, Wx, Wy):
"""
Travel to the the point Wx,Wy in world coordinates
"""
(x, y, theta), (_, _, _) = self.metrics()
dx = Wx - x
dy = Wy - y
alpha = atan2(dy,dx)
beta = (alpha - theta) % (2*PI)
beta = beta if beta <= P... |
def generate_init_population(self):
"""Generation of initial population
"""
logger.info(f"Generating initial population (Number of frogs: {self.total_bugs})")
red_male_bugs = np.empty((self.male_bugs, self.bins_data.no_of_items, self.female_bugs))
min_score_ids = [-1] * ... | The code executes the Firebug Swarm Optimization (FSO) algorithm to solve a bin packing problem. It initializes a population, performs optimization, records the best solution's bins and free capacities, logs execution time, and writes results to "Result.txt". The function returns the optimal solution and computation ti... | def run_fso(self, data_path):
logger.info("Starting Firebug Swarm Optimization (FSO) Algorithm")
self.data_path = data_path
self.bins_data.extract_from_file(self.data_path)
s1 = time.time()
self.generate_init_population()
self.main_search()
e1 = time.time()
... |
def make_heap(self, frequency):
for key in frequency:
node = HeapNode(key, frequency[key])
heapq.heappush(self.heap, node)
def merge_nodes(heap):
count = 0
while (len(heap) > 1):
node1 = heapq.heappop(heap)
node2 = heapq.heappop(heap)
... | The code generates Huffman codes from given character frequencies by building a priority queue, merging nodes into a binary tree, and assigning binary codes to each character. It returns the resulting Huffman codes. | def create_code(self, frequency):
self.make_heap(frequency)
self.heap = self.merge_nodes(self.heap)
self.make_codes()
return self.codes |
def make_min_que(self, frequency):
node = HeapNode("leaf", 0, count=len(frequency))
heapq.heappush(self.min_que, node)
for i in range(len(frequency)-1):
node = heapq.heappop(self.min_que)
counter = node.count - 1
node1 = HeapNode("leaf", node.freq + self.left,... | This code generates Huffman codes from a frequency dictionary by normalizing node values, sorting frequencies, building a priority queue, merging nodes, and creating weighted codes for data compression. | def create_code(self, frequency):
if self.right >= self.left:
self.left = self.left / self.right
self.right = 1
else:
self.right = self.right / self.left
self.left = 1
frequency = {k: frequency[k] for k in sorted(frequency, key=frequency.get, reve... |
def init_sim(self):
"""" Initializes simulation by retrieving initial frequencies and codes for every letter """
self.codes = self.coding.create_code(self.initial_freq)
self.codes_to_freq = {self.codes[k]: self.initial_freq[k] for k in self.codes.keys()}
self.codes_to_char = {y: x for x,... | The code simulates typing a target sentence with noise, tracking decisions, errors, and performance metrics. It uses a specified coding algorithm (e.g., Weighted Huffman) to encode letters, introduces noise, decodes the result, and compares noisy performance to the optimal case. Metrics include total decisions, ones/ze... | def simulate(self, noise):
"""" Run the simulation"""
self.noise = noise
if self.coding_algorithm == "Weighted":
self.coding = WeightedHuffmanCoding(self.noise[0], self.noise[1])
data = []
columns = ['N', 'Algorithm', 'Noise', 'TotalClicks', 'NmOfOnes', 'NmOfZeros']
... |
def primal_dual(g_params, X, y, M, num_iter=100, reg = 1e-1, print_every=0, inexact_update=True):
D, tau, T, Sigma, SD, TDT = g_params
sizeM = np.sum(M)
y_M = M * y
obj = obj_func(D, X, M, y_M, reg)
d, N = X.shape
E = D.shape[0]
w = np.zeros((num_iter,d,N))
u = np.zeros((num_iter, d, E))... | The main task of the code is to run experiments using a primal-dual optimization method on given data (X, y) with parameters (g_params, reg, prob). It initializes a random feature selection matrix M, executes the optimization process, and returns results like weights, objective history, and accuracy metrics. If specifi... | def run_experiments(g_params, X, y, num_iter, reg, prob, M=None, print_every=0, compare_with_lr = False):
if M is None:
N = X.shape[1]
M = np.zeros(N)
while True:
M = np.array([1 if np.random.rand(1)<prob else 0 for k in range(N)])
if np.sum(M)>0:
brea... |
def incident_matrix(graph):
v1, v2, weights = graph.get_edge_list()
a= np.append(weights, -weights)
b = np.append(v1, v2)
c = np.append(np.arange(v1.size), np.arange(v1.size))
D = sparse.coo_matrix((a, (c, b)), shape=(v1.size, graph.N))
#D = np.zeros((v1.size, graph.N))
#D[np.arange(v1.size... | The code trains a graph-based model by running multiple experiments with varying regularization (`reg`) and probability (`prob`) parameters. It computes graph-related matrices, iterates over experimental configurations, and evaluates model performance (accuracy and non-accuracy) across iterations. Results are stored in... | def train(graph, X, y, opt_acc, num_iter, reg, prob, num_exps, M=None, is_plot=False, prefix="chain2", is_saved=False,
print_every=0, compare_with_lr=False):
D, weights = incident_matrix(graph)
tau, T, Sigma, SD, TDT = diag_matrices(graph, D, weights)
g_params = D, tau, T, Sigma, SD, TDT
if np... |
def load_sgns_embedding(filepath):
embedding = dict()
vocab = set()
with open(filepath, 'r') as f:
lines = f.readlines()
vocab_size, embedding_size = lines[0].split()
for i in range(1, len(lines)):
line = lines[i].split()
vocab.add(line[0])
embeddi... | The code evaluates a pre-trained SGNS embedding by loading the model, generating training embeddings and labels, then assessing its performance using an evaluation function. The printed path suffix likely indicates the embedding file being processed. | def eval_sgns_embedding(embedding_path):
print(embedding_path[-12:])
embedding = load_sgns_embedding(embedding_path)
training_embeddings, labels = train_embeddings(embedding)
evaluate(embedding, training_embeddings, labels) |
def load_glove_embedding(filepath):
config = load_config()
with open(os.path.join(config.cooccurrence_dir, "vocab.pkl"), "rb") as f:
sys.path.append('nlp_glove_implementation/glove/src')
vocab = pickle.load(f)
model = GloVe(
vocab_size=config.vocab_size,
embedding_size=confi... | The function evaluates GloVe embeddings by loading them, extracting vocabulary indices, preparing training data, and assessing performance using an evaluation metric. It returns the evaluation result. | def eval_glove_embeddings(embedding_path):
print(embedding_path[-12:])
embedding, vocab = load_glove_embedding(embedding_path)
vocab = vocab.token2index.keys()
training_embeddings, labels = train_embeddings(embedding, vocab)
return evaluate(embedding, training_embeddings, labels, vocab) |
def get_top_words():
vocab = load_glove_embedding("/csse/users/grh102/Documents/cosc442/unsupervised-systems/nlp_glove_implementation/glove/data/vectors1.txt")[1]
top_words_indices = np.argsort(vocab.token_counts)[-1000:]
top_words = [vocab.index2token[index] for index in top_words_indices]
return top_w... | This code evaluates the intrinsic quality of SGNS word embeddings by computing the J@n metric. It loads five SGNS models from specified files, retrieves top words and vocabulary, and calculates the J@n score for the top words across models. The result is printed as "SGNS" followed by the computed J@n value, assessing t... | def intrinsic_eval_sgns_embedding():
sgns_base_dir = "/csse/users/grh102/Documents/cosc442/unsupervised-systems/word2vec-master/vectors"
top_words, vocab = get_top_words()
models = []
for i in range(1, 6):
model, vocab = load_sgns_embedding(sgns_base_dir + str(i) + ".bin")
models.append... |
def get_top_words():
vocab = load_glove_embedding("/csse/users/grh102/Documents/cosc442/unsupervised-systems/nlp_glove_implementation/glove/data/vectors1.txt")[1]
top_words_indices = np.argsort(vocab.token_counts)[-1000:]
top_words = [vocab.index2token[index] for index in top_words_indices]
return top_w... | The code evaluates GloVe embeddings by calculating the Jaccard similarity (J@N) between top words and embeddings from multiple GloVe models. It loads five pre-trained GloVe models, computes the J@10 score for the top words using their vocabulary, and prints the result to assess the embeddings' semantic coherence and qu... | def intrinsic_eval_glove_embeddings():
glove_base_dir = "/csse/users/grh102/Documents/cosc442/unsupervised-systems/nlp_glove_implementation/glove/data/vectors"
top_words, vocab = get_top_words()
models = []
for i in range(1, 6):
models.append(load_glove_embedding(glove_base_dir + str(i) + ".txt... |
def generate_starting_pop(func_params, bit_count):
population = []
for i in range(0, POPULATION_SIZE):
population.append(generate_chromosome(func_params, bit_count))
return population
def evaluate_fitness(population:list ,no_of_params,no_of_bits,function_name):
fitness_population :list = []
... | The code implements a genetic algorithm (GA) to minimize benchmark functions (De_Jong, Rastrigin, Schwefel, Michalewicz). It generates an initial population, iteratively evaluates fitness, selects chromosomes, applies crossover/mutation, and adjusts rates adaptively if no improvement occurs. The algorithm tracks the gl... | def ga(function_name,no_params):
start_time = time.time()
global CROSSOVER_RATE
global MUTATION_RATE
not_found = 0
match function_name.__name__:
case 'De_Jong':
start_population = generate_starting_pop(no_params,N_DEJON)
global_minim = 1000
for i ... |
def decode(solution, a, b, no_of_bits):
return (a + binatodeci(solution)*(b-a)/(pow(2, no_of_bits)-1))
def generate_neighbours(solution): #length is the slicing length
vn = []
#get the current param representation
for line, entry in enumerate(solution):
aux... | The code implements a **hill climbing algorithm** to optimize a given function. It iteratively generates random binary strings, converts them to real parameters, evaluates the function, and explores neighbors (via Hamming distance) to find improved solutions. Depending on the `improv` flag (best or first), it selects t... | def hill_climbing(t, no_of_bits, a, b, function, improv,no_of_params): # improv -- 0 for best , 1 for first
best = None
#number of test to be made
with open("results.ansi","a") as res :
for i in range(0, t):
#local = False
print(f'iteration number {i}')
# vc = np.random.randint(2, s... |
def train():
Xtr = np.load(mydir+'Xtr.npy')
Ytr = np.load(mydir+'Ytr.npy')
n = Xtr.shape[1]
X_train = torch.from_numpy(Xtr).float()
Y_train = torch.from_numpy(Ytr).float()
model = Model(n,h)
opt = optim.SGD(model.parameters(), lr=1e-2, momentum=0.9, weight_decay=5e-4)
E... | The main task of the code is to load a pre-trained neural network model, split private test data into two subsets, and perform private fine-tuning experiments by running 10 iterations of tuning on the data. The results, including tuning and test accuracies, are saved in the specified directory. The code also includes c... | def main():
model_path = '/Adult/adult_mlp'
# classifier training and save model
training_tag = False
if training_tag:
train()
model = torch.load(model_path)
model.eval()
# load private data
Xte = np.load(mydir+'Xte.npy')
Yte = np.load(mydir+'Yte.npy')
# split
Xte... |
def load_pc_file(self, filenames, path):
return load_pc_file(filenames, path)
def load_pc_files(self, filenames, path):
return load_pc_files(filenames, path) | This method retrieves a query point cloud and associated positive/negative samples for training. It loads the query, selects positives from pre-defined indices, randomly samples negatives, filters out invalid negatives, and adds an extra negative (neg2) to avoid overlap with positives. The output includes query, positi... | def __getitem__(self, index):
query = self.load_pc_file(self.files[index], self.data_dir)
if self.return_only_query:
return {'query': query, 'query_idx': index}
pos = np.where(self.is_pos[index, :])[0]
np.random.shuffle(pos)
pos_files = []
act_num_pos = len(... |
def run_rolling_average_trials(self, current_task, threshold, window_size): # pass entire list of trials on resume
shape_list = [StimShape.RECT, StimShape.CIRCLE] # list of lists in order to generate random trial_configs
timeout_list = [2, 4, 6]
if len(current_task.sessions) > 0:
session = current_task.sessio... | This function processes an experiment by identifying incomplete tasks, selecting the first open task, and executing trials based on the task's progression type (rolling average, session-based, or target-based). It runs corresponding trial methods with parameters, then checks if the task is completed, printing status up... | def continue_task_experiment(self, experiment):
# check tasks
open_tasks = [task for task in experiment.tasks if not task.complete] # already sorted
if len(open_tasks) == 0:
print('\n\n\nall tasks complete, experiment done')
return
#for current_task in open_tasks
current_task = open_tasks[0]
progressi... |
def check_key_down(event, ai_settings, screen, sound, ships, bullets):
if event.key == pg.K_RIGHT:
for ship in ships:
ship.moving_right = True
elif event.key == pg.K_LEFT:
for ship in ships:
ship.moving_left = True
elif event.key == pg.K_SPACE:
fire_bullets(ai... | This function processes game events such as quitting, key presses/releases, and mouse clicks. It handles player input for movement, shooting, starting the game via a play button, and accessing scores via a scores button. Event types include QUIT, KEYDOWN/KEYUP for ship control, and MOUSEBUTTONDOWN to trigger button act... | def check_events(ai_settings, screen, play_button, scores_button, stats, sb, sound, ships, aliens, bullets):
for event in pg.event.get():
if event.type == pg.QUIT:
sys.exit()
elif event.type == pg.KEYDOWN:
check_key_down(event, ai_settings, screen, sound, ships, bullets)
... |
def check_fleet_edges(ai_settings, aliens):
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(ai_settings, aliens)
break
def ship_hit(ai_settings, screen, stats, sb, sound, ships, aliens, bullets, alien_bullets, UFOs):
if stats.ship_left > 1:
s... | This function updates alien behavior in a game, including checking fleet edges, updating positions, detecting collisions with player ships (triggering ship_hit), checking if aliens reach the screen bottom, managing alien removal when dead, and initiating alien bullet firing. It maintains alien lists and handles game st... | def update_aliens(ai_settings, screen, stats, sb, sound, ships, aliens, bullets, alien_bullets, timer, aliens_list,
UFOs):
check_fleet_edges(ai_settings, aliens)
aliens.update()
for ship in ships:
if pg.sprite.spritecollideany(ship, aliens):
ship_hit(ai_settings, screen... |
def get_pawn_moves(self, r, c):
moves = []
if self.whiteToMove:
if r == 6 and self.board[4][c] == '--' and self.board[5][c] == '--':
moves.append(Move((r, c), (r-2, c), self.board))
if r >= 1 and self.board[r-1][c] == '--':
moves.append(Move((r, c)... | The main task of the code is to generate all valid moves for the current player's pieces on a chessboard. It iterates through each piece, checks if it belongs to the active player, and appends possible moves using specialized methods for each piece type (pawn, rook, bishop, knight, queen, king). The function returns a ... | def get_possible_moves(self):
moves = []
for (r, rValue) in enumerate(self.board):
for (c, piece) in enumerate(rValue):
if piece == '--' or (piece[0] == 'b' and self.whiteToMove) \
or (piece[0] == 'w' and not self.whiteToMove):
cont... |
def listToArray(self):
lst = []
if self.empty():
return lst
## add values to lst by doing n sucsessor operations from firstItem:
min_node = self.firstItem
for i in range(self.root.size):
lst.append(min_node.getValue())
min_node = self.getSucses... | The main task of the code is to sort a list by separating None values, sorting the non-None elements using quicksort, appending the None values at the end, and constructing a tree from the combined sorted array. | def sort(self):
array = self.listToArray()
none_lst = []
value_lst = []
for value in array:
if value == None:
none_lst.append(value)
else:
value_lst.append(value)
sorted_array = self.quicksort(value_lst)
return self.... |
def listToArray(self):
lst = []
if self.empty():
return lst
## add values to lst by doing n sucsessor operations from firstItem:
min_node = self.firstItem
for i in range(self.root.size):
lst.append(min_node.getValue())
min_node = self.getSucses... | The code's main task is to generate a permutation of the original list's elements by shuffling them and then constructing a tree structure from the shuffled array. This involves converting the list to an array, randomizing its order, and creating a tree using the rearranged data. The method encapsulates the process of ... | def permutation(self):
array = self.listToArray()
shuffled_array = self.shuffle_list(array)
return self.create_tree_from_array(shuffled_array) |
def empty(self):
return self.size == 0
def treeSelect(self, i):
def treeSelect_rec(node, k):
rank = node.getLeft().getSize() + 1
if k == rank:
return node
elif k < rank:
return treeSelect_rec(node.getLeft(), k)
else:
... | The code inserts a value into an AVL tree, creating a new node with virtual children. It handles three cases: inserting into an empty tree, at the end, or elsewhere. It updates tree pointers, adjusts size and first/last item references, rebalances via rotations, and propagates size updates upward. The main task is main... | def insert(self, i, val):
# 1. create a new node with virtual sons, his size = 1, height = 0.
new_node = AVLNode(val)
new_node.setLeft(AVLNode())
new_node.setRight(AVLNode())
new_node.right.setParent(new_node)
new_node.left.setParent(new_node)
new_node.updateHeigh... |
def treeSelect(self, i):
def treeSelect_rec(node, k):
rank = node.getLeft().getSize() + 1
if k == rank:
return node
elif k < rank:
return treeSelect_rec(node.getLeft(), k)
else:
return treeSelect_rec(node.getRight(),... | This code deletes a node at index `i` from a tree structure by handling four cases: leaf node, node with only left child, node with only right child, and node with both children. It maintains tree size, rebalances the tree post-deletion, and updates the first/last item pointers. The function returns a value related to ... | def delete(self, i):
if i >= self.size:
return -1
if i < 0:
return -1
node = self.treeSelect(i) # find node to delete
self.size -= 1 # maintain tree size
## case1: node is leaf
if node.getSize() == 1:
self.deleteLeaf(node)
... |
def empty(self):
return self.size == 0
def insert(self, i, val):
# 1. create a new node with virtual sons, his size = 1, height = 0.
new_node = AVLNode(val)
new_node.setLeft(AVLNode())
new_node.setRight(AVLNode())
new_node.right.setParent(new_node)
new_node.left.s... | The code concatenates two trees by handling edge cases (empty lists, single-node trees) and merging based on height differences. It returns the absolute height difference between the original trees, updating self's structure by copying or inserting nodes as needed. | def concat(self, lst):
# 1. edge cases for empty lists:
if self.empty() or lst.empty():
if self.empty() and lst.empty():
return 0
elif self.empty() and not lst.empty():
# turn self to lst:
self.root = lst.root
self.f... |
def generate_points(n, dim, limits):
points = rnd.random([n, dim])
points = points * (limits[1] - limits[0]) + limits[0]
return points
def optimize(points, bounds):
opt_points = []
opt_values = []
for point in points:
res = opt.dual_annealing(eggholder, x0=point, bounds=bounds, maxiter=100)
opt_po... | The code simulates the dynamic evolution of regions by iteratively adding optimized points, randomly merging or splitting regions, and tracking metrics like variation rates, region counts, and merge/split events over a specified number of iterations. The goal is to analyze how regions adapt and change structure through... | def simulate(iterations, n_regions, n_points, limits=[-500.0, 500.0], dim=2):
points = generate_points(n_points, dim, limits)
opt_limits = [limits for x in range(0, dim)]
optimized_points, values = optimize(points, opt_limits)
regions = create_k_regions(n_regions, optimized_points)
region_metrics = []
glob... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.