dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def put_charts():
put_markdown("## Charts")
put_html(charts.get_block_miners()).style("width: 60vw; height: 40rem")
put_markdown(
"###### This graph shows the miners who mined the most blocks from a sample of 1,000 blocks."
)
put_markdown("---")
def put_blocks():
put_markdown("## Blocks"... | The code defines a function `put_navbar()` that generates a vertical navigation bar using a grid layout. It displays clickable markdown headings ("Charts", "Blocks", "Transactions") which trigger corresponding functions (`put_charts()`, `put_blocks()`, `put_transactions()`) when clicked. The navbar is structured as a s... | def put_navbar():
put_grid(
[
[
put_markdown("### PyWebIO Ether Demo"),
put_markdown("#### Charts").onclick(lambda: put_charts()),
put_markdown("#### Blocks").onclick(lambda: put_blocks()),
put_markdown("#### Transactions").onclick(... |
def predict(data, model):
return model.predict(data, verbose=1)
def compute_dice_coef(y_true, y_pred):
"""
Computes the Dice-Coefficient of a prediction given its ground truth.
:param y_true: Ground truth.
:param y_pred: Prediction.
:return: Dice-Coefficient value.
"""
smooth = 1. # smo... | The code implements a Cost-Effective Active Learning (CEAL) step to iteratively update labeled and unlabeled training datasets. It uses pre-trained UNET models to compute predictions and uncertainty for unlabeled samples, then selects samples for manual labeling ("oracle") based on uncertainty and accuracy metrics. If ... | def compute_train_sets(X_train, y_train, labeled_index, unlabeled_index, weights, iteration):
"""
Performs the Cost-Effective Active Learning labeling step, giving the available training data for each iteration.
:param X_train: Overall training data.
:param y_train: Overall training labels. Including th... |
def register_marshmallow_schema(self, schema: CustomSchema) -> None:
"""Register schemas for openapi doc - using concrete
instance of marshmallow schema. Not class of marshmallow
schema, but instance, because it is more flexible"""
self.defined_marshmallow_schemas.add(schema)
def set_res... | This function adds a new OpenAPI path/method to the documentation by updating the openapi_object with operation details, registering request/response schemas, and setting query parameters. It skips processing the '/schema/' path to avoid redundancy. | def add_openapi_path(
self,
path: str,
method: str,
request_schema: CustomSchema = None,
response_schema: CustomSchema = None,
query_params: dict = None,
) -> None:
# in the framework /schema/ is used for openapi, therefore no need
# create openapi des... |
def conflict_in_field(d1, d2, field):
""" Detect if the object named 'field' in dict d1 is not equal to an object of the same name in dict d2."""
return d1[field] != d2[field]
def conflict_in_version(h1, h2):
""" Compare software version number between 2 headers.
Parameters
----------
h1 : ... | This function checks for critical conflicts between two file headers by comparing parameters like filetype, version, sample rate, and signal configurations. It ignores non-critical differences such as notes and reference channels. The function returns True if significant discrepancies are found, indicating incompatible... | def conflict_in_headers(h1, h2):
""" Compare critical values (like channel numbers and names) between 2 headers.
Non-critical differences that can be ignored include:
notch filter mode, impedance frequency, notes, and reference channel
Parameters
----------
h1 : dict
Dict containing... |
def peek_timestamp(position, header):
""" Peek into the data file associated with the given header, and return either the first or last timestamp of that file
Parameters
----------
position : str
Either 'first' to get the first timestamp of the file, or 'last' to get the last timestamp of t... | The function identifies and collects headers of files compatible with an original Intan file for merging. It scans the directory for .rhd/.rhs files (excluding the original), checks for header consistency and continuous timestamps, and returns headers of valid mergeable files while printing confirmation messages. | def get_mergeable_files(original_header):
""" Return a list of filenames that have headers similar enough to the original intan file that merging is possible
Parameters
----------
original_header : dict
Dict containing previously read header information from the original intan file
... |
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Rapid Reports"))
self.DB_list.setCurrentText(_translate("MainWindow", "Select Table"))
self.DB_list.setPlaceholderText(_translate("MainWindow", "Select ... | The main task of the code is to set up a graphical user interface (GUI) for a data analysis tool. It initializes a MainWindow with various UI components like combo boxes for database selection, variable interests, analysis types, and sorting options. It creates a table widget for displaying data, buttons for running an... | def setupUi(self, MainWindow,con):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(809, 750)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretc... |
def sorter(self):
sort_dic={'Ascending':True,'Descending':False,'None':''}
int_flag=sort_dic[self.sorting_interest.currentText()]
rel_flag=sort_dic[self.sorting_related.currentText()]
if self.sorting_interest.currentText() != 'None':
self.data_table=self.data_table.sort_valu... | The main task of the code is to dynamically update a table view by clearing existing widgets from a grid layout, creating a new QTableWidget, and populating it with data based on user selections or aggregation parameters. It checks for selected list items or aggregation settings, triggers data retrieval/sorting functio... | def table_view (self,x,y):
for i in reversed(range(self.gridLayout.count())):
self.gridLayout.itemAt(i).widget().deleteLater()
self.tableWidget = QtWidgets.QTableWidget(self.gridLayoutWidget)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
... |
def get_data(self,x,y):
t1=list(self.vars[self.vars['variables']==x]['tables'])[0]
pk1=list(pd.read_sql_query(("SHOW KEYS FROM "+self.DB_list.currentText()+"."+t1+" WHERE Key_name = 'PRIMARY'"), self.connection)['Column_name'])
fk1=list(pd.read_sql_query("SHOW KEYS FROM "+self.DB_list.currentTex... | The main task of the code is to process input data (x,y) by either directly retrieving data or applying aggregation functions based on a selection, then sorting, loading the results into a table, and finally opening a visualization window using the first two columns of the processed data. | def best_chart(self,x,y):
if self.aggrigation.currentText()=='None':
self.get_data(x,y)
self.sorter()
self.load_data(self.data_table)
else:
self.agg_functions(x,y)
self.sorter()
self.load_data(self.data_table)
self.... |
def table_view (self,x,y):
for i in reversed(range(self.gridLayout.count())):
self.gridLayout.itemAt(i).widget().deleteLater()
self.tableWidget = QtWidgets.QTableWidget(self.gridLayoutWidget)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
... | The code's main task is to determine the selected analysis type from a UI dropdown, retrieve current interest and related topic selections, and execute corresponding analysis methods: generating a table/report, creating a chart, or running descriptive analysis based on the chosen type. | def analysis (self, index):
self.current_interest=self.Interest_list.currentText()
self.current_related=self.related_list.currentText()
if self.Analysis_type.currentText()=='Table (Report)':
self.table_view(self.current_interest,self.current_related)
elif self.Analysis_type.c... |
def _validate_args(self, args: List[str]) -> None:
if len(args) == 0:
self.parser.print_help()
sys.exit(0)
def _show_error(self, error: str) -> None:
self._show(
"There was an error while handling a dns query.",
f'Error message: "{error}"',
is_... | The code processes DNS record queries by validating command-line arguments, parsing them into a namespace, executing a DNS query, and displaying either the result or an error message based on the query's outcome. | def run(self, args: List[str]) -> None:
self._validate_args(args)
namespace = self.parser.parse_args(args)
result: DNSRecordResponse = self.query( # type: ignore
entry=DNSRecordQuery(
domain_name=namespace.domain,
many=namespace.many,
... |
def add_new_number(grids, N, row, col):
# puts 0 in every grid in the place of the new number
# and puts 10 for the corresponding grid
grids[0][row, col] = N
grids[N][row, col] = 10
for n in range(1, 10):
if n != N:
grids[n][row, col] = 0
else:
r0_cell = int(r... | This code solves a Sudoku puzzle by initializing multiple grids to track possible values, propagating constraints through functions like `add_new_number`, and iteratively applying logic to eliminate possibilities until the grid is fully solved. | def solve(sudoku_grid):
print('Unsolved grid:')
print(sudoku_grid)
grids = []
for _ in range(10):
grids.append(np.ones((9, 9), dtype=np.int) * (-1))
grids[0] = sudoku_grid
for n in range(1, 10):
idx = np.where(grids[0] == n)
R, C = idx
grid = grids[n]
fo... |
def dubins_LSL(dub_ir, out):
temp = dub_ir.d + dub_ir.sa - dub_ir.sb
p_sq = 2+dub_ir.d_sq - (2*dub_ir.c_ab) + (2*dub_ir.d * (dub_ir.sa - dub_ir.sb))
if p_sq>=0:
temp1 = math.atan2((dub_ir.cb - dub_ir.ca),temp)
out = (mod2pi(temp1-dub_ir.alpha),
math.sqrt(p_sq),
... | This function selects and executes a specific Dubins path planning algorithm based on the provided `path_type` (e.g., LSL, RSL, LSR, etc.), passing `dub_ir` and `out` parameters to the corresponding method. It returns the result of the chosen algorithm or `-1` if the `path_type` is invalid. | def dubins_word(dub_ir,path_type,out):
result = -1
if path_type == dubins_path_type["LSL"]:
result = dubins_LSL(dub_ir,out)
elif path_type == dubins_path_type["RSL"]:
result = dubins_RSL(dub_ir,out)
elif path_type == dubins_path_type["LSR"]:
result = dubins_LSR(dub_ir,out)
el... |
def get_time(start_time):
current_time = time.time() - start_time
return current_time
def motionGradient(traj, dt):
return abs(traj[0]-traj[-1])/dt
def user_input():
while True:
ans = input("Continue ? y/n/reboot : ")
if ans == "n":
reboot()
stop_motors()
... | The function `singleAct` controls a motor to move an actuator along a specified trajectory, recording position and time data. It adjusts motor operating mode, calculates motion gradients, and iteratively updates the motor position while monitoring its status. The movement direction and trajectory endpoints are determin... | def singleAct(motor_object, torque_motor, traj, dt, forward, start_time):
"""change position of one actuator with a given speed """
# INITIALIZATION
data_pos = [[], []]
data_pos_torque = [[], []]
# MOTORS
if motor_object.get_operating_mode() == motor_object.CURRENT_CONTROL_MODE:
motor_ob... |
def user_input():
while True:
ans = input("Continue ? y/n/reboot : ")
if ans == "n":
reboot()
stop_motors()
sys.exit("EXIT PROGRAM")
elif ans == "y":
break
elif ans == "reboot":
reboot()
else:
print("This... | The code controls two motors (motor_L and motor_R) to follow a trajectory through alternating clockwise and anticlockwise motions, collecting position data during manipulation phases. It initializes motor positions, executes sequential movements with specific timing and control modes, stores position lists in dictionar... | def controlRolling(motor_L, motor_R, traj):
#### PUT THE FINGERS AT THEIR INITIAL POSITION ####
# INITIALIZATION DATA
data_pos_L = [[], []]
data_pos_R = [[], []]
dict_pos = {}
clockwise = True
anticlockwise = False
# INITIALIZE THE GRASP
user_input()
dt = 50
graspManip(moto... |
def controlRolling(motor_L, motor_R, traj):
#### PUT THE FINGERS AT THEIR INITIAL POSITION ####
# INITIALIZATION DATA
data_pos_L = [[], []]
data_pos_R = [[], []]
dict_pos = {}
clockwise = True
anticlockwise = False
# INITIALIZE THE GRASP
user_input()
dt = 50
graspManip(moto... | The code processes trajectory data from two devices, retrieves position data, and prompts the user to either store the data with a filename and plot it, or plot the results directly. It handles user input to decide storage, plotting, or exit, ensuring data is visualized based on user choice. | def manipulate(dxl_traj):
""" perform the manipulation and store the date given the user input"""
[data_pos_L, data_pos_R, data_pos_trial] = controlRolling(my_dxl_L, my_dxl_R, dxl_traj)
while True:
ans = input ("Do you want to store the data (y/n) or just plot 'plot'?")
if ans == "y":
... |
def predict(logits, threshold):
probs = logits
predictions = []
for idx in range(probs.size(0)):
output = []
for l in range(0, probs.size(1)):
if probs[idx, l] >= threshold:
output.append(l)
if len(output) == 0:
output.append(torch.argmax(probs... | The function trains a model for multi-label or single-label classification using specified data loaders and hyperparameters. It performs forward passes, computes loss with a given function, and optimizes the model using Adam. During validation, it evaluates performance using F1-score and thresholds, saving the best mod... | def train(model, train_dataloader, val_dataloader, learning_rate, tokenizer, max_len, epochs, checkpoint_name, grad_acu_steps, labels_to_id, thresholds_multi_label, default_threshold, loss_func):
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
optimizer = Adam(mode... |
def Greeting(intent_request):
session_attributes = get_session_attributes(intent_request)
text = "Hi there, I'm your dining concierge, what can I help you with today?"
message = {
'contentType': 'PlainText',
'content': text
}
fulfillment_state = "Fulfilled"
retur... | The code routes incoming intent requests to specific handler functions based on the detected intent name (e.g., Greeting, DiningSuggestions, ThankYou). It extracts the intent name from the request, logs debug information, and conditionally invokes the corresponding function. If the intent is unrecognized, it raises an ... | def dispatch(intent_request):
intent_name = intent_request['currentIntent']['name']
logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name']))
# Dispatch to the bot's intent handlers
logger.debug('intent:{}'.format(intent_name))
if int... |
def reposToConstraints(self, Ps):
for i in range(len(Ps)):
indices=Ps[i]<self.cons[:,0]
# print(indices)
Ps[i][indices]=self.cons[:,0][indices]
indices=Ps[i]>self.cons[:,1]
Ps[i][indices]=self.cons[:,1][indices]
return Ps
def greedySelect(self, old_pos, new_pos):
old_objs=self.... | This function updates food source positions in a swarm optimization algorithm by randomly adjusting positions toward a target, applying constraints, greedily selecting improved positions, updating the algorithm's state, and tracking unselected positions to refine search efficiency. | def beesRoutine(self, target=None):
assert(not target is None)
r1=np.random.random_sample((len(self.food_pos),1))
new_pos=self.food_pos+r1*self.acceleration*(target-self.food_pos)
new_pos = self.reposToConstraints(new_pos)
selected_idx = self.greedySelect(self.food_pos, new_pos)
self.food_pos[se... |
def beesRoutine(self, target=None):
assert(not target is None)
r1=np.random.random_sample((len(self.food_pos),1))
new_pos=self.food_pos+r1*self.acceleration*(target-self.food_pos)
new_pos = self.reposToConstraints(new_pos)
selected_idx = self.greedySelect(self.food_pos, new_pos)
self.food_pos[se... | This code implements a bee colony optimization algorithm with Comprehensive Learning (CL) strategy. It iteratively updates food positions via employed bees, onlooker bees (using CL masks to combine EA solutions), and scout bees (replacing outdated positions). The process explores solutions, applies CL to enhance learni... | def train(self, iters):
for _ in range(iters):
# employed bees
self.beesRoutine(target=self.food_pos)
# onlooker bees
# prepare Comprehensive Learning
target_m=self.EA[np.random.randint(len(self.EA), size=len(self.food_pos))]
target_notm=np.array([self.EA[np.random.choice(np.a... |
def displayStudents(self):
self.displayClasses()
classid = int(input('Class: '))
students = self.db.getStudentsByClassId(classid)
print("Students List")
for std in students:
print(f'{std.id}-{std.name} {std.surname}')
return classid
def addStudent(sel... | The code defines a menu-driven application for managing students and teachers. It displays options to list students, add/update/delete students, add teachers, view class lessons, or exit. The loop continuously prompts user input, executing corresponding methods based on the selected option until 'E' is chosen to exit. | def initApp(self):
msg = "*****\n1-Students List\n2-Add Student\n3-Update Student\n4-Delete Student\n5-Add Teacher\n6-Class Lessons\n7-Exit(E)"
while True:
print(msg)
option = input("Option: ")
if option == '1':
self.displayStudents()
elif ... |
def clear_form(_) -> None:
if form_select.value == "Product":
code_tf.value = ""
category_tf.value = ""
description_tf.value = ""
quantity_tf.value = ""
moq_tf.value = ""
elif form_select.value == "Order":
order_id_tf.value = ""
... | The main task of the code is to refresh a UI page by clearing the form, refreshing the table data, executing a search if the search table is visible, and updating the page interface. | def refresh_page(_) -> None:
clear_form(_)
refresh_table(_)
if search_data_table.visible:
search(_)
page.update() |
def int_check(value) -> str | int:
try:
return int(value)
except ValueError:
return str(value)
def presence_check(query, params) -> bool:
cursor.execute(query, params)
if cursor.rowcount > 0:
return True
else:
return False
def try_c... | The main task of the code is to either update existing product data in a database or insert new product records, including category, description, quantity, and minimum order quantity (MOQ), while maintaining stock balance calculations. It checks for existing product codes, updates relevant tables if present, or inserts... | def add_product_data(_) -> None:
code = str(code_tf.value)
category = int_check(category_tf.value)
description = str(description_tf.value)
quantity = int_check(quantity_tf.value)
moq = int_check(moq_tf.value)
if presence_check("SELECT * FROM products WHERE code = %s", (co... |
def obtain_moq(code) -> int:
cursor.execute(
"SELECT moq FROM stock_levels WHERE code = %s",
(code,),
)
return int(cursor.fetchone()[0])
def presence_check(query, params) -> bool:
cursor.execute(query, params)
if cursor.rowcount > 0:
return Tru... | This function adds an order to a database by validating input data (product code, customer name, and quantity against MOQ), inserting the order if valid, updating stock levels and balances, handling errors via rollback, and refreshing the page. | def add_order_data(_) -> None:
code = str(code_tf.value)
name = str(name_tf.value)
if str(order_quantity_tf.value).isnumeric() and code != "":
if int(order_quantity_tf.value) >= obtain_moq(code):
quantity = int(order_quantity_tf.value)
else:
... |
def presence_check(query, params) -> bool:
cursor.execute(query, params)
if cursor.rowcount > 0:
return True
else:
return False
def try_commit(query, params) -> None:
try:
cursor.execute(query, params)
connection.commit()
except psy... | This function adds or updates customer data in a database. It retrieves name and address from text fields, checks if the customer exists via a SELECT query, and either updates the address or inserts a new record. Finally, it refreshes the page to reflect changes. | def add_customer_data(_) -> None:
name = str(name_tf.value)
address = str(address_tf.value)
if presence_check("SELECT * FROM customers WHERE name = %s", (name,)):
try_commit(
"UPDATE customers SET address = %s WHERE name = %s", (address, name)
)
el... |
def int_check(value) -> str | int:
try:
return int(value)
except ValueError:
return str(value)
def presence_check(query, params) -> bool:
cursor.execute(query, params)
if cursor.rowcount > 0:
return True
else:
return False
def obtai... | This function removes an order by checking its existence, updating stock levels and balances, then deleting the order. It retrieves the order's code, quantity, and on-order status, adjusts stock levels by subtracting the order quantity, updates the stock balance, and deletes the order record. If the order doesn't exist... | def remove_order_data(_) -> None:
order_id = int_check(order_id_tf.value)
if presence_check("SELECT * FROM orders WHERE order_id = %s", (order_id,)):
cursor.execute("SELECT code FROM orders WHERE order_id = %s", (order_id,))
code = str(cursor.fetchone()[0])
on_order =... |
def run_ci(self, test):
all_tests = {
"cputest": self.__get_ci_cputest,
"riscv-tests": self.__get_ci_rvtest,
"misc-tests": self.__get_ci_misc,
"mc-tests": self.__get_ci_mc,
"nodiff-tests": self.__get_ci_nodiff,
"microbench": self.__am_apps_... | The code executes tasks based on command-line arguments. It prioritizes CI/CI-VCS actions, then processes a sequence of conditional operations like generating Verilog code, building simulations, running workloads, or cleaning. It iterates through valid actions, executing them in order and returning the first non-zero r... | def run(self, args):
if args.ci is not None:
return self.run_ci(args.ci)
if args.ci_vcs is not None:
return self.run_ci_vcs(args.ci_vcs)
actions = [
(args.generate, lambda _ : self.generate_verilog()),
(args.vcs_gen, lambda _ : self.generate_sim_ve... |
def _download(self) -> None:
response = requests.get("https://figshare.com/ndownloader/files/11826395", stream=True)
download_filepath = self.base_folder.joinpath(self._RESOURCES['compress'][0])
total_size = int(response.headers.get('content-length', 0))
with tqdm(total... | This code initializes a dataset class for the UMAFall fall detection dataset, handling download, extraction, and preprocessing. It checks for required files, downloads/verifies the dataset, extracts it if needed, preprocesses data for training, and loads the processed dataset into a DataFrame for use in machine learnin... | def __init__(
self,
split: str = "train",
sr: int = 20,
window: set = (10, 0.5),
location: list = ["Wrist"],
download: bool = False
) -> None:
super().__init__()
self.download = download
self.location = location
# sampling... |
def _generate_locations(self):
locations = []
existing_coord = set()
for i in range(20):
for type in LocationType.text_to_entry.values():
x_coord, y_coord = (random.randint(0, 20), random.randint(0, 20))
while (x_coord, y_coord) in existing_coord:
... | The `generate_world` method initializes a game world by creating locations, mobs, items, distributing items across locations, and establishing paths between them to form a cohesive environment. | def generate_world(self):
self._generate_locations()
self._generate_mobs()
self._generate_items()
self._distribute_items()
self._create_paths() |
def funcGenData(df, noAtt):
tempData = np.zeros((1, df.shape[1]))
for k in range(0, df.shape[1]-1):
fe_type = ''
fe_type = df.dtypes[k]
fe_type = str(fe_type)
min_val = df.iloc[:, k].min()
max_val = df.iloc[:, k].max()
if('int' in f... | The function `funcgenerateTestData` generates a synthetic test dataset of 4500 unique samples from the input DataFrame `df`, ensuring no duplicates by checking each generated sample against the test matrix. It writes the resulting test data to a CSV file named `TestingData.csv` and calls `generateTestTrain` to create t... | def funcgenerateTestData(df):
#df.drop('Class', axis=1, inplace=True)
#Fixing no. of test data
#tst_pm = round(0.9*df.shape[0])
MAX_ORACLE = 5000
tst_pm = round(0.9*MAX_ORACLE)
testMatrix = np.zeros(((tst_pm+1), df.shape[1]))
#testMatrix = [0]* 2000
noOfAttributes = df.shape[1]-1
... |
def funcgenerateTestData(df):
#df.drop('Class', axis=1, inplace=True)
#Fixing no. of test data
#tst_pm = round(0.9*df.shape[0])
MAX_ORACLE = 5000
tst_pm = round(0.9*MAX_ORACLE)
testMatrix = np.zeros(((tst_pm+1), df.shape[1]))
#testMatrix = [0]* 2000
noOfAttributes = df.shape[1]-1
... | (The code verifies a model's monotonicity by iteratively generating counterexamples using Z3, pruning data, and retraining a decision tree. It checks if model predictions align with the tree, tracks non-monotonic cases, and returns their ratio relative to total samples. The process uses oracle data, logical constraints... | def funcMain(model, df, noOfFe, MAX_SAMPLES):
#Initializing counts
count = 0
nmon_count = 0
retr_count = 0
cexSet = ()
with open('typeMonfile.txt') as fileCond:
type_file_content = fileCond.readlines()
type_file_content = [x.strip() for x in type_file_content]
if((ty... |
def rmove():
dir = './output/align/'
for f in os.listdir(dir):
os.remove(os.path.join(dir, f)) # Remove files in align directory
dir = './output/eulerian/'
for f in os.listdir(dir):
os.remove(os.path.join(dir, f)) # Remove files in eulerian directory
dir = './output/graph/'... | The code processes genomic data from a FASTQ file, allowing users to analyze sequences via k-mer analysis. It handles three modes: single k-mer with read range (-l), k-mer range (-k), or both (-kl). The main task involves extracting input parameters, loading genome data, and executing k-mer-based processing loops to se... | def main():
# ----------------------------------------------------------------------------------------------------------
# User enters prefered file
if(len(sys.argv) == 2):
rmove()
inpt = sys.argv[1] # Extracting fastq file name from arguments
... |
def _check_events(self):
"""
Responds to keypresses and mouse clicks; checks if quit.
"""
# Track user actions (event) with event for loop
for event in pygame.event.get(): # list of events
# If user quits, exit game
if event.type == pygame.QUIT:
... | The main task of the code is to execute a game loop that continuously checks for events, updates game elements (ship and bullets), removes off-screen bullets, redraws the screen, and maintains a 60 FPS frame rate. It ensures smooth gameplay by iterating through bullets to clean up out-of-bound projectiles while trackin... | def run_game(self):
"""
Starts game loop, redrawing Pygame surface on every pass and
updating screen on each pass.
"""
while True:
# Check game events and respond accordingly to event.
self._check_events()
self.ship.update()
self._... |
def get_out_degree(self, entity: Entity) -> int:
return len(self.get_out_edges(entity))
def has_similar_relation(self, relation: Relation, threshold=0.8) -> bool:
for candidate_relation in self.relations:
if (
self.similarity_function(relation["head"], candidate_relation["hea... | The function refines implicit entity links by iteratively selecting entities with the lowest out-degree, finding the most similar entity, computing their embedding difference, and adding a new implicit relation if it doesn't already exist. This process continues until fewer than two entities remain, aiming to identify ... | def refine_implicit_links(self):
if len(self.entities) < 2:
return
entities = list(self.entities.values())
while len(entities) > 1:
entities.sort(key=lambda e: self.get_out_degree(e))
lowest_degree = entities.pop(0)
entities.sort(
... |
def write_log(self, log_text):
""" Write log by print() or logger """
if self.log_mod == 0:
try:
now_time = datetime.datetime.now()
print(now_time.strftime("%d.%m.%Y_%H:%M") + " " + log_text)
except UnicodeEncodeError:
print("Your... | This function automates unfollowing users based on a scheduled interval and daily limit. It checks if the current time exceeds the next allowed unfollow time and if daily unfollows remain. In mode 0, it logs and executes unfollows, updating the cooldown. In mode 1, it triggers a protocol-specific unfollow process. The ... | def new_auto_mod_unfollow(self):
if time.time() > self.next_iteration["Unfollow"] and self.unfollow_per_day != 0:
if self.bot_mode == 0:
log_string = "Trying to unfollow #%i: " % (self.unfollow_counter + 1)
self.write_log(log_string)
self.auto_unfollow... |
def get_media_id_by_tag(self, tag):
""" Get media ID set, by your hashtag """
if self.login_status:
log_string = "Get media id by tag: %s" % (tag)
self.write_log(log_string)
if self.login_status == 1:
url_tag = self.url_tag % (tag)
try... | This function automates social media interactions within a specified time window. It repeatedly checks the current time, and if within start/end hours, performs actions like fetching media by tags, liking, following, unfollowing, and commenting. It manages like counts to avoid overuse and sleeps for 3 seconds between i... | def new_auto_mod(self):
while True:
now = datetime.datetime.now()
if (
datetime.time(self.start_at_h, self.start_at_m) <= now.time()
and now.time() <= datetime.time(self.end_at_h, self.end_at_m)
):
# ------------------- ... |
def parse(puzzle_input):
return puzzle_input.split('\n')
def part1(data):
sum = 0
for i, line in enumerate(data):
id = i+1
if (not anyColorCountsOver(line)):
sum = sum + id
return sum
def part2(data):
sum = 0
for line in data:
games = line.split(':')[1]
... | The code solves a puzzle by parsing input data, computing two distinct solutions using part1() and part2() functions, then returning both results as a tuple. The main task involves processing input, executing separate solution logic for each puzzle part, and aggregating outputs. | def solve(puzzle_input):
"""Solve the puzzle for the given input."""
data = parse(puzzle_input)
solution1 = part1(data)
solution2 = part2(data)
return solution1, solution2 |
def parse(puzzle_input):
lines = puzzle_input.split('\n')
seeds = [int(i) for i in (lines[0].split('seeds: ')[1]).split()]
seedToSoil, index = getAlmanacMap(lines, 2)
soilToFertilizer, index = getAlmanacMap(lines, index)
fertilizerToWater, index = getAlmanacMap(lines, index)
waterToLight, index... | The code solves a puzzle by parsing input data into seeds and conversion maps between soil, fertilizer, water, light, temperature, humidity, and location. It computes two solutions: part1 finds the minimum location value for individual seeds using the mappings, while part2 determines the minimum location for seed range... | def solve(puzzle_input):
"""Solve the puzzle for the given input."""
seeds, seedToSoil, soilToFertilizer, fertilizerToWater, waterToLight, lightToTemperature, temperatureToHumidity, humidityToLocation = parse(puzzle_input)
solution1 = part1(seeds, seedToSoil, soilToFertilizer, fertilizerToWater, waterToLigh... |
def diference(self,rootL,rootR):
heightL = 0
heightR = 0
if rootL != None:
heightL = rootL.height
if rootR != None:
heightR = rootR.height
return heightL - heightR
def rightRotation(self,root):
global rotCounter
rotCounter+=1
child=root.L
root.L = child.R
child.R = root
root = self.updateHei... | This code checks the balance of an AVL tree node after insertion. It performs rotations (left/right/left-right/right-left) to rebalance the tree if the height difference between left and right subtrees exceeds 1, ensuring the tree remains height-balanced. | def checkDiference(self,root,insertedWord):
if self.diference(root.L,root.R) > 1:
if insertedWord < root.L.word:
root = self.rightRotation(root)
elif root.L.word < insertedWord :
root = self.leftRightRotation(root)
elif self.diference(root.L,root.R) < -1:
if insertedWord < root.R.word:
root ... |
def updateHeight(self,root):
heightL = 0
heightR = 0
if root.L != None:
heightL = root.L.height
if root.R != None:
heightR = root.R.height
root.height = 1 + max(heightL,heightR)
return root
def checkDiference(self,root,insertedWord):
if self.diference(root.L,root.R) > 1:
if insertedWord < root.L... | This function inserts a word into an AVL tree, appending line numbers if the word already exists. It recursively places the word in the correct position based on lexicographical order, updates node heights, and checks for balance to maintain AVL properties. | def insert(self, root, word, line):
if root == None:
return Node(word,line)
elif word < root.word:
root.L = self.insert(root.L,word,line)
elif root.word < word:
root.R = self.insert(root.R,word,line)
else:
if line not in root.line:
root.line.append(line)
root = self.updateHeight(root)
root =... |
def getAngle(a, b, c):
ang = math.degrees(math.atan2(c[1]-b[1], c[0]-b[0]) - math.atan2(a[1]-b[1], a[0]-b[0]))
if ang<0:
ang += 360
if ang >180:
ang = 360 - ang
return ang
def check_angles(angles):
Shoulder_Elbow_Wrist = None
Hip_Shoulder_Elbow = None
Knee_Hip_Shoulder = Non... | The code processes a frame's pose data to detect body angles, validate form for push-ups, track movement states (up/down), increment a counter on valid transitions, and provide real-time feedback via messages. It filters low-confidence points, calculates angles for pose correctness, checks starting positions, and ensur... | def process_frame(frame):
global CURRENT_STATE
global LABLES
global RIGHT_INDX
global LEFT_INDX
global ANGLES
global LAST_STATE
global STATES
global COUNTER
pose = frame['pose']
pose = { k:v for k,v in pose.items() if v['score']>=0.2 }
right_pose = { k:v for k,v in pose.ite... |
def find_remaining_ROIs(self):
#purpose of this funciton is to get the dictionary with roi filenames and coords for cropping
time.sleep(0.5)
print("Okay, I will locate ROIs of first folder for best match search:")
time.sleep(1)
folder = self.directory
initial_template = s... | The main task of the code is to align and process the best images by organizing ROI data, creating a dedicated folder for processed results, and executing alignment operations on selected files. It checks if a decision flag is set, preprocesses data, structures file paths, ensures a clean output directory, and triggers... | def align_best(self):
time.sleep(0.5)
if self.decision == 1:
if self.decision == 1:
#get dict of names of template ROIS and their coords
self.find_remaining_ROIs()
first_folder_values = self.results
self.find_best_results()
... |
def parseRequestLine(self, line):
try:
self.method, self.path, self.protocol = line.split(' ')
except:
self.method = ''
self.path = ''
self.protocol = ''
self.method = self.method.strip()
self.path = self.path.strip()
self.protocol ... | The code parses HTTP request data by splitting the input into headers and body, then processes each part using methods like parseRequestLine, parseHeaders, parseBody, parseParams, and parseBoundary to extract and handle request components such as the request line, headers, body content, parameters, and boundary markers... | def parse(self):
temp = self.data.split('\r\n\r\n')
lines = temp[0].split('\r\n')
body = ''
for i in range(1,len(temp)):
body += temp[i]+ '\r\n\r\n'
lines.append(body)
self.parseRequestLine(lines[0])
self.parseHeaders(lines[1:-1])
self.parseBod... |
def oneD():
realization = simulate([0.05, 0.1, 0.01])
d = [["S","I",expected(1,2, realization), 20],
["S","R",expected(1,3, realization), 30],
["S","S",expected(1,1, realization), 130]]
df = pd.DataFrame(d,columns=[" From "," To "," Simulated ", " Analytical "])
print(" ... | The code defines a main function that acts as a menu-driven interface, allowing users to select tasks (e.g., 1d, 1f, 1g, etc.) to execute corresponding functions. It handles user input, invokes specific operations, and outputs results, such as calculating expected values and variances for task 2b. The loop continues un... | def main():
print("What task do you want to see? Type")
print("1d")
print("1f")
print("1g")
print("1h")
print("2a")
print("2b")
print("q to quit\n")
while True:
np.random.seed(1) # Note: We set a seed so that you'll get the same realization as us, comment out to reinstate ran... |
def task1c():
allStates = simCold()
plotStates(allStates)
def task1d():
allStates = simCold()
longRun(allStates)
def task1e():
allStates = simCold()
print("Average time between heavy infections: ")
print("One realization: ", countBetween(allStates))
N = 1000
timeAtStart = time.time(... | The main task is to provide a menu-driven interface allowing users to select and execute specific tasks (1c, 1d, 1e, 2a, 2b, 2c) or quit. It uses a loop to repeatedly prompt for input, calls corresponding functions based on user choice, and includes a fixed random seed for reproducibility. The 'q' option exits the loop... | def main():
print("What task do you want to see? Type")
print("1c")
print("1d")
print("1e")
print("2a")
print("2b")
print("2c")
print("q to quit\n")
while True:
np.random.seed(23) # Note: We set a seed so that you'll get the same realization as us, comment out to reinstate r... |
def Generate():
global ei,ej
#set all cells in grid to unvisited
for i in range(0, height):
line = []
for j in range(0, width):
line.append("u")
maze.append(line)
#random starting point that isn't in one of the four corners
s_height = int(random.random()*heig... | This code visualizes pathfinding algorithms (BFS, DFS, A*, Dijkstra) on a maze using Pygame. It prompts the user to select an algorithm, generates a maze, executes the chosen algorithm to find a path, and dynamically displays the search process by redrawing the maze and path in real-time. Global variables manage the wi... | def main():
alg = int(input("What algorithm do you want to visualise?\nBFS (1)\nDFS (2)\nA* (3)\nDijkstra (4)\n"))
global WINDOW,a,matrix,path,fpsClock,times
WINDOW = pg.display.set_mode([(width*g_width),(height*g_height)])
WINDOW.fill(GRAY)
fpsClock = pg.time.Clock()
running = True
don... |
def __init__(self, settings, parent=None):
super().__init__(parent)
self.signals = self.Signals()
self.parent_obj = parent
self.ui = Ui_SettingsDialog()
self.ui.setupUi(self)
self.ui.saveButton.clicked.connect(self.saveButtonClick)
self.ui.cancelButton.clicked.con... | This code initializes a MainWindow by loading UI components, reading version information from a JSON file, configuring settings, setting the window icon, connecting button signals to functions, creating a thread pool, setting up a status timer, and restoring window geometry/state from settings. It prepares the applicat... | def __init__(self):
super(MainWindow, self).__init__()
#Load UI Components
self.setupUi(self)
#Read Version File From Resources
version_file = QFile(":version.json")
version_file.open(QFile.ReadOnly)
text_stream = QTextStream(version_file)
version_file_te... |
def __check_for_matching_grids(forecast_table_xarray, aux_data_matrix):
"""Checks for matching grids between xarray table and numpy matrix.
This method can only check for matching grid *shapes* -- not precisely
matching grids -- since numpy arrays do not carry metadata about the grid.
M = number of ro... | The function calculates Storm Relative Helicity (SRH) by interpolating wind data to specified heights, adjusting for storm motion, and integrating helicity values over vertical layers. It returns positive and negative helicity matrices for each height, along with storm motion components and surface pressures. The proce... | def get_storm_relative_helicity(
forecast_table_xarray, do_multiprocessing, top_heights_m_agl,
surface_geopotential_matrix_m2_s02,
surface_pressure_matrix_pascals=None):
"""At each horizontal grid point, converts SRH from sfc to a given height.
Emulating helicity() from winds.py in the ... |
def make_binary_tree():
print("Creating binary tree")
tree_nodes[0] = [1,10,19,28,37]
create_child_nodes(0,0)
def assign_starting_index_of_level():
sum = 0
global tree_depth
for level in range(int(tree_depth + 1)):
level_starting_index.append(int(sum))
sum = sum + 2**level
def cl... | The main task of the code is to classify a given time series input (`test_time_series`) using a pre-built binary tree structure. It initializes the tree, assigns level indices, and applies the classification to return two results (`z` and `y`), likely representing class labels or predictions. | def main_function(test_time_series):
make_binary_tree()
assign_starting_index_of_level()
z,y = classify_time_series(test_time_series)
return z,y |
def check_availability(branch_long_name, book_isbn):
"""
Returns the number of copies of the selected book based on
the user's branch.
"""
select_num_copies = (
"select numCopies from BookCopy where libraryID = %s and bookID = %s;"
)
branch_short_name = retrieve_branch_short_name(bra... | The function processes a book return by updating the book's copy count in the branch's inventory and marking the checkout record as returned. It checks the branch's current copy count, increments it if existing, or inserts a new entry if none. It updates the checkout's return date and checks for overdue status, handlin... | def return_book(book_data, branch_long_name, username):
isbn = book_data["isbn"]
num_copies = check_availability(branch_long_name, isbn)
branch_short_name = retrieve_branch_short_name(branch_long_name)
if num_copies > 0:
update_numcopies = (
"update BookCopy set numCopies = %s where... |
def search_for_path(start_node, target_node):
path_from_start = []
path_from_target = []
# finds path from target node back to origin
previous = target_node.get_previous()
while (not previous.is_target(node_list[0].get_vector())):
path_from_target.append(previous)
previous = previo... | The main task of the code is to navigate from the current node to a target node by first finding a path, then iteratively checking if a direct line-of-sight exists between the current and target nodes. If so, it moves directly to the target; otherwise, it progresses step-by-step through intermediate nodes in the path, ... | def path_to_node(target_node):
global current_node
path = search_for_path(current_node, target_node)
for node in path:
if (check_los(current_node, target_node)):
move_to_node(target_node)
current_node = target_node
break
else:
move_to_node(node... |
def check_los(start_node, target_node):
#check LoS between current node and another node
move_vector = target_node.get_vector() - start_node.get_vector()
turn_to(vector_to_bearing(move_vector))
if (sensing.get_distance() >= vector_to_distance(move_vector)):
start_node.add_connection(target_node... | The code evaluates a path to a target node by iteratively checking line-of-sight, exploring unexplored nodes, and selecting the best connected or explored node based on scores. It maintains a search count, tracks explored nodes, and adjusts the current node until a direct path to the target is found or the optimal rout... | def evaluate_path(target_node):
path = []
global current_node
path.append(current_node)
global node_list
global explored_list
no_path = True
searches = 0
while (no_path):
searches += 1
if (check_los(current_node, target)):
move_to_node(target_node)
... |
def personalize_template(self) -> Folder:
template = self.settings.template
# Add the makefile_template to the files list of the DEFAULT_TEMPLATE
name = self.settings.name
template.name = template.name.replace("{{name}}", name)
for tfile in template.files:
tfile.con... | The code initializes a project by creating a directory structure based on a personalized template at a specified path. It checks for existing directories (unless forced) and creates them, logs the action, generates necessary folders, and optionally initializes a Git repository with initial commits if configured. | def __call__(self) -> None:
"""
Initialize a project with the specified parameters.
"""
path = self.settings.path
template = self.personalize_template()
root = path / template.name
if not self.settings.force:
self.check_path(root)
root.mkdir(... |
def tcl_menu():
choice = '0'
while choice == '0':
print("SubMenu Choice: Choose 1 of 3 choices")
print("Choose 1 for Tclsh w/ local files")
print("Choose 2 for Tclsh w/ hosted dylibs")
print("Choose 3 to exit")
choice = input("Please make a choice: ")
if choice ... | This script is a macOS initial access payload generator that creates various malicious payloads through a menu system. It offers 12 options, including installer packages, mobile configurations, Office macros, disk images, and more. The code creates a 'Payloads' directory, displays a choice menu, and routes users to spe... | def main():
print("Mystikal: macOS Initial Access Payload Generator")
Path("./Payloads/").mkdir(parents=True, exist_ok=True)
choice = '0'
while choice == '0':
print("Main Choice: Choose 1 of 12 choices")
print("Choose 1 for Installer Packages")
print("Choose 2 for Mobile Configur... |
def reverse_atoms_in_cluster(possibilities):
for rot in range(len(possibilities)):
for atom in range(len(possibilities[rot])):
if possibilities[rot][atom] == 'Cu':
possibilities[rot][atom] = 'Ni'
else:
possibilities[rot][atom] = 'Cu'
return possibi... | The function `compute` generates clusters by first creating a list of all clusters using `creating_list_of_all_clusters(a, b)`, then appending reversed versions of these clusters via `reverse_atoms_in_cluster`. The combined clusters are normalized using `normalize_db` and returned. The parameters `a` and `b` (default 0... | def compute(a=0,b=7):
r_clusters = reverse_atoms_in_cluster(creating_list_of_all_clusters(a,b))
clusters = creating_list_of_all_clusters(a,b)
clusters += r_clusters
clusters = normalize_db(clusters)
return clusters |
def getFontDetails(link):
pdf = PdfFileReader(link)
fonts = set()
embedded = set()
for page in pdf.pages:
obj = page.getObject()
f, e = walk(obj['/Resources'], fonts, embedded)
fonts = fonts.union(f)
embedded = embedded.union(e)
unembedded = fonts - embedded
fo... | The function processes an uploaded PDF file by extracting font details and text data, matches font names to determine embedding status, and returns PDF metadata along with updated font information in a JSON response. | def getFontData(request):
link=io.BytesIO(request.FILES['file'].read())
font1=getFontDetails(link)
font2=getTextData(link)
for i in range(0, len(font2)):
for j in range(0, len(font1)):
if (font2[i]['name'] == font1[j]['name']):
font2[i]['embedded'] = font1[j]['embed... |
def get_root(self) -> AVLNode:
"""
returns the root of the tree representing the dictionary. \n
Complexity: O(1).
:return: the root, None if the dictionary is empty.
"""
return self.root
def tree_position(self, new_node_key: int) -> AVLNode:
"""
Finds insertion position of a node with a given key new_no... | This function inserts a key-value pair into an AVL tree, maintaining balance through rebalancing operations. It returns the count of rebalancing steps performed. The insertion uses tree_position to find the parent node, attaches the new node as left/right child, updates attributes, and triggers balancing starting from ... | def insert(self, key: int, val) -> int:
"""
inserts val at position i in the dictionary
\n
Complexity: O(log(n)) since it uses tree_position() and balance() afterward.
:param key: key of item that is to be inserted to self, @pre currently does not appear in the dictionary.
:param val: the value of the item
... |
def get_pointer_to_appropriate_subtree_with_specific_height(self, tree_root: AVLNode, requested_height: int, smaller: bool) -> AVLNode:
# complexity analysis: the method going down to a leaf, by that it does at most log(n) actions, every action cost
# O(1) and hence the complexity is O(log(n))
"""
the method se... | This method merges two AVL trees by connecting them through a middle node, considering their heights. It identifies a suitable subtree from the taller tree to match the shorter tree's height, then links the trees. If heights are equal, it directly connects them. The root is updated based on the connection, and the midd... | def choose_order_and_connect(self, smaller_tree_root: AVLNode, middle_node: AVLNode, bigger_tree_root: AVLNode):
"""
the method receive the trees and the node received in join after checking which of them has bigger keys
the method compare the height of the trees and then send the taller tree to a method that fin... |
def get_root(self) -> AVLNode:
"""
returns the root of the tree representing the dictionary. \n
Complexity: O(1).
:return: the root, None if the dictionary is empty.
"""
return self.root
def insert(self, key: int, val) -> int:
"""
inserts val at position i in the dictionary
\n
Complexity: O(log(n)) ... | The main task of the code is to merge two AVL trees (self and tree2) using a specified key and value, ensuring the combined tree maintains AVL properties. It handles edge cases where one or both trees are empty, inserts the key between the trees, and returns the absolute height difference between the original trees. Th... | def join(self, tree2, key: int, val) -> int:
"""
joins self with key and another AVLTree. \n
Complexity: O(log(n)).
\n
@pre: all keys in self are smaller than key and all keys in tree2 are larger than key
:param tree2: a dictionary to be joined with self
:param key: The key separating self with tree2
:p... |
def play_game():
global background
global bird
background = random.choice([background_1, background_2])
bird = random.choice([bird_blue, bird_red, bird_yellow])
if background == background_2:
fps = 240
else:
fps = 240
global jump
global player_y
global player_speed
global pipe_x
global pipe_y
global run... | The main task of the code is to manage a Pygame main menu loop, handling exit events (QUIT/ESC), triggering the game start via key presses, displaying high scores, and rendering background/base elements along with score text. It maintains the menu state until user interaction or exit commands terminate the loop. | def main_menu():
global run_menu
run_menu = True
while run_menu:
for event in pygame.event.get():
#Exit
if event.type == pygame.QUIT:
run_menu = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run_menu = False
else:
play_game()
import_highscore()
lo... |
def game_menu(game_board, building_pool):
turn_counter = 1
while True:
reply = isFull(game_board)
if reply is True:
endgame(game_board, building_pool)
break
# Print turn and game board
print("\nTurn " + str(turn_counter))
print_game(game_board, bu... | The code implements a menu-driven interface for a game, allowing users to start a new game, load a saved game, view high scores, adjust settings, or exit. It validates user input, handles game initialization, and manages game states by calling functions like set_game, load_file, and highscores_menu. The loop persists u... | def main():
size = None
buildings = None
while True:
print("\nWelcome, mayor of Simp City!")
print("----------------------------")
print("\n1. Start new game")
print("2. Load saved game")
print("3. Show High Scores")
print("4. Options")
print("\n0. Ex... |
def confusion(theta, sample_config, dist_config):
lst = [sample_config['n11']*(1-cdf_dist(dist_config['11_name'])(theta[0].item(), *dist_config['11'])),\
sample_config['n11']*(cdf_dist(dist_config['11_name'])(theta[0].item(), *dist_config['11'])),\
sample_config['n01']*(1-cdf_dist(dist_config['0... | The function `alternative_train` trains a model by alternately updating parameters (θ₀, θ₁) using an approximation method to minimize a loss function, balancing accuracy and fairness. It iteratively computes confusion matrices, tracks training/validation losses, accuracy, and fairness metrics, and saves the best parame... | def alternative_train(theta, train_config, valid_config, c, lamda, iter_num, verbose_iter, verbose = False, show_fig = True):
loss_path, theta_path, loss_real_path, acc_path, fair_path, bal_acc_path = [], [], [], [], [], []
loss_valid_path = []
best_loss = np.inf
A = train_config['A']
samp... |
def square_under_attack(self, r, c):
self.white_to_move = not self.white_to_move # switch to opponent's turn
opp_moves = self.get_all_possible_moves()
self.white_to_move = not self.white_to_move # switch turn back
for move in opp_moves:
if move.end_row == r and move.end_col... | This function generates possible castling moves for the king if the current square isn't under attack and castling rights exist. It checks for both kingside and queenside castling permissions, then calls respective methods to add valid castling moves to the provided list. | def get_castle_moves(self, r, c, moves):
if self.square_under_attack(r, c):
return # nothing, you cant castle if you are in check
if (self.white_to_move and self.currents_castling_rights.wks) or (
not self.white_to_move and self.currents_castling_rights.bks):
sel... |
def get_all_possible_moves(self):
moves = []
for r in range(len(self.board)): # num of rows (8)
for c in range(len(self.board[r])): # num of cols in the row (8)
turn = self.board[r][c][0]
if (turn == 'w' and self.white_to_move) or (turn == 'b' and not self.whi... | The function generates all valid moves by first creating possible moves, then simulating each to check if they leave the king in check. Invalid moves are removed, and checkmate/stalemate statuses are determined. It temporarily stores and restores en passant and castling rights during validation, ensuring accurate move ... | def get_all_valid_moves(self):
temp_enpassant_possible = self.en_passant_possible_at
temp_castle_rights = CastleRights(self.currents_castling_rights.wks, self.currents_castling_rights.bks,
self.currents_castling_rights.wqs, self.currents_castling_rights.bqs)
... |
def resolve_schema_references(schema, definitions):
"""
Resolves the references of a schema, at a single 'level'.
"""
if isinstance(schema, dict) and "$ref" in schema.keys():
schema = definitions.get(schema.get("$ref").split("/")[-1], {})
return schema
def force_array(data):
"""
Returns a list of data, even if... | The code generates an HTML document by creating structured components from schema data, including titles, documentation links, and code examples. It uses a template (base.html) and replaces a placeholder with dynamically generated content, incorporating recursive code rendering and copy functionality for examples. | def generate_html(data, definitions):
"""
Expects a dictionary containing component names and schema data
"""
components = tb.TagBuilder("div").decorate("class", "site-content")
for component_name, schema in data.get('properties').items():
schema = resolve_schema_references(schema, definitions)
component =... |
def consider_valid_flood_options(maze_copy, seen_nodes, seen_pipes, potential_directions):
valid_directions = []
for test_dir in potential_directions:
test_pos = add_coords(test_dir["pos"], test_dir["dir"])
if test_pos in seen_nodes:
continue
if { "pos": test_pos, "approach":... | The function attempts to determine if a given start position in a maze can escape by exploring valid paths, considering circuit intersections, and checking against trapped/free nodes/pipes. It traces a pathway, evaluates directional options, and checks for escape conditions or conflicts with predefined node/pipe states... | def attempt_escape(maze_copy, start_pos, circuit, trapped_nodes, free_nodes, trapped_pipes, free_pipes):
escaped = False
pathway = [start_pos]
considered_pipes = []
options = consider_valid_flood_options(maze_copy, pathway, considered_pipes, [
{"pos": start_pos, "dir": (0, 1), "qual": "R"},
... |
def read_multiple_bws(bw_files, res = 1):
all_bws = {}
open_fhandles = [pyBigWig.open(fname) for fname in bw_files]
for fname, handle in zip(bw_files, open_fhandles):
print(fname)
all_bws[fname] = bigwig_to_arrays(handle, res = res)
return (all_bws, open_fhandles)
def traveling_ratio(arr... | The code processes genomic regions from a BED file, querying multiple bigWig files to compute specified summary statistics (e.g., mean, median, TR) across regions. It handles gzip-compressed files, maps samples to filenames, applies user-defined functions, and outputs results based on parameters like resolution and NA ... | def query_main(args):
import bed_utils
inbed = bed_utils.BedFile()
inbed.from_bed_file(args.regions)
res = args.res
all_bws, open_fhandles = read_multiple_bws(args.infiles, res = res)
if args.gzip:
import gzip
if args.samp_names:
samp_to_fname = {samp_name : fname for f... |
def open_multiple_bigwigs(file_list):
out_handles = []
for inf in file_list:
out_handles.append(pyBigWig.open(inf))
return out_handles
def convert_bigwigs_to_arrays(handle_list, res = 5):
out_arrays = []
for handle in handle_list:
out_arrays.append(bigwig_to_arrays(handle, res = res)... | The code processes bigwig files from two groups (groupA and groupB) by applying specified within-group operations (e.g., mean, median) and between-group comparisons (e.g., log2ratio, subtract). It reads, converts, and combines data arrays, performs the operations, and writes the results to an output bigwig file, handli... | def multicompare_main(args):
within_operation_dict = {"mean": np.nanmean,
"median": np.nanmedian,
"max": np.nanmax,
"min": np.nanmin}
between_operation_dict ={"log2ratio": compare_log2ratio,
"add": compare_add,
"subtract": compare_subtract,
... |
def initial_setup(self):
args = self.get_program_arguments()
self.classes_of_interest = args.class_list
self.similarity_threshold = args.similar
print("\n\nThe desired classes of interest are: " + str(self.classes_of_interest))
print("The desired similarity percentage is: " + str(self.similarity_threshold... | The code automates testing of a mobile app by interacting with UI elements. It loops through interest classes, taps buttons, tracks screen changes, and manages timeouts. If a timeout occurs, it prints results and exits. It reparses elements when needed, switches interest classes upon completion, and updates a hashtable... | def test(self):
self.initial_setup()
while True:
# if timeout is set, after given time, end the script and print the screen hashtable
if not self.run_forever:
if time.time() > self.timeout:
print("Time limit excedeed.")
self.print_screens_hashtable()
break
currently_untapped_in_... |
def grab_all_names(directory):
all_csv_paths = grab_all_paths(directory)
all_names = []
for path in all_csv_paths:
name = path[46:-4]
all_names.append(name)
all_names.sort()
return all_names
def make_matrix_and_map(cat_names, size):
name_map = {}
matrix = [[0]*size for i in r... | The main task of the code is to process semiconductor data from a directory by generating matrices, categorizing information, and exporting results to CSV files for analysis. It involves creating a matrix of category relationships, bucketing pairs into groups, and generating CSV outputs for major categories, subcategor... | def main():
directory = '/Users/andeyng/Desktop/semiconductors/nxp_pmc'
cat_names = grab_all_names(directory)
matrix, name_map = make_matrix_and_map(cat_names, len(cat_names))
url_dict = map_urls(directory)
# TO DO: change the path to respective local path
matrix_path = '/Users/andeyng/Desktop/... |
def create_variable_node(self, name, parent):
assert parent is not None, \
"a variable should have at least one parent"
if parent.name in QUANTIFIER:
variable_node = Node(name)
variable_node.quantifer = parent
variable_node.scoped.extend(parent.scoped)
... | This function converts a logical formula into a dense graph structure by recursively creating nodes for variables, constants, quantifiers, negations, connectives, and functors, linking them as parent-child relationships to represent the formula's syntax and semantics. | def formula_to_dense_graph(self, formula, parent=None):
if isinstance(formula, str):
if re.match(VARIABLE_PATTERN, formula):
variable_node = self.create_variable_node(formula, parent)
return variable_node
if re.match(FUNCTOR_PATTERN, formula) or (formula ... |
def getContributingWords(self, sentence, emotion):
contributingWords = []
for word in sentence.words:
if word.hasEmotion:
if emotion in word.emotions:
contributingWords.append(word)
return contributingWords
def getNeutralReplacements(self, word, s... | The code's main task is to neutralize emotional content in a sentence by identifying emotion-related words, replacing them with neutral alternatives, and returning the adjusted text. It uses `getContributingWords` to detect relevant terms, `getNeutralReplacements` to find substitutes, and `replace_words` to apply chang... | def remove(self, sentence, source_emotion, emotion_lower_bound, adjustment_type):
replacements = {}
contributingWords = self.getContributingWords(sentence, source_emotion)
for word in contributingWords:
replacements[word.word] = self.getNeutralReplacements(word, source_emotion, emot... |
def getContributingWords(self, sentence, emotion):
contributingWords = []
for word in sentence.words:
if word.hasEmotion:
if emotion in word.emotions:
contributingWords.append(word)
return contributingWords
def getEqualIntensWithDifferentEmotion(s... | The code replaces emotion-related words in a sentence with synonyms of the target emotion while maintaining similar intensity, using predefined mappings. It identifies contributing words based on the source emotion, substitutes them with emotion-adjusted equivalents, and returns the modified sentence. | def replace(self, sentence, adjustment_type, source_emotion, target_emotion):
replacements = {}
if adjustment_type == AdjustmentType.REPLACE:
contributingWords = self.getContributingWords(sentence, source_emotion)
for word in contributingWords:
replacements[word.... |
def getContributingWords(self, sentence, emotion):
contributingWords = []
for word in sentence.words:
if word.hasEmotion:
if emotion in word.emotions:
contributingWords.append(word)
return contributingWords
def getMoreIntenseMainEmotionWord(self, ... | The code modifies a sentence by replacing words with more or less intense emotional synonyms based on the specified adjustment type (e.g., intensifying or reducing main/specific emotions), then returns the adjusted sentence as a string. | def intensify(self, sentence, adjustment_type, emotion=None):
replacements = {}
if adjustment_type == AdjustmentType.MORE_INTENSE_MAIN:
contributingWords = self.getContributingWords(sentence, sentence.getMainEmotion()[0])
print(contributingWords)
for word in contribu... |
def goto_next_turn(self, capture):
frame, frame_nb = self.goto_next(capture, self.COORDS["hourglass_area"], self.hourglass, skip_loading=True)
if frame is None:
return None, -1
return self.extract_turn(frame), frame_nb
def goto_next_battle(self, capture):
return self.goto_nex... | This code processes a video file to extract and save battle team data. It opens the video, navigates through frames to identify battles, extracts team details (pets, status, XP, stats) from each battle frame, saves the data with frame/turn context, and writes all collected team information to storage after processing. ... | def run_sync(self):
capture = cv2.VideoCapture(self.video_file)
turn, _ = self.goto_next_turn(capture)
frame, frame_nb = self.goto_next_battle(capture)
while frame is not None:
self.logger.info(f"Frame {frame_nb}: battle found")
pets, status, xps, stats = self.ext... |
def goto_next_turn(self, capture):
frame, frame_nb = self.goto_next(capture, self.COORDS["hourglass_area"], self.hourglass, skip_loading=True)
if frame is None:
return None, -1
return self.extract_turn(frame), frame_nb
def goto_next_battle(self, capture):
return self.goto_nex... | This function debugs a video by capturing frames, locating battles, extracting team data (pets, status, XP, stats), and logging details. It skips to a specified frame (minus 200), identifies the next battle, and saves extracted data without persisting images. The goal is to analyze specific video frames for battle info... | def debug(self, frame_nb=None):
capture = cv2.VideoCapture(self.video_file)
print(os.path.dirname(self.video_file).ljust(35), frame_nb)
if frame_nb:
capture.set(cv2.CAP_PROP_POS_FRAMES, frame_nb - 200)
turn, _ = self.goto_next_turn(capture)
frame, frame_nb = self.got... |
def load_data():
data_df = pd.read_json(TRAINING_DATA_PATH, lines=True)
train_df = data_df.sample(frac=1-VALIDATION_SPLIT, random_state=42)
validation_df = data_df.drop(train_df.index)
features_train, book_ratings_train, features_val, book_ratings_val, feature_columns = preprocess_data(train_df, validat... | The main task of the code is to train a machine learning model using book rating data. It loads training and validation datasets, constructs a model with input dimensions matching the features, compiles and trains the model, visualizes the training history (e.g., loss/accuracy curves), and saves the trained model to a ... | def main():
features_train, book_ratings_train, features_val, book_ratings_val = load_data()
model = build_model((features_train.shape[1],))
history = compile_and_train(model, features_train, book_ratings_train, features_val, book_ratings_val)
plot_training_history(history)
model.save(MODEL_SAVE_PAT... |
def precedent_coref_resol(doc):
entities_pn = get_entities(doc, ['OTHER_PERSON', 'ORG', 'PETITIONER', 'RESPONDENT'])
entities_precedents = get_entities(doc, ['PRECEDENT'])
precedent_breakup = split_precedents(entities_precedents)
precedent_clusters = create_precedent_clusters(precedent_breakup, thresh... | The main task of the code is to enhance a document's entity information by resolving coreferences for precedents, other persons, and statutes, then merging them while removing overlaps. It updates the document's entities and stores resolved clusters in user data for further processing. | def postprocessing(nlp_doc):
precedent_clusters = precedent_coref_resol(nlp_doc)
other_person_entites = other_person_coref_res(nlp_doc)
pro_sta_clusters, stat_clusters = pro_statute_coref_resol(nlp_doc)
all_entities = remove_overlapping_entities(nlp_doc.ents, pro_sta... |
def get_all_annotations_neighbourhood_avg(self, img, annotations):
return [self.get_annotation_neighbourhood_avg(img, anno) for anno in annotations]
def find_best_shuffle_pos(self, downscaled_img, neighborhood_avg_info, annotation):
n_avg, (h_, w_) = neighborhood_avg_info
(h, w) = (np.ceil(h_ * ... | This code performs image augmentation by generating new annotations through neighborhood averaging and downsampling. It finds optimal shuffle positions for annotations, creates multiple augmented images via morphing, and returns them with combined original and new annotations. The process involves downsizing, calculati... | def augment(self, image, annotations):
neighbourhood_avg_infos = self.get_all_annotations_neighbourhood_avg(image, annotations)
downscaled_img = cv.resize(image, None, fx=self.downscale_ratio, fy=self.downscale_ratio,
interpolation=cv.INTER_CUBIC)
new_centers_i... |
def phonenumber(self,phone_number):
phone_code = self.get_country_code(self.scrolled_listbox.selected_item)
phone_number = phone_code + phone_number
phone = PhoneNumber(phone_number)
latitude, longitude = phone.map_location()
coordinates = (latitude, longitude)
return coo... | The code handles phone number input via a textbox or dialog, validates it, and triggers map view initialization with the provided number. | def enter_pressed(self):
phone_number = self.phone_number_textbox.get().lower()
# If phone_number is not provided
if len(phone_number)<1:
dialog = ctk.CTkInputDialog(
text="Type in a phonenumber:", title="Phonenumber Register")
phonenumber = dialog.get_inp... |
def arm_gaze_pose(self):
"""
zero pose:
value: 0.0004565715789794922
, value: -3.117290735244751
, value: 3.1388797760009766
, value: 1.5720899105072021
, value: -0.0005409717559814453
, value: -1.5700340270996094
"""
arm_gaze_pose = [0.0, ... | The code's main task is to detect and grasp objects (banana/bottle) by rotating the robot's body, adjusting arm parameters based on object type, and retrying grasps up to three times if initial attempts fail. It uses predefined offsets and rotation values for each object, retracts the arm upon successful grasp, and ret... | def gaze_on_ground(self):
self.arm_gaze_pose()
body_rotations = [45, -45, -45, 45]
while True:
for angle in body_rotations:
self.rotate_body(angle, 3)
self.prev_pose = self.get_body_tform_in_vision()
# RUN DIMITR... |
def init_spot(self):
"""
Turn Spot motors on and stand up - blocks until finished
"""
self.robot.power_on(timeout_sec=20)
assert self.robot.is_powered_on(), "Robot power on failed."
command_client = self.robot.ensure_client(RobotCommandClient.default_service_name)
... | The code's main task is to control a robot (like Spot) to detect objects, navigate to specific ARUCO-marked trash bins, grasp and drop items using its arm, and return to a ready pose. It initializes the robot, uses vision to identify objects, moves to the target bin, adjusts position, opens the gripper to release the i... | def main(self):
with bosdyn.client.lease.LeaseKeepAlive(self.motion_client, must_acquire=True, return_at_exit=True):
# Turn Spot on and stand up
self.init_spot()
while 1:
ID, s_offset1, s_offset2, arm_offset, rot_val = self.gaze_on_ground()
... |
def phase_setup(ser):
"""Setup: signal baud rate, get version, and command BL enter."""
baud_detect_byte = b"U"
logging.debug("Phase:\tSetup")
# Handle the serial startup blip
ser.reset_input_buffer()
logging.debug("\tCleared startup blip")
ser.write(baud_detect_byte) # send the baud det... | This script is a command-line tool for programming Artemis boards via serial bootloader. It connects to a specified COM port, attempts to enter bootloader mode, and uploads a binary file if successful. It handles arguments for port, baud rate, file, and verbosity, and provides feedback on connection status and success. | def main():
"""Main function."""
parser = argparse.ArgumentParser(
description="SparkFun Serial Bootloader for Artemis"
)
parser.add_argument("port", help="Serial COMx Port")
parser.add_argument(
"-b",
dest="baud",
default=115200,
type=int,
help="Bau... |
def parse_arguments():
"""Parse CLI arguments."""
parser = argparse.ArgumentParser(
description="Combination script to upload application binaries to Artemis module. "
"Includes:\n"
"\t'- bin2blob: create OTA blob from binary image'\n"
"\t'- blob2wired: create wired update image ... | The main task of the code is to process a binary file into a secure blob format using parameters like authentication, encryption, and protection settings, then convert the blob into a wired image for deployment. It handles input/output file management, logging, and optional cleanup. The TODO indicates a need to link th... | def main():
"""Main function."""
# Read the arguments.
args = parse_arguments()
defs.am_set_print_level(args.loglevel)
bin2blob_process(
args.loadaddress_blob,
args.app_file,
args.magic_num,
args.crc_i,
args.crc_b,
args.auth_i,
args.auth_b,
... |
def log(message: str):
if not shared.opts.data.get('civitai_link_logging', True): return
print(f'Civitai Link: {message}')
def on_activities_list(payload: CommandActivitiesList):
payload['activities'] = civitai.activities
payload['status'] = 'success'
command_response(payload)
def on_activities_clea... | This function handles incoming commands by logging the command type, adding it to Civitai's activity records, and routing the payload to specific handler functions based on the command type (e.g., managing activities or resources). It acts as a dispatcher for different command operations, ensuring appropriate actions a... | def on_command(payload: Command):
command = payload['type']
log(f"Incoming Command: {payload['type']}")
civitai.add_activity(payload)
if command == 'activities:list': return on_activities_list(payload)
elif command == 'activities:clear': return on_activities_clear(payload)
elif command == 'acti... |
def get_resource_by_hash(hash: str):
resources = load_resource_list([])
found = [resource for resource in resources if hash.lower() == resource['hash'] and ('downloading' not in resource or resource['downloading'] != True)]
if found:
return found[0]
return None
def log(message):
"""Log a m... | This function removes a resource by verifying its hash and type, deletes the associated file if it exists, logs the removal, and reloads relevant resource lists or models based on the resource type (e.g., Checkpoint, Hypernetwork). | def remove_resource(resource: ResourceRequest):
removed = None
target = get_resource_by_hash(resource['hash'])
if target is None or target['type'] != resource['type']: removed = False
elif os.path.exists(target['path']):
os.remove(target['path'])
removed = True
if removed == True:
... |
def get_resource_by_hash(hash: str):
resources = load_resource_list([])
found = [resource for resource in resources if hash.lower() == resource['hash'] and ('downloading' not in resource or resource['downloading'] != True)]
if found:
return found[0]
return None
def log(message):
"""Log a m... | This function loads a resource by first checking if it already exists via its hash. If not, it adds the resource to a list and triggers type-specific loading functions (e.g., models, configs, hypernetworks) based on the resource type. The `on_progress` callback is passed for tracking progress. | def load_resource(resource: ResourceRequest, on_progress=None):
resource['hash'] = resource['hash'].lower()
existing_resource = get_resource_by_hash(resource['hash'])
if existing_resource:
log(f'Already have resource: {resource["name"]}')
return
resources.append({'type': resource['type'... |
def get_model_version_by_hash(hash: str):
response = req(f"/model-versions/by-hash/{hash}")
return response
def log(message):
"""Log a message to the console."""
print(f'Civitai: {message}')
def load_resource(resource: ResourceRequest, on_progress=None):
resource['hash'] = resource['hash'].lower()
... | The main task of the code is to retrieve a model's primary checkpoint file using a given hash. It fetches the model version, identifies the primary file, constructs a resource request with the file's metadata, and loads the resource. If the hash is invalid, it logs an error and returns None. | def fetch_model_by_hash(hash: str):
model_version = get_model_version_by_hash(hash)
if model_version is None:
log(f'Could not find model version with hash {hash}')
return None
file = [x for x in model_version['files'] if x['primary'] == True][0]
resource = ResourceRequest(
name=... |
def trainingData(trainingFile, transition, likelihood):
prevPos = "Begin_Sent"
transition['Begin_Sent'] = dict()
transition['End_Sent'] = dict()
line = trainingFile.readline()
while line != None:
if len(line) == 0:
break
prevPos = updatePriors(likelihood, transition, line... | The code trains a probabilistic model using training data to build transition and likelihood dictionaries, then applies this model to tag sequences in development data by processing sentences through a tagging function. | def main(args):
trainingName = args[1]
developmentName = args[2]
likelihood = dict()
transition = dict()
trainingFile = open(trainingName, "r")
trainingData(trainingFile, transition, likelihood)
trainingFile.close()
developmentFile = open(developmentName, "r")
allSentences = creat... |
def CalcCombineShear(h,Ca,tsk,tsp,Iyy,Izz,zbar,Sy,Sz,stiff,Dx,T):
q1, q2, q3,q4,theta,s2,s3,s4 = CalcShearFlow(h,Ca,tsk,tsp,Iyy,Izz,zbar,Sy,Sz,stiff,Dx)
qt1, qt2, Gdethetadz = CalcShearTorq(Ca, h, tsk, tsp,T)
q1 = q1 + qt1.item()
q2 = q2 -qt1.item() + qt2.item()
q3 = q3 - qt2.item()
... | This function calculates the maximum von Mises stress in an aileron structure under combined bending and shear loads. It iterates through x-positions, computes shear flows, bending stresses, and von Mises stresses using helper functions, then identifies the maximum stress location (z,y,x) across all cross-sections. The... | def AileronFullStress(x,Sy,Sz,My,Mz,T,Ca,h,la,tsp,tsk,Iyy,Izz,zbar,Dx,stiff):
#define x
maxstresslist = []
zcoordlist = []
ycoordlist = []
xcoordlist = []
for i in np.arange(len(x)):
#Find shear flows
q1,q2,q3,q4,theta,s2,s3,s4 = CalcCombineShear(h,Ca,tsk,tsp,Iyy,Izz,z... |
def forward_propagation(x):
activations = [x]
inp = x.copy()
for l in range(0,len(weights)):
outp = []
for r in range(0,len(weights[l])):
temp = biases[l][r]
for c in range(0,len(weights[l][r])):
temp += (weights[l][r][c] * inp[c])
outp.app... | This code trains a neural network by performing forward and back propagation on each data point in a batch, accumulating gradients across the batch, then updating weights and biases using gradient descent with the specified learning rate. | def train(batch,learning_rate):
global weights
global biases
b_grad = [[0 for r in range(0,len(biases[l]))] for l in range(0,len(biases))]
w_grad = [[[0 for c in range(0,len(weights[l][r]))] for r in range(0,len(weights[l]))] for l in range(0,len(weights))]
for d in batch:
activations = forw... |
def _trace_resource_initializers(accessible_objects):
"""Create concrete functions from `TrackableResource` objects."""
resource_initializers = []
def _wrap_initializer(obj):
obj.initialize()
return constant_op.constant(1.) # Dummy control output
for obj in accessible_objects:
if isinstance(obj, ... | This function generates a MetaGraphDef for a SavedModel by populating it with resource initializers, a saver, signature functions, and asset information. It creates an exported graph containing necessary operations, maps resources, adds initialization logic, and incorporates signatures for serving. The result enables c... | def _fill_meta_graph_def(meta_graph_def, saveable_view, signature_functions):
"""Generates a MetaGraph which calls `signature_functions`.
Args:
meta_graph_def: The MetaGraphDef proto to fill.
saveable_view: The _SaveableView being exported.
signature_functions: A dictionary mapping signature keys to co... |
def _find_function_to_export(saveable_view):
"""Function to export, None if no suitable function was found."""
# If the user did not specify signatures, check the root object for a function
# that can be made into a signature.
functions = saveable_view.functions[saveable_view.root]
signature = functions.get(D... | The code exports a TensorFlow `Checkpointable` object (e.g., a model) to the SavedModel format for serving. It saves the object's variables, assets, and specified `@tf.function`-decorated methods (signatures) into a directory. If no signatures are provided, it automatically detects and uses one. The exported model supp... | def save(obj, export_dir, signatures=None):
# pylint: disable=line-too-long
"""Exports the Checkpointable object `obj` to [SavedModel format](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md).
Example usage:
```python
class Adder(tf.train.Checkpoint):
@tf.fun... |
def getPairs(inputString: str) -> list[ElfPair]:
elfs = [line.split(",") for line in inputString.splitlines()]
pairs = [(elf[0].split("-"), elf[1].split("-")) for elf in elfs]
return pairs
def countOverlaps(pairs: list[ElfPair], pairOverlaps: Callable[[ElfPair], bool]) -> int:
return reduce(
lam... | The code reads pairs of numbers from a file, counts how many pairs completely overlap and how many partially overlap, prints the partially overlapping pairs, and returns both counts. It processes input data to analyze and report overlapping intervals. Your return | def run():
inputStr = input.readFile("day4/input.txt")
pairs = getPairs(inputStr)
p1 = countOverlaps(pairs, pairCompletelyOverlaps)
p2 = countOverlaps(pairs, pairOverlaps)
for pair in pairs:
if pairOverlaps(pair):
print(pair)
return p1, p2 |
def set_default_vals(self):
#this creates a zero matrix of dimensions 'dimensions'
matrix = []
for i in range(0, self.dimensions[0]):
matrix.append([])
for j in range(0, self.dimensions[1]):
matrix[i].append(0)
self.set_elements(matrix)
def set_ele... | The code prompts the user to input a matrix's dimensions and elements, constructs the matrix, stores it in the object, and confirms correctness. If the user rejects the input, it recursively restarts the input process. | def query_elements(self):
rows, columns = [int(dimension) for dimension in input('Input the dimensions of the matrix in "rows, columns" format: ').split(', ')]
matrix = []
self.dimensions = [rows, columns]
self.set_default_vals()
for i in range(rows):
matrix.append... |
def query_dimensions(self):
rows, columns = [int(dimension) for dimension in input('Input the dimensions of the matrix in "row, column" format: ').split(', ')]
self.dimensions = [rows, columns]
def set_default_vals(self):
#this creates a zero matrix of dimensions 'dimensions'
matrix = []... | The code initializes a zero matrix by checking dimensions, querying for [1,1] size if needed, setting default values, and structuring rows/columns. | def create_zero_matrix(self):
if self.dimensions == [1,1]:
self.query_dimensions()
self.set_default_vals()
self.set_rows()
self.set_columns() |
def query_elements(self):
rows, columns = [int(dimension) for dimension in input('Input the dimensions of the matrix in "rows, columns" format: ').split(', ')]
matrix = []
self.dimensions = [rows, columns]
self.set_default_vals()
for i in range(rows):
matrix.append... | This code initializes a matrix object with customizable parameters. It checks conditions to determine whether to create an identity matrix, zero matrix, prompt for user input to define elements, or raise a query about the matrix type. The logic prioritizes specific flags (identity/zero) over default element input, ensu... | def __init__(self, dimensions=[1, 1], elements=None, identity=False, zero=False):
if dimensions == [1, 1] and elements == None and identity==False and zero==False:
self.query_elements()
self.refresh_matrix()
elif identity == True:
print('creating identity mat... |
def FietsIDGetter(StationId):
conn = ConnectToBD()
cur = conn.cursor()
cur.execute("SELECT current FROM Sloten WHERE StationID = ?", (StationId,))
with conn:
cur = conn.cursor()
for i in cur.execute("SELECT current, id FROM Sloten WHERE StationID = ?", (StationId,)):
if i[0] ... | This code provides a command-line interface for managing bike rental operations, allowing users to rent/return bikes, check bike/user statuses, view station slot availability, and generate web pages. It uses a menu-driven approach with database interactions for data retrieval and updates, looping until the user chooses... | def GebruikerInterface():
print("1. Fiets ontlenen\n2. Fiets terug zetten\n3. Status fiets met id\
\n4. Status slots in station\n5. Status Gebruiker met id\n6. Genereer webpagina voor huidige situatie\nq. Exit")
keuze = input("\n")
match keuze:
case "1":
print("Fiets ontlenen:... |
def take_pic(self):
self.img = self.pibot.get_image()
if not self.data is None:
self.data.write_image(self.img)
def control(self):
if args.play_data:
lv, rv = self.pibot.set_velocity()
else:
lv, rv = self.pibot.set_velocity(
... | The main task of the code is to handle a robot's movement and correction when reaching the end of a path. It reverses the robot, captures images, updates SLAM data, and checks for ArUco markers. If fewer than two markers are detected, it enters a correction loop to adjust orientation by rotating left/right until valid ... | def check_waypoint(self):
if self.command['autopathplan'] == True and self.current_path !=0:
L = len(self.current_path) - self.step
if (L==1)and(self.reverse==1):
print("STAARTING TIME METH")
start_t = time.time()
self.command['motion'] = [... |
def update_counters(self, game_state):
self.turn_counter += 1
if self.turns_has_to_flee > 0:
self.turns_has_to_flee -= 1
if self.turns_with_capsule_effect > 0:
self.turns_with_capsule_effect -= 1
logging.info(f"Attacker: Capsule effect active, remaining turns... | The function `choose_action` determines the next move based on game state: updates counters, checks if food eaten exceeds a threshold or enemy food is absent to return, decides to attack if in own field, or acts in enemy territory otherwise. It delegates to specific methods for each strategic decision. | def choose_action(self, game_state: GameState):
# Update the counters on every turn
self.update_counters(game_state)
# Decide which course of action to follow
if self.food_eaten > FOOD_EATEN_TO_RETURN or len(get_food_positions_enemy(self, game_state)) == 0:
return self.decid... |
def all2edges(self,node_attr,edge_attr,global_attr):
#update edges
# node:[num_times,num_node,num_feature]
# edge:[num_]
# node2edge
#sender2edges
#reciver2edges
num_nodes=node_attr.shape[0]
rel_rec,rel_send=getrel(num_nodes)
x1=node_attr
r... | The main task of the code is to perform a forward pass in a graph neural network by sequentially updating edges, global attributes, and nodes. It takes input features (nodes, edges, global), updates edges using `all2edges`, updates global attributes with `all2globals` (using updated edges), then updates nodes with `all... | def forward(self, inputs, edge_attr, global_attr):
#the input contains: x, e, g
#output tensor:size of out_channels
x_n = inputs
# update edges
edges=self.all2edges(x_n,edge_attr,global_attr)
# update global
globals=self.all2globals(x_n,edges,global_attr)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.