dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_campaign(desc):
logging.info('Identifying the Campaign ID')
# Removing extra spaces (if any)
desc = str(desc).strip()
camp_id = pd.read_sql_query(f"""
SELECT id
FROM campaign_list
WHERE LOWER(description) = LOWER('{desc}');
""", db_conn)
# Case-Match statement to g... | This function uploads donation data to a gift API by processing a DataFrame, determining gift/receipt dates, mapping currency types, constructing parameters with conditional fields, and sending a POST request to the Blackbaud API endpoint for gifts. | def upload_donation(df, const_id):
logging.info(f"Uploading donation for RE ID: {const_id} and Donation Portal Ref. No.: {df['dtlDonor_id']}")
# Search Campaign
camp_id = get_campaign(df['project'])
# Identify Gift and Receipt Date
date_1 = pd.to_datetime(df['transdate'])
date_2 = pd.to_dateti... |
def is_alphanumeric(s):
if len(s) != 10:
return False
if not s.isalnum():
return False
if s.isalpha() or s.isdigit():
return False
return True
def update_pan(pan, const_id):
logging.info('Updating PAN Numbers')
# Check whether PAN exists in RE
# Get Alias list
ur... | The function `update_constituent` updates a constituent's record in a database based on donation type (online/offline). For online donations (PAYU/SBIIB), it validates and updates PAN, email, address, education, phone numbers, and checks names. For offline donations, it only verifies name matches against Raisers Edge. ... | def update_constituent(df, const_id):
logging.info(f'Updating the constituent record: {const_id} for any updates')
# Check if the donation is Online/Offline
match df['provid']:
# Online
# Update Record as these are provided by Alum
case 'PAYU' | 'SBIIB':
# PAN Numbers
... |
def search_constituent(email, phone, pan):
logging.info('Searching constituent in Raisers Edge')
i = 0
params = {}
# Formatting phone
phone = ''.join([x for x in str(phone) if x.isdigit()])
phone = phone if len(phone) > 6 else np.NaN
for search_text in [email, pan, phone]:
if not... | The function `locate_donor` identifies a constituent ID by querying a database using an email and phone number from a DataFrame. It filters invalid emails, executes SQL queries to match details, and handles cases with no matches by searching or creating new constituents. It returns the matched ID, creates a new constit... | def locate_donor(df):
email = df['email']
email = np.NaN if email.lower() in ['wqexj@example.com', 'wmuml@example.com', 'mbnbo@example.com', 'ctgih@example.com'] else email
phone = df['contactno']
pan = df['pancard']
if len(str(phone)) > 3:
const_id = pd.read_sql_query(
f'''
... |
def points_generator(DATA_PATH, OBJECT_LIST, OBJECT_NUMS, MAP_PATH, random=True):
obj_list = []
obj_length = len(OBJECT_LIST)
for obj_index in range(obj_length):
obj_name = OBJECT_LIST[obj_index]
print('read points from file: ', os.path.join(DATA_PATH, obj_name+'.txt'))
obj_... | The code generates training data and labels for a machine learning model by reading images and labels, generating positive/negative coordinates, applying optional data augmentation (shifting), combining and shuffling coordinates, extracting patches from images/labels, and returning processed data. It also removes exist... | def data_generator(DATA_PATH, MAP_PATH, LABEL_PATH, OBJECT_LIST, OBJECT_NUMS, WIN_SIZE, NB_CLASSES,\
shift_augment=False, shift_range=(0, 0), num_shift=2, times4multi=1,\
check_data=False, gamma=1.0, random=True):
img = cv2.imread(MAP_PATH)
label = cv2.imread(LABEL_PATH)
... |
def clear(self):
""" Clear all widgets. """
for widget in self.main_frame.winfo_children():
widget.destroy()
cells.clear()
if self.timer_frame is not None:
for widget in self.timer_frame.winfo_children():
widget.destroy()
cells... | This function solves a Sudoku puzzle using a brute-force algorithm when a button is clicked. It initializes a BruteForce solver with puzzle data, disables the button to prevent repeated calls, and invokes the solve_puzzle method with the brute-force solver type to compute the solution. | def on_click_solve_brute_force(self):
""" Solve sudoku using brute force algorithm. """
self.clear()
self.toggle_button("!button2", False)
brute_force = BruteForce(self.puzzle_data, self.size_data,
self.row_set, self.col_set, self.sub_grid_set)
se... |
def clear(self):
""" Clear all widgets. """
for widget in self.main_frame.winfo_children():
widget.destroy()
cells.clear()
if self.timer_frame is not None:
for widget in self.timer_frame.winfo_children():
widget.destroy()
cells... | The main task of the code is to solve a Sudoku puzzle using a Constraint Satisfaction Problem (CSP) algorithm. It clears prior data, disables the solve button, initializes a CSP object with the puzzle, and invokes the solving process with the specified solver type. | def on_click_solve_csp(self):
""" Solve sudoku using CSP algorithm. """
self.clear()
self.toggle_button("!button3", False)
csp = CSP(self.puzzle_data)
self.solve_puzzle(csp, SolverType.CSP) |
def init_board(self):
"""
Initialize a sudoku board as a 2D array of Squares, and the domain of each square.
"""
board = [[None for _ in range(self.size_data)] for _ in range(self.size_data)]
for i, j in itertools.product(range(self.size_data), range(self.size_data)):
... | The code's main task is to solve a puzzle using Constraint Satisfaction Problem (CSP) techniques. It initializes the board and constraints, applies the AC-3 algorithm for constraint propagation, and employs multiprocessing to solve the CSP, returning a boolean indicating success. | def solve(self):
"""
Initialize the board and constraints, and then solve the puzzle using CSP.
:return: if successfully found a solution, bool
"""
self.init_board()
self.init_binary_constraints()
self.ac3(self.init_arc_constraints())
return self.solve_csp... |
def generate_puzzle_solution(self):
""" Generate puzzle data from a Board. """
for i, j in itertools.product(range(self.size_data), range(self.size_data)):
self.puzzle_data[i][j] = self.board[i][j].domain[0]
def select_unassigned(self):
"""
Select the best square to assign n... | This code implements a backtracking algorithm for solving Constraint Satisfaction Problems (CSPs), using MRV (Minimum Remaining Values) and degree heuristics to select variables, least constraining value heuristic for ordering values, and MAC (Maintaining Arc Consistency) with AC-3 for constraint propagation. It checks... | def backtrack(self):
"""CSP back tracking algorithm."""
# Return true if all squares have been assigned a value
if len(self.unassigned) == 0:
self.generate_puzzle_solution()
return True
# MRV heuristic with degree heuristic for tiebreak
next_empty = self.... |
def is_consistent(self, next_empty, v):
""" Check if the neighbors of next_empty is arc-consistent with it. """
return not any(
len(self.board[neighbor[0]][neighbor[1]].domain) == 1
and v in self.board[neighbor[0]][neighbor[1]].domain
for neighbor in next_empty.neighb... | This function performs backtracking with constraint propagation (MAC) in a CSP solver. It assigns a value to a cell, checks consistency, propagates constraints via AC-3, recursively solves the puzzle, and reverts changes if the backtrack fails. It manages domain revisions and unassigned cells during inference, returnin... | def backtrack_mp_helper(self, target_cell, v, saved_values):
"""
Recursive csp algorithm with constraint propagation. This is almost the same function
as backtrack, but it is a wrapper to set up multiprocessing correctly.
"""
if self.is_consistent(target_cell, v):
# A... |
def set_mode(self, mode="training"):
"""Sets the mode of the model. If mode==training, the model parameters are expected to be updated."""
# Change the mode of models, depending on whether we are training them, or using them for evaluation.
if mode == "training":
self.contrastive_enc... | The code trains a contrastive learning model using a provided data loader, tracking training and validation losses across batches and epochs. It initializes loss metrics, iterates through training epochs, computes contrastive loss for each batch, updates model parameters, and validates periodically. Results are saved a... | def fit(self, data_loader):
"""
:param IterableDataset data_loader: Pytorch data loader.
:return: None
Fits model to the data using contrastive learning.
"""
# Training dataset
train_loader = data_loader.train_loader
# Validation dataset
validatio... |
def load_models(self):
"""
:return: None
Used to load weights saved at the end of the training.
"""
for model_name in self.model_dict:
p = self._model_path + "/" + model_name + ".pt"
print(p)
model = th.load(p, map_location=self.device)
... | The code's main task is to continue training a pre-trained model by loading existing models, fitting them with the provided data loader, saving updated weights, and printing a completion message. This process, termed "tuning," refines the model's parameters using new data while retaining prior learning. The method ensu... | def tune(self, data_loader):
"""
:return: None
Continues training of previously pre-trained model
"""
self.load_models()
self.fit(data_loader)
self.save_weights()
print("Done with tuning the model.") |
def extract_attributes(attribute_file, logger):
logger.info("Loading attribute json file.")
with open(attribute_file) as f:
attributes = json.load(f)
attr = {}
for image in attributes:
attr_dict = {}
for obj in image["attributes"]:
if "attributes" in obj:
... | The code extracts sequence-to-sequence (s2s) data from a region graph and attribute file, processes it using parallel data extraction, and saves the resulting dataset as a TSV file in the specified output directory. | def extract_s2s(region_graph_file, attribute_file, output_dir):
logger = logging.getLogger(__name__)
attr = extract_attributes(attribute_file, logger)
data = extract_parallel_data(
region_graph_file, attr, logger
)
serialize(data, path.join(output_dir, "seq2seq.tsv"), logger) |
def get_data_of_document(path, filter="total"):
with open(path, 'r') as f:
data = f.read()
year = 0
if len(path.split('/')) > 2:
year = int(re.search(r'\d+', path.split('/')[-2]).group())
document_name = os.path.basename(path).replace(".tei.xml", "")
Bs_data = BeautifulSoup... | This code processes XML documents in a directory by extracting data, calculating TF-IDF for words and keywords, writing results to JSON files, and cleaning data structures before outputting processed information. It iterates through files, parses XML content, computes term frequencies, and stores results in structured ... | def get_all_document_data(directory_path):
# iterate over all xml files in directory
data = []
count = 0
for paths in os.walk(directory_path):
for path in paths[2]:
if (path.endswith(".xml")):
single_data = get_data_of_document(paths[0] + "/" + path)
i... |
def _parse_jump_target() -> None:
nonlocal index
_expect(
GrinTokenKind.LITERAL_INTEGER, GrinTokenKind.LITERAL_STRING,
GrinTokenKind.IDENTIFIER)
index += 1
def _token_is(*kinds: GrinTokenKind) -> bool:
return index < len(tokens) and tokens[index].kind() in kinds... | The function `_parse_jump` parses a jump instruction by first calling `_parse_jump_target` to determine the target address. It then checks if the next token is `IF`, and if so, increments the index and parses a conditional expression consisting of a value, comparison operator, and another value, likely for conditional ... | def _parse_jump() -> None:
nonlocal index
_parse_jump_target()
if _token_is(GrinTokenKind.IF):
index += 1
_parse_value()
_parse_comparison_operator()
_parse_value() |
def get_last_user_checkin(user):
usuarios = Usuario().get_all()
for u in usuarios:
if u.username == user:
u.last_login += get_delta_less3()
return u.last_login
def get_time():
date_format = "%Y-%m-%d %H:%M:%S.000Z"
return dt.strptime(dt.now(get_sp_tz()).strftime(date_form... | The code handles a POST request to save a user's report (relatorio) with check-in/check-out times, content, class number, and course to a database, then logs the user out and redirects to login. For GET requests, it renders the index page displaying the user's last check-in time in milliseconds since epoch. | def index(request):
user = str(request.user)
checkin = get_last_user_checkin(user)
if str(request.method) == "POST":
relatorio = Relatorio(
username=user,
checkout=get_time(),
checkin=checkin,
conteudo=request.POST["conteudo"],
naula=reques... |
def add(x: float, y: float) -> float:
return x + y
def multiply(x: float, y: float) -> float:
return x * y
def square(x: float) -> float:
return multiply(x, x)
def add_squares(x: float, y: float) -> float:
return add(square(x), square(y)) | The main task of the code is to execute four mathematical operations—addition, multiplication, squaring a number, and summing squares—using predefined functions with specific parameters (5+10, 5×100, 8², and 10²+100²), then print each result sequentially. | def main():
sum_of_nums = add(5, 10)
print(sum_of_nums)
multiplication = multiply(5, 100)
print(multiplication)
square_of_nums = square(8)
print(square_of_nums)
add_square_nums = add_squares(10, 100)
print(add_square_nums) |
def get_tile(g, threshold):
p = conv_g_to_p(g, threshold)
t = conv_p_to_t(p)
return t
def t_to_qkey(t, l):
tile_x = t[0]
tile_y = t[1]
quadkey = ""
for i in range(l):
bit = l - i
digit = ord('0')
mask = 1 << (bit - 1) # if (bit - 1) > 0 else 1 >> (bit - 1)
if... | The code generates map tiles between two geographic coordinates, converts them to quadkeys, downloads corresponding images, and stitches them into a final map image. It takes coordinates as inputs, calculates tile ranges, iterates through tiles, creates quadkeys, fetches images for each, and combines them. | def main():
lat1 = float(sys.argv[1])
lon1 = float(sys.argv[2])
lat2 = float(sys.argv[3])
lon2 = float(sys.argv[4])
l = 17
print("--Generating Tiles for given 2 points--")
x = get_tile((lat1,lon1), l)
y = get_tile((lat2,lon2), l)
print("---Generating Tiles between 2 points---")
... |
def find_matches(rgb, rgbs, threshold):
return \
list(
sorted(
filter(lambda x: x[1] < threshold,
((i, hamming(rgb, cand_rgb))
for i, cand_rgb in enumerate(rgbs))
), key = lambda x: x[1],
)
)
def camelCase(name):
return ''.join(
word[0].upper() + word[1:]
... | The function allows users to select matching RGB colors from candidate lists for each CID, ensuring valid indices and no duplicate names, then returns the selected color-name pairs after input validation. | def find_match(cids, rgbs, rgb_name, matching, cnt=8):
ref_rgbs = list(rgb for rgb, name in rgb_name)
taken = set(r[2] for r in matching)
candss = []
for cid, rgb in zip(cids, rgbs):
print(f"\ncands for {cid} (#{rgb:06x}):")
cands = find_matches(rgb, ref_rgbs, 100000)
for i,(j,d) in enumerate(cand... |
def determineClassLabels(self, dataSet):
oneLabels = 0
zeroLabels = 0
labels = [0, 0]
for dataPoint in dataSet:
if dataPoint[2] == 1:
oneLabels = oneLabels + 1
elif dataPoint[2] == 0:
zeroLabels = zeroLabels + 1
labels[0] = ... | The code implements the ID3 algorithm to recursively build a decision tree for classification. It checks base cases (pure node, no attributes, depth limit) to create leaf nodes. Otherwise, it selects the best attribute via entropy, creates a node, partitions data, and recursively constructs child nodes for each bin. Th... | def ID3(self, dataSet, target_attribute, attributes, depth, parentNode):
labelDistribution = self.determineClassLabels(dataSet)
#base cases
if labelDistribution[0] == 0:
leaf = Node("Label = 1", parent=parentNode)
elif labelDistribution[1] == 0:
... |
def determineClassLabels(self, dataSet):
labels = [0, 0, 0, 0, 0]
for dataPoint in dataSet:
classLabel = int(dataPoint[11])
if classLabel == 1:
labels[0]+= 1
elif classLabel == 2:
labels[1]+= 1
elif classLabel == 3:
... | The code implements the ID3 algorithm to build a decision tree recursively. It determines the most common class label, handles base cases (pure dataset or max depth), selects the best attribute for splitting, creates tree nodes, and processes child datasets for categorical/numerical attributes, recursively constructing... | def ID3(self, dataSet, target_attribute, attributes, depth, parentNode, categoricalValues):
labelDistribution = self.determineClassLabels(dataSet)
labelMax = -1
mostCommonLabel = -1
for label in range(0,len(labelDistribution)):
if labelDistribution[label] ... |
def _install_pip_packages (reload = False, quiet = False): # <<<
import subprocess, sys
if 'qiskit' in sys.modules and not reload:
if not quiet:
print ("== Installing/checking needed pip packages: aborted since "
"qiskit has already been imported and reload was not "
... | The function initializes a configuration environment by installing required pip packages, setting up configuration files (settings and account), and applying patches. Parameters control reloading, quiet mode, and file paths. | def init (reload = False, quiet = False, qiskitrc_filename = None,
settings_filename = None):
_install_pip_packages (reload = reload, quiet = quiet)
_setup_settings (reload = reload, quiet = quiet,
filename = settings_filename)
_setup_account (reload = reload, quiet = quiet,
... |
def around(position):
"""" return six point around the position as a list """
x, y = position
around_point = [(x + 1, y)]
if y % 2 == 0:
around_point.append((x, y + 1))
around_point.append((x - 1, y + 1))
around_point.append((x - 1, y))
around_point.append((x - 1, y - 1))... | This function determines valid moves for a spider piece on a board by checking surrounding positions in a three-step pattern. It returns all valid positions if `all_position` is True, otherwise checks if the destination position is reachable. The spider moves by verifying surrounding points, ensuring each step is withi... | def spider_move(des_position, position, board, piece, all_position=False):
result = []
arounds = around(position)
if check_surrounding(position, board, piece):
for around_point in arounds:
if spider_checking(around_point, board, piece):
first = around_point
... |
def piece_in_game(self, piece):
""" return True if piece in game """
return piece in self.pieces.keys()
def move(self, piece, direction, ref_piece):
color = piece[0]
if not (color + "Q1") in self.pieces:
return "queen has not entered the game"
# give the old position... | This function determines whether to move or insert a game piece based on its validity and the game state. It checks if 'ref_piece' is in the game, then evaluates 'piece' to either move it in the specified direction or insert it at a calculated position if invalid. If 'piece' is already in the game, it triggers a move; ... | def read_command(self, piece, direction, ref_piece):
if self.piece_in_game(ref_piece):
if self.piece_in_game(piece):
return self.move(piece, direction, ref_piece)
else:
if self.piece_is_invalid(piece):
return self.insert_piece(piece, se... |
def initial_condition_for_move(piece, board):
new_board = copy.deepcopy(board)
x, y = new_board.pieces.get(piece) # old position of the piece
# only upper piece can move
if not new_board.board[y][x][-1] == piece:
return False
new_board.board[y][x].remove(piece)
del new_board.pieces[p... | The function `can_move` checks if a game piece can move to a target position based on its role (e.g., Ant, Beetle) and the board state. It uses continuity rules if enabled, retrieves the piece's current position, and delegates validation to role-specific movement functions. Returns `True` if movement is valid, `False` ... | def can_move(piece, des_position, board, continuity=True):
""" check that movement is possible based on piece role """
# it can be 'A', 'B', 'L', 'Q', 'S'
piece_role = piece[1]
new_board = None
if continuity:
new_board = initial_condition_for_move(piece, board)
if new_board is False... |
def join_path(*dirs):
# return os.path.join(path, parent)
return Path(*dirs)
def get_workspace():
workspace = None
if ENV_WORKSPACE in env:
workspace = env[ENV_WORKSPACE]
work = parse_args().workspace
if(work is not None):
workspace = work
elif(workspace == None):
wor... | The function retrieves data from a specified file path by combining the workspace directory with the input path. It checks if the file exists; if not, it returns an empty list. Otherwise, it fetches and returns all input data from the file. | def get_from_mapping(path):
path = join_path(get_workspace(), path)
if(exist_path(path) == False):
return ['']
else:
return get_all_input(path) |
def join_path(*dirs):
# return os.path.join(path, parent)
return Path(*dirs)
def exist_path(path):
return os.path.exists(path)
def get_from_mapping(path):
path = join_path(get_workspace(), path)
if(exist_path(path) == False):
return ['']
else:
return get_all_input(path)
def check... | This function processes input data by writing formatted content to files. It checks environment variables to determine if all values should be processed, creates/overwrites files at specified paths, and appends processed input lines with comments and separators. It handles multiple values, validates extensions, and use... | def process_inputs(key, value, path_out):
full_path = join_path(path_out, key)
get_all: bool = False
if(ENV_GET_ALL in env):
get_all_values = env[ENV_GET_ALL].split(SPLIT_MULTI_VALUE)
get_all = key in get_all_values
print("----PROCESSING: {}".format(full_path))
if(exist_path(full_pa... |
def make_album_collection():
'''
more albums can be added, but make sure to save it like song title#song#song title#song osv
the name of the file should be albumname_lyrics.txt
save it in same folder
'''
shelf = {}
add_album(shelf, 'folklore', 'Taylor Swift')
add_album(shelf, 'evermore',... | The code implements a song quiz game where users guess missing words in scrambled lyrics and identify song titles. It tracks points, allows multiple attempts, and calculates scores. The game loops until the user quits, displaying total points and average score per round. | def the_game():
#a point system might be added later :)
#adjust to right degree of difficulity
k = 20 # max number of words to be used
b = 12 # number of blank spaces
shelf = make_album_collection()
game_intro()
points = 0
rounds = 0
while True:
rounds += 1
... |
def find_best_algo(mscclpp_algos, niter):
assert len(mscclpp_algos) > 0
best_time = 10000000.0
best_algo = None
for algo in mscclpp_algos:
config, cur_time = find_best_config(algo, niter)
if cur_time < best_time:
best_time = cur_time
best_algo = algo
a... | The code benchmarks MSCCL++ and NCCL AllReduce algorithms by initializing GPU memory, selecting appropriate algorithms based on data size and GPU configuration, measuring execution time and bandwidth, verifying correctness, and recording results in a table. It compares performance metrics like time, bandwidth, and spee... | def run_benchmark(
mscclpp_group: mscclpp_comm.CommGroup, nccl_op: nccl.NcclCommunicator, table: PrettyTable, niter: int, nelem: int
):
memory = cp.zeros(nelem, dtype=data_type)
memory_out = cp.zeros(nelem, dtype=data_type)
cp.cuda.runtime.deviceSynchronize()
proxy_service = ProxyService()
if M... |
def sorted_png_fnam(dir):
def fnam_sort(l):
def tryint(s):
try:
return int(s)
except:
return s
def key(s):
return [tryint(s) for s in re.split('([0-9]+)', s)]
return sorted(l, key=key)
fnam = [f for f in os.listdir(dir)]... | This code processes images from a directory by loading them into a GIMP image, calculating a standardized width and doubled height based on the largest image dimensions. It then pairs images, pasting them side-by-side into a new layer, creating a collage-like composition. If an odd number of images exists, it raises an... | def pairwise(img, dir):
fnam = sorted_png_fnam(dir)
imgs = [pdb.gimp_file_load(DirRoot + fn, DirRoot + fn, run_mode=RUN_NONINTERACTIVE) for fn in fnam]
enufw = max([img_lay(x, 0).width for x in imgs])
enufh = max([img_lay(x, 0).height for x in imgs]) * 2
niter = int(math.ceil(len(imgs) / 2.0))
f... |
def gpx_find_tra_dist_min(gpx: GPX, pnt: vec_t) -> GPXTrack:
return min([(tra_find_pnt_dist(tra, pnt), tra,) for tra in gpx.tracks], key=lambda x: x[0])[1]
def tra_find_lseg_idx_closest(tra: GPXTrack, pnt: vec_t) -> int:
return min([(pnt_lineseg_dist(pnt, segS, segE), idx,) for idx, segS, segE in tra_iter_pts(t... | This function inserts a given GPX track point into the closest line segment of the nearest track in a GPX object, modifying the track in-place. It first identifies the track closest to the point, locates the nearest line segment within that track, and inserts the point immediately after the segment's end point. | def gpx_insert_lseg_closest_inplace(gpx: GPX, pnt: GPXTrackPoint):
tra = gpx_find_tra_dist_min(gpx, pnt)
idx = tra_find_lseg_idx_closest(tra, pnt)
tra_seg(tra).points.insert(idx + 1, pnt) |
def figure5aTrail(t):
# 3 replicas
if is_rw(): # rw
conc=[20, 40, 60, 80, 100, 130, 160, 190, 200, 220, 260, 300, 340, 380, 420, 460, 500, 540, 580]
else: # tpca
conc=[20, 40, 60, 80, 100, 130, 160, 190, 200, 220, 260, 300, 340, 380, 420]
data_3=[] # (currency, 50th, tps, 99th, all_late... | The code processes multiple trials of data (data_3_all and data_5_all) by aggregating statistical metrics (median, variance, percentiles) across trials for each data point. It updates the primary data structures (data_3 and data_5) with these aggregated values, likely to generate visualizations like Figure 5a, which co... | def figure5a():
data_3_all, data_5_all=[],[]
for i in range(FIGURE5a_TARIALS):
data_3_t, data_5_t = figure5aTrail(i+1)
data_3_all.append(data_3_t)
data_5_all.append(data_5_t)
data_3=data_3_all[0]
data_5=data_5_all[0]
H=len(data_3)
for i in range(H):
tmp_50th=[]
... |
def figure6aTrail(t):
if is_rw():
conc=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
else:
conc=[1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
data_r=[] # (currency, 50th, tps, 99th, all_latency, tps-var)
for i in conc:
folder=BASE+"/figure6a_"+str(t)+"/results_"+str(i)
... | The code processes multiple trials by aggregating data across them. It computes median and variance for specific metrics (e.g., TPS) across trials, updating the original dataset with aggregated statistics. The function returns a modified dataset containing median values, percentiles, and variances for each entry, likel... | def figure6a():
data_r_all = []
for i in range(FIGURE6a_TARIALS):
data_r_t = figure6aTrail(i+1)
data_r_all.append(data_r_t)
data_r=data_r_all[0]
H=len(data_r)
for i in range(H):
tmp_50th=[]
tmp_tps=[]
tmp_99th=[]
tmp_all=[]
for j in range(FIG... |
def figure5a():
data_3_all, data_5_all=[],[]
for i in range(FIGURE5a_TARIALS):
data_3_t, data_5_t = figure5aTrail(i+1)
data_3_all.append(data_3_t)
data_5_all.append(data_5_t)
data_3=data_3_all[0]
data_5=data_5_all[0]
H=len(data_3)
for i in range(H):
tmp_50th=[]
... | The function `load_process_data` retrieves and processes specific metrics (e.g., TPS, 50th/99th percentiles, variance) from experiment data based on the input protocol (`raft`, `copilot`, `ref-copilot`, or `etcd`), experiment type (`exp`), role (`ty`), and replication factor (`rep`). It calls protocol-specific data-loa... | def load_process_data(protocol, ty, exp, rep): # (tps, 50th, 99th, tps-var)
if protocol == "raft":
if exp == 0:
data_3, data_5 = figure5a()
if rep == 3:
for e in data_3:
if e[0] == CK:
return e[2], e[1], e[3], e[5]
... |
def figure5a():
data_3_all, data_5_all=[],[]
for i in range(FIGURE5a_TARIALS):
data_3_t, data_5_t = figure5aTrail(i+1)
data_3_all.append(data_3_t)
data_5_all.append(data_5_t)
data_3=data_3_all[0]
data_5=data_5_all[0]
H=len(data_3)
for i in range(H):
tmp_50th=[]
... | This function retrieves and processes latency data for different distributed protocols (e.g., Raft, Copilot) based on experimental configurations. It selects appropriate data sources (figureXa/b) depending on protocol, experiment type (exp), and replication factor (rep). The data is filtered, transformed into a percent... | def get_cdf_data(protocol, ty, exp, rep):
latency = []
if protocol == "raft":
if exp==0: # no slowness
data_3, data_5 = figure5a()
else:
data_3, data_5 = figure5b()
if rep == 3:
for e in data_3:
if exp==0:
if e[0] =... |
def _get_addons_paths(c, include_odoo=True):
addons_path = []
base_dir = get_project_base(c)
for addon_directory in (c.odoo_addons_directories if include_odoo else []) or []:
addons_path.append(os.path.join(base_dir, addon_directory))
for addon_directory in c.custom_addons_directories or []:
... | This function collects available Odoo custom modules by searching specified directories, combines them with custom addons if provided, and optionally joins the list into a string using a separator. It returns the list of module paths or a joined string based on the 'join' parameter. | def _get_odoo_addons(c, join=False):
"""List of available custom modules"""
addons = []
for directory in _get_addons_paths(c, include_odoo=False):
if c.debug:
log.debug("Directory to fetch Odoo addons: %s" % directory)
addons += _get_addons_from_directory(directory)
if c.cu... |
def lint_xml(c, addons=''):
"""Run xmllint"""
log.info('• XML Linter')
if os.name == 'nt':
log.warning('Skip test on Windows')
return
c.run('find . -maxdepth 4 -type f -iname "*.xml" '
'| xargs -I \'{}\' xmllint -noout \'{}\'')
def lint_flake8(c, addons=''):
"""Run flake8""... | The function `lint` performs static code analysis by executing three linters: `lint_xml`, `lint_flake8`, and `lint_odoo_lint`, each with parameters `c` and `addons`. Its main task is to enforce code quality, style, and framework-specific rules (e.g., XML structure, Python syntax, Odoo conventions) across the codebase. | def lint(c, addons=''):
"""Run static code checks"""
lint_xml(c, addons)
lint_flake8(c, addons)
lint_odoo_lint(c, addons) |
def _get_odoo_addons(c, join=False):
"""List of available custom modules"""
addons = []
for directory in _get_addons_paths(c, include_odoo=False):
if c.debug:
log.debug("Directory to fetch Odoo addons: %s" % directory)
addons += _get_addons_from_directory(directory)
if c.cu... | This function executes unit tests for an Odoo project, handling setup, coverage, and database management. It initializes addons, cleans databases if required, constructs test commands, and runs tests with or without coverage analysis, generating reports and HTML outputs when enabled. | def unit_test(c, with_coverage=False, addons='', build=False, database_name=''):
"""Launch unit tests"""
log.info('• Unittest')
if not addons:
addons = _get_odoo_addons(c, join=',')
if not with_coverage:
with_coverage = c.with_coverage
if build:
clean(c, database_name)
... |
def log2(n): # helper function which returns log2(n)
if (n == 1): # time complexity: O(log(n))
return 0 # space complexity: O(1)
else: # base case: log2(1) = 0
ans = 0
while (n > 1): ... | The code builds a heap structure from collision data by filtering valid entries (time > -1), storing their indices and positions, and then heapifying the structure level-by-level from the bottom up to maintain the heap property. It initializes collision indices, constructs a heap of valid collisions, and ensures the he... | def build(self, lst_of_coll_time, lst_of_coll_pos): # time complexity O(n), space complexity O(n)
count = 0
for i in range(len(lst_of_coll_time)):
if (lst_of_coll_time[i] > -1):
self._indexes[i] = count
... |
def horizontal_reflection(mapo: List[str], map_index: int, clean_mirrors: Dict[int, Tuple[Tuple[int, int], bool]],
is_vertical: bool=False) -> int:
for i in range(1, len(mapo)):
if mapo[i] == mapo[i-1]:
mirror = (i-1, i)
res = check_mirror_horizontal(mapo, m... | (The function `reflection` calculates the total number of valid horizontal and vertical reflections in a grid structure by summing the results of two operations: `horizontal_reflection` on the original grid and `vertical_reflection` on a transposed version of the grid, using specified mirror positions and orientations ... | def reflection(mapo: List[str], map_index: int, clean_mirrors: Dict[int, Tuple[Tuple[int, int], bool]]) -> int:
return (horizontal_reflection(mapo, map_index, clean_mirrors) +
vertical_reflection(trans_array(mapo), map_index, clean_mirrors)) |
def is_number_box(bx):
strall = bx.get_text()
if len(strall)<1:
return False
if bx.x1-bx.x0>200:# some long lenth boxes for bullet no etc.
return False
words = strall.split('\n')
#todo: check for character
ustr = u"—"
truecount, falsecount = 0, 0
for word in words... | The code identifies tables in a PDF page by analyzing text boxes and lines. It separates numeric text boxes from regular text, merges them into columns based on spatial proximity, and combines columns into table structures. It checks for left-aligned text to confirm table columns, visualizes detected tables, and saves ... | def find_table_in_page(page, pno):
numtexts = []
rects = []
lines = []
textstr = []
pagenos = []
numTextCount, lineCount = 0, 0
isLandscape = False
page_link = ''
global tminx
global tminy
global tmaxx
global tmaxy
tminx, tminy, tmaxx, tmaxy =1000, 1000, 0... |
def login(self, username, password, peerServerPort):
message = "LOGIN " + username + " " + password + " " + peerServerPort
self.tcpSocket.send(message.encode())
response = self.tcpSocket.recv(1024).decode()
if response == "login-success":
self.username = username
... | This code initializes a client application that connects to a server via TCP and UDP sockets, allowing users to login, create accounts, manage chat rooms, and communicate through a menu-driven interface. It handles user authentication, maintains online user lists, and facilitates both one-on-one and group chats, with o... | def __init__(self):
self.serverIP = input("Enter Server IP: ")
self.serverPort = SERVER_TCP_PORT
self.tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.tcpSocket.connect((self.serverIP, self.serverPort))
self.udpSocket = socket.socket(socket.AF_INET, socket.SOCK_... |
def minZeroes(board):
matrix = np.ones((9,9),dtype="int64")
coords = []
for row in range(9):
for col in range(9):
matrix[row,col] = zeroCount(board,row,col)
for row in range(9):
for col in range(9):
if matrix[row,col] == matrix.min():
... | The code attempts to solve a Sudoku-like puzzle by iteratively identifying cells with singleton possibilities (unique values) in rows and columns. It processes the board and its transpose to fill zeros, recursively repeating the process up to n times. If zeros remain, it invokes `completeBoard` to finalize the solution... | def function(board,n=1000):
initialStart = minZeroes(board)
if n == 1:
if 0 in board:
print("board not solved\n")
return board
for start in initialStart:
row,col = start[0],start[1]
for i in range(9):
rowChoices = rowOptions(board, r... |
def get_letters(prompt):
"""Prompt user for input and accept only letters or
empty input. Reprompt if validation fails.
Args:
prompt (string): prompt string, passed to input()
Returns:
value: the user's validated input
"""
while True:
value = wordprompt(prompt)
... | The code provides an interactive tool to solve Wordle puzzles by filtering possible words based on user-provided hints: excluded letters, confirmed correct letters/positions (green), and correct letters in wrong positions (yellow). It reads a wordlist, updates constraints dynamically, and narrows down potential solutio... | def main():
"""Let's unwordle interactively!"""
signal.signal(signal.SIGINT, signal_handler)
try:
with open("words.json", encoding="utf-8") as word_file:
all_words = json.load(word_file)
except EnvironmentError:
print("Could not open wordlist. Try fetchdict.py!")
sy... |
def rate_type(type):
if "lec" in type.lower() or "sem" in type.lower():
return 0
elif "dis" in type.lower() or "lab" in type.lower():
return 1
else:
raise ValueError("Something went wrong")
def rate_time(time):
time_format = "%I:%M%p"
start, end = time.split('-')
if 'p' ... | The main task of the code is to generate a non-overlapping class schedule by selecting open sections for each course, prioritizing main sections (lectures/seminars) and compatible secondary sections (discussions/labs), while sorting sections by type, rating, and time. It raises an error if no valid sections can be sche... | def make_schedule(classes):
schedule = []
for i in range(len(classes)):
classes[i] = [classes[i][0]] + sorted(classes[i][1:], key=lambda x: (rate_type(x.type), -x.rating, -rate_time(x.schedule[x.schedule.index(" ") + 1:])))
for course in classes:
main_sections = [section for section in co... |
def safe_cast(val, to_type, default=None):
try:
return to_type(val)
except (ValueError, TypeError):
return default
def perform_heating(param1):
print("mqttListener: Heating function not implemented")
def perform_air_cond(param1):
user_degree = 0
if param1 == 1:
user_degree = ... | The code processes incoming MQTT messages by decoding their payload, validating the data type, and executing specific functions (perform_heating/perform_air_cond) based on the message topic. It skips retained messages and invalid payloads, then publishes a response to a predefined topic when handling the "setAirCond" c... | def on_message(client, userdata, message):
print("mqttListener: Message received ", str(message.payload.decode("utf-8")))
print("mqttListener: Message topic=", message.topic)
print("mqttListener: Message qos=", message.qos)
print("mqttListener: Message retain flag=", message.retain)
the_int_string ... |
def getBet(balance):
linesAmount = get_number_of_lines()
print(f"You are betting on {linesAmount} lines.")
print(f"Your current balance is ${balance}")
highestAmount = balance/linesAmount
highestAmount = math.floor(highestAmount)
validInput = False
while validInput == False:
bettingI... | This function simulates a slot machine spin by taking a balance, generating a random grid of symbols, calculating winnings based on symbol values and bet lines, and returning the net profit/loss after deducting the total bet from the winnings. | def spin(balance, ROWS, COLS, symbol_count, symbol_value):
print(f"Your balance is ${balance}")
bet, lines = getBet(balance)
total_bet = bet*lines
slots = get_slot_machine_spin(ROWS, COLS, symbol_count)
print_slot_machine(slots)
winnings, winning_lines = check_winnings(slots, lines, bet, symbol_... |
def get_possible_squares(self, caller_piece, squares): # just if its moves are physically possible
# make sure squares are on board
temp_squares = squares.copy()
for square in temp_squares:
if square[0] > 7 or square[0] < 0 or square[1] > 7 or square[1] < 0:
squares.... | The main task of the code is to determine all legal moves for a chess piece by first generating possible squares, checking for castling opportunities, and then filtering out any moves that would leave the player's king in check. This ensures only valid, non-threatening moves are returned for the given piece. | def get_available_squares(self, caller_piece, squares): # if its moves are legal
squares = self.get_possible_squares(caller_piece, squares)
squares = self.check_for_castling(caller_piece, squares)
# check if putting own king in check
temp_squares = squares.copy()
for square in t... |
def init_transformer(is_eval: bool = True):
"""
Initialize the Transformer model by constructing the encoder and decoder.
Parse both the encoder and decoder into the Seq2Seq, initialize the weights, and load in the best trained
parameters.
:param is_eval: If function is being used for training or e... | The code initializes a transformer model, translates a sample sentence from a validation dataset, calculates the corpus BLEU score for evaluation, saves attention weights for visualization, and stores performance metrics. It focuses on assessing the model's translation quality and generating interpretability insights t... | def main():
model = init_transformer()
val_df = pd.read_json(env.VAL_DF_MODIFIED_PATH)
src = val_df.intent[0]
src = src.split(" ")
translation, attention = translate_sentence(src, Const.Input, Const.Output, model, env.DEVICE)
save_attention(src, translation, attention)
c_bleu = calculate_bl... |
def create_optimizer_and_scheduler(self, num_training_steps: int):
optimizer, lr_scheduler = create_optimizer(self.args.learning_rate,num_training_steps,self.args.warmup_steps,adam_epsilon=self.args.adam_epsilon,weight_decay_rate=self.args.weight_decay)
return optimizer, lr_scheduler
def get_dataloader(... | The code trains a machine learning model using distributed strategies, logs training metrics (examples, batch size, steps), evaluates periodically with F1 scoring, adjusts learning rates, and saves the model when F1 improves. It tracks loss, updates the optimizer, and iterates over epochs with batched data, ensuring ef... | def train(self) -> None:
train_example_nums,eval_example_nums = len(self.train_dataset),len(self.eval_dataset)
num_steps = math.ceil(train_example_nums / self.args.batch_size)
t_total = num_steps * self.args.num_train_epochs
epochs = self.args.num_train_epochs
with self.args.str... |
def _take_action(self, name: str) -> bool:
deltas = []
for _act in self.action[name][0]:
if self.discrete:
deltas.append(1 if _act else -1)
else:
deltas.append(_act)
for i, _delta in enumerate(deltas):
_delta = clamp(_delta, -se... | The code processes each action by executing it, calculating rewards, and storing results. It verifies all actions are present, iterates through names to perform actions, computes rewards, accumulates them, and records step outcomes for each name. | def step(self) -> None:
assert all(action is not None for action in self.action.values())
for name in self.names:
done = self._take_action(name)
reward = self._compute_reward(name, done)
self.rewards[name] += reward
self.step_result[name] = self._make_bat... |
def end_session(self):
self.clear_input()
self.submit_answer()
exit()
def submit_answer(self):
self.results.append_result(
s_num = self.session,
s_ts_start = self.time_start,
s_ts_end = self.time_end,
q_ts_start = self.time_start_q,
... | This function processes user input in an interactive session. It handles quitting (KEY_Q), submitting answers (KEY_ENTER), backspacing (KEY_BACKSPACE), and appending numeric values (KEY_NUM) to a temporary answer string. The core task is managing input events to update session state, validate inputs, and trigger action... | def submit_input(self, k:int):
if k == KEY_Q:
self.end_session()
elif k == KEY_ENTER:
if self.i_answer != "":
self.submit_answer()
self.clear_input()
elif k == KEY_BACKSPACE:
self.i_answer = self.i_answer[:-1]
elif k in ... |
def next_question(self):
self.time_start_q = time.time()
self.q_num += 1
self.question = self.question_factory.generate()
def submit_input(self, k:int):
if k == KEY_Q:
self.end_session()
elif k == KEY_ENTER:
if self.i_answer != "":
self.su... | The code renders a dynamic menu interface for a training session, displaying real-time stats (time remaining, question progress), current questions, and user input. It uses curses for terminal handling, updates the screen continuously, and allows exiting via 'q'. Main tasks: initializing screen settings, rendering UI e... | def draw_menu(self, stdscr):
self.stdscr = stdscr
k = 0
# Clear and refresh the screen for a blank canvas
self.stdscr.clear()
self.stdscr.refresh()
# Timeout for inputs
# -1 is returned if nothing is pressed
self.stdscr.timeout(int(1000 / self.FPS))
... |
def get_next_text() -> None:
"""Reads the next 'important' sequence of characters from input into the buffer"""
global buffer_index
# Look for the start of a viable sequence
while True:
char = read_input()
# Check what the character is
if char == MULTI_LINE_CHAR:
go... | (The function `assemble_next_mnemonic` retrieves the next mnemonic value from a provided table by hashing a buffer, looking up the hash in the table, and returning the corresponding value. If the hash is not found, it prints an error and raises a `NameError`. The buffer is modified and indexed globally, with specific h... | def assemble_next_mnemonic(table: list) -> int:
"""
Fetches and returns the value of the next mnemonic from the given table.
CANNOT BE USED FOR INSTRUCTIONS.
"""
global buffer_index
get_next_text()
if buffer_index == 2:
buffer[2] = 0
buffer_index += 1
hash_val = hash_... |
def label_lookup() -> int:
"""Takes the label found in the heap (like [>,L,a,b,l,e]) and returns its value from the label table."""
table_index = 0
# Loop through the label table
while True:
# Check if we're out of labels to search through.
if table_index >= label_table_index:
... | The function `get_numeric_value` interprets a buffer's contents as a numeric value, handling decimal, hexadecimal, and binary formats. It checks the first character for a reference label, then determines the number's type and base (10, 16, or 2) based on subsequent characters. It supports negative values and returns th... | def get_numeric_value() -> int:
"""Interprets the contents of the buffer as a number, and returns its value."""
first_char = buffer[0]
# This is the "label hack" trick.
if first_char == REF_CHAR: # This can, if used incorrectly, cause problems.
return label_lookup() # its effects are pretty c... |
def write_0_to_input() -> None:
"""Writes 0 to the input circuit, resetting the input pointer."""
global input_pointer
input_pointer = 0
def get_next_text() -> None:
"""Reads the next 'important' sequence of characters from input into the buffer"""
global buffer_index
# Look for the start of a ... | The function processes an input file to build a label table during the first pass. It identifies labels, constants, and instructions, recording their positions in the label table. It adjusts the program counter based on data types (e.g., labels, constants, arrays) and skips operands for instructions using a bitmap. Err... | def build_tables() -> None:
"""Does the first pass through the file, building the label table."""
print("Building tables...") # For debugging, this should be left in.
global label_table_index
write_0_to_input()
program_counter = 0
while True:
# Place the next chunk of admissible text ... |
def write_0_to_input() -> None:
"""Writes 0 to the input circuit, resetting the input pointer."""
global input_pointer
input_pointer = 0
def get_next_text() -> None:
"""Reads the next 'important' sequence of characters from input into the buffer"""
global buffer_index
# Look for the start of a ... | The code translates assembly language into machine code during the second pass of processing a file. It processes text chunks by identifying their type (references, constants, strings, etc.), retrieves values, and writes corresponding machine code outputs. Special handling includes resolving labels, handling numeric va... | def assemble() -> None:
"""Does the second pass through the file, translating assembly into machine code."""
print("Assembling...") # For debugging, this should be left in.
write_0_to_input()
while True:
# Place the next chunk of admissible text into the heap.
get_next_text()
... |
def generateCsvLogs():
try:
logging.debug("ETL - generateCsvLogs - Iniciando o processo")
with open("raw_data/equipment_failure_sensors.log") as f:
listNew = list(generateDict(f))
if listNew:
logs_csv = pd.DataFrame(listNew)
logs_csv.to_csv("pr... | The main task of the code is to execute an ETL (Extract, Transform, Load) process by generating CSV logs and equipment data, inserting them into a database, and logging execution details. It initializes logging to record debug information in 'elt-process.log', measures the process duration, and handles exceptions to en... | def main():
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
filename='elt-process.log',
filemode='w+',
level=logging.DEBUG
)
try:
start_time = datetime.now()
generateCsvLogs()
generateCsvEquip()
dataInsert()
elap... |
def get_edges(multi_polygon):
edges = []
y_max = -sys.maxsize - 1
y_min = sys.maxsize
for ring in multi_polygon:
y_min = min(y_min, min(ring, key=attrgetter("y")).y)
y_max = max(y_max, max(ring, key=attrgetter("y")).y)
edges.extend(edges_from_ring(ring))
return edges, y_min,... | This function rasterizes a multi-polygon using a scan-line algorithm. It processes horizontal scan lines, manages active edges, and fills the area by plotting x-ranges based on edge pairs. The 'level' parameter determines plotting logic (plot0/plot1), while edges are updated incrementally. The result is a dictionary re... | def fill_multi_polygon(multi_polygon, level):
area = dict()
edges, y_min, y_max = get_edges(multi_polygon)
active_edges = []
for y_line in range(y_min, y_max):
active_edges.extend(insert_edges(edges, y_line))
active_edges = sorted(remove_edges(active_edges, y_line))
# Draw the ... |
def wolf_is_victory(self):
i = self.wolf.i
wolf_point = self.options.board_size - 1 if self.options.who_is_top == Foo.WOLF else 0
if i == wolf_point:
return True
else:
return False
def wolf_is_lost(self):
wolf_available_moves = self.get_available_moves_for... | The main task of the code is to determine the winner of a game between a wolf and sheep by checking three conditions: 1) if the wolf has already won, 2) if the wolf has lost, or 3) if the sheep has no available moves on their turn, which results in a wolf victory. The function updates the game's "won" status and return... | def check_victory(self):
# Wolf victory
if self.wolf_is_victory():
self.options.won = Foo.WOLF
return self.options.won
# Sheep victory
if self.wolf_is_lost():
self.options.won = Foo.SHEEP
return self.options.won
# Wolf victory
... |
def prepare_map(self):
self.map.clear()
for i in range(self.options.board_size):
tmp_map = []
for j in range(self.options.board_size):
tmp_map.append(0)
self.map.append(tmp_map)
self.map[self.wolf.i][self.wolf.j] = Foo.WOLF
cells = se... | This function implements the minimax algorithm with alpha-beta pruning for a wolf-sheep game, evaluating optimal moves by recursively analyzing possible game states. It determines the best move for the current player (sheep or wolf) based on heuristic evaluations, checks for winning positions, and applies pruning to im... | def min_max(self, player, rec_level, alpha, beta):
dangerous_wolf_position =False
if rec_level == 0:
self.prepare_map()
is_sheep = True if (player == Foo.SHEEP) else False
best_move = self.NOT_INITIALIZED
min_max = self.MIN_VALUE if is_sheep else self.MAX_VALUE;
... |
def min_max(self, player, rec_level, alpha, beta):
dangerous_wolf_position =False
if rec_level == 0:
self.prepare_map()
is_sheep = True if (player == Foo.SHEEP) else False
best_move = self.NOT_INITIALIZED
min_max = self.MIN_VALUE if is_sheep else self.MAX_VALUE;
... | The main task of the code is to execute an AI move using the Minimax algorithm with alpha-beta pruning. It calculates the best move for the current player (Wolf or Sheep), updates the game state, validates the move's feasibility, and applies it to the board if valid. If invalid, it reports an error. The code also measu... | def run_AI(self, player):
# _______ RUN RESULT MINMAX
start = time.time()
best_move = self.min_max(player, 0, - self.BIG_VALUE, self.BIG_VALUE)
end = time.time()
print("Minmax operation time is {0}.".format(end - start))
self.gb.update()
if self.options.whose_mov... |
def count_digits (n):
global i
global c
global d
if n > i:
d += 1
i += 9*c
c *= 10
count_digits (n)
else:
print(d)
def list_find_max(n):
lst = [int(item) for item in n.split()]
find_max(lst, 0, 0)
def count_tags(code,tag,i,s):
if i >= len(code):
print(s)
else:
splits = len(... | The main task of the code is to present a menu-driven program offering three operations: counting digits in a number, finding the maximum value in a list of integers, and counting specific HTML tags in user-input code. The program prompts the user to select an option, collects necessary inputs, and executes the corresp... | def main():
print("1. Count Digits")
print("2. Find Max")
print("3. Count Tags")
print("4. Exit")
print("---------------------------------------")
ch = int(input("Enter a number for corrisponding choice: "))
if (ch == 1):
n = int(input("Enter Integer number to count digits: "))
count_digits (n)
... |
def is_gitlab_project(node):
return True if node.id > 0 else False
def get_project(gitlab, id):
try:
project=gitlab.projects.get(id)
except:
log.info(sys.exc_info())
return project
def check_ref_branch(project, ref):
yaml_data = get_yaml(project, '.gitlab-ci.yml', ref)
[print(sta... | This function manages GitLab branch operations based on command-line arguments. It checks if a project is GitLab-related, then creates, removes, or lists branches depending on "--create", "--remove", or "--list" flags. It handles errors during branch operations, logging fatal errors if exceptions occur. | def security_branch(action):
if is_gitlab_project(action.node):
time.sleep(1)
gitlab = action.arguments["gitlab"]
log.debug("updating existing project {0}".format(action.path))
project=get_project(gitlab, action.node.id)
# print(action.arguments)
if(action.arguments[... |
def make_node(self, name, parent, url, id=-1):
node = Node(name=name, parent=parent, url=url, id=id)
node.root_path = self.root_path(node)
return node
def get_projects(self, group, parent):
projects = group.projects.list(as_list=False)
self.progress.update_progress_length(len(pro... | This function retrieves all subgroups of a given GitLab group recursively, creates nodes for each subgroup with their parent relationship, updates progress tracking, and fetches projects within each subgroup. It uses recursion to handle nested subgroup structures and builds a hierarchical representation of groups and p... | def get_subgroups(self, group, parent):
subgroups = group.subgroups.list(as_list=False)
self.progress.update_progress_length(len(subgroups))
for subgroup_def in subgroups:
subgroup = self.gitlab.groups.get(subgroup_def.id)
node = self.make_node(subgroup.name, parent, url=... |
def make_node(self, name, parent, url, id=-1):
node = Node(name=name, parent=parent, url=url, id=id)
node.root_path = self.root_path(node)
return node
def get_subgroups(self, group, parent):
subgroups = group.subgroups.list(as_list=False)
self.progress.update_progress_length(len(... | (The function loads a tree structure from GitLab by iterating through top-level groups, creating nodes for each group, and recursively fetching their subgroups and projects. It tracks progress using a progress bar, initializes it with the number of groups, processes each group to build the hierarchy, and logs the total... | def load_tree_from_gitlab(self):
groups = self.gitlab.groups.list(as_list=False)
self.progress.init_progress(len(groups))
for group in groups:
if group.parent_id is None:
node = self.make_node(group.name, self.root, url=group.web_url)
self.progress.sho... |
def load_tree_from_file(self):
with open(self.in_file, 'r') as stream:
dct = yaml.safe_load(stream)
self.root = DictImporter().import_(dct)
def load_tree_from_gitlab(self):
groups = self.gitlab.groups.list(as_list=False)
self.progress.init_progress(len(groups))
fo... | The code's main task is to load a tree structure from either a file or a GitLab server, depending on the `self.in_file` flag, then log the number of projects in the root node and apply filtering to the tree. It initializes or reloads the tree data source, ensuring the root node's leaves are processed for subsequent ope... | def load_tree(self):
if self.in_file:
log.debug("Loading tree from file [{}]".format(self.in_file))
self.load_tree_from_file()
else:
log.debug(
"Loading projects tree gitlab server [{}]".format(self.url))
self.load_tree_from_gitlab()
... |
def center(X):
X = np.array(X)
mean = X.mean(axis=1, keepdims=True)
return X - mean
def whitening(X):
cov = np.cov(X)
d, E = np.linalg.eigh(cov)
D = np.diag(d)
D_inv = np.sqrt(np.linalg.inv(D))
X_whitened = np.dot(E, np.dot(D_inv, np.dot(E.T, X)))
return X_whitened
def calculate_new_... | The code performs Independent Component Analysis (ICA) to separate mixed signals into statistically independent components. It preprocesses data by centering and whitening, initializes a weight matrix, and iteratively updates weights using a custom `calculate_new_w` function. Orthogonality constraints are enforced by s... | def ica(X, iterations, tolerance = 1e-5):
# preprocessing
X = center(X)
X = whitening(X)
components_nr = X.shape[0]
# initialise W
W = np.zeros((components_nr, components_nr), dtype = X.dtype)
# iteratively update W
for i in range(components_nr):
w = np.random.rand(components_n... |
def mix_sources(mixtures, apply_noise = False, noise_mag = 0.02):
for i in range(len(mixtures)):
max_val = np.max(mixtures[i])
min_val = np.min(mixtures[i])
if max_val > 1 or min_val < 1:
mixtures[i] = mixtures[i] / (max_val / 2) - 0.5
X = np.c_[[mix for mix in mixtures]]
... | The code tests an Independent Component Analysis (ICA) algorithm by generating synthetic signals (sinusoidal, square, sawtooth), mixing them with a predefined matrix, applying ICA to recover original sources, and plotting the results for comparison. It validates ICA's ability to separate mixed signals into their indepe... | def test_method():
n_samples = 2000
time = np.linspace(0, 8, n_samples)
# signals
s1 = np.sin(2*time) #sinusoidal
s2 = np.sign(np.sin(3*time)) #square
s3 = signal.sawtooth(2*np.pi * time) # sawtooth
sources = [s1, s2, s3]
# combine signal
X = mix_sources(sources)
A = np.arr... |
def mix_sources(mixtures, apply_noise = False, noise_mag = 0.02):
for i in range(len(mixtures)):
max_val = np.max(mixtures[i])
min_val = np.min(mixtures[i])
if max_val > 1 or min_val < 1:
mixtures[i] = mixtures[i] / (max_val / 2) - 0.5
X = np.c_[[mix for mix in mixtures]]
... | The code performs Independent Component Analysis (ICA) on mixed audio signals to separate them into original sources. It loads mixed and source audio files, artificially mixes sources, applies ICA for separation, compares results visually, and saves the recovered signals as WAV files. | def audio_test_method():
# load files
sample_rate, mix1 = wavfile.read('Independent Component Analysis\AudioFiles\mix1.wav')
sample_rate, mix2 = wavfile.read('Independent Component Analysis\AudioFiles\mix2.wav')
sample_rate, source1 = wavfile.read('Independent Component Analysis\AudioFiles\source1.wav')... |
def build_encoder(self):
print("-----------build encoder: %s-----------" % self.backbone_name)
#starter_block
outputs = self._start_block('conv1')
print("after start block:", outputs.shape)
#block1
outputs = self._bottleneck_resblock(outputs, 256, self.resnet_strides[0], ... | The code constructs a neural network by first extracting low- and high-level features via an encoder, then refining them using a dual attention mechanism to enhance feature representation, and finally generating outputs through a decoder that processes the refined features. | def build_network(self):
low_level_feat, high_level_feat = self.build_encoder()
refined_low_level_feat, refined_high_level_feat = self._DualAttention(high_level_feat, low_level_feat)
self.outputs = self.build_decoder(refined_low_level_feat, refined_high_level_feat) |
def find_all_users(self) -> list[str]:
search_command = f'ldapsearch -x -LLL -b "ou=users,{self.domain}" "(objectclass=posixAccount)" | grep "dn: "'
raw_out = subprocess.check_output(shlex.split(search_command)).decode('utf-8').split()
users = [x for x in raw_out if x != 'dn:']
return us... | The main task of the code is to generate new passwords for all users, create an LDIF file to modify LDAP passwords, write user-password pairs to an output file, execute the LDAP modification command using a temporary password, and clean up temporary files. It handles user discovery, password generation, LDIF formatting... | def change_all_passwords(self, output_file: str, length: int, password: bool = False) -> None:
users = self.find_all_users()
user_passwords = self.generate_user_passwords(users, length, password=password)
modify_ldif = ''
with open(output_file, 'w') as f:
for user in users:
... |
def find_all_users(self) -> list[str]:
search_command = f'ldapsearch -x -LLL -b "ou=users,{self.domain}" "(objectclass=posixAccount)" | grep "dn: "'
raw_out = subprocess.check_output(shlex.split(search_command)).decode('utf-8').split()
users = [x for x in raw_out if x != 'dn:']
return us... | This function generates new passwords for all users, creates LDIF entries to update passwords, and saves results. It retrieves all users, generates randomized passwords (with optional passphrase), constructs LDIF modification records, writes passwords to a file in chunks, and outputs the LDIF content to a file for bulk... | def change_all_passwords(self, ldif_file: str, password_file: str, length: int, passphrase: bool = False, split: int = 100) -> None:
users = self.find_all_users()
user_passwords = self.generate_user_passwords(users, length, passphrase=passphrase)
modify_ldif = ''
for user in users:
... |
def _append_data(self, t_day, daily_contacts, daily_obs):
"""
Add obs
"""
#check_inputs(t_day, daily_contacts, daily_obs)
# append daily_contacts and daily_obs
daily_transmissions = contacts_rec_to_csr(self.N, daily_contacts, self.lamb)
self.transmissions.append(d... | The code computes the rank of infected individuals by aggregating transmission and observation data over a time window (delta) using a mean-field approach. It updates internal data structures, calculates scores via `ranking_backtrack`, sums them into a cumulative infected count (`<I>`), and returns a ranked list of ind... | def rank(self, t_day, daily_contacts, daily_obs, data):
'''
computing rank of infected individuals
return: list -- [(index, value), ...]
'''
self.delta = min(self.delta_init, t_day)
# check that t=t_day in daily_contacts and t=t_day-1 in daily_obs
"""check_inputs(... |
def debug(self, message: str):
# basic logs
if 'true' in self._debug:
_LOGGER.debug(f"{self.host} | {message}")
def _check_port(self, port: int):
"""Check if gateway port open."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
return s.connect_... | The code's main task is to manage a main thread loop for connecting to an MQTT broker, enabling telnet, preparing gateway devices, updating time offsets, and maintaining mesh network operations. It continuously checks and re-enables telnet and MQTT connections, ensuring gateway setup and device configuration, then runs... | def run(self):
"""Main thread loop."""
self.debug("Start main thread")
self.mqtt.connect_async(self.host)
self.enabled = True
while self.enabled:
# if not telnet - enable it
if not self._check_port(23) and not self._enable_telnet():
time.... |
def debug(self, message: str):
# basic logs
if 'true' in self._debug:
_LOGGER.debug(f"{self.host} | {message}")
def process_message(self, data: dict):
if data['cmd'] == 'heartbeat':
# don't know if only one item
assert len(data['params']) == 1, data
... | The code processes incoming MQTT messages by routing them to specific handling functions based on their topics, such as processing Zigbee commands, BLE events, device state changes, and heartbeat data, while logging debug information and updating system states accordingly. | def on_message(self, client: Client, userdata, msg: MQTTMessage):
try:
topic = msg.topic
if 'mqtt' in self._debug:
self.debug(f"[MQ] {topic} {msg.payload.decode()}")
if topic == 'zigbee/send':
payload = json.loads(msg.payload)
... |
def lex(i_stream):
"""Makes lexical analysis
Returns: stream of tokens
"""
lexer = Python3Lexer(i_stream)
t_stream = CommonTokenStream(lexer)
t_stream.fill()
return t_stream
def parse(t_stream):
"""Handles parsing
Params:
t_stream: stream of tokens to parse
Ret... | The code processes input text by lexing it into tokens, parsing the tokens into an abstract syntax tree (AST), converting the AST to JSON with error handling, and writing the resulting JSON to an output file. | def launch():
i_stream = FileStream('in.txt', encoding='utf-8')
t_stream = lex(i_stream)
built_tree, error_listener = parse(t_stream)
result = tree_to_json(built_tree, error_listener)
with open('out.txt', 'w') as f_out:
f_out.write(result) |
def preprocess_pokec_dataset_df(rootdir, output_stats=False):
'''
Takes the raw user profiles as a dataframe and outputs just the 10,000 most
completed users that like cats and dogs.
Optionally outputs some statistics on the full data as well.
'''
filename = 'soc-pokec-profiles.txt'
dirname ... | The code prepares the Pokec dataset by preprocessing it, generating embeddings (SBERT, BERT_avg, BOWs, or FastText) based on the specified feature type, and constructing a graph. It returns the processed graph data with embedded features for further analysis or modeling. | def prepare_pokec_main(feat_type='sbert'):
'''
Puts together above pokec preprocessing functions.
'''
ss = Settings()
rootdir = ss.args.root_dir
preprocess_pokec_dataset_df(rootdir, output_stats=False)
if feat_type == 'sbert':
prepare_pokec_sentencebert_embeddings(rootdir)
elif f... |
def run(self, num_rand_labels, severity):
train, val, test = get_dataset(self.dataset_name, augument=True, test=True)
new_train = self.some_randomization(train, RANDOM_SEED, num_rand_labels) if num_rand_labels > 0 else train
test_corrupted = get_dataset("cifar10c", severity=severity)
pr... | The main task of the code is to reproduce experiments by running models with random labels under specified severity levels, saving logits, accuracies, and entropies, and generating visualizations comparing in-distribution (ID) vs. out-of-distribution (OOD) performance. It also analyzes disruptions by saving per-disrupt... | def reproduce(self):
for i in self.num_rand_labels:
self.run(i, self.severity)
self.pickle_preds() # save logits
self.repickle_preds(self.severity) # saves accuracies and entropies
self.plot_id_vs_ood_accs()
self.plot_id_vs_ood_ents()
self.repickle_preds_... |
def verificarCuenta(numeroCuenta):
global matrixCuentas
CantCuentasN=CantCuentas()
for i in range(CantCuentasN):
if numeroCuenta == matrixCuentas[i][1]:
return True
return False
def verificarPassword(contra):
global numeroDeCuenta
global matrixCuentas
pos=buscarPoscuenta(... | The function `retirarDinero` withdraws a specified amount from a user's account if the account is valid, the password is correct, and the account balance exceeds the requested amount. It updates the balance in the `matrixCuentas` data structure upon successful withdrawal, returning `True`, or returns `False` with an in... | def retirarDinero(cantDinero):
global numeroDeCuenta
global passDeCuenta
global matrixCuentas
dineroFloat=0
if verificarCuenta(numeroDeCuenta):
if verificarPassword(passDeCuenta):
dineroFloat=float(matrixCuentas[buscarPoscuenta(numeroDeCuenta)][2])
if dineroFloat>cant... |
def locateEgo(self):
point = Point()
point.x = self.ego_.pose.position.x
point.y = self.ego_.pose.position.y
min_idx = 0
if self.prev_index_ != -1:
min_idx = self.prev_index_
min_dist = 9999
if min_idx == 0:
for i in range(min_idx, len(sel... | The code's main task is to initiate a thread by checking if trajectory and pose are initialized, then determining the ego vehicle's position (`locateEgo`), identifying the current lane link, updating lane status (`laneStatus_2`), and executing a step (`run_step`) for path planning or control logic, ensuring the system ... | def startThread(self):
start_time_1 = time.time()
if self.trajectory_initialized_ and self.pose_initialized_:
self.locateEgo()
# self.fplist = calc_frenet_paths_total(self.frenet_hyper, self.current_speed / 3.6, self.ego_.lat_offset, 0.0, 0.0, self.ego_.s, 35.0 / 3.6, self.ref_p... |
def define_variables_ns(mesh):
# Define finite elements for velocity, pressure, and temperature
P1 = fe.VectorElement("Lagrange", mesh.ufl_cell(), 2) # Velocity
P2 = fe.FiniteElement("Lagrange", mesh.ufl_cell(), 1) # Pressure
viscosity_func_space = fe.FunctionSpace(mesh, P2)
phi_prev_interpolat... | The function updates or initializes a Navier-Stokes solver on a new mesh, interpolating old solutions, defining boundary conditions, and assembling problem forms. It returns the solver, solution vectors, and related variables for fluid dynamics simulations, handling both initial setup and mesh refinement updates. | def update_solver_on_new_mesh_ns(mesh, physical_parameters_dict, old_solution_vector_ns= None, old_solution_vector_0_ns=None,
old_solution_vector_0_pf=None, variables_dict= None):
global Bc
# define new solver after mesh refinement:
if old_solution_vector_ns is no... |
def get_adj_val(self, x, y, value=''):
x_min = (x - 1) if x > 0 else 0
y_min = (y - 1) if y > 0 else 0
x_max = x + 2
y_max = y + 2
box = self.view[x_min:x_max, y_min:y_max] == value
return self.__c(self.to_index(box, x_min, y_min), [(x, y)])
def __i(self, a: list, b: list):
"""return the intersection of a... | This function identifies edges in a grid that are "big" relative to a given (x,y) position and share unknowns with adjacent nodes. It defines bounds around (x,y), filters a local region's indices, and returns edges meeting criteria of higher value at (x,y) and overlapping unknowns in adjacency. | def get_edge_pair(self, x, y):
lbound = lambda a: (a - 2) if (a - 1) > 0 else 0
x_min, x_max = lbound(x), x + 3
y_min, y_max = lbound(y), y + 3
adj_mark = lambda a, b: len(self.get_adj_val(a, b, 'F'))
value = lambda a, b: int(self.view[a, b]) - adj_mark(a, b)
is_big = lambda a, b: value(x, y) >= value(a, b... |
def new_game(self):
if self.game._is_started == False:
self.unstuck()
self.game.clear(self.height // 2, self.width // 2)
def update(self):
self.view = self.game.view
def get_edges(self):
"""returns indices of every cell in the current game that borders an unknown cell"""
known = np.core.defchararray.not_e... | The code checks if the sum of adjacent unknown cells and marked cells around each edge cell matches the cell's displayed value. If so, it marks the unknown cells and attempts to resolve the game's stuck state. | def check(self):
self.new_game()
self.update()
self.stuck[0] = True
for cell in self.get_edges():
adj_unk = self.get_adj_val(*cell)
adj_mark = self.get_adj_val(*cell, 'F')
if len(adj_unk) + len(adj_mark) == int(self.view[cell]):
for i in adj_unk:
self.game.mark(*i)
self.unstuck() |
def new_game(self):
if self.game._is_started == False:
self.unstuck()
self.game.clear(self.height // 2, self.width // 2)
def update(self):
self.view = self.game.view
def get_edges(self):
"""returns indices of every cell in the current game that borders an unknown cell"""
known = np.core.defchararray.not_e... | The code's main task is to handle a game state update by initializing a new game, marking the agent as stuck, iterating over edge cells to check adjacent values, and clearing unknown cells when adjacent flags match the cell's view value, followed by unsticking the agent. This logic likely pertains to a grid-based puzzl... | def act(self):
self.new_game()
self.update()
self.stuck[1] = True
for cell in self.get_edges():
adj_unk = self.get_adj_val(*cell)
adj_mark = self.get_adj_val(*cell, 'F')
if len(adj_mark) == int(self.view[cell]):
for i in adj_unk:
self.game.clear(*i)
self.unstuck() |
def new_game(self):
if self.game._is_started == False:
self.unstuck()
self.game.clear(self.height // 2, self.width // 2)
def update(self):
self.view = self.game.view
def get_edges(self):
"""returns indices of every cell in the current game that borders an unknown cell"""
known = np.core.defchararray.not_e... | The code's main task is to analyze a game state, calculate cell values based on adjacent flags, compare differences to determine moves, and mark/clear cells to progress. It iterates through edges, evaluates pairs, and updates the game by flagging or unflagging cells to avoid being stuck, using internal methods for game... | def study(self):
self.new_game()
self.update()
self.stuck[2] = True
for cell in self.get_edges():
for pair in self.get_edge_pair(*cell):
c_value = int(self.view[cell]) - len(self.get_adj_val(*cell, 'F'))
p_value = int(self.view[pair]) - len(self.get_adj_val(*pair, 'F'))
c_ex_p = self.__c(self.get... |
def new_game(self):
if self.game._is_started == False:
self.unstuck()
self.game.clear(self.height // 2, self.width // 2)
def check(self):
self.new_game()
self.update()
self.stuck[0] = True
for cell in self.get_edges():
adj_unk = self.get_adj_val(*cell)
adj_mark = self.get_adj_val(*cell, 'F')
if... | The main task of the code is to execute a game-playing loop: initialize a new game, repeatedly check game status and perform actions until the game is lost or specific conditions are met, and study outcomes after each cycle. It handles game state validation, action execution, loss detection, and learning processes with... | def play(self):
self.new_game()
while all(self.stuck) == False:
while not self.game.lose and all(self.stuck[:2]) == False:
self.check()
self.act()
if self.game.lose:
break
self.study() |
def c_values(limits, step):
return np.round(np.arange(-limits, limits, step), 1)
def isotropic_gaussian(center, sd):
cov_matirx = sd**2 * np.identity(2)
return numpy.random.multivariate_normal(center, cov_matirx, 40)
def original_gaussian_cluster(neg_class, pos_class, filepath):
dataset = np.vstack((neg... | The function `gaussian_clustering` generates two synthetic Gaussian datasets centered at different points, labels them, and combines them into a single dataset. It evaluates clustering performance using parallel processing across parameter variations, identifies optimal clustering results, and visualizes both the origi... | def gaussian_clustering():
"""
executing gaussian clustering for question 2, creating 2 sets of gaussian data from different centers, labeling
them, combining them to form the dataset, and then running the clustering algorithm with the dataset and plotting
the clustering along with the un-clustered data... |
def mean(self) -> float:
''' This returns the sample mean of the percolation threshold based off T trials'''
return sum(self.sim_values) / self.T
def stddev(self) -> float:
''' This returns the standard deviation of the percolation threshold based off T trials'''
if self.T == 1: return 0... | The main task of the code is to print key simulation statistics after completing T trials, including the sample mean, standard deviation, 95% confidence interval, grid dimensions, and trial count. The function currently outputs these values with basic print statements, though the TODO comment suggests future improvemen... | def showSimulationResults(self) -> None:
''' This prints all the necessary statistics after completing T trials'''
# TODO: Make it look nicer and all lined up
#print(f"{'Sample Mean = ':<25 + self.mean():<50} )
print('Sample Mean = ', self.mean())
print('Standard Deviation = ',... |
def evolve(population, retain=0.2, random_select=0.05, mutate=0.01):
"""
Function for evolving a population , that is, creating
offspring (next generation population) from combining
(crossover) the fittest individuals of the current
population
:param population: the current population
:param... | The code simulates an evolutionary process where a population of genes competes in multiple tournaments. It evolves the population through natural selection, recombination, and mutation, evaluating each gene's fitness. After each tournament, it identifies the fittest gene (winner) and updates the best-performing gene i... | def fight(tournaments, population):
"""
Let the genes fight for their lives.
Create the population and select 2 random genes.
eval them both and check which one is the winner.
for every genotype in the gene check if it will mutate or recombine.
Check if the gene is our winning gene and display ... |
def create_keychain(*, keychain_password: str) -> None:
"""
Create a new keychain for the codesigning and notarization process.
This ephemeral keychain stores Apple ID credentials for `notarytool` and
code signing certificates for `codesign`.
"""
# Ensure keychain does not exist.
delete_ke... | (The function creates an ephemeral keychain with the provided password, imports notarization credentials and codesigning certificates, and configures the keychain to allow access by Apple-related tools (codesign, notarization) using the specified password. This prepares the keychain for secure code signing and notariza... | def setup_codesigning_and_notarization_keychain(*, keychain_password: str) -> None:
"""
Create and prepare a keychain for the codesigning and notarization process.
A new keychain with the given password is created and set to be ephemeral.
Notarization credentials and codesigning certificates are import... |
def log_group(group: str) -> Iterator[None]:
"""
Create an expandable log group in GitHub Actions job logs.
https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#grouping-log-lines
"""
print(f"::group::{group}")
try:
yield
finally:
print(":... | The function creates a disk image (DMG) containing codesigned binaries and resources for Apple notarization. It builds a temporary directory, copies files, generates a read/write UDIF image, sets the DMG icon (if provided), resizes and compresses the image, then codesigns the final DMG. Returns the path to the prepared... | def create_notarization_bundle(
*,
release_name: str,
binaries: list[Path],
resources: list[Path],
dmg_icon_url: Optional[str],
) -> Path:
"""
Create a disk image with the codesigned binaries to submit to the Apple
notarization service and prepare for distribution.
Returns `Path` ob... |
def log_group(group: str) -> Iterator[None]:
"""
Create an expandable log group in GitHub Actions job logs.
https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#grouping-log-lines
"""
print(f"::group::{group}")
try:
yield
finally:
print(":... | The main task of the code is to verify the integrity and codesigning of a stapled disk image and its contained binaries. It checks the disk image's staple using `xcrun stapler`, validates its signature with `spctl`, mounts the image, and then verifies and displays the code-signing details of each specified binary using... | def validate(*, bundle: Path, binary_names: list[str]) -> None:
"""
Verify the stapled disk image and codesigning of binaries within it.
"""
with log_group("Verify disk image staple"):
run_command_with_merged_output(
["/usr/bin/xcrun", "stapler", "validate", "-v", str(bundle)]
... |
def emit_metadata() -> None:
if os.getenv("CI") != "true":
return
with log_group("Workflow metadata"):
if repository := os.getenv("GITHUB_REPOSITORY"):
print(f"GitHub Repository: {repository}")
if actor := os.getenv("GITHUB_ACTOR"):
print(f"GitHub Actor: {actor}")... | The code creates Apple code signatures and notarized archives by processing specified binaries and resources. It validates file existence, sets up a temporary keychain, codesigns binaries, bundles them with resources, notarizes the bundle, and validates the result. It also handles optional DMG icon URLs, outputs the fi... | def main() -> int:
parser = argparse.ArgumentParser(
description="Create Apple code signatures and notarized archives"
)
parser.add_argument(
"-b",
"--binary",
action="append",
dest="binaries",
required=True,
type=Path,
help="path to binary to ... |
def create_writer(args):
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter("runs/" + args.output_foloder)
msg = ""
for key in vars(args):
msg += "{} = {}<br>".format(key, vars(args)[key])
writer.add_text("Parameter", msg, 0)
writer.flush()
writer.close()
r... | The main task of the code is to set up and execute a machine learning training pipeline. It initializes data loaders, checks hardware (GPU), loads training/validation data, creates a model, and trains it using specified configurations. Key steps include data splitting, model creation, GPU allocation, and training execu... | def main(args):
writer = create_writer(args)
device = checkGPU()
class_to_idx = readClassIdx(args)
data_list = readTrainImages(args)
train_data_list, val_data_list, _ = splitDataList(data_list, 0.9, 0.1)
model = create_model(args).to(device)
train_loader, val_loader = create_dataloader(
... |
def action(self, name):
while True:
print("1. View All Books\n2. View Specific Type\n3. View Certain Book\n4. View Books by Author")
print("5. Add Book\n6. View Cart\n7. Exit")
choice = input("Choice: ")
if choice == '1':
self.viewBooks()
... | The main task of the code is to authenticate a user by verifying their entered username and password against a list of stored users. If successful, it executes user-specific actions; if not, it provides options to retry, reset the password, or exit the program. | def login(self):
username = input("Enter username: ")
password = input("Enter Password: ")
login = False
for user in self.users:
if user.userName == username and user.userPassword == password:
print("login successful!")
login = True
... |
def _decrement_forward(self):
"""Move forward back."""
if self._forward == 0:
self._forward = 2 * self._buffer_size - 1
else:
self._forward -= 1
def _get_token_tuple(self) -> Tuple[str, str]:
"""Return tuple with form (token_type, token_lexeme)"""
if self.... | This function processes an input file to return the next token by transitioning through states, handling EOF, line numbers, and errors. It manages buffer clearing, state resets, lookahead handling, and token validation, returning either the token or EOF with appropriate symbols and line tracking. | def get_next_token(self) -> Tuple[str, str]:
"""Return next token of input_file."""
if self._is_file_ended:
return self.EOF, self.EOF_symbol
self._token_buffer.clear()
self._current_state = self._states[0]
while True:
# Check terminal
if self.... |
def on_event(self):
for event in pygame.event.get():
if event.type == QUIT:
self.running = False
elif event.type == MOUSEBUTTONDOWN and event.button == G.LMB:
self.draggingFlag = True
self.mouseDown = True
elif event.type == MOU... | The code defines a game loop that continuously checks for board updates, updates piece moves when changes occur, processes events, renders the game state, and exits properly when the loop ends. | def on_start(self):
while self.running:
if self.boardUpdated:
self.pieces.update_moves()
self.boardUpdated = False
self.on_event()
self.render()
self.on_quit() |
def find_persons(frame):
yunet = cv2.FaceDetectorYN.create(
model=r"C:\Users\User\Desktop\MarathonVisionOCR\libfacedetection\yunet.onnx",
config="",
input_size=(320, 320),
score_threshold=0.6,
nms_threshold=0.3,
top_k=5,
backend_id=cv2.dnn.DNN_BACKEND_DEFAULT,... | The main task of the code is to detect and locate text regions on individuals within a snapshot image. It reads an image, identifies person regions using `find_persons`, extracts text regions from each person with `find_text_on_every_person`, and displays the image. The focus is on isolating text associated with each d... | def ocr_snapshot():
image = cv2.imread(".\data\snapshot_3.png")
persons_rois = find_persons(image)
text_rois = find_text_on_every_person(image, persons_rois)
show("image", image, True) |
def evaluation_step():
global best_validation_score
# Log start of validation
logging.info(f"Validation started")
# Set gpt2 in evaluation mode
dgst.eval()
logging.info("DGST model set in evaluation mode")
# Do validation step
best_validation_score, valid... | The main task of the code is to execute a training loop over multiple epochs, processing mini-batches to train a model. It logs training progress at specified intervals, performs validation checks periodically, and saves model checkpoints at the end of each epoch. The loop manages global step counters, accumulates loss... | def training_loop():
global global_step_idx
# Initialise variables
n_epochs = optimizer_configs.get('n_epochs', 0)
validation_period = evaluation_configs.get('validation_period', len(corpus_loaders[DataSetSplit('train')]))
logging_period = evaluation_configs.get('logging_period'... |
def init_environment(config_file_path: str):
# Declare global variables
global random_seed, device, mixed_precision, writer, training_configs
global model_config_map, corpus_config_map, loss_configs_map, \
optimizer_configs_map, lr_scheduler_configs_map, evaluation_configs_map
global current_exp... | The main task of the code is to train and evaluate a GPT-2 model using multiple training configurations. It initializes the environment, loads data, sets up the model and optimizer, trains the model, evaluates its performance, and cleans up resources after each configuration iteration. | def main(args: Namespace):
global config_id
# Perform preparation steps
# Prepare the environment
init_environment(args.config_file_path)
# Iterate over training configs
for config_id in training_configs:
# Set environmental configs
set_env()
# Create gpt2 and tokeniser
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.