dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def disable_swap():
print('disabling swap...')
if '/sbin' not in os.environ['PATH']:
os.environ['PATH'] += ':/sbin'
commands = [
"dphys-swapfile swapoff",
"dphys-swapfile uninstall",
"update-rc.d dphys-swapfile remove",
"systemctl disable dphys-swapfile",
]
... | The main task of the code is to configure a system for containerized environments by disabling swap memory, enabling cgroups for resource management, and setting the root directory, ensuring isolated and controlled execution of processes. | def main():
disable_swap()
enable_cgroups()
set_root() |
def get_sentences_and_entities(fine_entity: str):
sentences_with_entity = dataset_provider.get_by_fine_grained_type_fewnerd(fine_entity)["hits"]["hits"]
same_type, different_type = [], []
for sentence in sentences_with_entity:
sentence_text = sentence["_source"]["full_text"]
entities_of_fine... | The code processes entity pairs from various categories using a pre-initialized LLaMA3 model to determine a threshold for classification or similarity analysis. It iterates through combinations of same-type entities, compares them against different-type entities, and applies the 'find_threshold_hooked' function to eval... | def main():
clearml_poc.clearml_init()
assert torch.cuda.is_available(), "no gpu available"
global llama3
llama3 = llama3_interface.LLama3Interface()
layers_count = 33
layers_list = list(range(layers_count))
types = [
"language",
"athlete",
"mountain",
"mus... |
def format_data(coords_list=None):
"""
Does some stats and stuff
:return:
"""
if coords_list is None:
mvb = (51.45591, -2.603067)
cd = (51.4648, -2.6254)
kd = (51.462553, -2.597698)
coords_list = [mvb, cd, kd]
# Random number generator
# np.random.se... | The code generates isochrone polygons from input coordinates by formatting data, building a map centered on a point, creating isochrones, and extracting intersection coordinates. It processes these into a flattened list of polygon coordinates for output. | def get_poly(data):
print("1")
center, coords_list = format_data(coords_list=data)
print("2")
# build the map using a central point
map_ = build_map(center, dist=3000, ntype="walk")
print("3")
# make the list of isochrone polygons
polys, intersection = make_intersect(coords_list, map_)
... |
def get_edge_mask(self,
src_nid,
tgt_nid,
ghetero,
feat_nids,
prune_max_degree=-1,
k_core=2,
prune_graph=True,
with_path_loss=True):
... | The code generates path explanations for a predicted link between source and target nodes in a heterogenous graph. It extracts a computation subgraph, learns edge masks using GNN layers, prunes the graph (via degree/k-core), and retrieves top paths. Paths are converted to original node IDs, with optional edge masks for... | def explain(self,
src_nid,
tgt_nid,
ghetero,
num_hops=2,
prune_max_degree=-1,
k_core=2,
num_paths=1,
max_path_length=3,
prune_graph=True,
with_path_loss=T... |
def get_page_url():
"""
Initial function to get the list of page urls with respect to different alphabet.
:return: list of urls
"""
page_url_list = []
url = "http://devri.bzh/dictionnaire/a/"
session = CachedSession()
page = session.get(url)
soup = BeautifulSoup(page.content, "html.p... | The main task of the code is to scrape and process data from web pages by first retrieving a list of page URLs, extracting entry URLs from those pages, fetching entry details, and finally writing the collected data into a CSV file named "breton_devri.csv". The code also forces the use of IPv4 for network requests. | def main():
# force requests to use ipv4
urllib3_cn.allowed_gai_family = allowed_gai_family
page_url_list = get_page_url()
entry_url_list = get_entry_url_list(page_url_list)
entry_list = get_entry(entry_url_list)
write_to_csv(entry_list, "data/breton_devri.csv") |
def availability(desin, orig, model):
base = [0,1,2,3]
#print(base)
base.pop(base.index(desin))
#print(base)
base.pop(base.index(orig))
if type(model.get_top_cheese(base[0])) == type(None):
return base[0]
if type(model.get_top_cheese(base[1])) == type(None):
return base[1]
de... | This function implements a recursive solution to the Tower of Hanoi problem, moving 'n' disks from an original peg to a destination peg using an intermediate peg. It splits the disks into top and bottom sections, recursively moves the top section to the intermediate peg, then the bottom section directly to the destinat... | def move_stool(model,n, i, ori, des):
if n == 1:
model.move(ori, des)
else:
top = n-i
bottom = i
inter = availability(ori, des, model)
move_stool(model, top, get_i(best_i(top)), ori, inter)
move_stool(model, bottom, get_i(bes... |
def availability(desin, orig, model):
base = [0,1,2,3]
#print(base)
base.pop(base.index(desin))
#print(base)
base.pop(base.index(orig))
if type(model.get_top_cheese(base[0])) == type(None):
return base[0]
if type(model.get_top_cheese(base[1])) == type(None):
return base[1] ... | This function recursively solves the Tower of Hanoi puzzle by moving `n` disks from an origin peg to a destination peg using an intermediate peg. It handles animation via sleep and print statements if enabled, splits disks into top/bottom sections, and recursively transfers them. The `availability` function determines ... | def move_stool(model,n, i, ori, des, animate, tm):
tim = tm
o = ori
d = des
if n == 1:
model.move(o, d)
try:
if animate == True:
time.sleep(tim)
print(model)
except TypeError:
print("dangit... |
def move_stool(model,n, i, ori, des, animate, tm):
tim = tm
o = ori
d = des
if n == 1:
model.move(o, d)
try:
if animate == True:
time.sleep(tim)
print(model)
except TypeError:
print("dangit... | The function `tour_of_four_stools` moves a tower of cheeses from the first stool to the fourth using a four-stool Tower of Hanoi algorithm. It utilizes the `move_stool` function recursively, with parameters determining the number of cheeses, source, and destination stools. The task involves calculating optimal intermed... | def tour_of_four_stools(model, delay_btw_moves=0.5, animate=True):
"""Move a tower of cheeses from the first stool in model to the fourth.
@type model: TOAHModel
TOAHModel with tower of cheese on first stool and three empty
stools
@type delay_btw_moves: float
time delay between move... |
def copy_grid(self):
return self.grid.copy()
def alive_remains_alive(self, pos: List) -> bool:
"""Evaluate whether a 'alive' cell (value 1) remains 'alive'."""
return 2 <= self.get_total_number_of_neighbours(pos) <= 3
def dead_becomes_alive(self, pos: List) -> bool:
"""Evaluate whether a... | The main task of the code is to compute the next state of a Game of Life grid by evaluating each cell's survival or birth based on its neighbors. It creates a copy of the current grid, applies rules to determine if alive cells remain alive or dead cells become alive, updates the copy accordingly, and replaces the origi... | def compute_new_grid(self):
"""Evaluate the game of life and as a result update 'self.grid'"""
# make a copy of the grid
new_grid = self.copy_grid()
# evaluate each cell in the grid
for row_num in range(0, self.grid_shape[0]):
for col_num in range(0, self.grid_shape[... |
def load(self):
print('# loading govdb')
govdb=Roll( self,WW2ROLLSCSV,0 )
print('# processing govdb')
self.process_gov(govdb)
print()
print("#################")
for fn,sk in CONVERT:
self.alldb.append( Roll(self,CSVDIR+fn,sk) )
print()
print('# processing')
t=0
maindb=... | The code initializes a class instance by setting up data structures (alldb, rows, dictionaries) and performing three key operations: loading data, verifying data integrity, and comparing US vs government data to ensure consistency. | def __init__(self):
self.alldb=[]
self.rows=[]
self.by_servicenumber={}
self.by_surname={}
self.govdb={}
#
self.load()
self.verify()
self.verify_us_vs_gov() |
def get_description_from_readmeMd(markdown: str) -> Description:
parser = marko.parser.Parser()
ast = cast(marko.block.BlockElement, parser.parse(markdown))
description: Description = {"title": "", "subtitle": ""}
for block in ast.children:
# skip blank lines
if isinstance(block, marko.b... | The function `get_dir_info` retrieves metadata descriptions from specific files (e.g., README.md, package.json, pyproject.toml) within a given directory. It checks each file, reads its content, and uses targeted parsing functions to extract descriptions, storing them in a dictionary with predefined keys for structured ... | def get_dir_info(path: str) -> dict[str, Description]:
"""Get full description of dir `path`"""
p = os.listdir(path)
descriptions = {}
for i in p:
logger.trace(f"reading {i}")
if i.lower() == "readme.md":
descriptions[SOURCE_README_MD] = get_description_from_readmeMd(
... |
def minimumSpanningTree(self):
tree = []
visited_nodes = [0]
unvisited_nodes = [i for i in range(1, self.n)]
while len(unvisited_nodes) > 0:
start, end, min_dist = 0, 0, math.inf
for i in visited_nodes:
for j in unvisited_nodes:
... | The function implements Christofides' algorithm for approximating solutions to the Traveling Salesman Problem (TSP) on metric graphs. It constructs a minimum spanning tree (MST), adds edges to make all nodes even-degree via perfect matching, forms an Eulerian circuit, removes duplicate nodes, and returns the optimized ... | def Christofides(self):
# work for both case
minSpanningTree = self.minimumSpanningTree()
perfectMatch = self.perfectMatching(minSpanningTree)
graph = minSpanningTree + perfectMatch
eulerian = self.eulerianCircuit(graph)
self.removeDuplicate(eulerian)
return sel... |
def showStartScreen():
titleFont = pygame.font.Font('freesansbold.ttf', 100)
titleSurf1 = titleFont.render('Wormy', True, RED, BLACK)
titleSurf2 = titleFont.render('The Game!', True, DARKGRAY)
degrees1 = 0
degrees2 = 0
while True:
DISPLAYSURF.fill(BGCOLOR)
rotatedSurf1 = pygame.... | The main task of the code is to initialize a Pygame game with a window, clock, and font, then run a game loop that displays a start screen, executes the game logic, and shows a game-over screen upon completion. It sets up essential game components and manages the flow between different game states. | def main():
global FPSCLOCK, DISPLAYSURF, BASICFONT
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
pygame.display.set_caption('Wormy Is a Good Game!')
showStartScreen()
... |
def get_db_meta_data(argument):
switcher = DB_META_DATA
return switcher.get(argument, False)
def run_sqlserver_commands(query):
"""Run SQL_SERVER commands using sqlcmd utility.
"""
subprocess.call(
['sqlcmd', '-S', db_host, '-U', database_config['user'], '-P', database_config['password'], '-... | This function creates databases and executes associated scripts for specified database engines (SQL Server, MySQL, Oracle). It checks configuration metadata, creates databases if no scripts exist, or runs provided scripts if they exist. Engine-specific commands handle database creation and script execution, with Oracle... | def setup_databases(db_names):
"""Create required databases.
"""
base_path = Path(workspace + "/" + PRODUCT_STORAGE_DIR_NAME + "/" + dist_name + "/" + 'dbscripts')
engine = db_engine.upper()
db_meta_data = get_db_meta_data(engine)
if db_meta_data:
databases = db_meta_data["DB_SETUP"][pro... |
def fix(imput):
output = np.zeros([100, 100, 3])
for i in range(100):
for j in range(100):
output[i][j] = [imput[i][j][0],
imput[i][j][0],
imput[i][j][0]]
return output
def convert2(self, image_no):
return self.generat... | The code's main task is to randomly select an image from the `Images_BW` list, display it after applying a `fix` function, and visualize two converted versions of the image using `self.convert2` and `self.convert` methods. It generates four subplots to show the original fixed image and the two converted outputs, then d... | def evaluate(self):
n = random.randint(0, len(Images_BW)-1)
plt.figure(1)
plt.imshow(fix(Images_BW[n]))
plt.figure(2)
#plt.imshow(Images_CL[n])
im = self.convert2(n)
im2 = self.convert(n)
plt... |
def train_encoder(self, batch = 4):
train_data = []
train_data2 = []
label_data = []
for i in range(batch):
im_no = random.randint(0, len(Images_BW) - 1)
train_data.append(Images_BW[im_no])
train_data2.append(noise(im_no))
label_data.app... | The code trains an encoder by calling `train_encoder` with a batch size, records the loss, and periodically evaluates the model, saves checkpoints, and resets memory every 10 iterations. It also prints the loss and increments the iteration counter. | def train(self, batch_size = 4):
#self.train_encoder(batch_size)
loss = self.train_encoder(batch_size)
#self.train_dis(batch_size)
#self.train_gen(batch_size)
#dtry = 0
#while (self.av_gen() > 0.7 or self.av_dis() < 0.2 or self.av_gen() > self.av_dis()) and dt... |
def cmd_parser():
parser = argparse.ArgumentParser()
g = parser.add_argument_group('Arguments')
#g.add_argument('-distances', '--distance-matrix', nargs='?', required=False,\
# type=str, default='distances.csv')
g.add_argument('-colors', '--color-matrix', nargs='?', required=False,\
... | (The main task of the code is to parse command-line arguments, read a color matrix from a file, process input parameters like the number of medians and requirement list, and execute a calculation based on the specified command. Results are logged to a file or stdout. The code initializes logging, loads data, and invoke... | def main():
tstart = time.time()
## handling command line arguments
parser = cmd_parser()
opts = vars(parser.parse_args())
#dist_matrix_file = opts['distance_matrix']
color_matrix_file = opts['color_matrix']
num_of_medians = opts['num_of_medians']
requirement_list = np.arra... |
def scaling_nof_centers(command,\
unique = True,\
range = [4, 5, 6, 7, 8, 9],\
objective = None,\
results_dir = 'exp-results',\
test_run = False,
many_solutions_lp_only = True):
print("scaling_nof_centers", command, unique, range)
... | The code evaluates the performance of different algorithms (linear-program, brute-force, dynamic-program) under varying uniqueness constraints and scaling parameters (k, t, n) for a given objective. It systematically tests algorithm behavior by iterating through predefined data ranges, storing results in the specified ... | def test_batch_scaling(objective, results_dir, test_run = False):
for unique in [True, False]: # worst case first
for algo_type in ['linear-program', 'brute-force', 'dynamic-program']:
################################
# scaling 'k'
if test_run:
range_data ... |
def scaling_nof_centers(command,\
unique = True,\
range = [4, 5, 6, 7, 8, 9],\
objective = None,\
results_dir = 'exp-results',\
test_run = False,
many_solutions_lp_only = True):
print("scaling_nof_centers", command, unique, range)
... | The code tests the scalability of a linear programming (LP) algorithm by running experiments with varying parameters: 'k' (number of centers), 't' (groups), and 'n' (facilities). It uses log-spaced ranges for 'n' and linear ranges for 'k'/'t', calling specific scaling functions to evaluate performance under different c... | def test_batch_scaling_LP_search(objective, results_dir, test_run = False):
algo_type = 'linear-program'
unique = False
################################
# scaling 'k'
range_data = list(range(4, 7))
#end if
scaling_nof_centers(algo_type,\
unique,\
... |
def cmd_parser():
parser = argparse.ArgumentParser()
g = parser.add_argument_group('Arguments')
g.add_argument('-batch', '--batch-type', nargs='?', required=False, type=str,\
default='feasibility', choices=['feasibility', 'optimal', 'bicriteria'])
g.add_argument('-obj', '--objective',... | The main task of the code is to parse command-line arguments, validate input parameters, create a timestamped results directory, and execute scheduled experiments based on the specified batch type (feasibility, optimal, or bicriteria). It ensures required parameters like 'objective' are provided for bicriteria runs and... | def main():
parser = cmd_parser()
opts = vars(parser.parse_args())
batch_type = opts['batch_type']
objective = opts['objective']
results_dir = opts['results_dir']
test_run = opts['test_run']
if batch_type == 'bicriteria' and objective == None:
sys.stderr.write("Err... |
def draw_background(self):
if self.status == -1:
self.screen.blit(self.game_menu.image, (0, 0))
# shawdow
self.render_font("DREAM", 150, (WIDTH / 2 + 4, 120 + 4), TITLE_TEXT_SHADOW_COLOR)
# title
self.render_font("DREAM", 150, (WIDTH / 2, 120), TITLE_T... | The code executes a game loop that updates the game state, renders graphics, and handles input. It draws the background and sound effects, checks the game status, and conditionally updates elements like the player, village interface, NPCs, and UI (equipment/status bar). It manages player movement, event handling, curso... | def run(self):
self.draw_background()
self.sfx_handling()
# everything happened when not in menu screen
if not self.status == -1 and not self.status == 0:
if not self.in_village:
self.draw_line()
self.node_sprites.draw(self.screen)
... |
def sort_controllers(controllers):
# get home for sorting
home = controllers["HomeController.cs"]
excluded_controllers = ["HomeController.cs", "v2Controller.cs"]
sorted_controllers = dict(
[("HomeController.cs", home)] + sorted( [ (k,v) for k,v in controllers.items() if not k in exclude... | The main task of the code is to generate a formatted HTML sidebar by sorting input controllers, creating navigation links for each controller's actions, and concatenating them into a structured HTML string. It processes controller-action pairs, transforms them into HTML elements using the `html` function, and returns t... | def create_sidebar(controllers):
controllers = sort_controllers(controllers)
sidebar = ""
for controller, actions in controllers.items():
links = "\n".join(create_links(controller, actions))
sidebar += html(controller, links)
return sidebar |
def get_arm_xyz_from_screen(scr_x, scr_y):
if not 'hand-eye' in params:
print('No hand-eye calibration')
sys.exit(0)
coef = np.array(params['hand-eye']['coef'])
intercept = np.array(params['hand-eye']['intercept'])
arm_x, arm_y, arm_z = coef.dot(np.array([scr_x, scr_y])) + intercept
... | The main task of the code is to test robotic arm movement by iterating over predefined screen coordinates, converting them to 3D arm positions, lifting the arm, moving to target positions, and pausing for observation. It sets a global test position variable during each test step, then resets it, ultimately returning th... | def test_xy():
global test_pos
h, w = frame.shape[:2]
for scr_x in np.linspace(w / 3, w * 2 / 3, 2):
for scr_y in np.linspace(h // 2, h * 2 // 3, 2):
arm_x, arm_y, arm_z = get_arm_xyz_from_screen(scr_x, scr_y)
for _ in move_xyz(arm_x, arm_y, LIFT_Z):
yield
... |
def move_to_ready():
degs = [ 0, 0, -90, -90, 0, 0 ]
for _ in move_all_joints(degs):
yield
def open_hand():
for _ in move_joint(hand_idx, 100):
yield
def move_xyz(x, y, z, move_time=None):
pose = get_pose_from_xyz(x, y, z)
for _ in move_linear(pose, move_time):
yield
def clo... | The main task of the code is to control a robotic arm to pick up an object from a specified location (arm_x, arm_y, arm_z) by moving to a ready position, lowering the arm to grasp the object, closing the hand, lifting it, and then moving to predefined poses (pose1, pose2) to reposition the object before releasing it an... | def grab(work_scr_x, work_scr_y, arm_x, arm_y, arm_z):
old_move_time = set_move_time(1)
for _ in move_to_ready():
yield
for _ in open_hand():
yield
for _ in move_xyz(arm_x, arm_y, LIFT_Z):
yield
# Lower the hand
z = arm_z - (PLACE_Z - PICK_Z)
for _ in move_xyz(ar... |
def get_cell(self, alias):
"""
Get a Cell object by its alias
Args:
alias (str): Alias of cell
Returns:
Cell: The Cell object itself
"""
alias.upper()
cell_pos = utils.parse_alias(alias)
if cell_pos['col'] not in self.columns_alias:
raise AliasNotFound(col=cell_pos['col'])
for indx, cell ... | This method updates a cell's value based on the provided alias and value. It checks if the existing cell's type matches the inferred type of the new value. If compatible, it updates the cell's content (e.g., parsing expressions for ExpressionCell). If the type differs, it removes the old cell and creates a new one with... | def update_cell(self, alias, value):
"""
Updates every a concrete cell
Returns:
boolean: Success
"""
cell_2_update, idx = self.get_cell(alias)
new_type = utils.infer_cell_type(value=value)
# Updating cells without changing its type
if isinstance(cell_2_update, globals()[new_type]):
if new_type ... |
def json_pretty_string(self, json_obj):
return json.dumps(json_obj, sort_keys=True, indent=4)
def create_file_name(self, file_name):
return self._work_dir / Path(file_name)
def write_to_file(self, dest_file, data, label):
try:
f = dest_file.open( "a" )
f.write("{} Response:\n".format(label))
... | The main task of the code is to compare responses from two nodes (test and reference) by sending identical requests. It checks for HTTP status codes, processes JSON responses (removing tags, renaming fields), detects errors, and verifies response equality. If discrepancies are found, it logs differences, writes respons... | def compare_results(self, args, print_response = False, test_node_is_hive = TEST_NODE_IS_HIVE, reference_node_is_hive = REFERENCE_NODE_IS_HIVE):
try:
from requests import post
print("Sending query:\n{}".format(self.json_pretty_string(args)))
resp1 = post(self._test_node, data=json.dumps(args))
... |
def load_file(path:str):
ret = {}
with open(path, 'r') as f:
ret = json.load(f)
return ret
def map_posts(posts:list):
mapped = {}
for post in posts:
key = post['author'] + '/' + post['permlink']
assert not key in mapped, "Duplicated post"
mapped[key] = post
return mapped
def process_post(pos... | This code processes and compares posts from two input files (input_orig_path and input_out_path), generates a pattern list (pat), matches posts between the files, sorts the results based on specified fields (e.g., id, pending_payout_value), and saves the processed output to a specified path (output_pat_path). It handle... | def main():
if len(sys.argv) != 4 and len(sys.argv) != 5:
print( "Usage: __name__ input_orig_path input_out_path output_pat_path [reorder_field]" )
exit ()
orig = load_file(sys.argv[1])
out = load_file(sys.argv[2])
if os.path.exists(sys.argv[3]):
os.remove(sys.argv[3])
if isinstance(orig,list):
... |
def get_token_spans(text):
offset = 0
for s in sent_tokenize(text):
offset = text.find(s, offset)
yield sentence_tokens(s, offset)
def get_trigger(s, e, entities, phosphorylations):
for tlbl, trigger, entity, rule in phosphorylations:
if entities[trigger][2] >= s and entities[trigger... | The function processes annotated data files to prepare training samples for language models. It parses entity and event annotations, normalizes text with placeholders, and constructs input, positional, character, and rule language models. Data is sanitized, triggers/entities are replaced, and samples are generated for ... | def prepare_data(
dirname,
event_type,
input_lang=Lang("1"),
pos_lang=Lang("2"),
char_lang=Lang("3"),
rule_lang=Lang("4"),
train=list(),
valids=None,
n_sample=0,
):
raw_train = dict()
if valids:
vj = json.load(open(valids))
else:
vj = dict()
with open(... |
def get_token_spans(text):
offset = 0
for s in sent_tokenize(text):
offset = text.find(s, offset)
yield sentence_tokens(s, offset)
def get_entity(s, e, entities, x):
for entity in entities:
if (
entities[entity][2] > s
and entities[entity][1] < e
a... | The main task of the code is to process annotated text files (.a1) and corresponding raw text files (.txt) to generate structured test data for NLP tasks. It extracts entity annotations, replaces entities with placeholders, and builds linguistic representations (input, position, character) using specified language mode... | def prepare_test_data(
dirname,
input_lang=Lang("1"),
pos_lang=Lang("2"),
char_lang=Lang("3"),
rule_lang=Lang("4"),
):
raw_test = list()
maxl = 0
for fname in glob.glob(os.path.join(dirname, "*.a1")):
root = os.path.splitext(fname)[0]
name = os.path.basename(root)
... |
def get_training(filepath):
train_df = pd.read_csv(filepath)
train_df.columns = ["id", "genre"]
train_df.head()
ids = train_df["id"]
padded = []
wavs = []
for id in ids:
pad = str(id).zfill(8)
padded.append(pad)
wavs.append("{0:s}.wav".format(pad))
train_df["pad... | The code processes audio data for machine learning by loading training/test CSV files, splitting data into training/validation/test sets, extracting audio features, normalizing features via min-max scaling and standardization, saving processed data as NumPy arrays, and generating predictions using a model to output gen... | def driver():
# test numpy
print(np.max([2, 5, 7, 1]))
train_fp = r"D:\proj3_data\project3\train.csv"
# train_fp = r'D:\repos\CS529_Project3\train1.csv'
test_fp = r"D:\proj3_data\project3\new_test_idx.csv"
# test_fp = r'D:\repos\CS529_Project3\test1.csv'
train_df = get_training(train_fp)
... |
def showNumber(num, marker=mrkDot, sep=" ", part=5,
DBG=False):
""" Getting graphical representation of a number.
Args:
num: int - number to be graphically represented,
marker: str - char for a marker,
sep: str - number parts (sections) separator,
part: int - leng... | The main task of the code is to test mathematical operations (showNumber, mul, add, sub, div) with varying numbers and markers. It iterates through number-lists, applies operations using corresponding markers from mrkrs, prints results/error messages, and verifies marker types. The code evaluates how different markers ... | def main():
nrs = [3, 7, 11., 11]
bes = [2, 3, 4, 5]
mrkrs = [mrkDot, mrkCat, mrkDog, mrkSnake]
for i, nr in enumerate(nrs):
marker = mrkrs[i]
nrGraph, errMsg = showNumber(nr, marker)
print(f"{i}) {nr}: {nrGraph = }\n{errMsg = }")
print(mrkDot, type(mrkDot))
print(mrkDog,... |
def transform(mat):
sum_list = list(map(sum, mat))
bool_indices = list(map(lambda x: x == 0, sum_list))
indices = set([i for i, x in enumerate(bool_indices) if x])
new_mat = []
for i in range(len(mat)):
new_mat.append(list(map(lambda x: Fraction(0, 1) if(sum_list[i] == 0) else simplify(x, su... | The code computes the solution to a linear system by transforming the matrix, decomposing it into Q and R, inverting Q, and multiplying with R. It then calculates the least common multiple (LCM) of denominators in the resulting row vector, scales the vector elements by this LCM, and appends the LCM as the final element... | def solution(mat):
res = transform(mat)
if res[1] == len(mat):
return [1, 1]
Q, R = splitQR(*res)
inv = inverse(Q)
res = mat_mult(inv, R)
row = res[0]
l = 1
for item in row:
l = lcm(l, item.denominator)
res = list(map(lambda x: int(x.numerator*l/x.denominator), row))
... |
def remove_edges(self, edges):
'''
Adds a list of (i,j) where i,j are in range(n) and reinitialize the
structures
'''
for e in edges:
if e[1] in self.FSs[e[0]]:
self.edges = np.delete(self.edges, np.where(self.edges == e))
self.FS_costs... | The code implements the Ford-Fulkerson algorithm to compute the maximum flow in a flow network by iteratively finding augmenting paths in the residual graph and updating capacities. It modifies the graph structure by adding a super-source and super-sink, adjusting edges based on capacities, and uses BFS to identify aug... | def ford_fulkerson(self):
'''
Returns ford_fulkerson's max flux in a flux graph
'''
if not self.maxflux:
print('cannot apply for fulkerson, graph is not a flow graph')
print('''warning! this algorithm takes O(m^2n)!''')
print('O(m^2n) = O(', self.n*len(self.ed... |
def _handle_module_load_event(self, event):
self._send_module_event_notification(event, is_load=True)
def _handle_module_unload_event(self, event):
self._send_module_event_notification(event, is_load=False)
def _send_user_output(self, level, text):
self._debugger_store.ipc_channel.send_output_me... | This function handles LLDB target events by checking the event type and routing it to specific handlers: modules loaded/unloaded events trigger corresponding methods, symbol-loaded events log a message, and unknown events use a generic handler. It acts as a dispatcher for target-related events in the LLDB debugging fra... | def _handle_target_event(self, event):
lldb = get_lldb()
if event.GetType() == lldb.SBTarget.eBroadcastBitModulesLoaded:
self._handle_module_load_event(event)
elif event.GetType() == lldb.SBTarget.eBroadcastBitModulesUnloaded:
self._handle_module_unload_event(event)
... |
def _handle_target_event(self, event):
lldb = get_lldb()
if event.GetType() == lldb.SBTarget.eBroadcastBitModulesLoaded:
self._handle_module_load_event(event)
elif event.GetType() == lldb.SBTarget.eBroadcastBitModulesUnloaded:
self._handle_module_unload_event(event)
... | The code processes LLDB events in a loop, handling target, process, breakpoint, and watchpoint events via specific handlers. It terminates the event loop, shuts down the Chrome server app, and detaches or kills the inferior process based on the debugging mode. | def run(self):
lldb = get_lldb()
while not self.should_quit:
event = lldb.SBEvent()
if self._listener.WaitForEvent(1, event):
if lldb.SBTarget.EventIsTargetEvent(event):
self._handle_target_event(event)
elif lldb.SBProcess.Event... |
def rnd_proto_init(self):
"""
Initialize the prototypes randomly.
"""
# Define the prototypes (random init)
return tf.Variable(
initial_value=tf.random_uniform(
[utils.n_protos(),
utils.im_height(),
utils.im_width()],
... | The code constructs the IUPG model as a TensorFlow graph, defining placeholders for input images and labels, initializing prototypes, processing inputs through a neural network, computing distances between samples and prototypes, and calculating the loss with L2 regularization. It sets up the graph structure, including... | def _build_IUPG(self):
"""
Build the IUPG model as a TF graph.
"""
# Set the random seed in TF for repeatability
tf.compat.v1.random.set_random_seed(self.random_seed)
# Placeholder for batch of images
self.X_batch = tf.compat.v1.placeholder(
tf.float3... |
def _get_new_bibs(self, created_date_from, created_date_to):
result = self.sierra_api.bibs_get(
created_date={'range_from': created_date_from, 'range_to': created_date_to},
fields='id,author,materialType,lang,createdDate',
deleted=False,
suppressed=False
)... | The main task of the code is to process newly created bib records by retrieving them, filtering out duplicates, converting IDs to integers, handling errors, and updating tracking variables. It logs progress and issues, skips already processed records, and returns the count of new bibs along with updated timestamps for ... | def _process_batch(self, last_bib_created_at, last_bib_record_number, run_log):
new_bibs = self._get_new_bibs(last_bib_created_at, run_log.started_at)
num_bibs_found = len(new_bibs)
run_log.num_bibs_found += num_bibs_found
self._log_info(
run_log,
'Found {} new bi... |
def _last_bib_seen(self):
#
# Resume find the bib record with the highest id that we've seen previously, and resume from it's creation date.
#
try:
last_biblog = BibLog.objects.order_by('-bib_created_at')[0]
last_bib_record_number = last_biblog.bib_record_number
... | The main task of the code is to process bib records in batches via the Sierra API, track progress with a RunLog entry, and handle errors by logging exceptions. It retrieves the last processed bib from previous runs, iterates through batches until no new records are found or a limit is reached, and ensures run details a... | def handle(self, *args, **options):
run_log = RunLog(started_at=now())
run_log.save()
try:
self.stdout.write('This run will be recorded into run log id {}'.format(run_log.id))
self.sierra_api = SierraApi_v2.login(
settings.SIERRA_API.base_url,
... |
def build_tree(self, dataset, min_support):
"""
Function for handling building tree
"""
header_table = {}
for transaction in dataset:
for item in transaction:
header_table[item] = header_table.get(
item, 0) + dataset[transaction]
... | The code implements the FP-Growth algorithm to mine frequent itemsets from a dataset. It constructs an FP-tree, prunes it, and recursively identifies frequent patterns by projecting conditional trees. Frequent itemsets are generated by combining patterns from conditional bases with current items, ensuring they meet the... | def fp_growth(self, dataset, min_support):
"""
This is for generate fp growth
"""
fp_tree, header_table = self.build_tree(dataset, min_support)
frequent_patterns = []
if fp_tree is None:
return frequent_patterns
header_table = self.pruning_tree(heade... |
def show_start_screen():
"""Displays the start screen of the game."""
title_font = pygame.font.Font('freesansbold.ttf', 100)
title_surface_one = title_font.render('Snake!', True, WHITE, DARK_GREEN)
title_surface_two = title_font.render('Snake!', True, GREEN)
degrees_one = 0
degrees_two = 0
... | The main task of the code is to initialize a Pygame-based Snake game, display a start screen and speed selection menu, run the game loop with chosen frames-per-second settings, and handle game over screens to restart or exit. It manages game state transitions between menus, gameplay, and end screens while maintaining t... | def main():
"""The main game loop."""
global FPS_CLOCK, DISPLAY_SURFACE, BASIC_FONT
pygame.init()
FPS_CLOCK = pygame.time.Clock()
DISPLAY_SURFACE = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
BASIC_FONT = pygame.font.Font('freesansbold.ttf', 18)
pygame.display.set_caption('Snake'... |
def initialize(gen_file: str) -> None:
global FILE_OBJECT
FILE_OBJECT = open(gen_file, 'w', encoding='utf-8')
for cmd in TEX_COMMAND_HEAD:
fwriteln(cmd)
def write_commands(fs: list) -> None:
for f in fs:
fwriteln(f2cmd(f))
def finalize() -> None:
global FILE_OBJECT
for cmd in TEX... | The code generates a file (using a default path/name if unspecified) by initializing the file, writing commands from the input list `fs`, and finalizing the process. | def generate(fs: list, gen_file: str =None) -> None:
if gen_file is None:
gen_file = f"{DEFAULT_PATH}{DEFAULT_FILE}"
initialize(gen_file)
write_commands(fs)
finalize() |
def getMe(self, **kw):
if kw.get("token"):
res = json.loads(requests.post(f"{self.apiUrl+kw.get('token')}/getMe", timeout=5).content)
return res
res = json.loads(requests.post(f"{self.apiUrl+self.botToken}/getMe").content)
return res
def getUpdate(self, **kw):
if ... | This code runs a bot server that continuously checks for updates, processes them if available, and maintains a loop with a cooldown period. It first verifies the bot's status, then enters a loop to fetch and handle updates until stopped. | def runServer(self, **kw):
isBot = self.getMe()
if not isBot.get("ok"):
print("Error: Couldn't Get Your Bot")
return
self.serverRunning = True
while self.serverRunning:
updates = self.getUpdate()
result = updates.get("result")
i... |
def glColor(r, g, b):
return bytes([b, g, r])
def norm(v0):
v0length = length(v0)
if not v0length:
return V3(0, 0, 0)
return V3(v0.x/v0length, v0.y/v0length, v0.z/v0length)
def cross(v0, v1):
return V3(
v0.y * v1.z - v0.z * v1.y,
v0.z * v1.x - v0.x * v1.z,
v0.x * v1.y - v0.y * v1.x,
)
def sub(v0, v1):
... | The code loads a 3D model from an OBJ file, applies translation and scaling transformations to vertices, calculates face normals and lighting intensity based on a directional light source, and renders each face as shaded triangles using color derived from the intensity. It handles both triangular and quadrilateral face... | def load(self, filename, translate, scale):
model = Obj(filename)
light = V3(0,0,1)
for face in model.faces:
vcount = len(face)
vertices = []
for j in range(vcount):
f1 = face[j][0] - 1
f2 = face[(j + 1) % vcount][0] - 1
v1 = model.vertices[f1]
v2 = model.vertices[f2]
x1 = r... |
def play_move_on_board(self, board, move, p1_color):
new_board = deepcopy(board)
for i in range(-1,2):
for j in range(-1,2):
if self.check_direction(board,move,i,j,p1_color):
new_board = self.flip_tiles_in_direction(new_board, move,i,j,p1_color)
re... | The function selects the optimal move by evaluating each valid move's potential outcome. It simulates the player's move, checks if the opponent has no valid responses (returning the move immediately if so), otherwise predicts the opponent's best move, then evaluates all subsequent player moves on the resulting board. I... | def select_final_move(self, valid_moves, board):
mega_score = -10000
for i in range(len(valid_moves)):
best_score = -10000000
board1 = self.play_move_on_board(board, valid_moves[i], self.my_color)
opponent_valid_moves = self.find_valid_moves(board1, self.opponent_colo... |
def play_move_on_board(self, board, move, p1_color):
new_board = deepcopy(board)
for i in range(-1,2):
for j in range(-1,2):
if self.check_direction(board,move,i,j,p1_color):
new_board = self.flip_tiles_in_direction(new_board, move,i,j,p1_color)
re... | This function recursively simulates future game rounds by evaluating board states, tracking the best score, and exploring valid moves for the opponent. It plays a move on the board, checks depth, evaluates the board if at depth 1, finds valid and high-value moves for the opponent, then recursively calls itself with red... | def simulate_next_rounds(self,depth, move, board, p1_color):
if(p1_color == 1):
p2_color = 0
else:
p2_color = 1
if depth == 0:
return
else:
new_board = self.play_move_on_board(board, move, p1_color)
if (depth == 1):
... |
def input_size(interpreter):
"""Gets a model's input size as (width, height) tuple.
Args:
interpreter: The ``tf.lite.Interpreter`` holding the model.
Returns:
The input tensor size as (width, height) tuple.
"""
_, height, width, _ = input_details(interpreter, "shape")
return width, h... | The main task of the code is to perform semantic segmentation on an input image using a pre-trained EdgeTPU model. It processes the input image, resizes it (with optional aspect ratio preservation), runs inference, generates a segmentation mask, and combines the original image with the mask result. The output is saved ... | def main():
parser = argparse.ArgumentParser()
# parser.add_argument('--model', required=True,
# help='Path of the segmentation model.')
parser.add_argument("--input", required=True, help="File path of the input image.")
parser.add_argument(
"--output",
defaul... |
def generar_listas_por_tipo_hora_extra_con_cedula(list_files):
data = extraer_data_excel(list_files)
info_horas_extras = {}
for hora_extra_key in HORAS_EXTRAS_CONSTANTES_ARRAY:
info_horas_extras[HORA_EXTRAS_CODE[hora_extra_key]] = []
for hora_extra in data:
if float(hora_extra[hora_extra_key]) > 0:
peer =... | The code processes input files to categorize extra hour data by type, writes each category into separate text files, and compresses these files into a zip archive for return. | def generate_txt_file_data_extra_hours(list_files):
result = generar_listas_por_tipo_hora_extra_con_cedula(list_files)
for info in result:
write_txt_file_by_type_extra_hour(result[info], info)
code = zip_files_extra_hours_txt()
return code |
def size(self):
return len(self.data)
def bubbleUp(self,index):
parent = (index-1)//2
if(index>0 and self.comp(self.key[index],self.key[parent]) ):
self.swap(index,parent)
index = parent
self.bubbleUp(parent)
def decreaseKey(self,value,newKey):
index =... | This code implements a priority queue's push operation, inserting a new key-value pair or updating an existing value's priority. If the value is new, it appends the data, updates the index, and performs bubble-up to maintain heap order. If the value exists, it calls decreaseKey to adjust its priority, ensuring efficien... | def push(self,key,value):
if self.index[value] == -1:
self.data.append(value)
self.key.append(key)
self.index[value] = self.size()-1
self.bubbleUp(self.size()-1)
else:
self.decreaseKey(value,key) |
def list_size(self):
current = self.head
count = 0
while current:
count += 1
current = current.next
return count
def delete_at_the_beginning(self):
if self.is_empty():
return
else:
element = self.head.data
self.h... | This method deletes a node at a specified position in a linked list. It validates the position, handles deletion at the beginning, end, or middle. For middle positions, it traverses to the node, adjusts pointers to bypass it, and returns the deleted element's data. | def delete_at_any_position(self, pos):
if pos > self.list_size() or pos < 1:
print("\nInvalid Position")
return
if pos == 1:
return self.delete_at_the_beginning()
elif pos == self.list_size():
return self.delete_at_the_end()
else:
... |
def returnOrigin(elements):
min_x = float('inf') # Start with a very large number
min_y = float('inf')
for element in elements:
if __name__ != '__main__':
points = element.points
else:
points = element['points']
for point in points:
if __name__ !=... | The main task of the code is to generate FDS (Fire Dynamics Simulator) input code from geometric elements and parameters. It processes building obstructions, stairs, and mesh structures, converting them into FDS-compatible format. The function initializes an FDS array, adds obstructions and stair details, creates meshe... | def testFunction(elements, z, wall_height, wall_thickness, stair_height, px_per_m, fire_floor, total_floors, stair_enclosure_roof_z):
# turn obstructions into fds code and send back
fds_array = header.copy() # Initialize fds_array here
obstruction_list = []
stair_obstruction_list = []
cell_size = 0... |
def get_path_to_tile(self,start,end):
if(start == end):
return [end]
frontier = Queue()
frontier.put(start)
self.came_from = {}
self.came_from[start] = None
while(not frontier.empty()):
current = frontier.get()
neighbors = ... | The code updates an enemy's movement toward the player by calculating a path, handling collisions, and animating movement. If the enemy has a turret, it spins, attacks periodically by firing bullets in cardinal/diagonal directions, and manages bullet updates. It also checks for player collisions to trigger explosions a... | def update(self):
if not self.turret:
#check for explosion
dist = self.game.player.pos - self.pos
if(dist.length() <= self.game.TILE_SIZE/2):
self.game.explo.append(Explosion(self.game,self.pos))
self.game.player.hp -= 5
return ... |
def game_over(self):
return self.check_winner(self.human_player) or self.check_winner(self.ai_player) or self.check_draw()
def print_board(self):
for row in [self.board[i:i+3] for i in range(0, 9, 3)]:
print("|", " | ".join(row), "|")
def make_move(self, position, player):
self.board... | The code implements a Tic-Tac-Toe game where a human player ('X') competes against an AI ('O'). It handles game flow by printing the board, accepting human input, validating moves, and letting the AI choose its best move. The loop continues until the game ends, then declares the winner or a draw. | def play(self):
print("Welcome to Tic-Tac-Toe! You are 'X', and the AI is 'O'.")
while not self.game_over():
self.print_board()
# Human player's turn
try:
human_move = int(input("Enter your move (1-9): ")) - 1
if self.board[human_move]... |
def chooseLogicForArray(self, marker):
for i in list(self.marker_in_wc.keys()):
if marker in self.marker_in_wc[i]:
return True
def moveAcrossWC(self, marker, dice_num, new_pos):
# print('start func move')
if dice_num in list(self.marker_in_wc.keys()):
prin... | The main task of the code is to determine movement points for a game piece based on a condition. It checks if a specific logic applies to the marker: if true, it calculates points using `moveAcrossWC`; otherwise, it uses `createArrayOfPoints`. The result is structured as a nested list of coordinates, representing valid... | def chooseWay(self, new_pos, dice_num, marker):
if self.chooseLogicForArray(marker) is True:
points = self.moveAcrossWC(marker, dice_num, new_pos)
points = [[points[0]], [points[1]]]
else:
points = self.createArrayOfPoints(new_pos, dice_num, marker)
return po... |
def isMarkerInGame(self, marker):
for i in [self.top_X_border, self.bot_X_border, self.left_Y_border, self.right_Y_border]:
if self.markers[marker][0] == i or self.markers[marker][1] == i:
return True
for i in list(self.wc_coord.keys()):
for j in list(self.wc_coo... | The function `moveMarker` handles the movement of a game marker based on a dice roll. It checks if the marker is already in play; if so, it updates its position. If not, and the dice shows 6, it moves the marker from its home position to the starting point. The function returns updated marker positions, all markers, an... | def moveMarker(self, marker, dice_num):
marker_color = re.split(r'_', marker)[0]
in_game = self.isMarkerInGame(marker)
if in_game is True:
self.setMarkerPos(marker, dice_num)
# self.circle = 1
else:
if dice_num == 6:
# marker_color = re... |
def find_node(self, key):
if key is None:
raise ValueError('Key in find_node is None')
for node in self.to_array_nodes():
if node.key is key:
return node
return None
def height_REFRASHER(self, node):
now = node
while now.parent is not None:... | The code inserts a new node into an AVL tree, ensuring no duplicate keys and validating non-null inputs. If the key exists, it returns False. Otherwise, it creates a new node, attaches it to the appropriate position (left/right child), updates parent pointers, and triggers height-related updates. The insertion maintain... | def insert(self, key, value):
"""Inserts a new node into AVL tree.
:param key: Key of the new node.
:param value: Data of the new node. May be None. Nodes with the same key
are not allowed. In this case False is returned. None-Keys and None-Values are
not allowed. In this case an... |
def find_node(self, key):
if key is None:
raise ValueError('Key in find_node is None')
for node in self.to_array_nodes():
if node.key is key:
return node
return None
def if_same_height(self, curr):
while curr is not None:
try:
... | This code removes a node with a specified key from a tree structure, handling cases for nodes with no children, one child, or two children. It adjusts parent-child relationships, updates the tree, and ensures structural integrity using helper methods like `if_same_height` and `refrash_all`. It returns `True` if the nod... | def remove_by_key(self, key):
"""Removes node with given key.
:param key: Key of node to remove.
:return True If node was found and deleted, False otherwise.
@raises ValueError if the key is None.
"""
if key is None:
return ValueError('Key is None in remove_by... |
def _sliding_chunks_query_key_matmul( query: torch.Tensor, key: torch.Tensor, window_overlap: int):
"""Matrix multiplication of query and key tensors using with a sliding window attention pattern.
This implementation splits the input into overlapping chunks of size 2w (e.g. 512 for pretrained Longformer)
wi... | The code implements a hybrid attention mechanism combining **local and global attention** in the Longformer model. It processes input tensors (query, key, value) with a sliding window for local attention and handles global attention tokens via mask-based selection. Key steps include:
1. **Local attention** using a sl... | def attention_longformer(query: torch.Tensor,
key: torch.Tensor,
value,
query_global,
key_global,
value_global,
attention_mask,
attention_window,... |
def is_inside(self, row, col):
if row < 0 or row >= self.grid_height:
return False
if col < 0 or col >= self.grid_width:
return False
return True
def is_occupied(self, row, col):
# return False if the cell is out of the grid
if not self.is_inside(row, col):
retur... | This function updates the game grid by placing tiles from a stopped tetromino, checks for game-over conditions, merges tiles in columns, clears full lines, and handles falling tetrominoes via connected labeling. It returns whether the game is over. | def update_grid(self, tiles_to_place):
# place all the tiles of the stopped tetromino onto the game grid
n_rows, n_cols = len(tiles_to_place), len(tiles_to_place[0])
min_x=self.grid_width-1
max_x=0
for col in range(n_cols):
for row in range(n_rows):
# place each occupi... |
def write(self, line: str = "") -> None:
self.python_file.write(" " * self.base_indent + str(line) + "\n")
def to_python_name(name: str) -> str:
return "v_" + re.sub(r"\W", "_", name)
def value_info_to_prefix(self, vi: onnx.ValueInfoProto) -> str:
if vi.type.WhichOneof("value") == "sequence_type":
... | The main task of the code is to convert an ONNX graph into executable code by processing inputs, initializers, nodes, and outputs. It generates Python code using a builder API, handling various input types (arrays, lists, None) and node attributes, then writes corresponding method calls for each graph component to cons... | def graph_to_code(
self, graph: onnx.GraphProto, inputs: dict[str, npt.NDArray] = {}
) -> None:
self.write("# inputs")
initializers = [x.name for x in graph.initializer]
for input_ in graph.input:
name = input_.name
if name in inputs:
if isinst... |
def write(self, line: str = "") -> None:
self.python_file.write(" " * self.base_indent + str(line) + "\n")
def graph_to_code(
self, graph: onnx.GraphProto, inputs: dict[str, npt.NDArray] = {}
) -> None:
self.write("# inputs")
initializers = [x.name for x in graph.initializer]
... | The code generates Python code to export an ONNX model or test case, writing the exporter script, handling model attributes, and saving the exported model. It creates an output directory, processes inputs, writes builder code, manages opset imports, and exports the model or test case to the specified path. | def generate(
self, model_or_test_case: onnx.ModelProto | str | Path, output_dir: str | Path
) -> None:
self.output_dir = Path(output_dir)
if self.output_dir.exists():
shutil.rmtree(self.output_dir)
self.storage_dir = self.output_dir / "storage"
self.storage_dir.m... |
def printOptions(options):
if options:
print("\nHere is the option:") if len(options) == 1 else print("\nHere are the options:")
for option in options:
print(option['target'], option['description'])
def deleteOption(fileName, book, pageNumber, optionIndex, name):
confirm = input("Are... | The main task of the code is to allow users to edit a gamebook's pages by modifying content, adding/editing/deleting options, or deleting pages entirely. It provides a menu-driven interface for selecting pages and actions, validates inputs, updates the book structure, and saves changes to the file. The function handles... | def editPage(book, fileName):
while True:
pageNumber = input("Which page do you want to edit? ")
if pageNumber in book['pages']:
while True:
choice = input("(1) Edit page "+pageNumber+"'s content,\n(2) it's options\n(3) or delete it?\n ")
if choice == "1":... |
def openBook(fileName):
with open(fileName, 'r', encoding='utf8') as f:
book = json.load(f)
return book
def addPage(book):
while True:
intPageNum = 0
while True:
if not str(intPageNum) in book['pages']:
break
intPageNum += 1
pageNumber ... | This function allows users to edit a gamebook by adding pages, modifying specific pages, or updating metadata (title, author, summary). It repeatedly prompts for actions until the user exits, saving changes to the file after each operation. | def editBook(fileName, goToAddPage):
book = openBook(fileName)
while True:
if goToAddPage:
book = addPage(book)
saveBook(fileName, book)
choice = input("(1) Add new pages to this gamebook,\n(2) edit a specific page\n(3) or change it's title, author or summary?\n ")
... |
def transition(self, state, action):
assert not (self.is_terminal_state(state))
assert action in self.get_available_actions(state)
# prepare parts of result state
ptm = state.ptm
board = [[elt for elt in row] for row in state.board]
rows, cols = len(board), len(board[0])... | This function transitions a game state by applying an action, updates player positions, checks for ending conditions via space constraints, and returns a new state with updated board, player locations, turn, and other attributes. It ensures proper turn progression, reverts changes if both players are eliminated, and co... | def transition_runner(self, state, action):
state = self.transition(state, action)
ptm = self.get_next_player(state.ptm) # should not switch
next_ptm = self.get_next_player(ptm)
if ptm != self.start_player:
_player_locs = state.player_locs.copy()
self.move_ww(... |
def main_menu(self):
#print the options you have
print()
print()
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("Welcome to the Python Bank System")
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("1) Admin login")
print ("2) Quit Python Bank System")
print (" ")
option = int(input ("Choose your opti... | The code defines a method `run_main_options` that presents a main menu loop for an admin system. It repeatedly displays options until the user selects to exit. If the user chooses to log in, it prompts for admin credentials, validates them via `admin_login`, and if successful, transitions to admin-specific operations v... | def run_main_options(self):
loop = 1
while loop == 1:
choice = self.main_menu()
if choice == 1:
username = input ("\n Please input admin username: ")
password = input ("\n Please input admin password: ")
msg, admin_obj = self.admin_login(username, password)
print(msg)
if admin_obj != None ... |
def forget_previous_frame(window,form=None):
_list = window.winfo_children()
for item in _list:
if item.winfo_children():
_list.extend(item.winfo_children())
for item in _list:
if item.widgetName == "frame":
item.pack_forget()
if not form:
Form = Frame(root, height=300)
Form.pack(side=TOP, pady=20,... | The code creates a GUI form for customer search, allowing users to input a customer's first name. It includes a submit button to validate the input and a back button to return to main options. The form displays a label for input, a text field for the customer name, and dynamically updates a label for feedback, likely s... | def customer_search():
Form = forget_previous_frame(root)
lbl_username = Label(Form, text = "Enter Customer first name:", font=('arial', 10)).pack(padx=10, pady=10)
customer = Entry(Form, textvariable="", font=(14))
customer.pack(padx=10, pady=10)
global lbl_text
lbl_text = Label(Form, text='', font=('arial... |
def forget_previous_frame(window,form=None):
_list = window.winfo_children()
for item in _list:
if item.winfo_children():
_list.extend(item.winfo_children())
for item in _list:
if item.widgetName == "frame":
item.pack_forget()
if not form:
Form = Frame(root, height=300)
Form.pack(side=TOP, pady=20,... | The main task of the code is to create a GUI interface for importing customer details from a file. It sets up a form with a file path input field, "Import" and "Back" buttons, and displays a welcome message. The "Import" button triggers a file processing function, while the "Back" button returns to the main options. | def process_import_customer_details():
Form = forget_previous_frame(root)
Form1 = Frame(root, height=300)
Form1.pack(side=TOP)
welcomeLabel = Label(Form, text ="Import customer details from file",font=('Helvetica 12 bold', 12),fg="brown").pack()
lbl_text = Label(Form, text ="",font=('Helvetica 10 bold', 10)... |
def _get_choices(self):
if len(self.dices_thrown) != 0:
return # choose a dice
self.choices = ["Pass"]
if len(self.dices_own) != self.dice_number:
self.choices.append("Throw")
if self.dices_own.count(6) == 0: # you have no worms
return
dice... | The function `next_play` executes the next move for the current player by generating state/action files, invoking the player's program (either via system command or class method), recording the action, updating the game state, and advancing the turn if the game continues. It handles player transitions, state resets, an... | def next_play(self, players, root):
"""Execute the next move of the right player and record stata/action in a file"""
self._get_choices()
# Generate current state file
file_code = str(self.current_turn)+"_"+str(self.current_player)+"_"+str(self.current_throw)
state_file = root ... |
def user_data(self, initials: str, name: str, description: str):
return Container(
padding=padding.only(top=30, left=10),
content=Row(
controls=[
Container(
width=50,
height=42,
bg... | The code builds a UI layout with an animated container containing user data, search bar, icons, and settings. It structures a column with aligned components, using borders, padding, and animations for a responsive, styled interface. | def build(self):
self.view = Container(
animate=animation.Animation(
duration=500, curve=AnimationCurve.FAST_LINEAR_TO_SLOW_EASE_IN),
width=250,
padding=10,
expand=True,
bgcolor='#f2f2f2',
border=border.only(right=border.Bor... |
def searchAssemblyPatterns(self):
if self.codeUnit.getProcessor().getType() == ProcessorType.X86 \
or self.codeUnit.getProcessor().getType() == ProcessorType.X86_64:
self.searchX86Patterns()
elif self.codeUnit.getProcessor().getType() == ProcessorType.ARM:
self.searchARMPatterns()
elif sel... | The main task of the code is to execute multiple heuristic-based string search methods (pattern matching, brute-force header scanning, linear sweeps) to identify and collect strings from data, conditional on enabled flags. It prints progress/status updates, handles debug logging if enabled, and outputs statistics upon ... | def run(self):
global HEUR_PATTERN_MATCHING, HEUR_LINEAR_SWEEP_DATA_ITEM, HEUR_STRING_HEADER_BRUTEFORCE, HEUR_LINEAR_SWEEP, DEBUG_MODE
print('> %s: building strings...' % self.__class__.__name__),
if HEUR_PATTERN_MATCHING:
self.searchAssemblyPatterns()
self.createFoundStrings(heuristic='... |
def _get_state(self):
'''
Gets the complete state for one timestep
'''
game_data = self.game.gameData
ballSpeed = game_data.ball_state.ballSpeed
ballState = game_data.ball_state.state
corrected_ball_speed = to_range(ballSpeed if ballState is 0 else 0, 1200.0)
... | The code updates the agent's state, records experiences (state, action, reward, next state), handles terminal states by resetting trackers, propagates significant rewards, and selects the next action using `_choose_action`, while also managing animation state countdowns for the player. | def update(self, forceReward=None, terminal=False):
'''
Updates the state, calls _choose_action and sets the current
state and action as the previous
'''
# Get the old and new state bundles
state = self._get_state()
previous_bundled_states = self.state_bundle.get... |
def build_model(tfds, data_loader, name='model', activation='sigmoid'):
"""Generator for the model.
Customize this generator for other types of algorithm
that fits the project requirements
Args:
tfds_train: TensorFlow Dataset for training
data_loader: data loader class instance
name[optional... | This function builds, compiles, trains, and evaluates a machine learning model using provided datasets and a data loader, logging metrics to a CSV file. It returns the trained model, training logger, and training history. | def build_and_evaluate(
tfds_train,
tfds_val,
data_loader,
epoch=100,
model_name='model',
csv_metrics_filepath ='metrics',
):
"""Composite function, or a wrapper, for all of the above.
A Wrapper for ease of modelling and training of a given dataset
into the generator made previously.
... |
def git(*args):
return run('git', args)
def gclient(*args):
return run('gclient', args)
def parse_revinfo(output):
expr = re.compile(GCLIENT_LINE)
config = dict()
urls = dict()
for line in output.split('\n'):
match = expr.match(line.strip())
if match:
dep = match.grou... | (The code compares dependencies between two git revisions using gclient revinfo, identifies changed dependencies, and generates a commit message listing them. It uses temporary directories to isolate operations, supports dry-run testing, and logs details if verbose. The main task is to detect and report dependency chan... | def main(raw_args):
parser = argparse.ArgumentParser()
parser.add_argument('--old-revision', help='Old git revision in the roll.', required=True)
parser.add_argument(
'--dry-run',
help='Test out functionality without making changes.',
action='store_true',
default=False)
p... |
def alarm_on(self):
''' May check additional criteria, eg phone is at home '''
return not self.snoozed() and self.in_active_period()
def worn_in_active_period(self):
# TODO: speed up?
# start at end and work backwords until hit wake time?
logger.debug('worn_in_active_period')
... | This function determines if an alarm should activate by checking four conditions: whether the alarm is armed, if it was worn during the active period, if it's currently being worn, and if it has been off long enough. Each condition is logged for debugging, and the function returns False if any check fails; otherwise, i... | def should_alarm_be_going_off(self):
logger.info('')
logger.debug('check if: alarm is armed')
if not self.alarm_on():
logger.debug('check abort: alarm is not armed')
return False
logger.debug('check continue: alarm is armed')
logger.debug('check if: has b... |
def is_playing(self):
logger.debug('media_controller status %s', self.get_chromecast().media_controller.status)
return self.media_status().player_state == 'PLAYING'
def status(self):
return self.get_chromecast().status
def get_chromecast(self):
if self._chromecast is None or self.cancele... | This function waits for the media to start playing within a specified timeout, logging progress and timing out if playback doesn't initiate. It repeatedly checks the playing status, sleeps between checks, and raises an assertion error if playback fails to start within the timeout period. | def wait_for_playing(self, timeout=10, sleep=.5):
# TODO: threading
logger.debug('')
for i in range(int(timeout/sleep)):
if self.is_playing():
time.sleep(sleep)
return
logger.debug('sleeping')
time.sleep(sleep)
logger.de... |
def is_playing(self):
logger.debug('media_controller status %s', self.get_chromecast().media_controller.status)
return self.media_status().player_state == 'PLAYING'
def is_paused(self):
logger.debug('media_controller status %s', self.get_chromecast().media_controller.status)
return self.... | This code handles media playback by stopping existing playback, generating a VLC command for the given media path, muting to prevent audio noise, executing the command, capturing the new VLC process, waiting for playback to start, then unmute. It also checks for existing playback states and manages pausing/resuming or ... | def play(self, media_path=None):
logger.debug('play %s', media_path)
if media_path is None:
if self.is_playing():
logger.debug('already playing')
return
if self.is_paused():
self.unpause()
return
assert medi... |
def get_env(args):
if args.prod == True:
eprint("Targeting production system")
return "prod"
else:
return "dev"
def load_env_file(env, useEnvVars):
if env == "prod" == True and useEnvVars == True:
template = load_env_file("dev", False)
for key in template.keys():
... | The main task of the code is to orchestrate the deployment or deletion of Kubernetes charts using Minikube, based on command-line arguments. It loads environment settings, constructs deployment commands, updates dependencies if specified, starts Minikube, and either deletes or installs charts. It includes checks for er... | def main(args):
env = get_env(args)
env_settings = load_env_file(env, args.useEnvVars)
commands = CommandBuilder(env, env_settings, args)
if args.updateDependencies:
update_helm_dependencies()
minikube_start(args.hardReinstall, commands)
charts = get_charts(env, args.charts)
if args.... |
def get_tokens():
tokens = None
try:
# if we already have tokens, load and use them
tokens = load_data_from_file(DATA_FILE)['tokens']
except:
pass
if not tokens:
# if we need to get tokens, start the Native App authentication process
tokens = do_native_app_authen... | (The code initiates a file transfer between two endpoints using the Globus Transfer API. It checks previous task status to avoid redundant transfers, ensures destination paths exist, configures transfer settings with checksum synchronization, submits the transfer task, and provides a monitoring link. Key steps include ... | def main():
tokens = get_tokens()
transfer = setup_transfer_client(tokens['transfer.api.globus.org'])
try:
task_data = load_data_from_file(DATA_FILE)['task']
task = transfer.get_task(task_data['task_id'])
if task['status'] not in PREVIOUS_TASK_RUN_CASES:
print('The last... |
def get(self, type_, id_):
if self.data[type_][id_][0]["id"] == id_:
return self.data[type_][id_]
else:
gen = (x for x in self.data[type_] if x[0]["id"] == id_)
return next(gen)
def delete_action(self, action_id):
try:
action = self.get("actions", ... | This function deletes a unit by removing its associated actions, traits, weapons, and transported subunits. It also handles transport relationships by optionally removing the unit from its parent transport's list, avoiding recursive deletion issues. | def delete_unit(self, unit_id, via_transport=False):
# via_transport: This unit deletion is occuring as a result of the parent transport being deleted,
# so there is no need to also delete the unit from the parent transport's list.
try:
unit = self.get("units", unit_id)
excep... |
def create_constellation(constellation, M):
if (constellation == 'PSK'):
return _create_constellation_psk(M)
elif (constellation == 'QAM'):
return _create_constellation_qam(M)
else:
return None
def _plot_constellation(constellation):
fig, ax = plt.subplots(1, 1, figsize=(8, 5))
... | The code runs a simulation to evaluate communication system performance across multiple SNR values. It transmits and receives data using specified parameters, calculates metrics like SER, BER, BLER, and channel MSE, and compiles results into a DataFrame for analysis. | def run_simulation(file_name, channel_matrix, equalizer, constellation, Tx_SNRs, crc_polynomial, crc_length, n_pilot):
global M_constellation
alphabet = create_constellation(constellation=constellation, M=M_constellation)
_plot_constellation(constellation=alphabet)
data = read_bitmap(file_name)
... |
def ptrace_attach(self):
if not self.ptrace_started:
res = self._ptrace(True)
self.ptrace_started = True
return res
def read_bytes(self, address, bytes=4):
if self.read_ptrace:
self.ptrace_attach()
data = b""
if not LARGE_FILE_SUPPORT:
... | The code writes data to a specified memory address in a process using ptrace, handling alignment by splitting data into 4/8-byte chunks, padding with existing data if needed, adjusting endianness, and using PTRACE_POKEDATA. It ensures proper memory access, error handling, and detaches after writing. | def write_bytes(self, address, data):
if not self.ptrace_started:
self.ptrace_attach()
c_pid = c_pid_t(self.pid)
# we can only copy data per range of 4 or 8 bytes
word_size = ctypes.sizeof(ctypes.c_void_p)
# mprotect(address, len(data)+(len(data)%word_size), PROT_WR... |
def unsaved_changes(self):
# if it's still untitled can assume unsaved changes as long as it's not empty
current_text = self.text_input.toPlainText()
if self.filename == None:
if len(current_text) == 0:
return False
else:
return True
... | The code's main task is to handle creating a new file by checking for unsaved changes. If changes exist, it prompts the user to save them. If the user confirms, it saves the file; otherwise, it cancels the new file creation. Finally, it resets properties like filename and text content to initialize a new file. | def new_file_method(self):
# checking if latest updates have been saved
if self.unsaved_changes():
# dialog to ask whether to save
want_to_save = qtw.QMessageBox.question(self, 'Save Changes', 'There are unsaved changes. Would you like to save?',
qtw.QMessageBox.Yes |... |
def get_stocks_by_group(self, group: StockGrouping, date=None):
'''
Group all stocks in a portfolio on a given date by criteria. Returns all stocks if group is None.
Parameters
-----------
group: StockGrouping
date: str (YYYY-mm-dd)
Returns
-------
... | This function calculates the allocation percentage of each stock group relative to the total portfolio value on a given date. It returns a sorted list of groups by their percentage weight, optionally including the list of stocks in each group. | def get_group_allocations(self, group: StockGrouping, date=None, include_stocks=False):
filter_dict = self.get_stocks_by_group(group, date=date)
self.total_val, _ = self.get_total_value(date)
res = {}
for group in filter_dict:
stocks = filter_dict[group]
val = sel... |
def cohesion(bird, flock, factor):
prox = 100
x = 0
y = 0
n = 0
for b in flock:
if dist(bird.pos_tuple(), b.pos_tuple()) < prox:
x += b.pos.x
y += b.pos.y
n += 1
if n:
x = x/n
y = y/n
return (factor*(x - bird.pos.x), factor*(y -... | This code simulates a flock of birds using Pygame, applying boid behavior rules (cohesion, separation, alignment) to update velocities. Birds avoid screen edges by adjusting speed, draw as white circles with velocity vectors as arrows, and the loop handles rendering, physics, and event handling at 30 FPS. | def main():
clock = pygame.time.Clock()
r = 10
vmax = 15
slow_down_v = 5
dt = 0.5
trail = []
eps = r/2
dist_error = 0
coh = 5e-3
sep = 5e-2
align = 5e-2
num_birds = 30
birds = [Bird( (random.randint(r,w-r), random.randint(r,h-r)) ) for _ in range(num_birds)]
ru... |
def get_num_stones(self, stone: int) -> int:
return len(np.where(self.board == stone)[0])
def calculate_connected_component_score(self):
self.visited = np.zeros((self.size, self.size), dtype=bool)
self.component_score = {constants.BLACK: [0, 0], constants.WHITE: [0, 0]}
for i i... | This function calculates the score for the current player in a game, considering stone counts, komi, connected components, cell scores, and liberties. It adjusts the score using multiple factors, returns the score difference if the game is over, or the adjusted score difference otherwise. | def get_score(self, curr_player):
players = [constants.BLACK, constants.WHITE]
num_stones = {player: self.get_num_stones(player) for player in players}
score = deepcopy(num_stones)
score[constants.OTHER_STONE[self.first_player]] += self.komi
print(self)
print(sc... |
def load_epsilon(self) -> None:
with open(constants.EPSILON_FILENAME, 'r') as fp:
self.epsilon = float(fp.read())
def load_q_values(self) -> None:
if not os.path.exists(constants.Q_TABLE_FILENAME):
with open(constants.Q_TABLE_FILENAME, 'wb') as fp:
empty_dict = {}... | The code trains a Q-learning agent by running multiple episodes, updating Q-values through gameplay, decaying exploration rate (epsilon), and managing Q-table size limits. It alternates starting players, logs progress, and persists epsilon/Q-values for continuity. | def learn(self, num_episodes=1):
self.load_epsilon()
self.load_q_values()
curr_episode = 1
init_game_states = [constants.CURR_PLAYER_WHITE,
constants.CURR_PLAYER_BLACK]
while curr_episode <= num_episodes and len(self.q) <= constants.MAX_QTABLE_SIZE:
... |
def find_captured_stones(self, played_stone) -> None:
self.liberty_score = {constants.BLACK: [0, 0], constants.WHITE: [0, 0]}
for cord, stone in np.ndenumerate(self.board):
if self.board[cord] != constants.EMPTY:
logger.debug(f'{cord}')
self.has_liberty(*cord... | This method places a stone on the board at coordinates (x,y), identifies and logs captured stones, updates the count of captured stones, removes them from the board, and records the new board state. | def place_stone(self, x: int, y: int, stone: int) -> None:
self.board[x][y] = stone
self.captured_stones = []
self.find_captured_stones(stone)
self.num_captured_stones[stone] = len(self.captured_stones)
logger.debug(f'self.captured_stones: {self.captured_stones}')
sel... |
def _build_url(self, path, args_dict=None):
""" Helper function for generating request URLS """
# Returns a list in the structure of urlparse.ParseResult
assert(self.protocol in ['http', 'https'])
scheme = self.protocol
netloc = self.host + ':' + str(self.port)
path = pa... | This code initializes a client for interacting with a server (likely ThoughtForge API) by configuring parameters from a JSON specification and environment variables, validating API key and version, checking server connectivity, and setting up a session and simulation. It handles exceptions, ensures session closure, and... | def __init__(self, json_specification, host=None, port=None, protocol='https', api_key=None, model_data=None):
try:
self.session_id = None
result = load_dotenv()
if api_key is None:
api_key = os.getenv("THOUGHTFORGE_API_KEY")
if host i... |
def get_data(_ticker, symbol, online, **kwargs):
df, statement_mappings = get_statements_data(_ticker, symbol, online, **kwargs)
absolute_df = df.pipe(absolute_analysis)
horizontal_df = df.pipe(horizontal_analysis, statement_mappings)
vertical_df = df.pipe(vertical_analysis, statement_mappings)
rat... | The main task of the code is to provide an interactive financial data visualization tool. It retrieves financial statements (balance sheet, cash flow, income statement) for specified tickers, allows users to select analysis types (absolute, horizontal, vertical), ratios, and attributes, then generates customizable line... | def main(tickers, symbol, strings: dict, online: bool):
st.header("Financial Statements")
frequency = st.sidebar.selectbox(label="Frequency", options=["Annual", "Quarter"])
frequency = frequency[:1].lower()
df, regular_variables, ratio_variables = get_data(tickers, symbol, online, trailing=False, freq... |
def set_position_by_priority (self, position_dict):
for IDs in self.priority:
if len(IDs) > 1: # Synchronized actuation
for ID in IDs:
target_position = round(position_dict[ID] * 11.375)
target_position_byte_array... | The code executes a sequence of motor/actuator control commands with a delay, operating in either 'position' or 'torque' mode. In 'position' mode, it sets positions sequentially. In 'torque' mode, it first configures specified motors to torque control (releasing torque, changing mode, re-enabling torque), then applies ... | def play_by_priority (self, sequance, delay, mode='position'):
if mode == 'position':
for seq in sequance:
self.set_position_by_priority(seq)
time.sleep(delay)
elif mode == 'torque':
targets_TDs = []
... |
def get_bucket_name(record):
return record['s3']['bucket']['name']
def get_object_key(record):
return record['s3']['object']['key']
def get_data_set(bucket_name, key_name):
tmp_file_path = '/tmp/' + uuid.uuid4().get_hex()
boto3.client('s3').download_file(bucket_name, key_name, tmp_file_path)
return ... | The code processes S3 event records to extract bucket and object metadata, retrieves associated dataset information, and stores this metadata in a DynamoDB table for tracking or querying, then closes the dataset resource. | def shred_metadata(self, event):
for record in event['Records']:
bucket_name = get_bucket_name(record)
key_name = get_object_key(record)
data_set = get_data_set(bucket_name, key_name)
self.send_metadata_to_dynamodb_table(data_set, bucket_name, key_name)
... |
def get_data(self):
file_name = f'trades_{self.exchange}_{self.from_date}_{self.to_date}_{self.symbols}.csv.gz'
file_path = f'./datasets/{file_name}'
def default_file_name(exchange: str, data_type: str, date: datetime, symbol: str, format: str):
return file_name
... | The code processes market data by iterating over rows, collecting historical candle data for specified timeframes, and processing each row's message. It enforces a timeout, executes trades, and logs closed trades into a DataFrame. The method handles trade execution, balance updates, and trade closure based on predefine... | def run(self):
self.get_data()
starting_timestamp = time.time()
timeout = self.timeout * 60 # in minutes
for i, r in self.data.iterrows():
if timeout and (time.time() - starting_timestamp) > timeout:
break
candles = {}
for... |
def empty_cells(board):
return any([col == '_' for row in board for col in row])
def row_check(board):
for row in board:
if row[0] != '_' and row.count(row[0]) == len(row):
return row[0]
return False
def col_check(board):
row_list = []
for i in range(3):
row_list.append([... | The main task of the code is to determine if a game (e.g., Tic-Tac-Toe) is still ongoing. It checks if there are remaining empty cells and ensures no row, column, diagonal, or impossible conditions have been met. The function returns `True` only if the game is not yet finished, i.e., no winner has been declared, the ga... | def finish_check(board):
return empty_cells(board) and not row_check(board) and not col_check(board) \
and not diagonal_check(board) and not impossible_check(board) |
def impossible_check(board):
x_count = [col for row in board for col in row].count('X')
o_count = [col for row in board for col in row].count('O')
difference = max(x_count, o_count) - min(x_count, o_count) >= 2
return difference or both_win(board)
def row_check(board):
for row in board:
if ... | This function determines the state of a tic-tac-toe game board by checking for wins, draws, or invalid states. It first verifies if X or O has won via rows, columns, or diagonals, then checks for a draw, ongoing game, or impossibility. Results are printed as "X wins", "O wins", "Draw", "Game not finished", or "Impossib... | def check_state(board):
if (not impossible_check(board)) and (row_check(board) == 'X' or col_check(board) == 'X'
or diagonal_check(board) == 'X'):
print('X wins')
elif (not impossible_check(board)) and (row_check(board) == 'O' or col_check(board) == 'O'
... |
def has_valid_token(user_email: str):
if len(UserSpotifyAuthenticated.objects.filter(email=user_email)) == 0:
user_sa = UserSpotifyAuthenticated(email=user_email)
user_sa.save()
usa = UserSpotifyAuthenticated.objects.filter(email=user_email)[0]
token = usa.token
token_date = usa.token_d... | The code retrieves user history and playlist info, authenticates via token, calls a recommendation endpoint, fetches track names, and returns URIs/names in a JSON response, handling coldstart scenarios and invalid tokens. | def get_recommendation(request: Request):
user_email = request.query_params.get('email')
if not has_valid_token(user_email):
return HttpResponseForbidden
token = get_token(user_email)
history = request.query_params.get('userHistory')
playlist_name = request.query_params.get('playlistName')
... |
def activate_fn_layer(self, event: InputEvent):
self.is_fn_active = True
self.is_fn_used = False
self.fn_activate_time = event.timestamp()
self.first_fn_event = None
self.first_fn_event_passed: bool = False
def deactivate_fn_layer(self):
self.is_fn_active = False
def _wr... | This code handles keyboard events with a function layer (FN). It activates/deactivates the FN layer based on the spacebar's key-down/up states, modifies event codes when FN is inactive, and writes events conditionally, including special handling for the first FN event and timing thresholds to determine when to output m... | def send(self, event: InputEvent):
if event.type == ecodes.EV_KEY and event.code == ecodes.KEY_SPACE:
if event.value == KeyEvent.key_down and not self.is_fn_active:
self.activate_fn_layer(event)
elif event.value == KeyEvent.key_up:
self.deactivate_fn_laye... |
def _write_key_down(self, key_code, sec, usec):
self._write_event(InputEvent(sec, usec, ecodes.EV_KEY, key_code, KeyEvent.key_down))
def _write_event(self, event: InputEvent):
if event.type == ecodes.EV_KEY:
self.update_pressed_keys(event)
_key_state = ('up', 'down', 'hold')[eve... | This function handles EV_KEY events for the FN key layer. It checks if the key is the FN key, manages the first FN event by deferring processing, activates the FN layer by sending a modifier key down, and ensures proper event sequencing. It avoids reprocessing the same key and handles the initial FN press asynchronousl... | def _handle_fn_event(self, event: InputEvent):
if event.type == ecodes.EV_KEY:
key_code = event.code
if key_code == self.key_code:
return
# pass the event unmodified if the key was pressed before FN layer activated
if key_code not in self.pressed... |
def activate_fn_layer(self, event: InputEvent):
self.is_fn_active = True
self.is_fn_used = False
self.fn_activate_time = event.timestamp()
self.first_fn_event = None
self.first_fn_event_passed: bool = False
def deactivate_fn_layer(self, event: InputEvent):
self.is_fn_act... | This code processes key events to manage a function layer activation. It checks for key presses and releases, activating/deactivating the function layer based on the event value and state. If the function layer is inactive, it writes key events with timing checks for modifier thresholds. When active, it handles functio... | def send(self, event: InputEvent):
if event.type == ecodes.EV_KEY and event.code == self.key_code:
if event.value == KeyEvent.key_down and not self.is_fn_active:
self.activate_fn_layer(event)
elif event.value == KeyEvent.key_up:
self.deactivate_fn_layer(e... |
def __back_propagate(self, image, target):
"""Returns the gradients of the parameters for a single training example."""
biases_gradients = [np.zeros((n,1)) for n in self.sizes[1:]]
weights_gradients = [np.zeros((n,m)) for n,m in zip(self.sizes[1:],self.sizes[:-1])]
a = image
act... | This code implements mini-batch gradient descent to train a neural network. It shuffles training data, divides it into mini-batches, computes gradients via backpropagation for each batch, updates weights/biases with learning rate and L2 regularization, and tracks training/testing costs. It evaluates model performance o... | def SGD(self, training_data, test_data = None, mini_batch_size = 10, epochs = 10 ,learning_rate = 0.5, lmbd = 0):
"""Trains the network using mini-batch gradiend descent."""
training_data = list(training_data)
len_training_data = len(training_data)
print(len_training_data)
if tes... |
def calc_rejection(graph: nx.classes.digraph):
def inner(node):
#graph.nodes[node]["classifier"].reduction = 1 / graph.nodes[node]["reduction ratio"]
downstream = list(nx.dfs_postorder_nodes(graph, node))
ratios = [graph.nodes[n]["reduction ratio"] for n in downstream]
total_reductio... | The function updates a directed graph's throughput and performance metrics by propagating statistical data from the root node to leaves, calculating link and operational power, and determining overall pipeline performance. It copies the graph, computes rejection ratios, updates link throughput, and derives power/resour... | def update_throughput(graph: nx.classes.digraph):
graph = graph.copy()
#call the recursive update function on the root node
root = graph.graph["Root Node"]
#calculate the global reduction ratio
calc_rejection(graph)
#propagate from root to leaves
message_size(graph, root)
propagate_... |
def detectors(detector_data: pd.DataFrame):
n = len(detector_data)
nodes = []
edges = []
for i in range(n):
detector = detector_data.iloc[i]
name = detector["Detector"]
classifier = DummyClassifier()
node_properties = {
"sample data": detec... | The code constructs a directed acyclic graph (DAG) from detector and trigger system data, incorporating complexity functions. It adds nodes/edges from detectors and triggers, validates acyclicity, assigns complexity functions to nodes, identifies the root node, updates throughput, and returns the validated graph struct... | def construct_graph(detector_data: pd.DataFrame, trigger_data: pd.DataFrame, globals: pd.DataFrame, functions: dict):
g = nx.DiGraph()
#add the nodes for detectors
detector_nodes, detector_edges = detectors(detector_data)
g.add_nodes_from(detector_nodes)
#add the nodes for trigger systems
trigge... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.