dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def getRegister(self, registerAddress): # Get contents of a register
try:
return self.read_i2c_block_data(self.deviceAddress, registerAddress, 1)[0]
except Exception as e:
print("Error reading register: " + str(e))
return False
def setRegister(self, registerAddress... | The code configures the onboard Low-Drop-Out (LDO) voltage regulator by validating the input value (2.4–4.5V), updating the NAU7802_CTRL1 register to set the LDO level, and enabling the AVDDS power supply via a bit mask. It ensures the LDO value is within 0b111 (7) and writes the adjusted value to the register, then re... | def setLDO(self, ldoValue): # Set the onboard Low-Drop-Out voltage regulator to a given value. 2.4, 2.7, 3.0, 3.3, 3.6, 3.9, 4.2, 4.5V are available
if ldoValue > 0b111:
ldoValue = 0b111 # Error check
# Set the value of the LDO
value = self.getRegister(Scale_Registers['NAU7802... |
def isConnected(self): # Returns true if device acks at the I2C address
try:
self.read_byte(self.deviceAddress)
return True
except:
return False
def reset(self): # Resets all registers to Power Of Defaults
self.setBit(PU_CTRL_Bits['NAU7802_PU_CTRL_RR'], ... | The main task of the code is to initialize a sensor device by checking I2C communication, resetting registers, configuring power settings, gain, sample rate, and calibration parameters, and returning a boolean result indicating setup success. | def begin(self, initialized = True): # Check communication and initialize sensor
# Check if the device ack's over I2C
if self.isConnected() == False:
# There are rare times when the sensor is occupied and doesn't ack. A 2nd try resolves this.
if self.isConnected() == False:
... |
def make_directory(name : str):
# if the directory does NOT exist, create it
if not os.path.isdir(name):
os.mkdir(name)
def initializePoseTools():
pose = mp.solutions.pose
mp_drawing = mp.solutions.drawing_utils
return pose, mp_drawing
def pose_process_image(openCVFrame, poseModel :... | The function processes a video to extract pose angles from each frame using MediaPipe Pose, saves annotated frames to a directory, and returns a tuple containing the list of calculated angles per frame and the directory name where images are stored. | def get_frames_angles(video_path) -> tuple:
# main part of function is frames
frame_angles : list = []
basename = os.path.basename(video_path)
image_name , _ = os.path.splitext(basename)
make_directory(image_name)
pose , poseDrawing = initializePoseTools()
# frames = [
... |
def convertToMp4(path) -> str:
# funnyVideo.mov
_, extension = os.path.splitext(path)
if extension != '.mp4':
mp4_path = Path(path).stem + '.mp4'
clip = VideoFileClip(path)
clip.write_videofile(mp4_path, codec='libx264')
return mp4_path
return path
def get_fram... | The main task of the code is to process two videos by converting them to MP4 format, extract frame angles (body joint angles), apply machine learning to identify key frames, and generate image URLs based on the extracted data. The function aims to analyze and compare video content using pose angle analysis and ML-drive... | def process_videos(videoPath1 : str , videoPath2 : str):
print("Processing Videos")
# 1) TO MP4
# We want the video to be .mp4
videoPath1 = convertToMp4(videoPath1)
videoPath2 = convertToMp4(videoPath2)
# We want to get the "Frame Angles"
# Frame Angles -- Array of diff... |
def normalize(self, point, padding=5):
return (self.shift[0]+point[0]+padding,self.shift[1]+point[1]+padding)
def generate_inside_points(self):
possible_vertices = self.square_point_pattern()
for dot in possible_vertices:
intersections = 0
for line in self.lines:
... | The code generates an SVG file by scaling a drawing to fit a 1024x1024 canvas, draws circles for vertices, creates a visibility graph, fetches player/enemy positions via API, computes a route, and renders movement paths as lines in the SVG, ensuring compatibility with iOS devices. | def save_svg(self):
""" Scale the drawing to fit inside a 1024x1024 canvas (iPhones don't like really large SVGs even if they have the same detail) """
import svgwrite
view_box_size = self.normalize(self.upper_right, 10)
if view_box_size[0] > view_box_size[1]:
canvas_size = (... |
def LoadParquet(self):
'''
Load parquet file and drop columns not inside the default or selected columns.
Wrong inputs will be ignored.
'''
select_columns = []
if self.add_columns != None:
if isinstance(self.add_columns,str):
select_... | The main task of the code is to construct a hierarchical dictionary (`image_loader`) mapping patients, studies, and series to their corresponding DICOM file paths from a DataFrame. It processes each patient/study/series, validates paths, organizes files, and writes the structure to 'image_loader.json'. If enabled, it a... | def GetImageLoader(self) -> dict:
self.LoadParquet()
self.pat_dict = {
patient: {
study: self.df[(self.df.patient_id == patient) & (self.df.study_uid == study)].series_uid.tolist()
for study in self... |
def play_sound(file_path):
"""
Function Responsible for playing sound from passed file_path as parameter via vlc module
"""
player = vlc_instance.media_player_new()
media = vlc_instance.media_new(file_path)
player.set_media(media)
player.play()
return player
def game_loop(screen):
""... | The main task of the code is to create a game start menu with play/quit buttons, handle user input events, play background music, and manage transitions to the game loop or exit. It continuously renders the menu, checks for mouse clicks to trigger actions, and maintains a 60 FPS loop for smooth visuals and audio playba... | def main_menu(screen, WIDTH, HEIGHT):
"""
Function which creates whole start menu in game and is responsible for running game loop
"""
menu_song_player = play_sound(sounds_dir +"\menuSong.mp3")
while True:
if menu_song_player.is_playing() == False:
menu_song_player.play()
... |
def run_gifts(self):
self.click_item(self.home["Gifts"], 1)
HeroWarsFarmer.detect_and_push('send')
try:
HeroWarsFarmer.detect_and_push('send_presents', 1)
except RuntimeError:
print('Gifts already sent')
HeroWarsFarmer.detect_and_push('close')
Hero... | The main task of the code is to trigger a sequence of game-related actions upon startup: distributing gifts (`run_gifts`), unlocking heroic chest contents (`open_heroic_chest`), initiating an outland scenario (`run_outland`), and activating an airship-related process (`run_airship`). These functions collectively initia... | def start_up(self):
self.run_gifts()
self.open_heroic_chest()
self.run_outland()
self.run_airship() |
def locate_file_any_suffix(needle, haystack=None):
if not haystack:
haystack = pyautogui.screenshot()
for f in glob.glob('screenshots\\' + needle + "*.PNG"):
loc = pyautogui.locate(f, haystack)
if loc:
return pyautogui.center(loc)
return None
d... | The code detects specific elements in a game tower floor via screenshots, attempting up to 10 times to identify battle, treasure, or buff chests. If detected, it triggers corresponding actions (battle, treasure, buff handling). If none are found after retries, it raises an error indicating failure to identify the floor... | def run_tower_floor(self):
print('detecting floor')
count = 0
loc = None
while count < 10:
print('detecting...')
floor_screen_capture = pyautogui.screenshot()
loc = self.locate_file_any_suffix('tower_to_battle', floor_screen_capture)
if l... |
def choose_operation():
return int(input("""
Operations:
1. Add a new task
2. Assign task to a team member
3. Complete a task
4. Generate report
5. Exit
Please select an operation: """))
def handle_id(tasks,task_id):
for task in tasks:
task['id'] = task_id
task_id+=1
... | The code implements a menu-driven task management system. It allows users to add tasks/subtasks, assign tasks to team members, mark tasks as complete, generate time estimates reports, and exit. The system uses recursive functions to handle hierarchical tasks, with a loop presenting operation choices and executing corre... | def main():
tasks = init.init_tasks()
is_contionue = True
while is_contionue:
choice = choose_operation()
print()
handle_id(tasks,1)
if choice == 1:
# Add Task
prompt_task_choices(tasks)
print()
add_id = int(input("To add... |
def load_data(df):
df["length"] = df["sentence"].apply(lambda x: len(x.split()))
df = df[df["length"]<500]
short = df[(df.word1.isnull()==False) & (df.word2.isnull())]
long = df[(df.word1.isnull()) & (df.word2.isnull()==False)]
try:
count = min(len(short),len(long))
except ValueErr... | The function computes accuracy scores for 24 different 'sense' categories in a dataframe using a classifier model and tokenizer. It iterates through each sense group, tokenizes sentences, evaluates model performance, and aggregates results into a list of scores. | def compute_scores(df, model, tokenizer):
"""
:param df: Dataframe
:param model: Classifier
:return:
"""
bert_scores = []
for i in range(1,25):
df1 = df[df["sense"] == i]
sentences, labels = load_data(df1)
token_list = build_tokens(tokenizer, sentences)
sco... |
def find_files(path):
return [f for f in listdir(path) if ImageExtension.is_image_ext(join(path, f))]
def check_files_extensions(files):
ext = get_ext(files[0])
for f in files:
if not f.endswith(f".{ext}"):
warnings.warn("Files extensions are not identity.")
def matc... | This code inspects a directory for image files, checks if any images exist, validates the count (warns if odd), verifies file extensions, matches image pairs, and returns the list of files, matched pairs, and a divider. It uses logging to report issues like missing images or invalid counts. | def inspect(self, directory, logger):
files = self.find_files(directory)
if len(files) == 0:
logger.warn('Images not found in %s' % directory)
if len(files) % 2 == 0:
logger.warn('Found odd number of images in dataset.')
warnings.warn('Found odd number of imag... |
def parse_lexicon(lexicon_csv_path, lexicon_test, hatebase_include):
"""
Reads in CSV containing lexicon and produces phrase list for matching based on columns
:param lexicon_csv_path: file path to CSV file containing various phrase lists of potentially harmful or
otherwise noteworthy terms to identify
... | The main task of the code is to process raw data using specified lexicons to identify term matches in EAD and MARCXML files, generating structured CSV outputs. It parses lexicon lists, applies spaCy's PhraseMatcher for term detection, and processes input files (if provided) to build and save matched results in the desi... | def main(lexicon_csv_path, lexicon_test, hatebase_include, output_path, ead_path, marcxml_path):
"""
Once main arguments have been collected, access raw data, process, and produce outputs that enumerate matches to
given lexicons
:param lexicon_csv_path: (String) absolute or relative file path obtained e... |
def create_data_set_dict(list_of_data_set_path):
print("Creating DataSets by loading files:{}".format(list_of_data_set_path))
dict_of_datasets = dict()
for data_set_path in list_of_data_set_path:
data_set_tmp = xr.load_dataset(data_set_path)
if "name" in data_set_tmp.attrs:
data_set_name = data_set_tmp.attrs[... | The code preprocesses datasets by removing specified NaN values and standardizing data according to parameters. It checks for successful NaN removal, saves preprocessed data, standardizes datasets using GAN methods, validates results, and outputs success/failure status. Key steps include data loading, NaN handling, sta... | def data_preprocess(list_of_data_set_path, parameters):
dim_along = parameters["nan_dim_along"]
data_irrelevant = parameters["nan_data_irrelevant"]
output_folder = parameters["output_folder"]
file_format = parameters["file_format"]
dict_of_datasets = create_data_set_dict(list_of_data_set_path)
remove_nan(dict_o... |
def pretrain(self, epochs=20):
'''
This method trains the generator without using a disctiminator/adversarial training.
output: generator model
'''
self.pretrain_train_loss = []
self.pretrain_val_loss = []
batch_size = self.parameters['train']['batch_size']
train_dataset = tf.data.Dataset.from... | This function automates model training based on flags: if auto_run is enabled, it either pretrains a non-GAN model (20 epochs) or handles GAN training (pretraining/loading weights then training GAN). It checks is_GAN, doing_pretrain, and loading_pretrain states to decide workflow steps, returning results or warnings if... | def execute_my_work_flow(self):
if self.auto_run == True:
if self.is_GAN == False:
if self.doing_pretrain == True:
#use keras to train simple generator is is_Gan==False
return self.pretrain(epochs=20)
else:
print("No work to do since to GAN and no pretrain requested.")
elif self.is_GAN ... |
def add_or_update_window_from_wmctrl(self, id: str, monitor: int, geometry: tuple, class_name: str, window_title: str):
# get the input for this by parsing a wmctrl -xGl call
program_name = get_program_name(window_title=window_title, class_name=class_name).lower()
program = None
for p in... | This function processes a list of window data by adding/updating each window's properties (ID, monitor, geometry, class name, title) in the internal window manager. It then removes any non-updated windows and resets all 'updated' flags to false, ensuring the window state remains consistent and up-to-date. | def add_or_update_windows(self, windows):
for w in windows:
id = w['id']
monitor = w['monitor']
geometry = (w['width'], w['height'])
class_name = w['class_name']
window_title = w['window_title']
self.add_or_update_window_from_wmctrl(id=id,
... |
def generate_initial_state():
rand_list = [rand() for i in range(k_dim)]
summ = np.sum(rand_list)
rand_list = list(map(lambda i: i / summ, rand_list))
return rand_list
def objective(portfolio_product_ratio, current_iteration, y_intercept_penalty, temp_penalty_scores) -> tuple:
train_values_on_last_day = []
... | The code implements a simulated annealing algorithm to optimize a portfolio by maximizing an objective function while keeping risk below a threshold. It iteratively generates candidate portfolios, evaluates their returns and risk, and accepts worse solutions probabilistically based on temperature. The algorithm tracks ... | def simulated_annealing(objective, n_iterations, starting_step_size, temp, k_dim):
y_intercept_penalty = math.log(n_iterations + 1)
temp_penalty_scores = []
best_ratio_list = []
best_obj_val_list = []
best_returns_list = []
returns_list = []
risk_list = []
best = generate_initial_state(... |
def changeReset(self,N,timesteps,dL):
self.deltaL=dL
self.N=N
self.timesteps=timesteps
self.reset()
def cycle(self):
d=self.randomChoices()
cyclehappens = np.random.choice(a=[False, True], size=(self.N,), p=[1-self.probcycle, self.probcycle])
#First 2 recoils
... | The code simulates the time evolution of a system's position and velocity over multiple timesteps. It records the system's state (position, velocity) at each step, updates position with velocity, applies semiclassical recoil effects via the `cycle()` method, and incorporates gravitational acceleration. The loop runs un... | def evolve(self,N,ts,dL):
#Here we set the parameteres and reset our distributions
self.changeReset(N,ts,dL)
#We are going to make time evolve for a given amount of timesteps
while self.T<self.timesteps:
#Here we record the postion and velocity of our s... |
def get_lemmatize(words, return_pos):
#words = nltk.word_tokenize(words)
recover_dict = {}
words = words.strip().split(' ')
pos_tags = [_[1] for _ in nltk.pos_tag(words)]
word_roots = []
for w, p in zip(words, pos_tags):
if is_ascii(w) and p in tag_dict:
lemm = lemmatizer.lem... | The main task of the code is to process a CSV file to build mappings of words to their positions, handle transliteration, and lemmatization. It then uses these mappings to process input sentences, normalizing them based on predefined rules and returning transformed results along with metadata. The function constructs d... | def sub_func(inputs):
name, entry = inputs
backbone = {}
trans_backbone = {}
transliterate = {}
tabs = []
recover_dicts = []
repeat = set()
with open('../data/all_csv/' + name, 'r') as f:
for k, _ in enumerate(f.readlines()):
#_ = _.decode('utf8')
tabs.app... |
def compute_log_probs(target_token_ids, logits, mask, average_sent_loss=False):
logits = logits[:, :-1, :].contiguous() # (batch, sequence_length, vocab_size)
target_token_ids = target_token_ids[:, 1:].contiguous() # (batch, sequence_length)
log_probs = F.log_softmax(logits, dim=-1)
log_probs... | The main task of the code is to generate dialogue responses using model_A, evaluate them with metrics like cosine similarity, Jaccard index, and context adequacy, and store scores/log probabilities in a buffer for reinforcement learning. It processes dialog tokens, generates multiple candidates, computes rewards, and u... | def collect_samples(batch,
model_A,
model_B,
top_p,
eos_token_id,
pad_token_id,
max_gen_length,
num_candidates,
human_reward,
use_cosine,
... |
def unannualized_return(r):
"""
Total return from a pd.Series of arithmetic returns
"""
compounded_growth = (1+r).cumprod().iloc[-1]-1
return compounded_growth
def annualized_return(r, periods_per_year=252):
"""
Annualized return from a pd.Series of arithmetic returns
"""
n_periods =... | The code computes key financial performance statistics for a time series, including unannualized/annualized returns, volatility, maximum drawdown, Sharpe/Sortino/Calmar ratios, and skewness, returning them as a formatted pandas Series for evaluation of investment strategies or portfolios. | def btstats(r: pd.Series):
r = r.dropna()
return pd.Series(
{"Return (%)": f'{unannualized_return(r):.2%}',
"Ann. Return (%)": f'{annualized_return(r):.2%}',
"Ann. Volatility (%)": f'{annualized_vol(r):.2%}',
"Max. Drawdown": f'{sortino_ratio(r):.3f}',
"Sharpe Ratio... |
def get_Jacobian_H(self, prior, indices):
'''
This function is used to calulate the Jacobian of the observation model
Size of the H matrix is 4Nt x 3M, where Nt is the observed features in until
time t and M is the total number of landmarks
'''
self.valid_indices = indi... | The function performs an Extended Kalman Filter (EKF) update to refine landmark and robot pose estimates using sensor observations. It calculates the Kalman gain from Jacobians and covariance matrices, updates landmark positions (p_mu) and robot pose (via exponential map), and adjusts combined covariance. When SLAM is ... | def ekf_update(self, p_mu, p_cov, features_t, valid_indices, combined_cov, vi_slam=True):
'''
Update function of the Extended Kalman Filter
Equations follow the equations in slide 9 - Lecture 13
Inputs:
p_mu = landmark piror mu
p_cov = landmark p... |
def build_heap(self, arr):
lenght = self.heap_size
for i in range((lenght//2)-1, -1, -1):
self.heapify(arr, i)
def swap(self, arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
def heapify(self, arr, i):
l = (i*2)+1
r = (i*2)+2
if l < self.heap_size and arr[l] > arr[... | The code implements heap sort by building a max heap from the array, then repeatedly extracting the maximum element (swapping it with the last element of the current heap) and reducing the heap size, followed by heapifying the root to maintain the max heap property, resulting in a sorted array in ascending order. | def heap_sort(self, arr):
self.heap_size = len(arr)
self.build_heap(arr)
for i in range(len(arr)-1, 0, -1):
self.swap(arr, 0, i)
self.heap_size -= 1
self.heapify(arr, 0) |
def topological_sort(self):
self.dfs()
t_s = list(self.nodes)
t_s.sort(key=lambda x: x.dfs_end_time, reverse=True)
return t_s
def initialize_single_source(self, s):
for node in self.nodes:
node.distance = float('inf')
node.predecessor = None
s.dist... | This function computes the shortest paths from a source node `s` in a directed acyclic graph (DAG) using topological sorting. It first performs a topological sort of the nodes, initializes single-source distances, then iterates through each node in topological order, relaxing all outgoing edges to ensure shortest-path ... | def dag_shortest_paths(self, s):
nodes = self.topological_sort()
self.initialize_single_source(s)
for u in nodes:
for v in self.adj(u):
self.relax(u, v) |
def generateSongs(self):
print("\n---Generating songs---\n")
for songIndex in range(self.songAmount):
song = Song()
song.createRandomBuildingBlock(self.buildingBlockAmount)
combinedSong = song.createSong()
self.db.createWAVfile(self.databasePath... | The code's main task is to initialize a new database by creating directories and storing song/building block data in a pickle file, then generate songs. It enters a loop asking the user if they want to combine building blocks by selecting random WAV files, repeating until the user declines. | def start(self):
if(self.newDatabase):
self.db.createDatabaseDirectory()
self.db.createPickleFile(self.databasePath + "\SongData", (self.songAmount,self.buildingBlockAmount)) # Write the data from the songs to a pickle file
self.generateSongs()
while(True):
... |
def initialize(LAMMPSData):
Init_Atoms = deepcopy(LAMMPSData.AtomsProperties.AllAtomsProperties)
Init_Bonds = deepcopy(LAMMPSData.Bonds)
Init_Angles = deepcopy(LAMMPSData.Angles)
Lx = np.float(LAMMPSData.xloxhi[1])-np.float(LAMMPSData.xloxhi[0])
Ly = np.float(LAMMPSData.yloyhi[1])-np.float(LAMMPSData.yloyhi[0])
L... | The main task of the code is to replicate a molecular system using LAMMPS data. It reads atomic data, initializes system parameters, applies a replication sequence, and iteratively expands the system by replicating atoms, bonds, and angles in specified directions. The function updates the system dimensions and structur... | def main_replicate(datafile, Replicate):
LAMMPSData = readdatalammps(datafile,'full')
Init_Atoms, Init_Bonds, Init_Angles, Lx, Ly, Lz = initialize(LAMMPSData)
seq_replicate = set_replicate(Replicate)
for jj in range(len(seq_replicate)):
ReplicatedAtoms, ReplicatedBonds, ReplicatedAngles, newLx, newLy, newLz = ... |
def score(node):
if not isinstance(node, list):
return 1
return score(node[1][0]) + score(node[1][1]) + 1
def is_sub_tree(t, s):
if not isinstance(t, list):
return -1
if not isinstance(s, list):
return -1
if comp(t, s):
return s[3]
else:
x1 = is_sub_tree(t... | The code identifies a common subtree between two tree structures `t` and `s`. It checks if `t` is a valid list-based tree and has a score above 3. If `t` is a subtree of `s`, it returns `(t[3], x)` where `x` is the match position. If not, it recursively searches the left and right children of `t` for a match. If no com... | def common_tree(t, s):
if not isinstance(t, list):
return (-1, -1)
if score(t) <= 3:
return (-1, -1)
x = is_sub_tree(t, s)
if x != -1:
return (t[3], x)
x = common_tree(t[1][0], s)
if x != (-1, -1):
return x
x = common_tree(t[1][1], s)
return x |
def maketree(forword):
# construct tree
valid_op = ['+', '-', '*', '/']
root = None
now = root
for word in forword:
if word in valid_op:
node = [word, [None, None], None]
if now == None:
root = node
now = root
else:
... | The code compares mathematical expression trees from two datasets (Math_23K and MathQA) by checking pairwise comparability and subtree relationships. It generates a list of index pairs indicating comparable trees and their hierarchical relationships, then saves these results in a JSON file for further analysis. | def main():
data1 = json.load(open("data/Math_23K_mbert_token_train.json"))["pairs"]
data2 = json.load(open("data/MathQA_mbert_token_train.json"))["pairs"]
pairs = []
data_pairs = []
cnt_0 = 0
tree_ls1 = [maketree(from_infix_to_prefix(_['expression'])) for _ in data1]
tree_ls2 = [maketree(... |
def ticket_payment_page_summary():
global payment
#Creating a new frame to show the booking details
ticket_details=btk.Frame(main_frame1)
ticket_details.pack(expand=True, fill='both')
#Creating a title for the booking details
booking_details_title=btk.Label(ticket_details, text='Booking details... | The code processes user selections for ticket, package, or ride pass types/quantities, calculates total prices using external modules, and transitions between pages (e.g., parenting page or payment summary) based on selected options. It stores data in global variables, initializes UI elements, and triggers page-specifi... | def load_page4():
global ticket_pass_page
global package_pass_page
global ride_pass_page
global selected_ticket_type
global pass_price
global total_price
global selected_children_ticket_amount
global selected_children_ticket
global selected_ticket_amount
global selected_package_t... |
def include_files(exp):
if 'include' in exp:
include = exp.pop('include')
for inc in include:
new = load_yaml(inc)
exp = deepermerge(exp, new)
return exp
def omit(blacklist, d):
return keyfilter(lambda k: k not in blacklist, d)
def parse_parent(base_job, strategy, fol... | This function loads an experiment configuration from a YAML file, processes it into individual jobs (either from grid parameters or parent configurations), assigns unique IDs to each job, and queues them for execution within a specified directory. It handles configuration inclusion, job generation, and job submission i... | def add_exp(exp_name, base_dir):
exp_file = os.path.join(base_dir, f'{exp_name}.yml')
exp = load_yaml(exp_file)
exp = include_files(exp)
exp_dir = os.path.join(base_dir, exp_name)
if 'grid' in exp:
base_job = omit(['grid'], exp)
jobs = parse_grid(exp['grid'], base_job)
elif 'par... |
def type_state_command(self, match):
self.frame_type = 'state_command'
self.who = match.group('who')
self.what = match.group('what')
self.what_param = match.captures('what_param')
self.where = match.group('where')
self.where_param = match.captures('where_param')
s... | The code parses a frame string using regular expressions to identify and handle different command types: state commands, state requests, dimension requests, or dimension writes. It matches the frame against regex patterns, extracts parameters like 'who', 'what', 'where', and 'dimension', then delegates processing to co... | def read_frame(self):
state_command_regex = r"^\*(?P<who>\d+)\*(?P<what>\d+)(#(?P<what_param>\d+))*\*(?P<where>\d+)(#(?P<where_param>\d+))*##$"
state_command_match = regex.search(state_command_regex, self.frame)
if state_command_match:
self.type_state_command(state_command_match)
... |
def command_connect(self):
self.logger.info('Starting COMMAND session with %s', self.own_server_address)
self.command_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.command_socket.connect(self.own_server_address)
data_received = self.command_socket.recv(4096)
i... | The main task of the code is to initialize a command sequence by establishing a connection, sending specific control commands to configure temperature zones and request energy data, and then reading responses from the socket. It logs received data frames and checks for disconnection if no frames are received, ensuring ... | def command_start(self):
self.command_connect()
# Send command requests
self.write_socket(b'*#1*0##')
for thermo_zone in self.thermo_zones.keys():
self.write_socket(('*#4*%s##' % thermo_zone).encode())
self.write_socket(('*#4*%s*60##' % thermo_zone).encode())
... |
def list_of_strings(self, my_list):
my_list2 = []
for element in my_list:
my_list2.append(str(element))
return my_list2
def check_available_sounds(self):
if (not os.path.isdir("Sounds")):
os.mkdir("Sounds")
return []
else:
return os... | This code initializes an alarm application by setting up screen dimensions, UI elements, and alarm parameters such as time, day, and sound options. It prepares lists for hours, minutes, and days, checks available sound files, and initializes variables to track alarm state, user input, and UI components. The `initUI()` ... | def __init__(self):
self.screen_width = root.winfo_screenwidth()
self.screen_height = root.winfo_screenheight()
self.title = "PyAlarm"
self.hours_list = self.list_of_strings(range(25))
self.minutes_list = self.list_of_strings(range(61))
self.day_list = ["Monday", "Tuesday... |
def run_multiple_inserts(self, table, columns, value_error_pairs):
for vals, err in value_error_pairs:
if err is None:
self.dbinsert(table, columns, vals)
else:
with pytest.raises(err):
self.dbinsert(table, columns, vals, msg=f'insert r... | The code tests foreign key constraints in a database by inserting invalid 'order' records with non-existent or null foreign keys (CustomerId, DeliveryId, StaffId), expecting exceptions like ForeignKeyViolation, UniqueViolation, and NotNullViolation. It verifies that inserts fail until valid related records (customers, ... | def test_order_insert(self):
# all should fail before customer
columns = 'OrderId', 'DateTime', 'TotalCharge', 'CustomerId', 'DeliveryId', 'StaffId'
d = datetime(2020, 1, 1, 1, 1, 0)
values = [
((0, d, 20, 0, 0, 0), Exception),
]
self.run_multiple_inserts('ord... |
def run_multiple_inserts(self, table, columns, value_error_pairs):
for vals, err in value_error_pairs:
if err is None:
self.dbinsert(table, columns, vals)
else:
with pytest.raises(err):
self.dbinsert(table, columns, vals, msg=f'insert r... | This test validates the constraints of the OrderItem table by inserting various test cases. It checks NOT NULL violations for required columns, ensures foreign key integrity with existing MenuItem and Order records, enforces quantity > 0, and verifies that duplicate OrderItem entries for the same MenuItem in different ... | def test_orderitem_insert(self):
columns = 'OrderItemId', 'OrderId', 'CustomerId', 'MenuItemId', 'Quantity', 'Charge'
# make sure each FK must be there (as bold lines)
values = [
((None, 0, 0, 0, 1, 20), NotNullViolation),
((0, None, 0, 0, 1, 20), NotNullViolation),
... |
def daily_employee_cost(self, table_viz=False, bar_viz=False):
"""
Outputs a dataframe that maps each state to the total cost needed to pay for employees
:param table_viz: display table of dataframe
:param bar_viz: display the dataframe in a bar graph
:return: d... | The code calculates total daily costs per U.S. state by combining employee wages and guest fees, then optionally visualizes results as a bar chart or formatted table. It merges two dataframes, sums costs, adds a total row, and generates visualizations with parameters like employee count, wage inflation, and compensatio... | def total_daily_state_costs(self, table_viz=False, bar_viz=False):
"""
Computes the total daily cost for each state
:param table_viz: display the dataframe visual
:param bar_viz: display the dataframe as a bar graph
:return: a dataframe with columns: state, tota... |
def current_branch():
return GIT.name_rev('--name-only', 'HEAD')
def run_test(role):
exit_code = os.system('cd roles/' + role + ' && molecule test')
if not exit_code == 0:
raise Exception('Molecule tests failed')
def changed_roles():
roles_map = map(role_name, changed_files())
return list(f... | The code evaluates whether to run tests for a given `role` based on the current Git branch and role status: tests are executed if the branch is 'main', the role has changed, or the role depends on changed roles; otherwise, it skips testing and prints a message. | def evaluate(role):
if current_branch() == 'main':
run_test(role)
elif role in changed_roles():
run_test(role)
elif role in roles_dependant_on_changed_roles():
run_test(role)
else:
print('Not running tests for: ' + role) |
def start_timer(self):
self.timer_running = True
if self.time_left > 0:
self.timer_label.config(text=f"Time left: {self.time_left} seconds")
self.time_left -= 1
self.root.after(1000, self.start_timer)
else:
self.check_answer(None)
def stop_timer(se... | The main task of the code is to load a random question from a list, display it with shuffled options, start a timer if not already running, disable the next button, and transition to showing the final score when all questions are exhausted. It manages UI updates, question selection, and timer states during a quiz appli... | def load_question(self):
if self.current_question < len(self.questions):
if not self.timer_running:
self.start_timer()
question_data = random.choice(self.questions)
self.questions.remove(question_data)
self.question_label.config(text=question_data[... |
def __bulid_1000a_loop(self):
data_element = self.edi_file_info[0].split('*')
self.index += 1
self.count = 1
segment = data_element.pop(0) + '-' + str(self.index)
self.final_segment[self.segment]['1000A'] = {}
self.final_segment[self.segment]['1000A'][segment] = {}
... | This method processes EDI file segments to build a nested dictionary structure. It identifies transaction set segments (NM1, HL, CLM), increments counters, and invokes specific loop-building functions (e.g., 1000A/1000B, 2000A/2000B, 2300). For other segments, it parses data elements, creates indexed segment keys, and ... | def __bulid_sub_dict(self):
for i in range(len(self.edi_file_info)):
i = 0
try:
if self.edi_file_info[i].split('*')[0] == 'NM1':
if self.NM1 == 0:
self.NM1 += 1
self.__bulid_1000a_loop()
... |
def __bulid_data_element(self, param):
self.count = 1
for self.data in self.data_element:
data_element_count = '{:02}'.format(self.count)
param[data_element_count] = self.data
self.count += 1
self.__pop_element(0)
def __bulid_se_dict(self):
for i in ra... | This method initializes a segment dictionary, checks if the segment starts with 'ST', and either sets a 'pending' status with additional data structures or processes data elements accordingly. It builds hierarchical data structures for segment handling, differentiating between 'ST' segments and others by calling specia... | def bulid_main_dict(self):
self.count = 1
self.final_segment[self.segment] = {}
if self.segment.split('-')[0] == 'ST':
self.count_st += 1
self.final_segment[self.segment]['status'] = 'pending'
self.__bulid_data_element(self.final_segment[self.segment])
... |
def generate_id():
return int(shortuuid.ShortUUID(alphabet="0123456789").random(length=10))
def get_current_status():
current_status = {
"status": "new",
"date": {
"date": datetime.datetime.now().date().strftime("%Y%m%d"),
"time": datetime.datetime.now().time().strftime("... | This code initializes an EDI processor by reading an EDI file, parsing its segments, generating metadata (ID, timestamp, status), and inserting structured data into a MongoDB collection. It prepares the file for further processing by splitting segments and initializing tracking variables for data extraction and storage... | def __init__(self, edi_file):
self.edi_file = edi_file
self.segment, self.data_element = None, None
self.index, self.count, self.count_st = 0, 1, 0
self.time = datetime.datetime.now().time().strftime("%H:%M:%S")
self.date = datetime.datetime.now().date().strftime("%Y%m%d")
... |
def checkblankreceipt(filename):
with open(filename, 'r') as file:
for line in file:
if line.strip(): # Check if the line has non-whitespace content
return(True)
return(False)
def remove_headers(queuepath):
with open(queuepath, 'r') as f:
lines = f.readlines()
if len(lines) >= 2 and lines[1].startswit... | The code monitors a file queuepath, waits for its creation, processes it if valid (non-blank), removes headers, executes mainProc, then moves the processed file to lastprint directory, repeating indefinitely. | def main():
while True:
queuepath = (r"C:\queue\job.txt")
lastprint = (r"C:\queue\last\job.txt")
if not os.path.exists(lastprint):
os.makedirs(lastprint[:-8])
open(lastprint, 'w').close()
while not os.path.exists(queuepath):
time.sleep(1)
if os.path.isfile(queuepath):
if checkblankreceipt(queuep... |
def clear_console():
"""Clears console view"""
command = "clear"
if os.name in ("nt", "dos"): # If Machine is running on Windows, use cls
command = "cls"
os.system(command)
def create_folders(database):
menu_title = " Select asset type to create folder"
count = 1
menu_items = []
... | The main task of the code is to display a menu of database operations and execute selected actions, such as creating folders, generating icons, transferring files, and generating reports, based on user input. It loops until the user selects "Quit" (option 11), handling each choice by calling corresponding functions wit... | def main_menu(database):
"""
Draw main menu
:param CommonDatabaseAccess database: reference to the database
:return:
"""
menu_title = " Select action"
menu_items = [
"[1] Create folders.",
"[2] Download all images.",
"[3] Make all icons. Where Preview.ico do not exist... |
def clear_console():
"""Clears console view"""
command = "clear"
if os.name in ("nt", "dos"): # If Machine is running on Windows, use cls
command = "cls"
os.system(command)
def asset_scan_by_asset_type(database, debug, categories):
"""Initial scan of the https://substance3d.adobe.com/assets... | This function displays a menu for selecting asset types to check for new assets, retrieves available types from the database, and processes user input to trigger scanning operations for specific types, all types, or individual categories, with an option to return to the previous menu. | def draw_asset_type_list_menu(database, debug):
"""Draws menu to select what asset type to check for new assets"""
menu_title = " Select asset type to check"
count = 1
menu_items = []
all_asset_types = database.get_all_asset_types()
for asset_type in all_asset_types:
menu_items.append(f"... |
def clear_console():
"""Clears console view"""
command = "clear"
if os.name in ("nt", "dos"): # If Machine is running on Windows, use cls
command = "cls"
os.system(command)
def initial_asset_type_and_category_scan(database, debug):
"""Initial scan of the https://substance3d.adobe.com/assets... | The code provides a menu-driven interface for scanning Adobe Substance 3D assets, offering options for initial scans (checking all assets), detailed scans (extracting variation image links), asset type filtering, and database checks. It uses argparse for configuration, a SQLite database for storage, and handles user in... | def main():
"""Main menu to select desired activity
Initial scan - checks https://substance3d.adobe.com/assets/allassets for all assets present
Detailed scan - opens each individual asset page to get links to variation images"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-d"... |
def create_loan_type():
name = fake.word()
max_amount = random.randint(10000, 50000)
min_amount = random.randint(1000, 5000)
interest_rate = random.randint(1, 10)
loan_fund = create_loan_fund()
loan_term = create_loan_term()
loan_type = LoanType.objects.create(
name=name,
max... | The main task of the code is to generate a random loan with predefined parameters. It creates a loan type, customer, and term using helper functions, assigns random values for loan amount (5000–50000) and interest rate (1–10), then instantiates and saves a Loan object to the database with these attributes. | def create_loan():
loan_type = create_loan_type()
amount = random.randint(5000, 50000)
interest_rate = random.randint(1, 10)
customer = create_customer()
term = create_loan_term()
loan = Loan.objects.create(loan_type=loan_type, amount=amount, interest_rate=interest_rate, customer=customer, term=... |
def create_customer():
user = create_user()
annual_income = random.randint(20000, 150000)
credit_score = random.randint(300, 850)
notes = fake.text()
customer = Customer.objects.create(user=user, annual_income=annual_income, credit_score=credit_score, notes=notes)
return customer
def create_loan... | The function `create_loan_request` generates a new loan request by creating a customer, random loan amount, loan term, and loan type, then saving these as a `LoanRequest` object in the database. It returns the created loan request instance. | def create_loan_request():
customer = create_customer()
amount = random.randint(5000, 50000)
term = create_loan_term()
loan_type = create_loan_type()
loan_request = LoanRequest.objects.create(
customer=customer,
amount=amount,
term=term,
loan_type=loan_type
)
... |
def create_loan():
loan_type = create_loan_type()
amount = random.randint(5000, 50000)
interest_rate = random.randint(1, 10)
customer = create_customer()
term = create_loan_term()
loan = Loan.objects.create(loan_type=loan_type, amount=amount, interest_rate=interest_rate, customer=customer, term=... | The main task of the code is to generate seed data for a database by creating multiple entries for entities like loans, customers, loan terms, and providers. The function iterates five times, each time invoking creation functions for these entities to populate the database with initial sample data for testing or demons... | def seed_data():
for _ in range(5):
create_loan()
create_customer()
create_loan_term()
create_loan_type()
create_loan_fund()
create_bank_personnel()
create_fund()
create_provider()
create_loan_request() |
def get_config():
if os.path.isfile(CONFIG_FILE_PATH):
try:
with open(CONFIG_FILE_PATH) as f:
config = json.load(f)
except ValueError:
print("There was an error decoding the 'config.json' file")
raise
else:
raise ImportError(
... | The main task of the code is to execute multiple Microsoft accounts using configurations and command-line arguments, handling credentials, disabling cookies for parallel runs, initializing Telegram/Discord messengers and Google Sheets reporting, then iterating through each account to perform tasks with specified parame... | def main():
"""
Run all accounts
"""
# change to top dir
dir_run_from = os.getcwd()
top_dir = os.path.dirname(sys.argv[0])
if top_dir and top_dir != dir_run_from:
os.chdir(top_dir)
config = get_config()
args = parse_search_args()
if args.email and args.password:
... |
def build_generator(self):
model = Sequential()
n_nodes = 256 * 4 * 4
model.add(Dense(n_nodes, input_dim=self.latent_dim))
model.add(LeakyReLU(alpha=0.2))
model.add(Reshape((4, 4, 256)))
for x in range(self.n_layers_gen):
# Layer 1 gen
model.add(... | This code trains a Generative Adversarial Network (GAN) using the provided training data. It alternates between updating the discriminator with real and generated samples, then trains the generator via the GAN model. The process iterates over epochs and batches, printing losses and periodically summarizing performance. | def train(self, X_train):
gen = self.build_generator()
disc = self.build_discriminator()
gan_model = self.build_gan(disc, gen)
tprint('GENERATOR')
gen.summary()
tprint('DISCRIMINATOR')
disc.summary()
tprint('TRAINING')
bat_per_epo = int(X_train.... |
def time_to_check(self):
return (
self.times.keys() and (time.time() - self.past_timer) > self.TIME_INTERVAL
)
def check_life(self):
sensors_ts = list(self.times.items()).copy()
for id_sens, timestamps in sensors_ts:
if len(timestamps) == 0:
self.s... | The code's main task is to periodically check system health, consistency, and status, then refresh the interface and compute FPS. It also listens for topics, likely in a loop for real-time updates or monitoring. | def spin(self):
if self.time_to_check():
self.check_life()
self.check_consistency()
self.update_status()
self.refresh()
self.compute_fps()
self.listen_topics() |
def time_to_check(self):
if len(self.times.keys()) == 0:
return False
master_cam = self.get_master_cam()
right_time = time.time() - self.past_timer > self.TIME_INTERVAL
return master_cam != None or right_time
def check_life(self):
sensors_ts = list(self.times.items(... | The `spin` method performs periodic checks: if `time_to_check()` is true, it runs `check_life()`, `check_consistency()`, `save_results()`, and `refresh()`. It then always calls `listen_topics()` to monitor updates. The task involves maintaining system state, validating consistency, storing results, and responding to ex... | def spin(self):
if self.time_to_check():
self.check_life()
self.check_consistency()
self.save_results()
self.refresh()
self.listen_topics() |
def _login_api_key(self):
self.session.headers.update({'Authorization': self.api_key})
self._get_account_info()
self.api_key_authenticated = True
def _login_cookie(self):
mainpage = 'https://redacted.ch/';
cookiedict = {"session": self.session_cookie}
cookies = requests.u... | The main task of the code is to authenticate a user using different methods in priority order: first via API key, then session cookie (with fallback to username/password if cookie fails), and finally directly via username/password if no credentials are provided. It ensures flexible login handling based on available aut... | def _login(self):
if self.api_key is not None and len(self.api_key) > 0:
self._login_api_key()
elif self.session_cookie is not None and len(str(self.session_cookie)) > 0:
try:
self._login_cookie()
except:
print("WARNING: session cookie ... |
def _cal_leaf(self, y):
'''function to calculate leaf node content'''
# finding the most common class in y
return Counter(y).most_common(1)[0][0]
def get_best_split(self, X, y, num_features):
''' function to find the best split '''
# initialize best split as an empty dictionary
... | The main task of the code is to recursively build a decision tree by splitting data based on information gain. It checks stopping conditions (minimum samples, maximum depth, pure labels) to create leaf nodes, otherwise finds the best split, recursively grows left/right subtrees, and returns a decision node with split d... | def grow_tree(self, X, y, depth=0):
'''the grow_tree method to build our tree '''
n_labels = len(set(y))
# setting samples_total to number of rows and features_total to number of columns of X
samples_total, features_total = np.shape(X)
# setting conditions for stopping
#... |
def _key_down_controller(self, event):
if event.key==pygame.K_RIGHT:
self.ship.right=True
elif event.key==pygame.K_LEFT:
self.ship.left=True
elif event.key==pygame.K_UP:
self.ship.up=True
elif event.key==pygame.K_DOWN:
self.ship.down=Tr... | The main task of the code is to handle user input events in a Pygame application. It checks for quit requests, keyboard key presses/releases, and mouse button clicks, delegating each event type to corresponding controller methods. The function processes events by iterating through pygame's event queue, extracting relev... | def _check_events(self):
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
elif event.type==pygame.KEYDOWN:
self._key_down_controller(event)
elif event.type==pygame.KEYUP:
self._ke... |
def _check_aliens(self):
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
if self.stats.ships_left>0:
self.stats.ships_left-=1
self.sb.prep_ships()
self.al... | This method updates alien behavior by checking their status, updating their positions, detecting collisions between the player's ship and aliens (triggering a hit response if collided), and verifying if any aliens have reached the bottom of the screen, likely initiating game-ending logic. It coordinates alien movement,... | def _update_aliens(self):
self._check_aliens()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom() |
def _check_events(self):
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
elif event.type==pygame.KEYDOWN:
self._key_down_controller(event)
elif event.type==pygame.KEYUP:
self._ke... | The code runs the game loop, continuously checking for events, updating game elements (ship, bullets, aliens) when the game is active, and refreshing the screen to render changes, maintaining gameplay flow until exited. | def run_game(self):
while True:
self._check_events()
if self.stats.game_active==True:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen() |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--app", type=str, help="Application to run (bfs, sssp, pagerank)")
parser.add_argument("-d", "--dataset", type=str, help="Dataset to run")
parser.add_argument("-x", "--experiment", type=int, default=-1, help="Experiment to run (0-4)... | The main task of the code is to parse command-line arguments, check Transparent Huge Page (THP) system settings, configure application/dataset parameters, construct input paths, and execute specified experiments or default benchmarks related to memory management and performance analysis. It handles THP configuration, v... | def main():
global apps, args, is_thp, datasets, vp_inputs
args = parse_args()
# Get THP settings
stdout = Popen("cat /sys/kernel/mm/transparent_hugepage/enabled", shell=True, stdout=PIPE).stdout
output_str1 = stdout.read().decode("utf-8")
stdout = Popen("cat /sys/kernel/mm/transparent_hugepage/defrag", s... |
def tree(label, branches=[]):
for branch in branches:
assert is_tree(branch)
return [label] + list(branches)
def label(tree):
return tree[0] | The code constructs a binary tree where each node's label is the sum of its children's labels, mirroring the Fibonacci sequence. For n > 1, it recursively builds left and right subtrees with labels Fib(n-2) and Fib(n-1), then combines them into a new tree with label Fib(n). The tree structure reflects Fibonacci recursi... | def fib_tree(n):
if n <= 1:
return tree(n)
else:
left, right = fib_tree(n - 2), fib_tree(n - 1)
return tree(label(left) + label(right), [left, right]) |
def is_leaf(tree):
return not branches(tree)
def tree(label, branches=[]):
for branch in branches:
assert is_tree(branch)
return [label] + list(branches)
def label(tree):
return tree[0]
def branches(tree):
return tree[1:] | The function `increment_leaves` recursively traverses a tree structure, incrementing the labels of all leaf nodes by 1 while preserving the tree's hierarchical structure. If a node is a leaf, its label is increased by 1. For non-leaf nodes, the function recursively applies itself to each branch, ensuring only terminal ... | def increment_leaves(t):
"""Return a tree like t but with leaf labels incremented"""
if is_leaf(t):
return tree(label(t) + 1)
else:
return tree(label(t), [increment_leaves(b) for b in branches(t)]) |
def tree(label, branches=[]):
for branch in branches:
assert is_tree(branch)
return [label] + list(branches)
def label(tree):
return tree[0]
def branches(tree):
return tree[1:] | (The function `increment` recursively creates a new tree with all node labels incremented by 1. It takes a tree `t`, adds 1 to its root label, and applies the same operation to each of its branches, constructing a new tree with the updated values. This ensures every node in the resulting tree has a label increased by 1... | def increment(t):
"""Return a tree like t but with all labels incremented"""
return tree(label(t) + 1, [increment(b) for b in branches(t)]) |
def all_trees(path='CHILDESTreebank-curr/suppes.parsed'):
return read_trees(open(path).readlines())
def replace(t, s, w):
"""Return a tree like T with all nodes labeled S replaced by word W.
>>> words(replace(example, 'JJ', 'huge'))
'a huge bug.'
"""
if label(t) == s:
return tree(s, [tr... | The main task of the code is to iterate through all syntax trees, replace occurrences of a substring `s` with `w` using the `replace` function, and print the original and modified versions of each tree (in lowercase) when changes are detected. | def replace_all(s, w):
"""Print the result of replace(t, s, w) for all syntax trees t."""
for t in all_trees():
r = replace(t, s, w)
if t != r:
print('Original: ', words(t).lower())
print('Replaced: ', words(r).lower())
input() |
def le_entrada(self):
logging.info(f'Processador de Consultas - Iniciando leitura do arquivo LEIA ({self.leia})')
self.dom = minidom.parse(self.leia)
self.query_number = get_xml_field(self.dom, 'QueryNumber')
logging.info(f'Processador de Consultas - Lidos {len(self.query_number... | The main task of the code is to execute a sequence of operations: first reading input data (`le_entrada`), then generating queries (`gera_consultas`), and finally producing expected outputs (`gera_esperados`). This method orchestrates data processing, query generation, and output creation in a structured workflow. | def run(self):
self.le_entrada()
self.gera_consultas()
self.gera_esperados() |
def is_legal_move(current_position, possible_move, board, colour):
"""
Determine if a move is legal or not.
A legal move is one which does not violate the bounds of the board, nor does it step onto opponents pieces.
:param current_position: a tuple representing co-ordinates
:param possible_move: one... | The function `simulate_move` simulates a piece movement on a board, verifying its legality, updating the board state, and returning details of the move. It checks if the move is valid using `is_legal_move`, computes the new position, records the pieces at the original and target positions before and after the move, upd... | def simulate_move(current_position, move, n, board, max_moves, spaces, color):
pre_add = None
post_add = None
pre_del = None
post_del = None
if is_legal_move(current_position, scale_vector(move, spaces), board, color):
future_position = add_vectors(current_position, scale_vector(move, spac... |
def is_legal_move(current_position, possible_move, board, colour):
"""
Determine if a move is legal or not.
A legal move is one which does not violate the bounds of the board, nor does it step onto opponents pieces.
:param current_position: a tuple representing co-ordinates
:param possible_move: one... | The function attempts to move a piece on a board by checking if the specified move (direction and distance) is legal. If valid, it updates the board state by moving the piece's coordinates, considering the piece's color, stack count, and maximum allowed moves. It returns the new coordinates if successful, otherwise ret... | def move_piece(current_position, move, n, board, max_moves, spaces, colour):
"""
Move a given piece, represented by co-ordinates. If a move is not possible, return False.
:param colour:
:param current_position: co-ordinates for a piece, represented as a tuple where positions 0 and 1 are x and y respecti... |
def search_local_checkpoint(path="./"):
ckptfile_list = Path(path).rglob("*.ckpt")
# make id list for those checkpoints without epoch number (are latest checkpoint)
nonHistory_list = [
str(Path(file).stem)
for file in ckptfile_list
if "-" not in str(Path(file).stem)
]
idList ... | The code generates 3D mesh models from a machine learning model's checkpoint, handling parameters like class, samples, and post-processing thresholds. It retrieves input data, manages checkpoint files (downloading/restoring from W&B), and generates meshes using specified configurations. If the primary checkpoint fails,... | def generateMesh():
global message_steptime
message_steptime = []
req = request.get_json(force=True)
run_id = req.get("run_id", None)
num_samples = int(req.get("num_samples", 1))
class_index = req.get("class_index", None)
class_name = req.get("class_name", None)
point_threshold = req.g... |
def search_local_checkpoint(path="./"):
ckptfile_list = Path(path).rglob("*.ckpt")
# make id list for those checkpoints without epoch number (are latest checkpoint)
nonHistory_list = [
str(Path(file).stem)
for file in ckptfile_list
if "-" not in str(Path(file).stem)
]
idList ... | The main task of the code is to generate 3D mesh data from selected model checkpoints based on input parameters like run_id, class_index, and post-processing settings. It retrieves checkpoint files from a W&B run, processes them to generate meshes using a specified model, and returns the results in JSON format. The fun... | def generateMeshHistory():
global message_steptime
message_steptime = []
req = request.get_json(force=True)
run_id = req.get("run_id", None)
num_samples = int(req.get("num_samples", 1))
class_index = req.get("class_index", None)
num_selected_checkpoint = int(req.get("num_selected_checkpoin... |
def conv2d(self, input, stride, padding, \
filter_size=[3, 3, 16, 32], dilations=[1, 1, 1, 1], activation="relu", name=""):
self.weights, self.w_names, weight = self.variable_maker(var_bank=self.weights, name_bank=self.w_names, \
shape=filter_size, name='%s_w' %(name))
self.biasis, ... | The main task of the code is to encode input data into a lower-dimensional latent representation. It uses convolutional layers with increasing filters (16→32→64), max-pooling, and a dense layer to compress spatial features into a latent code `z_code` of size `self.z_dim`, suitable for tasks like variational autoencoder... | def encoder(self, input, ksize=3):
print("\nEncode-1")
conv1_1 = self.conv2d(input=input, stride=1, padding='SAME', \
filter_size=[ksize, ksize, 1, 16], activation="lrelu", name="enconv1_1")
conv1_2 = self.conv2d(input=conv1_1, stride=1, padding='SAME', \
filter_size=[ks... |
def fully_connected(self, input, num_inputs, num_outputs, activation="relu", name=""):
self.weights, self.w_names, weight = self.variable_maker(var_bank=self.weights, name_bank=self.w_names, \
shape=[num_inputs, num_outputs], name='%s_w' %(name))
self.biasis, self.b_names, bias = self.varia... | This decoder function reconstructs an output tensor from a latent input by first passing it through dense layers, then upsampling via transposed convolutions and concatenating skip-connected features. It combines latent information with intermediate features, applies Leaky ReLU activations, and produces a final output ... | def decoder(self, input, ksize=3):
print("\nDecode-Dense")
[n, h, w, c] = self.fc_shapes[0]
fulcon2 = self.fully_connected(input=input, num_inputs=int(self.z_dim), \
num_outputs=512, activation="lrelu", name="defullcon2")
fulcon3 = self.fully_connected(input=fulcon2, num_inp... |
def conv2d(self, input, stride, padding, \
filter_size=[3, 3, 16, 32], dilations=[1, 1, 1, 1], activation="relu", name=""):
self.weights, self.w_names, weight = self.variable_maker(var_bank=self.weights, name_bank=self.w_names, \
shape=filter_size, name='%s_w' %(name))
self.biasis, ... | The code defines a discriminator network for distinguishing real/fake inputs. It processes the input through three convolutional blocks (with increasing filters: 16→32→64), max-pooling, and dense layers. Features are stored in a bank, culminating in a sigmoid-activated output score. The architecture uses ELU activation... | def discriminator(self, input, ksize=3):
featurebank = []
print("\nDiscriminate-1")
conv1_1 = self.conv2d(input=input, stride=1, padding='SAME', \
filter_size=[ksize, ksize, 1, 16], activation="elu", name="disconv1_1")
featurebank.append(conv1_1)
conv1_2 = self.conv... |
def encoder(self, input, ksize=3):
print("\nEncode-1")
conv1_1 = self.conv2d(input=input, stride=1, padding='SAME', \
filter_size=[ksize, ksize, 1, 16], activation="lrelu", name="enconv1_1")
conv1_2 = self.conv2d(input=conv1_1, stride=1, padding='SAME', \
filter_size=[ks... | The code defines a model-building function that constructs a generator and discriminator for a GAN. The generator encodes input data, decodes it to produce a reconstruction, and re-encodes the reconstruction. The discriminator evaluates both original and generated data, extracting features for real and fake inputs. The... | def build_model(self, input, ksize=3):
with tf.name_scope('generator') as scope_gen:
z_code = self.encoder(input=input, ksize=ksize)
x_hat = self.decoder(input=z_code, ksize=ksize)
z_code_hat = self.encoder(input=x_hat, ksize=ksize)
with tf.name_scope('discriminator... |
def _generate_logger_script(self) -> None:
self._internal_scripts_path.append(self._project_path + "/logger.pas")
variables = {
"LogFilePath": self.get_log_file_path(),
}
file = open(str(variables["LogFilePath"]), 'a+')
file.write("Startup Altium script\n")
fi... | The main task of the code is to execute a script in Altium Designer by generating necessary project files, launching the scripting environment, and managing the process. It creates required directories, constructs a command to run the script, and optionally waits for completion with a timeout. The function returns whet... | def run(self, wait_until_finished: bool = True, timeout: float = 10) -> bool:
r"""Runs the script based on the settings defined.
If Altium Designer is running it will run the script in that instance and leave it open.
If Altium Desinger is not running it will start a new instance and close it w... |
def setup(self):
'''
1. Draw Press space to continue
2. Wait for keypress
3. If pressed:
Start mainloop
'''
self.create_leap_inlet()
self.create_outlet()
self.set_targets(n_targets)
self.draw_text('Press space to continue.')
... | The code defines a `run` method that sequentially executes four key steps: initializing setup, waiting for a start signal (`wait_for_go`), conducting the main experimental process (`run_experiment`), and finalizing or concluding the operation (`finish`). Its primary task is to orchestrate and manage the lifecycle of an... | def run(self):
self.setup()
self.wait_for_go()
self.run_experiment()
self.finish() |
def setup(self):
''' Calls all separate components to setup
Args
----------
Returns
----------
'''
self.get_device_input_source_ids()
self.setup_recorder()
self.setup_trigger()
def start(self):
''' Starts the experiment UI and looks for ... | The main task of the code is to execute an experiment by initializing setup, launching the experiment, waiting for its completion via process monitoring, and finally terminating the experiment. The method serves as the core workflow controller, ensuring sequential execution of setup, execution, and cleanup phases for e... | def go(self):
''' Main entry point for running experiments.
Args
----------
Returns
----------
'''
self.setup()
# Run experiment
self.start()
# Wait until experiment finished
self.process.wait()
self.stop() |
def _process_udp(self, service_mapping):
if self.src_port <= self.dst_port:
if ("UDP", self.src_port) not in service_mapping.keys():
self.service = "Unassigned"
else:
self.service = service_mapping[("UDP", self.src_port)]
else:
if ("UDP... | This code processes network packets to determine their protocol type (UDP, TCP, or ICMP), extracts source/destination ports and duration, then delegates to protocol-specific processing methods. It uses service_mapping for UDP/TCP, calls common post-processing, and generates operations data. | def process(self, service_mapping):
if "udp" in self.packet_list[0] or "UDP" in self.packet_list[0]:
self.protocol_type = "UDP"
self.src_port = int(self.packet_list[0][self.protocol_type].srcport)
self.dst_port = int(self.packet_list[0][self.protocol_type].dstport)
... |
def initialization(self, is_train=False):
""" initialize self.model and self.criterion here """
# Bulid Logger
self.build_logger()
# Bulid Summary
if self.args.summary_writer:
self.summary_writer = SummaryWriter(log_dir=self.args.save_dir)
# show co... | The code trains a neural network model over multiple epochs, performing training iterations on the training dataset, validation on the validation set, and adjusting the learning rate. It tracks the best validation score, saves checkpoints and results when the score improves, and logs progress. The goal is to optimize m... | def train(self):
self.initialization(is_train=True)
torch.cuda.empty_cache()
for epoch in range(self.start_epoch, self.end_epoch):
self.epoch = epoch
# train for one epoch
torch.cuda.empty_cache()
self.run_iteration(self.train_loader... |
def initialization(self, is_train=False):
""" initialize self.model and self.criterion here """
# Bulid Logger
self.build_logger()
# Bulid Summary
if self.args.summary_writer:
self.summary_writer = SummaryWriter(log_dir=self.args.save_dir)
# show co... | The main task of the code is to validate a model using a validation dataset. It initializes the model in evaluation mode, runs a validation iteration to compute metrics (stored in `map`), verifies the existence of a model directory, saves validation results without marking them as the best model, and returns the comput... | def validate(self):
self.initialization(is_train=False)
map = self.run_iteration(self.val_loader, is_train=False)
model_dir = os.path.dirname(self.args.resume)
assert os.path.exists(model_dir) == True
self.save_result(model_dir, is_best=False)
return map |
def _copy_grid(self, from_grid, to_grid):
for y in range(9):
for x in range(9):
to_grid.cells[y][x].value = from_grid.cells[y][x].value
to_grid.cells[y][x].candidates = set(from_grid.cells[y][x].candidates)
to_grid.level = from_grid.level
def _set_value(self, ... | This function solves a Sudoku grid using backtracking by selecting the cell with the fewest candidates, testing each possible value, and recursively solving sub-problems. It copies the grid, applies constraints, checks validity, and returns a solved grid if found, otherwise proceeds with further guesses until exhaustio... | def _solve_by_guessing(self, grid):
grid.level += 1
guessing_cell = None
for row in grid.cells:
for cell in row:
if cell.value:
continue
if not guessing_cell or len(guessing_cell.candidates) > len(cell.candidates):
... |
def _solve_1(self, grid):
for unit in grid.units:
for cell in unit:
if cell.value:
self._set_value(cell, cell.value)
def _is_finished(self, grid):
return all(all(c.value for c in r) for r in grid.cells)
def _solve_n_within_unit(self, grid, n):
whil... | This code solves a grid by applying a series of solving techniques in increasing levels of complexity. It starts with level 1, then iteratively applies unit and cross-unit solving strategies for levels 2–8. If unsolved, it resorts to guessing at level 90. If the grid remains unsolved or invalid, it raises an exception.... | def solve(self, grid):
grid.level = 1
self._solve_1(grid)
if not self._is_finished(grid):
for i in range(2, 9):
grid.level = i
for j in range(i, 1, -1):
self._solve_n_within_unit(grid, j)
self._solve_n_cross_unit... |
def generate_smart_hands_for_opponents(state):
pid = state['raw_obs']['self'] # player id
other_card_amount = state['raw_obs']['num_cards_left'].copy()
other_card_amount.pop(pid)
remaining_cards = list(state['raw_obs']['others_hand']).copy()
current_hand = state['raw_obs']['current_hand']
hasR... | This code implements a Monte Carlo Tree Search (MCTS) agent that selects actions by simulating game outcomes. It builds decision trees through selection, expansion, rollout, and back-propagation phases, aggregating results from multiple trees to determine the optimal action using UCT (Upper Confidence Bound applied to ... | def step(self, state):
""" Predict the action given the curent state in gerenerating training data.
Args:
state (dict): An dictionary that represents the current state
Returns:
action (int): The action predicted (randomly chosen) by the random agent
"""
i... |
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def load_and_cache_examples(args, task, tokenizer, evaluate=False):
if args.local_rank not in [-1, 0]:
torch.distributed.barrier(... | The code trains and evaluates a pre-trained model (e.g., BERT) on a GLUE-style natural language understanding task. It sets up distributed training, loads data, trains the model, and saves checkpoints. If evaluation is enabled, it tests the model on validation/test sets using saved checkpoints, returning performance me... | def main(model, tokenizer, mode):
args = Arguments()
if os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train and not args.overwrite_output_dir:
raise ValueError(
"Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".for... |
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def load_and_cache_examples(args, task, tokenizer, evaluate=False):
if args.local_rank not in [-1, 0]:
torch.distributed.barrier(... | The code's main task is to train a model on a GLUE-style NLP task. It sets up device configuration, logging, and random seeds, validates the task name, loads task-specific data processors, prepares labels, moves the model to the specified device, and initiates training if enabled. The training process uses cached examp... | def main(args, model, tokenizer):
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
args.n_gpu = torch.cuda.device_count()
args.device = device
# Setup logging
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
... |
def _wait_for_opening_time(self) -> None:
"""Wait for scheduled booking opening time."""
seconds_to_sleep = 0.50
minimum_date_bookings_are_possible = self.booking_date - dt.timedelta(days=14)
booking_open_datetime = dt.datetime.combine(
minimum_date_bookings_are_possible,
... | The main task of the code is to recursively attempt to book a reservation by iterating through ranked time slots, logging failures when a slot cannot be booked, and raising an error if all attempts fail. It ensures booking occurs by waiting for the appropriate time, collecting available slots, ranking them, and persist... | def book(self) -> BookingConfirmation:
"""Attempt to book reservation."""
self._wait_for_opening_time()
slots = self._collect_slots()
ranked_slots = self._rank_slots(slots)
# Recursively attempt to book until success.
while (confirmation := self.request_booking(ranked_sl... |
def inference(image, keep_prob,z):
"""
Semantic segmentation network definition
:param image: input image. Should have values in range 0-255
:param keep_prob:
:return:
"""
print("setting up vgg initialized conv layers ...")
model_data = utils.get_model_data(FLAGS.model_dir, MODEL_URL)
... | The main task of the code is to train a neural network for image segmentation or reconstruction using a combination of input images, annotations, and a latent variable $ z $. It defines placeholders, computes a custom loss function involving masked image reconstruction, and performs training with gradient updates. The ... | def main(argv=None):
keep_probability = tf.placeholder(tf.float32, name="keep_probabilty")
image = tf.placeholder(tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="input_image")
annotation = tf.placeholder(tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 1], name="annotation")
z = tf.placeholde... |
def plus():
grid('+')
operator = '+'
for i in range(choiceNum):
i += 1
nextLine = "%s | " % i
for j in range(choiceNum):
nextLine = nextLine + str(eval("%s%s%s" % (j,operator,i)))
print(nextLine)
def minus():
grid('-')
operator = '-'
for i in range(cho... | The code defines a function `choice()` that prompts the user to input a mathematical operator (+, -, /, or *). Based on the input, it calls corresponding functions (`plus()`, `minus()`, `divide()`, or `multiply()`) to perform arithmetic operations. If an invalid operator is entered, it displays an error message, ensuri... | def choice():
operator = input("Input an appropriate operator. '+' , '-' , '/' or '*' .")
if operator == '+':
plus()
elif operator == '-':
minus()
elif operator == '/':
divide()
elif operator == '*':
multiply()
else:
print("Not a valid operator. Please ch... |
def CompileModel(self,lr):
#self.hvd_lr = lr*np.sqrt(hvd.size())
self.hvd_lr = lr
opt = tensorflow.keras.optimizers.Adam(learning_rate=self.hvd_lr)
opt = hvd.DistributedOptimizer(
opt, average_aggregated_gradients=True)
self.model1.compile(loss=weighted_binary_crosse... | The main task of the code is to train a machine learning model through iterative steps, adjusting model weights (weights_pull/weights_push) while monitoring convergence. It compiles the model with a learning rate, runs two training phases (Step1 and Step2) per iteration, and uses a patience-based early stopping mechani... | def Unfold(self):
self.BATCH_SIZE=self.opt['General']['BATCH_SIZE']
self.EPOCHS=self.opt['General']['EPOCHS']
self.CompileModel(float(self.opt['General']['LR']))
self.weights_pull = np.ones(self.weights_mc.shape[0])
self.weights_push = np.... |
def headersLink(self):
headers = self.driver.find_element_by_xpath('//*[@id="header"]/div[1]/div/div/div[2]/nav/ul')
li_list = headers.text.split('\n')
idx = 1
for li in li_list :
if(idx > len(li_list)):
break
sleep(3)
#test without log... | The code's main task is to execute a sequence of operations including handling headers, regional links, categories, events, channels, performing a search, and exiting. It orchestrates multiple methods to manage web scraping or data extraction tasks systematically. | def run(self):
self.headersLink()
self.regionalLink()
self.kategoriLainnyaLink()
self.eventLainnyaLink()
self.channelLainnyaLink()
self.search()
self.quit() |
def create_header(nav_data) -> dmc.Header:
return dmc.Header(
height=70,
fixed=True,
px=25,
children=[
dmc.Stack(
justify="center",
style={"height": 70},
children=dmc.Grid(
children=[
... | The main task of the code is to create a Dash application shell using Mantine UI, configuring dynamic theme handling (light/dark toggle), navigation components, URL routing, and layout structure. It sets up clientside callbacks for theme switching, component updates, and drawer interactions, returning a nested MantineP... | def create_app_shell(nav_data, children) -> dmc.MantineProvider:
clientside_callback(
""" function(data) { return data } """,
Output("mantine-docs-theme-provider", "theme"),
Input("theme-store", "data"),
)
clientside_callback(
"""function(n_clicks, data) {
if (da... |
def get_config(self, section, key):
""" Get the value of a key in a section.
Arguments:
section: section
key: key
"""
if self.config.has_option(self.module, key):
return self.config[self.module][key]
return self.config[section][key... | The code's main task is to send an email using a method specified in configuration. It checks the 'method' value (file, SMTP, Mailgun, or default Sendgrid), then writes the email body to a file or delegates delivery to the corresponding SMTP/Mailgun/Sendgrid method. The function handles four possible email delivery app... | def deliver(self, title, body):
""" Delivery email.
Arguments:
title: mail title
body: body text
"""
method = self.get_config('GENERAL', 'method')
if method == "file":
path = self.get_config('FILE', 'path')
with open(pat... |
def title():
""" Get title of mail. """
now = datetime.now()
return "Events {0}".format(now.strftime('%Y-%m-%d %H:%M:%S'))
def page(title):
""" Get HTML page.
Arguments:
title - title.
"""
return """<!DOCTYPE html>
<html dir="ltr" lang="en">
<h... | The code retrieves and sorts events based on time constants, formats them into HTML content, and sends the formatted data via email. It fetches a title and page template, constructs event data, orders events chronologically, generates styled HTML paragraphs, and triggers an email delivery with the compiled content. | def execute(self):
""" Events backbone handler. """
title = self.title()
page = self.page(title)
all_times = self.build_time_constants()
events = self.get_events(all_times)
if events:
events.sort(key=lambda tup: tup[0])
html = ""
for e... |
def creators(self, title, slug):
""" Add a Creators comics.
Args:
title: title of Creator comics
slug: short name of Creators comics
"""
url = "https://www.creators.com/read/{}".format(slug)
self.generic('class="fancybox"', 'img src="', title, ... | The code's main task is to collect and compile comic strips from multiple sources (e.g., Dilbert, Garfield, Calvin and Hobbes) into an HTML page titled with the current date/time. It uses predefined methods to fetch comics, formats them, and sends the compiled page via email. The process includes handling specific comi... | def execute(self):
""" Run the handler. """
title = "Comics {0}".format(time.strftime('%Y-%m-%d %H:%M:%S',
time.localtime()))
self.creators('Andy Capp', 'andy-capp')
self.creators('B.C.', 'bc')
self.kingdom('Beetle Bailey', 'beetl... |
def __connect_to_activedirectory():
domain = __read_required_setting("AD_DOMAIN")
if "AD_DOMAINCONTROLLER" in os.environ:
# Use explicitly defined DC.
domain_controllers = [os.environ["AD_DOMAINCONTROLLER"]]
else:
# Look up DC in DNS.
domain_controllers = ad.domain.ActiveDir... | The code creates a computer account in Active Directory for a GCE instance, ensuring proper authentication, authorization via project and AD checks, handling existing accounts, adding to MIG groups, setting a Kerberos password, and returning credentials for the computer to join the domain. | def __register_computer(request):
"""
Create a computer account for the joining computer.
"""
# Only accept requests with an Authorization header.
headerName = "Authorization"
if not headerName in request.headers:
logging.exception("Authentication missing")
return flask.abor... |
def __cleanup_computers(request):
"""
Clean up stale computer accounts.
"""
# Only accept requests with an Authorization header.
headerName = "Authorization"
if not headerName in request.headers:
logging.exception("Authentication missing")
return flask.abort(HTTP_AUTHENTICAT... | This function handles HTTP requests for a cloud service, routing based on URL path and method: POST /cleanup triggers cleanup, GET / serves a join script, POST / registers computers, and other requests return a 405 error. | def register_computer(request):
"""
Cloud Functions entry point.
"""
if request.path == "/cleanup" and request.method == "POST":
return __cleanup_computers(request)
elif request.path == "/" and request.method == "GET":
return __serve_join_script(request)
elif request.path == ... |
def getRobotVertices(xpos, ypos, wdeg, radius):
wdeg = -wdeg + 45
v1theta = -1 * wdeg + 90
v2theta = -1 * wdeg
v3theta = -1 * wdeg - 90
v4theta = -1 * wdeg - 180
v1x = radius * np.cos(v1theta * np.pi / 180)
v1y = radius * np.sin(v1theta * np.pi / 180)
v2x = radius * np.cos(v2theta * np.... | This function checks if a robot's pose (position and orientation) is valid by verifying its vertices against predefined boundary conditions. It calculates an adjusted angle, segments the robot's vertices, and applies specific collision/pose checks based on directional ranges. If any check fails, it returns False; other... | def checkRobotPoseUpdate(xpos, ypos, wdeg, radius):
# print(xpos, ypos)
robotVerticesArr = getRobotVertices(xpos, ypos, wdeg, radius)
degpv = wdeg + 45
times180 = int(abs(degpv) / 180)
# print(degpv, times180)
if times180 > 0:
if wdeg > 0:
if times180 % 2 == 0:
... |
def tree(label, branches=[]):
for branch in branches:
assert is_tree(branch), 'branches must trees'
return [label] + list(branches)
def label(tree):
return tree[0] | The function generates a binary tree where each node's label is the sum of its children's labels, recursively constructing Fibonacci-like structures. For n ≤ 1, it returns a leaf node with value n. For larger n, it creates left and right subtrees with n-2 and n-1, combining them into a new tree with the sum of their la... | def fib_tree(n):
if n <= 1:
return tree(n)
else:
left, right = fib_tree(n-2), fib_tree(n-1)
return tree(label(left)+label(right), [left, right]) |
def is_leaf(tree):
return not branches(tree)
def tree(label, branches=[]):
for branch in branches:
assert is_tree(branch), 'branches must trees'
return [label] + list(branches)
def label(tree):
return tree[0]
def branches(tree):
return tree[1:] | This function recursively increments the value of each leaf node in a tree by 1. If the input tree is a leaf, it returns a new tree with the label increased by 1. Otherwise, it applies the same operation to all branches and constructs a new tree with the original label and modified branches. | def increment_leave(t):
if is_leaf(t):
return tree(label(t) + 1)
else:
bs = [increment_leave(b) for b in branches(t)]
return tree(label(t), bs) |
def tree(label, branches=[]):
for branch in branches:
assert is_tree(branch), 'branches must trees'
return [label] + list(branches)
def label(tree):
return tree[0]
def branches(tree):
return tree[1:] | The code recursively increments the label of a tree and all its branches by 1, returning a new tree with updated values. | def increment(t):
return tree(label(t)+1, [increment(b) for b in branches(t)]) |
def _get_resource_headers(self):
access_token = self.get_access_token()
return {"Authorization": f"Bearer {access_token}"}
def _format_search_params(self, extra_search_params):
if extra_search_params is None:
return ""
if not isinstance(extra_search_params, dict):
... | The function retrieves a resource by constructing a URL endpoint using provided parameters (lookup_id, resource_type, version) and optional extra search criteria. It formats the endpoint, appends query parameters if specified, and executes a GET request with appropriate headers to fetch the resource data. | def get_resource(
self,
lookup_id,
resource_type,
version="v1",
extra_search=None,
extra_search_params=None,
):
headers = self._get_resource_headers()
endpoint = self.resource_lookup_root.format(
version=version, resource_type=resource_type... |
def create_date_win(self):
date_win = curses.newwin(1, self.width, 0, 0)
date_win.bkgdset(" ", curses.color_pair(Colors.DATE))
return date_win
def create_helpbar_win(self):
helpbar_win = curses.newwin(1, self.width, self.height - 1, 0)
helpbar_win.bkgdset(" ", curses.color_pair(C... | This code initializes a user interface for entering or editing a time log entry. It sets up screen dimensions, creates windows for displaying the date and help bar, defines labeled fields for start time, duration, activity, and text input, and prepares interactive elements for user input. The interface supports editing... | def __init__(self, scr, selected_day, entry, new_record=True):
self.scr = scr
self.entry = entry
self.date = selected_day.date
self.is_new_record = new_record
self.width = curses.COLS
self.height = curses.LINES
self.label_area_width = floor(self.width / 3)
... |
def fins(a, b):
"""
:param a: integer
:param b: integer
:return: integer
"""
return (a - 1) * (b - 1)
def coprime(a, b):
"""
:param a: integer
:param b: integer
:return: integer
"""
cop = get_primes_between(1, b, -1)
for i in cop:
if 1 < i < a and a % i != 0 a... | This code generates an RSA-like key pair by computing the product of two primes (primary_key), Euler's totient function (o_n), a coprime number (co_prime) with o_n, and the modular inverse (d) of co_prime modulo o_n. It returns the public exponent (co_prime), private exponent (d), and modulus (primary_key) for cryptogr... | def keygen(p1=1001, p2=271):
primary_key = p1 * p2 # primary key
o_n = fins(p1, p2) # (o(n))
co_prime = coprime(primary_key, o_n)
d = dkey(co_prime, o_n)
return co_prime, d, primary_key |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.