dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
p... | The function computes cross-related statistics (total, completed, failed, assist crosses) for each player in `df` using event data from `dfEvent`. It identifies cross events (passes/free kicks), categorizes them based on accuracy and assists, and appends these metrics as new columns to `df`. A separate DataFrame `dange... | def computeTotalNumberCross(df, dfEvent):
"""
For each player in df look the number of air duel inside a match
Parameters
----------
df : match_id gameweek team_id playerId minutes_played red_card yellow_card goals
The dataset extracted with playerMatchExtraction from json file of Wyscout m... |
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
p... | The code computes the total number of ground tackles (completed and failed) for each player in the input dataframe `df` by analyzing event data in `dfEvent`. It identifies dangerous tackles using specific event tags and positional logic, appending counts as new columns to `df`. A separate dataframe with dangerous tackl... | def computeTotalNumberTackels(df, dfEvent):
"""
For each player in df look the number of air duel inside a match
Parameters
----------
df : match_id gameweek team_id playerId minutes_played red_card yellow_card goals
The dataset extracted with playerMatchExtraction from json file of Wyscout... |
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
p... | The function `computeTotalNumberDribbling` calculates the total, completed, and failed dribbling events for each player in `df` by analyzing event data in `dfEvent`. It filters events by match and player, identifies "Ground attacking duel" events with specific tags (503/504), and counts completed (703/702) and failed (... | def computeTotalNumberDribbling(df, dfEvent):
"""
For each player in df look the number of DRIBBLING inside a match
Parameters
----------
df : match_id gameweek team_id playerId minutes_played red_card yellow_card goals
The dataset extracted with playerMatchExtraction from json file of Wysc... |
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
p... | The function computes air duel statistics for each player in the input dataframe by analyzing event data. It counts total air duels, successful (complete) duels, and failed duels, adding these as new columns to the original dataframe. Additionally, it generates a separate dataframe containing metrics related to dangero... | def computeTotalAirDuel(df, dfEvent):
"""
For each player in df look the number of air duel inside a match
Parameters
----------
df : match_id gameweek team_id playerId minutes_played red_card yellow_card goals
The dataset extracted with playerMatchExtraction from json file of Wyscout match... |
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
p... | The function `computeTotalNumberInterceptions` calculates the total and completed interceptions for each player in `df` by analyzing event data in `dfEvent`. It iterates through each player's match events, counts interceptions (tag 1401), identifies completed ones (tag 1801), and evaluates dangerous interceptions using... | def computeTotalNumberInterceptions(df, dfEvent):
"""
For each player in df look the number of Interceptions inside a match
Parameters
----------
df : match_id gameweek team_id playerId minutes_played red_card yellow_card goals
The dataset extracted with playerMatchExtraction from json file... |
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
p... | The main task of the code is to compute the total number of clearances (successful and failed) for each player in a match by analyzing event data. It processes player-event records, identifies clearance events using specific tags, categorizes them as completed or failed, and calculates dangerous clearances. The results... | def computeTotalNumberClearences(df, dfEvent):
"""
For each player in df look the number of Clearances inside a match
Parameters
----------
df : match_id gameweek team_id playerId minutes_played red_card yellow_card goals
The dataset extracted with playerMatchExtraction from json file of Wy... |
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
p... | The function `computeTotalNumberShot` calculates various shot-related statistics (e.g., total shots, goals, off-target shots, penalties) for each player in `df` using event data from `dfEvent`. It iterates through each player’s matches, filters relevant events, and classifies shots based on tags (e.g., 101 for goals, 1... | def computeTotalNumberShot(df, dfEvent):
"""
For each player in df look the number of SHOT inside a match
Parameters
----------
df : match_id gameweek team_id playerId minutes_played red_card yellow_card goals
The dataset extracted with playerMatchExtraction from json file of Wyscout matche... |
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
p... | The function computes foul and card statistics for each player in a match by processing event data. It counts total fouls, yellow/red cards, and dangerous fouls, appending these as new columns to the input dataframe. A separate dataframe tracks dangerous foul details. | def computeTotalNumberFoul(df, dfEvent):
"""
For each player in df look the number of foul inside a match
Parameters
----------
df : match_id gameweek team_id playerId minutes_played red_card yellow_card goals
The dataset extracted with playerMatchExtraction from json file of Wyscout matche... |
def attackToRight(listOfPosition):
'''
Given the first event of a match, start from passes position define if the team attack on left or right
##RECALL FROM EACH QUALITY FEATURE COMPUTATION
Params:
List of position at 0 the starting point of the pass
1 the ending poi... | The function `computeFoulFeatures` analyzes foul-related statistics in football matches by processing event data. It tracks fouls, tackles, and aerial duels for each player in specified matches, categorizing them into "suffered," "dangerous," and "tackle" metrics. It identifies responsible players, updates counters, an... | def computeFoulFeatures(df, listUniqueMatchId, dfEvent):
"""
For each match in the listUniqueMatcheId look the statistics regarding Fauls in a game
Parameters
----------
df : match_id gameweek team_id playerId minutes_played red_card yellow_card goals
The dataset extracted with playerMatchE... |
def parse_args():
# hyper-parameters are from ResNet paper
parser = argparse.ArgumentParser(description='PyTorch CIFAR10 training')
parser.add_argument('cmd', choices=['train', 'test'])
parser.add_argument('--data-dir', default='/home/xxx/cifar100', type=str,
help='the diretory t... | The code's main task is to execute either training or evaluation of a machine learning model based on command-line arguments. It parses inputs, sets up logging to a file and console, creates necessary directories, and invokes `run_training` or `run_test` depending on the 'cmd' parameter, which specifies 'train' or 'tes... | def main():
args = parse_args()
save_path = args.save_path = os.path.join(args.save_folder, args.arch)
if not os.path.exists(save_path):
os.makedirs(save_path)
args.logger_file = os.path.join(save_path, 'log_{}.txt'.format(args.cmd))
handlers = [logging.FileHandler(args.logger_file, mode='w'... |
def get_today_stock_list(self,type):
#stock_list = ["ICICI"]
file_name = self.input_dir + "\\today_analysis_list.csv"
data = pd.read_csv(file_name, encoding='ISO-8859-1')
if type == "today":
data = data[data["YES/NO"] == "Y"]
stock_list = list(data["SYMBOL"])
... | The main task of the code is to fetch intraday stock data for multiple stocks, process historical and current data intervals, generate analysis results, and plot dynamic graphs. It repeatedly retrieves old data, waits for updates, then combines current data with historical data to compute metrics, saves analysis to Exc... | def plot_intraday_graphs(self):
stock_list = self.get_today_stock_list("today")
file_name_excel = self.output_dir + "\\analysis_data_today.xlsx"
urls = self.get_urls(stock_list)
old_data = {}
avg_data = {}
time_intervel = 2
num_day = 9
current = datetime... |
def setup_from_discord_messages(self):
if not self.get_messages():
cprint('failed to get messages', RED)
return
n = len(self.messages)
self.k, self.n = 0, n
self.currently_found_model_page_ids = []
messages_actions = [lambda i:...]*n
# parse the reactions (so that self.n does not account for SKIPs)
... | The code initializes an environment by setting up data from Discord messages and Civitai favorites, installs Python dependencies and memory optimization tools (like TCMalloc) on non-Windows systems, and performs cleanup. It ensures the environment is ready for operation by creating a virtual environment, configuring al... | def setup(self):
self.setup_from_discord_messages()
if self.args['favorites']: self.setup_from_civitai_favorites()
self.save_cache()
self.set_relauncher_alias()
if not from_windows:
if not self.running_in_runpod_env:
cprint('\npopulating python env...', GREEN)
os.system('sudo apt install -y python3... |
def load_config(self):
if os.path.exists(self.config_filename) and os.path.getsize(self.config_filename):
with open(self.config_filename, 'rb') as f:
content = f.read()
if content != b'':
self.config = load_json_with_comments(content.decode('utf-8'))
else:
cprint(self.config_filename+' conten... | The code initializes a setup process by loading configuration files, parsing arguments, setting up environment variables, model directories, authentication headers, and cloning required repositories. It checks for a mounted config, handles cache loading, and prompts user confirmation post-initialization, with platform-... | def __init__(self):
if not self.config_loaded:
if not self.load_config(): exit(1)
self.parse_args(self.config['args_info'])
else:
self.parse_args(self.args_info)
if self.args['mount']:
self.mount_config()
elif self.config_loaded:
# proceed with the initialization setup
self.load_cache()
... |
def find_index(lst, key, value):
filtered = [i for i, d in enumerate(lst) if d.get(key) == value]
return filtered[0] if len(filtered) > 0 else -1
def cprint(string, color_code=30, end='\n'):
print(f"\033[{color_code}m{string}\033[0m", end=end)
def get_model_info(self, model_page_url):
# get its page
if not downl... | The function installs AI models by checking if they are already cached or exist locally. If not, it downloads models from URLs, handles different model types (e.g., TextualInversion, Poses), creates directories, extracts files, and updates the cache with installed models. It avoids redundant downloads and ensures prope... | def install_models(self, embeds):
for j in range(len(embeds)):
model_page_url = embeds[j]['url']
# check if model page is cached
model_index = find_index(self.cache['downloaded_models_in_discord_channel'], 'model_page_url', model_page_url)
if model_index == -1: model_index = find_index(self.cache['models... |
def facebook_users_timeline(self):
"""Several users"""
log.debug("Harvesting users with seeds %s", self.message.get("seeds"))
for seed in self.message.get("seeds", []): #todo
self.facebook_user_timeline(seed_id = seed.get("id"), username = seed.get("token"), nsid = seed.get("uid"... | The function determines the type of data to harvest from Facebook (timeline, bio, or ads) based on the message's "type" field and executes the corresponding method. It logs the harvest type and initiates the appropriate data collection process. If an unrecognized type is provided, it raises a KeyError. | def harvest_seeds(self):
"""
Will start appropriate harvest - as of now this
is unnecessary as timelines are the only fb types
being harvested but this could change
"""
harvest_type = self.message.get("type")
# Dispatch message based on type
log.debug("H... |
def send_to_node(self, n, data):
self.delete_closed_connections()
if n in self.nodes_connected:
try:
n.send(data)
except Exception as e:
print("HappyCoinNode send_to_node: Error while sending data to the node (" + str(e) + ")")
else:
... | This function synchronizes a node by sending all available blocks and unconfirmed transactions. It first signals the start of block transmission, iterates through retrieved blocks to send each as a new_block message with delays, transmits unconfirmed transactions, then signals completion to ensure the node updates its ... | def send_start_blocks(self,nodez):
data = {"func": "start_sending_blocks"}
self.send_to_node(nodez,data)
time.sleep(0.2)
send_blocks = self.return_blocks()
for block in send_blocks:
self.send_to_node(nodez,{"func":"new_block","block":block.block_to_dict()})
... |
def send_start_blocks(self,nodez):
data = {"func": "start_sending_blocks"}
self.send_to_node(nodez,data)
time.sleep(0.2)
send_blocks = self.return_blocks()
for block in send_blocks:
self.send_to_node(nodez,{"func":"new_block","block":block.block_to_dict()})
... | This function processes incoming messages by routing them to appropriate handlers based on their type. It handles block requests, new transactions, new blocks, and block transfer signals, logging unknown messages. It also prints details about the message source and destination ports for tracking and debugging. | def received_message(self, node, data):
if data["func"] == "request_blocks":
self.send_start_blocks(node)
elif data["func"] == "new_transaction":
self.recv_new_transaction(Transaction.dict_to_trans(data["trans"]))
elif data["func"] == "new_block":
print("RECEI... |
def connect():
global conn
if not conn:
global DB_FILE
DB_FILE = "session_db.sqlite"
conn = sqlite3.connect(DB_FILE)
conn.row_factory = sqlite3.Row
def create_session():
c = conn.cursor()
with closing(conn.cursor()) as c:
c.execute('''CREATE TABLE IF NOT EXISTS Session
... | The code's main task is to initialize a connection and session, retrieve the last session's money data, and return the 'stopMoney' attribute from it. | def start():
connect()
create_session()
global money
money = get_last_session()
return money.stopMoney |
def parse_sql_values(line):
values = line[line.find("` VALUES ") + 9:]
latest_row = []
reader = csv.reader(
[values],
delimiter=",",
doublequote=False,
escapechar="\\",
quotechar="'",
strict=True,
)
for reader_row in reader:
for column in reade... | The code processes Wikidata dumps to build a trie of QIDs for fast lookups and creates redirect mappings between identifiers. It reads SQL dump files, extracts QID mappings, constructs a Marisa Trie, and stores redirects in databases for efficient querying. | def build_trie_and_redirects(self, step=100000):
if not os.path.exists(cf.DIR_DUMP_WIKIDATA_PAGE):
raise Exception(f"Please download file {cf.DIR_DUMP_WIKIDATA_PAGE}")
if not os.path.exists(cf.DIR_DUMP_WIKIDATA_REDIRECT):
raise Exception(f"Please download file {cf.DIR_DUMP_WIKIDA... |
def build_trie_and_redirects(self, step=100000):
if not os.path.exists(cf.DIR_DUMP_WIKIDATA_PAGE):
raise Exception(f"Please download file {cf.DIR_DUMP_WIKIDATA_PAGE}")
if not os.path.exists(cf.DIR_DUMP_WIKIDATA_REDIRECT):
raise Exception(f"Please download file {cf.DIR_DUMP_WIKIDA... | The code's main task is to construct and optimize data structures: building a trie/redirect map, generating a parallelized JSON dump, optionally creating haswbstatements, and reducing file size via LMDB copying for efficient storage and retrieval. | def build(self):
# 1. Build trie and redirect
self.build_trie_and_redirects()
# 2. Build json dump
self.build_from_json_dump(n_process=6)
# 3. Build haswdstatement (Optional)
self.build_haswbstatements()
# 4. Post-processing to reduce file size
self.cop... |
def file_reader(file_name):
puzzle = []
file = open(file_name)
valid_inputs = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for ind in range(9):
line = file.readline()
row = line.split()
puzzle.append(row)
# convert each value in puzzle from a string to an integer
f... | The code solves a Sudoku puzzle using backtracking with MRV/degree heuristics and AC-3 constraint propagation. It reads a puzzle from a file, checks its validity, constructs a CSP, enforces arc consistency, and applies backtracking search. If solvable, it outputs the solution; otherwise, it reports failure. The process... | def main():
# Get the input file from the cmd command
parser = argparse.ArgumentParser(description='Solve Sudoku Puzzle with Backtracking Algorithm '
'with MRV/degree heuristics and RGB order')
parser.add_argument('filename', help='The input file containing t... |
def echo(my_serial):
my_serial.write(b'1')
time.sleep(0.1)
data = read_serial_data(my_serial)
if(len(data) > 0):
return data[0][:-1]
else:
return None
def random_numbers(my_serial):
my_serial.write(b'2')
time.sleep(0.1)
data = read_serial_data(my_serial)
if(len(data... | The code defines a user interface that processes commands from the user, interacting with a serial device (`my_serial`). It handles three commands: 'echo' (prints data from `echo()`), 'random' (generates and plots random numbers via `random_numbers()`), and 'exit' (terminates the loop). Invalid commands trigger an erro... | def user_interface(my_serial):
while True:
user_input = input('Enter a command: ')
if(user_input == 'echo'):
print(echo(my_serial))
elif(user_input == 'random'):
x, y = random_numbers(my_serial)
plot_data(x, y)
elif(user_input == 'exit')... |
def clientLogIn(sck):
user = sck.recv(1024).decode(FORMAT)
print("username:--" + user +"--")
USERNAME=user
sck.sendall(user.encode(FORMAT))
pswd = sck.recv(1024).decode(FORMAT)
print("password:--" + pswd +"--")
accepted = check_clientLogIn(user, pswd)
if accepted == 1:
... | This code handles client requests by receiving commands (e.g., login, signup, file operations) and executing corresponding functions. It maintains a connection loop, processes client actions like file sharing/retrieval, and terminates the session by closing the connection and removing the user from active accounts when... | def handle_Client(conn, addr):
while True:
option = conn.recv(1024).decode(FORMAT)
if option == LOGIN:
Ad.append(str(addr))
clientLogIn(conn)
elif option == SIGNUP:
clientSignUp(conn, addr)
elif option == LOGOUT:
Remove_LiveAc... |
def parseIndSupport(indSupportFile): # returns List of Independent Variables
f = open(indSupportFile, "r")
lines = f.readlines()
f.close()
indList = []
numVars = 0
for line in lines:
if line.startswith("p cnf"):
fields = line.split()
numVars = int(fields[2])
... | The code `CubeProbe` estimates or tests the total variation distance (dTV) between sampled solutions and the model count of a CNF formula. It uses specified samplers (QuickSampler, STS, CMSGen) to generate samples, computes parameters for accuracy, and runs in parallel threads. In 'est' mode, it outputs the dTV estimat... | def CubeProbe():
start_time = time.time()
parser = argparse.ArgumentParser()
parser.add_argument(
"--zeta", type=float, help="default = 0.3", default=0.3, dest="zeta"
)
parser.add_argument(
"--eta", type=float, help="default = 0.605", default=0.605, dest="eta"
)
parser.add_... |
def check_pixel(t):
r, g, b, a = t
avg = (r + g + b)/3
return avg < 10
def get_black_len(im: Image, xy):
count = 0
while check_pixel(im.getpixel(xy)):
count += 1
xy = (xy[0] + 1, xy[1])
return count
def paint(length, im: Image, xy):
start = xy[0] + get_black_len(im, xy) - len... | This function processes an image by iterating through each pixel to identify and mark specific regions. It checks pixel values, calculates lengths based on black pixel sequences, adjusts parameters dynamically, and applies red paint to designated areas. The modified image is saved to the specified file path. | def mark_red(im, fp):
h = im.height.real
w = im.width.real
first = size = 3
for row in range(h):
for line in range(w):
pix = (line, row)
if check_pixel(im.getpixel(pix)):
length = 4
if first > 0:
length = get_black_len(i... |
def _handle_collision(self):
ball = self.ball
left_paddle = self.left_paddle
right_paddle = self.right_paddle
#If ball hits the top or bottom
if ball.y + ball.radius >= self.window_height:
ball.y_vel *= -1
elif ball.y - ball.radius <= 0:
ball.y_ve... | The code's main task is to update the game state by moving the ball, handling collisions, and automatically adjusting paddle positions based on the ball's Y-coordinate. It also manages scoring logic for solo and two-player modes by checking if the ball goes out of bounds, resetting the ball, and updating scores accordi... | def loop(self):
if self.paused == False:
self.ball.move()
self._handle_collision()
#Automated paddle movement (Rule-Based)
if self.left_paddle.y_pos + self.left_paddle.height//2 > self.ball.y:
self.move_paddle(left=True, up=True)
if s... |
def draw_segmentation(self, image, alpha = 0.5):
return util_draw_seg(self.seg_map, image, alpha)
def draw_boxes(self, image, text=True):
return util_draw_detections(self.filtered_boxes, self.filtered_scores, image, text)
def draw_bird_eye(self, image, horizon_points):
seg_map = self.draw_2D(image, 0.00001, te... | The code's main task is to generate a combined image displaying two perspectives: a front view with segmentation and bounding boxes, and a bird's eye view derived from horizon points. It merges these views horizontally using NumPy's hstack function, returning a side-by-side visualization for multi-perspective analysis. | def draw_all(self, image, horizon_points, alpha = 0.5):
front_view = self.draw_segmentation(image, alpha)
front_view = self.draw_boxes(front_view)
bird_eye_view = self.draw_bird_eye(image, horizon_points)
combined_img = np.hstack((front_view, bird_eye_view))
return combined_img |
def Pizzo_2D_Euler_Upwind(q,r,dp,dr):
"""This function computes the upwind or propogated radial step of any primitive variable in the state vector q
------
parameters:
q = state vector
r = radius
dp = phi step index
dr = radial step index
"""
ur, rho, Pr, up = q
#... | This function implements the MacCormack scheme's predictor-corrector steps for 2D fluid dynamics simulations. It first computes a predictor solution using an upwind Euler method, then refines it via a corrector step. Boundary conditions are applied to the final result before returning the updated state vector. The meth... | def Pizzo_MacCormack_2D(q, dp, dr, r, theta = np.pi / 2):
"""This function combines the predictor and corrector step of the MacCormack scheme,
to be called as only one function when modeling
------
parameters:
q = solution state vector
r = radius
dp = phi step index
dr =... |
def Euler_Upwind_2D(Cx, q, r, dp, dr):
"""This function computes the upwind or propogated radial step of any primitive variable in the state vector q
------
parameters:
q = state vector
r = radius
dp = phi step index
dr = radial step index
Cx = artifical viscosity coe... | This function implements the MacCormack scheme for 2D simulations by combining a predictor step (using Euler upwind method with artificial viscosity) and a corrector step to compute updated solution states. It applies boundary conditions to the final solution and returns the stabilized result, essential for numerical s... | def MacCormack_2D(q, dp, dr, r, Cx, theta = np.pi / 2):
"""This function combines the predictor and corrector step of the MacCormack scheme,
to be called as only one function when simulating
------
parameters:
q = solution state vector
r = radius
dp = phi step index
dr =... |
def checkleapyear(self):
if(self.year % 4 == 0):
self.yearDict["Feb"] = 29
def init(self, days):
for d in range(days):
if d == 0:
lower = 0
upper = 24
else:
lower = upper
upper += 24
se... | This code initializes a class to process and visualize monthly data, setting up attributes like month, year, country lists, and day counts. It prepares data structures for daily bounds, permutations, and plots, calling methods to handle leap years and generate daily plots. | def __init__(self, month, monthlyDFDict, year, countryList, showPlot):
self.month = month # month to be plotted
self.monthDFDict = monthlyDFDict
self.monthDFList = monthlyDFDict[month]
self.countries = countryList
# print(countryList)
self.year = year
se... |
def read_status():
if os.path.exists(MOLECULES_DONE_FILEPATH):
print_and_flush('Node {}: Resuming from {}'.format(job_id, MOLECULES_DONE_FILEPATH))
with open(MOLECULES_DONE_FILEPATH, 'r') as f:
molecules_data = set(json.load(f))
else:
molecules_data = set()
return molecul... | The code distributes YANK molecular simulation tasks across parallel jobs. It processes molecules from PDB files, skips already-completed tasks, generates YANK input scripts, and runs simulations for assigned molecules while avoiding redundant calculations through status tracking. | def run_yank(job_id, n_jobs):
openmm_system_dir = os.path.join('..', 'openmmfiles')
pdb_dir = os.path.join('..', 'pdbfiles')
yank_script_template_filepath = 'yank_template.yaml'
# Read in YANK template script.
with open(yank_script_template_filepath, 'r') as f:
script_template = f.read()
... |
def shutdown():
global world
Logger.print('Shutting down...')
world.shutdown()
sys.exit(0)
return
def toggle_animate():
global animating
animating = not animating
if (animating):
glutTimerFunc(display_anim_time, animate, 0)
return
def step_anim(timestep):
global animat... | This function handles keyboard input to control animation playback, speed, and other actions in a GLUT application. It maps keys like Escape (shutdown), Space (toggle animation), >/< (step animation), ,/. (adjust speed), l/r (reload/reset), and g (toggle recording). It updates the display with glutPostRedisplay() after... | def keyboard(key, x, y):
world.keyboard(key, x, y)
if key == b'\x1b': # escape
shutdown()
elif key == b' ':
toggle_animate()
elif key == b'>':
step_anim(update_timestep)
elif key == b'<':
step_anim(-update_timestep)
elif key == b',':
change_playback_speed... |
def init_draw():
glutInit()
glutInitContextVersion(3, 3)
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE)
glutInitContextProfile(GLUT_COMPATIBILITY_PROFILE)
if sys.platform != 'win32':
glutSetOption(GLUT_MULTISAMPLE, 8)
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_M... | The main task of the code is to handle command-line arguments and orchestrate a drawing process by initializing graphics, reloading resources, setting up the drawing environment, and entering a main drawing loop for rendering or interactive tasks. | def main():
global args
# Command line arguments
args = sys.argv[1:]
init_draw()
reload()
setup_draw()
draw_main_loop()
return |
def tickers_add_BO_NS(tickers, EXCHANGE):
count = 0
# print("symbol", tickers)
for tickers_list1 in tickers:
tickers[count] = str(f"{tickers_list1}.{EXCHANGE}")
count = count + 1
# print(tickers)
return tickers
def yfinance_download_Close(tickers_list, start_date, end_date,interval):... | The code implements a Streamlit app for financial data analysis, offering navigation between 'Sector' and 'all MARRKET' (BSE/NSE). It fetches stock data via yfinance, processes CSV files, filters by sector/exchange, generates visualizations (pie charts), and exports results. Key tasks include data retrieval, filtering,... | def run():
with st.sidebar:
app = option_menu(
menu_title='Pondering ',
options=['Sector', 'all MARRKET'], #'Add Your Capital', 'Holding', 'Intraday', 'Options', 'Charges',
# 'Charges Debits and Credits', 'Dividends', 'Settings', 'about'],
... |
def check_size(eval_segm, gt_segm):
h_e, w_e = segm_size(eval_segm)
h_g, w_g = segm_size(gt_segm)
if (h_e != h_g) or (w_e != w_g):
raise EvalSegErr("DiffDim: Different dimensions of matrices!")
def union_classes(eval_segm, gt_segm):
eval_cl, _ = extract_classes(eval_segm)
gt_cl, _ = extract... | This code processes image pairs for segmentation evaluation by validating their sizes, aggregating unique classes from both images, extracting binary masks for each class, and updating counters to track overlaps (n_ii), predicted instances (n_ij), and ground truth instances (t_i). It accumulates these metrics for perfo... | def add_image_pair(self, eval_segm, gt_segm):
check_size(eval_segm, gt_segm) # sizes of two images have to be the same
# get the existing classes from provided images
temp_cl, temp_num_cl = union_classes(eval_segm, gt_segm)
self.current_classes = np.union1d(self.current_classes, temp_c... |
def make_unet(X, training):
"""Build a U-Net architecture
Args:
X (4-D Tensor): (N, H, W, C)
training (1-D Tensor): Boolean Tensor is required for batchnormalization layers
Returns:
output (4-D Tensor): (N, H, W, C)
Same shape as the `input` tensor
Notes:
U... | The main task of the code is to train a U-Net model for semantic segmentation using diverse datasets (specific cities, solar panels, or combinations). It configures data preprocessing by setting image mean values based on the selected training data, initializes TensorFlow placeholders and readers for training/validatio... | def main(flags):
IMG_MEAN = np.zeros(3)
image_std = [1.0, 1.0, 1.0]
# parameters of building data set
citylist = ['Norfolk', 'Arlington', 'Atlanta', 'Austin', 'Seekonk', 'NewHaven']
image_mean_list = {'Norfolk': [127.07435926, 129.40160709, 128.28713284],
'Arlington': [88.3030... |
def load_projects(filename) -> list[Project]:
"""Load projects from filename.
Returns a list of loaded projects."""
# Load JSON data.
with open(filename, "r", encoding="utf-8") as in_file:
projects = json.load(in_file)
# Recreate Project objects from JSON data.
for i, project in enumer... | The code allows users to manage a list of projects through a menu-driven interface, enabling them to load, save, display, filter by date, add, and update projects. It repeatedly presents options until the user chooses to quit, ensuring data persistence by saving changes to a file. | def main():
"""Allow user to load, save and manage a list of projects."""
projects = load_projects(FILENAME)
print(MENU)
choice = input(">>> ").upper()
while choice != "Q": # Quit.
if choice == "L": # Load.
filename = input("Filename: ")
projects = load_projects(f... |
def create_dangling_ptr_in_fpool(p):
add(p, TYPE_STRING, b"R"*0x20)
list_structure_ptr = int(get(p, 0, TYPE_LONG)) - 0x50
delete(p, 0)
print("[*] fill tcache of size 0x80")
fill_tcache = []
for i in range(8):
fill_tcache.append(add(p, TYPE_STRING, b"T"*0x7f))
fpool_tags = []
fo... | The code exploits a heap vulnerability by leaking heap and libc addresses, manipulating fpool pointers with tag-based address adjustments, and corrupting the __free_hook to execute arbitrary commands. It triggers a free operation on a crafted pointer to overwrite __free_hook with the system() function address, enabling... | def exploit(p, libc):
global CURRENT_IDX
CURRENT_IDX = 0
# start by leaking heap && libc addresses
list_structure_ptr, list_data_ptr, fpool_tags = create_dangling_ptr_in_fpool(p)
print("[*] good, now fpool[0] points to list. list_data_ptr == 0x%x" % list_data_ptr)
assert CURRENT_IDX == 1
... |
def parse_args():
argparser = argparse.ArgumentParser(
description="Build the distributable package. If the packaged application contains a file called 'deps.json', the list of string it contains is used to get dependencies using pip."
)
argparser.add_argument(
"-a",
"--app",
... | The main task of the code is to bundle a Python application into a standalone executable by installing dependencies, setting up a portable Python environment, packaging the app, and compressing the bundle. It handles directory management, launcher configuration, icon customization, and dependency installation from a JS... | def main():
args = parse_args()
print()
print("Bundling python app '{}'".format(args.name))
print("source directory = {}".format(args.app))
print("destination directory = {}".format(args.output))
print()
shutil.rmtree(args.output, ignore_errors=True)
os.makedirs(args.output)
pytho... |
def update_swing_times(self, time, new_swing_timer, first_swing=False):
"""Generate an updated list of swing times after changes to the swing
timer have occurred.
Arguments:
time (float): Simulation time at which swing timer is changing, in
seconds.
new_s... | The code simulates a combat scenario, tracking damage, energy, and combo points over time. It handles cooldowns, debuffs, trinket effects, and logging if enabled. The function returns time-series data, damage breakdowns, aura stats, and a combat log (if requested), modeling player actions, ability casts, and dynamic ga... | def run(self, log=False):
"""Run a simulated trajectory for the fight.
Arguments:
log (bool): If True, generate a full combat log of events within
the simulation. Defaults False.
Returns:
times, damage, energy, combos: Lists of the time,
... |
def deactivate(self, player, sim, time=None):
"""Deactivate the trinket buff when the duration has expired.
Arguments:
player (tbc_cat_sim.Player): Player object whose attributes will be
restored to their original values.
sim (tbc_cat_sim.Simulation): Simulation ... | This function updates a trinket's state in a simulation, checking for activation/deactivation at a given time. It calculates uptime, manages cooldowns, and triggers procs if conditions are met. If allowed, it activates the trinket, applies effects, and returns instant damage; otherwise, returns 0. | def update(self, time, player, sim, allow_activation=True):
"""Check for a trinket activation or deactivation at the specified
simulation time, and perform associated bookkeeping.
Arguments:
time (float): Simulation time, in seconds.
player (tbc_cat_sim.Player): Player o... |
def generate_single(duration, name) -> None:
save_wav(generate_noise(duration), name)
print(f'Generated: {name}.wav')
def generate_silence(duration, name):
num_channels = 1
sample_width = 2
num_frames = int(SAMPLE_RATE * duration)
silent_sample = b'\x00\x00'
with wave.open(f'sounds/{name}.... | The code generates audio files (beeps and silences) for a sound library, creating directories, producing base signals (dot/dash), silence intervals, and cycling through alphabetical characters to generate multiple sound files, culminating in a combined set of all base sounds. | def generate_beeps() -> None:
if os.path.exists('sounds/'):
shutil.rmtree('sounds/')
os.mkdir('sounds/')
# 1 time unit is 0.25s
# --- BASE SOUNDS ---
generate_single(0.25, '!DOT')
generate_single(0.75, '!DASH')
# --- SILENCE SOUNDS ---
generate_silence(0.25, '!GAP_SYMBOL')
... |
def getIpAddress(ipAddressUser):
"""Function to ask user for server ip"""
try:
returnTuple = socket.gethostbyname_ex(ipAddressUser)
return returnTuple[2][0]
except:
print("Invalid IP address provided")
sys.exit()
def getPortNumber():
"""Asks the user for the server port n... | The code defines a client-side function to connect to a server, request a file, and receive it. It prompts for the server IP, retrieves the address and port, creates a socket, connects to the server, sends a file request, and reads the response. The main task is to establish a connection, request a file, and handle the... | def startClientside():
"""Main function that runs client"""
ipAddressUser = input("Please enter the server IP:\n")
serverAddress = getIpAddress(ipAddressUser)
serverPort = getPortNumber()
fileName = getFileName()
clientSocket = createClientSocket()
clientSocket.settimeout(1)
connectToSer... |
def get_runtime_mode(self):
return self.__runtime_mode
def create_id(self):
return random.randint(0, 2147483647)
def send(self, buf):
if self.is_connected() is False:
raise gurgle_network_error('Connection has not been established')
self.__send_mutex.acquire()
try:
... | The main task of the code is to check if the user is authenticated, either by returning a cached value or querying a server for real-time status when online_check is enabled. It sends a JSON request to verify authentication status, processes the response, and updates the internal state accordingly. | def is_authenticated(self, online_check=False):
if self.get_runtime_mode() != gurgle.GURGLE_CLIENT:
return self.__is_authenticated
else:
if not online_check:
return self.__is_authenticated
message_id = self.create_id()
senddata = json.dumps... |
def create_id(self):
return random.randint(0, 2147483647)
def send(self, buf):
if self.is_connected() is False:
raise gurgle_network_error('Connection has not been established')
self.__send_mutex.acquire()
try:
self.__socket.send(buf)
except socket.error a... | This function checks if a specified authentication method is supported by querying the system, receiving the list of supported methods, and verifying if the provided method exists in that list. | def check_auth_method(self, current_used_method):
message_id = self.create_id()
data = json.dumps({
"id": message_id,
"cmd": "query",
"obj": "auth_method"
})
if self.send(encode(data)) != gurgle.GURGLE_SUCCESS:
return gurgle.GURGLE_FAILED_T... |
def create_id(self):
return random.randint(0, 2147483647)
def send(self, buf):
if self.is_connected() is False:
raise gurgle_network_error('Connection has not been established')
self.__send_mutex.acquire()
try:
self.__socket.send(buf)
except socket.error a... | The main task of the code is to verify the version by sending a "query" command to check if the received version matches the expected version. It handles sending/receiving data, checks for errors, and returns success/failure based on the response. If the received version does not match the local version, it returns Fal... | def check_version(self):
message_id = self.create_id()
data = json.dumps({
"id": message_id,
"cmd": "query",
"obj": "version"
})
if self.send(encode(data)) != gurgle.GURGLE_SUCCESS:
return gurgle.GURGLE_FAILED_TO_SEND
recv_data = se... |
def write_log(self, log, mode=None, l_level=None):
if mode is None:
mode = self.GURGLE_LOG_MODE_COMMON
if l_level is not None:
level = int(l_level)
else:
level = self.get_log_level()
if mode > level:
return None
if mode == gurgle.GU... | This function updates the user's presence information by sending a structured JSON message containing optional parameters like last name, first name, status, and mood. It validates inputs, ensures status is supported, constructs a presence update payload, sends it, and checks the response for errors, returning True on ... | def publish_self_presence_update(self, last_name=None, first_name=None, status=None, mood=None):
if (last_name == first_name == status == mood is None):
self.write_log('Empty params')
return True
if last_name is not None:
last_name = str(last_name)
if first_na... |
def analyse_full_id(self, full_id):
if full_id is None:
return None
try:
(protocol, ID) = full_id.split(':', 1)
except ValueError as err:
return None
if ID.find("@") == -1:
return None
(username, suffix) = ID.split("@", 1)
i... | This function subscribes a user to a group's messages by validating the group ID, constructing a JSON update request with subscription parameters, sending it, and printing the received response. | def new_friend(self, gid, message=None):
if type(gid) != str:
return False
if self.analyse_full_id(gid) is None:
self.write_log("Bad gid")
return False
message_id = self.create_id()
senddata = {
"id": message_id,
"cmd": "update"... |
def is_connected(self):
return self.__is_connected
def write_log(self, log, mode=None, l_level=None):
if mode is None:
mode = self.GURGLE_LOG_MODE_COMMON
if l_level is not None:
level = int(l_level)
else:
level = self.get_log_level()
if mode > ... | The main task of the code is to disconnect from a remote server by sending a "quit" command with a specified reason, handling responses, closing the connection, and resetting connection states. It checks if already disconnected, sends a JSON message if in client mode, waits for a reply, logs errors if needed, and ensur... | def disconnect_from_remote(self, reason="Unknown reason", message_id=0):
if not self.is_connected():
self.write_log('You have not connected to remote!'
, gurgle.GURGLE_LOG_MODE_ERROR)
return gurgle.GURGLE_FAILED_TO_CONNECT_TO_REMOTE
elif self.get_runtim... |
def is_authenticated(self, online_check=False):
if self.get_runtime_mode() != gurgle.GURGLE_CLIENT:
return self.__is_authenticated
else:
if not online_check:
return self.__is_authenticated
message_id = self.create_id()
senddata = json.dumps... | This function authenticates a user via password in a client mode by sending an authentication request, handling network errors, validating responses, and setting authentication status. It checks if the user is already authenticated, verifies credentials, sends a JSON-encoded auth command, processes the server reply, lo... | def plain_password_auth(self, id_, password, protocol='grgl'):
try:
status = self.is_authenticated()
except gurgle_network_error as e:
raise gurgle_network_error(e)
if status is True:
self.write_log("You have already been authenticated")
return gur... |
def create_id(self):
return random.randint(0, 2147483647)
def send(self, buf):
if self.is_connected() is False:
raise gurgle_network_error('Connection has not been established')
self.__send_mutex.acquire()
try:
self.__socket.send(buf)
except socket.error a... | The code sends a "ping" command with a unique ID, measures round-trip time, checks for a valid "cmd" response, logs the duration, and returns success/failure status. It ensures communication reliability by verifying response structure and timing. | def ping(self):
message_id = self.create_id()
senddata = json.dumps({
"id": message_id,
"cmd": "ping"
})
pre_sent_time = datetime.datetime.now().microsecond
if self.send(encode(senddata)) != gurgle.GURGLE_SUCCESS:
return gurgle.GURGLE_FAILED_TO... |
def write_log(self, log, mode=None, l_level=None):
if mode is None:
mode = self.GURGLE_LOG_MODE_COMMON
if l_level is not None:
level = int(l_level)
else:
level = self.get_log_level()
if mode > level:
return None
if mode == gurgle.GU... | The main task of the code is to handle object cleanup by logging deletion, disconnecting from a remote connection if active, and explicitly deleting specific instance attributes (`__recv_door_1`, `__recv_door_2`, mutexes, and `__package_list`) to release resources. | def __del__(self):
self.write_log('Gurgle Deleting....')
if self.is_connected():
self.disconnect_from_remote("Program was terminated")
del self.__recv_door_1
del self.__recv_door_2
del self.__recv_mutex
del self.__send_mutex
del self.__package_list |
def _printer(
self,
string,
indent=0,
font=None,
color=None,
href=None,
refresh=False,
alternate=False,
bash=None,
param1=None,
param2=None,
param3=None,
open_terminal=False,
):
font = font or self.CONFIG... | The code displays GitHub-related status information, including notifications, pull requests, and test statuses, with interactive commands for dismissal, configuration toggles, and utility actions. It handles error states, formats data visually, and provides user controls for managing GitHub interactions and settings. | def print_state(self):
if self.error:
self._printer(GLYPHS["github_logo"])
self._section_break()
self._printer("No connection")
else:
header_info = self._get_header_info()
header = self._build_header(**header_info)
self._printer(hea... |
def get_pull_requests(self):
"""Search for all pull_requests involving the user"""
with self.db.transaction() as conn:
user_teams = [
team
for repo, teams in conn.root.team_members.items()
for team, members in teams.items()
if s... | The main task of the code is to update pull request-related data by fetching codeowners files, team member information, and branch protection settings from repositories. It stores parsed data in a database, handling exceptions for missing files, and tracks pull request IDs in a set for current tracking. | def _update_pull_requests(self):
self.protection = {}
for pull_request in self.get_pull_requests():
repo = pull_request.repository
repo_key = f"{repo.owner.login}|{repo.name}"
if pull_request.base.ref not in self.protection:
self.protection[pull_reques... |
def _parse_notification(self, notification):
notif = notification.subject.copy()
comment_url = notif.get("latest_comment_url", "")
if comment_url and "comments" in comment_url:
notif["comment"] = json.loads(
self._client._get(comment_url).content.decode()
... | This function updates notifications by checking if they are new, parsing them, linking to corresponding pull requests (PRs), and triggering notifications if applicable. It retrieves PRs from the database, processes each notification, marks cleared ones, and stores parsed data. New notifications trigger alerts with titl... | def _update_notifications(self, mentions_only=False):
with self.db.transaction() as conn:
prs_by_url = {pr["url"]: pr for pr in conn.root.pull_requests.values()}
for notification in self._client.notifications():
notif_id = int(notification.id)
self.current_notificatio... |
def batchGetMapInfo(batch_maps):
mapFeats = []
for item in batch_maps:
json = map_to_json_converter.mapToJson(item)
id, onsets, notes, _ = jtf.jsonToFeatsColor(json) # also passes back SR but we ignore that SR here
cap = min(len(onsets), config.colorOnsetMax) # TODO limiting, can remov... | The code generates predictions using a model by processing map and audio data. It extracts onsets and features from maps/audio, reshapes them, and feeds them into the model with specified temperature. The prediction, including raw probabilities, is saved and returned, focusing on color-related outputs like 'don' and 'k... | def makePredictionFromMapAndAudio(model, mapFiles, audioFiles, SRs, temperature): # returns prediction from model. in: model, mapFiles, audioFiles, starRatings
print(f"Predicting with finishers {finishers}, includeAudio {config.includeAudioFeatsInColorModel}, temperature {temperature}")
# get onsets first... |
def draw(self, image, rect):
DISPLAYSURF.blit(image,rect)
def terminate(self):
pygame.quit()
sys.exit()
def paused(self):
# pause screen
unpause = False
# need to learn buttons for menus!
self.songChannel.pause()
self.effectChannel.pause()
pause_m... | The code renders a backpack inventory interface, displaying item quantities and allowing player interaction. It positions items in slots, updates the display with item images and text, handles mouse clicks to select/deselect items, and processes key events to toggle the inventory. The loop continuously updates the scre... | def drawBackpack(self):
looking = True
self.quantFont = pygame.font.Font("ArtAssets/slkscr.ttf", 20)
slotindex = 0
itemquantities = []
itemquantitiesrects = []
# setup item positions on backpack
for dict in self.player_one.inventory:
itemrect ... |
def terminate(self):
pygame.quit()
sys.exit()
def paused(self):
# pause screen
unpause = False
# need to learn buttons for menus!
self.songChannel.pause()
self.effectChannel.pause()
pause_menu = pygame.transform.scale(pygame.image.load("ArtAssets/menus/pa... | This code handles a boss fight mechanic in a game, managing monster behavior, player attacks, collision detection, and state transitions. It initializes monster attributes, processes events (attacks, movement, inventory), resets monster health if the player leaves, and updates visuals including health bars and loot. Th... | def bossFight(self):
#make sure to add so if the player leaves the arena, then the monster health resets if it was not killed
self.monster = self.current_tile.monsters
self.monster.setStartPos()
self.attack_timer = USEREVENT
pygame.time.set_timer(self.attack_timer, 1000)
... |
def draw(self, image, rect):
DISPLAYSURF.blit(image,rect)
def bossFight(self):
#make sure to add so if the player leaves the arena, then the monster health resets if it was not killed
self.monster = self.current_tile.monsters
self.monster.setStartPos()
self.attack_timer = USEREVE... | The code defines a game loop for a 2D adventure game, handling player movement, collision detection, item interactions, and tile transitions. It initializes game states, processes input events (keyboard, pause, inventory), manages dash mechanics, and updates the game world. The loop checks for monsters, triggers boss f... | def runGame(self):
# need to plot a note saying general game info (basic lore, no saving, etc.)
# things
self.days = 0
self.state = 'running' # keep track of game state
self.dash_timer = pygame.USEREVENT + 1
self.dash_enabled = False
self.dash_count = 3
#... |
def showStartScreen(self):
# have start menu with start game, exit to desktop, and credits
return
def runGame(self):
# need to plot a note saying general game info (basic lore, no saving, etc.)
# things
self.days = 0
self.state = 'running' # keep track of game state
... | The main task of the code is to initialize a Pygame game with sound, graphics, and display settings, then run the game loop, handle game over logic, and display start/game over screens. It sets up fonts, loads assets, configures audio channels, and manages the game's lifecycle through `showStartScreen()`, `runGame()`, ... | def main(self):
global FPSCLOCK, DISPLAYSURF, BASICFONT
pygame.init()
pygame.mixer.init()
self.font = pygame.font.Font("ArtAssets/slkscr.ttf", 36)
self.NatureSound = pygame.mixer.Sound(Nature)
self.songChannel = pygame.mixer.Channel(1)
self.effectChannel = pygame.... |
def func_q(tht): ##This throws some form of error when a 0 is input, it returns a nan
print(f'func_q tht: {tht}')
first = np.cos(tht) ** 2
second = np.sin(tht) ** (-2 * alpha)
print(f'func_q second: {second}')
third = c_zeta_2
fourth = 2 ** (1 - 2 * alpha)
fifth = k_a ** (2 * (1 - alpha))
... | The main task of the code is to calculate and plot the values of `si_array` and `svl_array` over a range of grazing angles. It defines theta ranges, computes corresponding `q_array`, allocates memory for results, evaluates `si_array` via numerical integration, and `svl_array` using a formula involving `func_vl`. Plots ... | def main():
# 1 to print/plot, 0 to not
variable_print_flag = True
svl_plot_flag = True
si_plot_flag = True
s_plot_flag = True
if variable_print_flag is True: # Line to print variables at the beginning of code
txt = "Variable List:\n"
for key, value in variables.items():
... |
def GetPlaytime(game_list: dict, days: int = None, count: int = None, member: discord.Member = None):
top_games = {}
for game_name, game_value in game_list.items():
# Initializes the gameplay dictionary with zeros for each game
top_games[game_name] = 0
# Skips game if there's not histor... | The main task of the code is to identify the game with the lowest calculated score, excluding blacklisted games or those without roles. It computes scores using playtime, player count, and time metrics (last played or days since added), then returns the game with the smallest score. | def GetLowestScoringGame(black_list: list):
# Initialize the playtime message and game refernces for the games played
game_refs = {}
for game_name, playtime in GetPlaytime(games).items():
days_since_added = GetDaysSinceAdded(game_name)
# Skip blacklisted games or games without a role assig... |
def face_area(captures):
if len(captures)==0:
return
captured_areas=[]
for i in captures:
captured_areas.append(i.area())
max_index = captured_areas.index(max(captured_areas))
return captures[max_index]
def get_EAR(eye):
ud_1 = distance.euclidean(eye[1], eye[5])
ud_2 = dista... | This code processes real-time video from a webcam to detect drowsiness and distraction using facial landmarks. It calculates Eye Aspect Ratio (EAR) and Mouth Aspect Ratio (MAR) to identify closed eyes (drowsiness) and yawning, triggering alerts, playing alarms, and displaying warnings. It also detects face absence (dis... | def facial_processing():
mixer.init()
eye_status = False
mouth_status = False
distraction_status = False
yawn_count = 0
face_detector = dlib.get_frontal_face_detector()
shape_prediction = dlib.shape_predictor(shape_predictor_path)
ls,le = face.FACIAL_LANDMARKS_IDXS["left_eye"]
rs,r... |
def search(query, restaurants):
"""Return each restaurant in restaurants that has query as a category.
Arguments:
query -- A string
restaurants -- A sequence of restaurants
"""
# BEGIN Question 10
return [i for i in restaurants if query in restaurant_categories(i)]
def rate_all(user, restau... | The code processes command-line arguments to run restaurant recommendations, load user data, filter restaurants by category, predict ratings, or list restaurant names. It performs k-means clustering on restaurant locations (if specified) and generates a visualization map with centroids, restaurant data, and user rating... | def main(*args):
import argparse
parser = argparse.ArgumentParser(
description='Run Recommendations',
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument('-u', '--user', type=str, choices=USER_FILES,
default='test_user',
met... |
def threshold(size, c):
return c / size
def find(C, u):
if C[u] != u:
C[u] = find(C, C[u])
return C[u]
def union(C, R, u, v, S):
u = find(C, u)
v = find(C, v)
if R[u] > R[v]:
C[v] = u
S[v] = S[u] = S[u] + S[v]
roots.remove(v)
else:
C[u] = v
... | This function implements a modified Kruskal's algorithm for graph segmentation, using threshold-based edge selection and union-find operations to generate a minimum spanning tree. It processes edges in sorted order, merges components under specific size and weight constraints, and maps the resulting cluster labels to p... | def kruskal(self):
self.E = [(self.G[u][v], u, v) for u in self.G for v in self.G[u]]
self.C = {u: u for u in self.G}
self.R = {u: 0 for u in self.G}
self.S = {u: 1 for u in range(len(self.G))}
self.ts = {x: self.threshold(1, self.c) for x in self.C}
self.E = sorted(sel... |
def prepareWorkspace(exp, mgfpath, dtapath, outpath):
mgfpath = Path(mgfpath)
dtapath = Path(dtapath)
outpath = Path(outpath)
# Get dta path for the experiment
dtapath = os.path.join(dtapath, exp + ".dta")
var_name_path = os.path.join(outpath, exp)
# Create output directory
if not os.pat... | The main task of the code is to process mass spectrometry data by reading input files, extracting experimental parameters, parsing mgf files, generating tquery files, and analyzing scans using the doVseq function to match theoretical sequences against experimental ion data for peptide identification. It handles multipl... | def main(args):
'''
Main function
'''
## USER PARAMS TO ADD ##
err = float(mass._sections['Parameters']['fragment_tolerance'])
min_dm = float(mass._sections['Parameters']['min_dm'])
min_match = int(mass._sections['Parameters']['min_ions_matched'])
# try:
# arg_dm = float(args.del... |
def is_clause(phi):
"""
Helper method that checks if a formula is a disjunction of literals.
"""
if not is_or(phi): return False
for literal in phi.children():
if is_not(literal): literal = literal.children()[0]
if not (is_bool_val(literal) or is_bool_var(literal)): return False
return True
def get_... | The code checks if a clause is "unit" (i.e., contains exactly one variable, either positively or negatively, but not both). It verifies the clause is valid, ensures it has only one variable, checks if it's already satisfied, and confirms the variable does not appear both positively and negatively. The function returns ... | def is_unit(phi):
""" Helper method that checks if a clause is unit. Assumes that assignment is already substituted. """
if not is_clause(phi):
raise Exception("Not a clause.")
if len(get_vars(phi)) != 1:
# clause has more than one unassigned literal
return False
if check_partial_assignment(And(phi)... |
def _convert_to_pandas(self, data):
if not isinstance(data, pd.DataFrame):
return pd.DataFrame(data)
else:
return data
def shuffle_data(self, data):
return data.sample(frac=1).reset_index(drop=True)
def _initiat_preprocessing(self):
"""This function automates the ... | The main task of the code is to initialize a data preprocessing class by converting input data to a pandas DataFrame, optionally shuffling it, storing labels (Y), and automatically initiating preprocessing if enabled. It handles data conversion, shuffling, and sets up preprocessing configuration based on user-defined p... | def __init__(self, data, Y=None, automatic_procedure: bool = True, shuffle: bool = True):
"""
Args:
data: The data we want to process, currently it only process pandas data frame,
and if not pandas it will convert it to pandas data frame.
Y: our labels that w... |
def generate_random_heat_source(mesh_resolution):
source_x = np.random.uniform(0, 1)
source_y = np.random.uniform(0, 1)
return f"exp(-(pow((x[0] - {source_x}), 2) + pow((x[1] - {source_y}), 2))/(2*sigma*sigma))"
def import_mesh(
prefix="mesh",
subdomains=False,
dim=2,
direct... | The main task of the code is to run multiple steady-state heat equation simulations using varying mesh resolutions. For each simulation, it generates a random heat source, solves the equation on different mesh resolutions, visualizes the solution, and saves results as PNG images and XDMF files. The process iterates ove... | def main_steady_state(mesh_resolutions, num_simulations):
for sim in range(num_simulations):
# load the mesh
# prefix = "mesh_{}_res_{}".format(sim, max(mesh_resolutions))
# mesh, boundaries_mf, association_table = import_mesh(prefix=prefix, subdomains=True, directory="meshes")
prin... |
def get_imglist(path):
if os.path.isfile(path):
imglist = [path]
else:
imglist = glob(os.path.join(path, '*.tif')) + glob(os.path.join(path, '*.tiff'))
imglist = [x for x in imglist if not 'mask' in x]
imglist = sorted(imglist, key=lambda f: [int(n) for n... | This code initializes a napari image viewer for processing datasets, loading images from a specified path, setting up UI elements with predefined labels/colors, and configuring hotkeys. It tracks state variables (counter, loaded, changed) and initializes the viewer to display the first image, preparing for interactive ... | def __init__(self, path):
self.imglist = self.get_imglist(path)
self.namelist = ['mating', 'budding']
self.colorlist = ['magenta', 'yellow']
self.counter = 0
self.loaded = False
self.changed = False
self.viewer = napari.Viewer()
self.set_hotkey... |
def readFile():
# file = open("caesarian - Copy.txt", "r+")
file = open("haberman.data", "r+")
fullData = file.readlines()
classes = []
for line in fullData:
line = line.split(',')
global elements
global counter
if counter == 0:
elements = len(line)
... | The main task of the code is to evaluate a machine learning model's performance by reading data, performing cross-validation, calculating accuracy, and, if the dataset is binary, computing precision, recall, and F-measure metrics. | def main():
readFile()
# FoldDataset()
crossValidation()
Accuracy(correctSum, 10, 2)
if binary == True:
precision()
recall()
f_measure() |
def TerminateThisSide(data, classes):
result = None
if not data:
return result
else:
counter = 0
for value in classes:
occurences = [int(row[-1]) for row in dataset].count(value)
if occurences > counter:
result = int(row[-1])
return res... | This function recursively splits a decision tree node by checking if left/right children exist, terminating splits at maximum depth or when no further splits are possible, and recursively applying splits to child nodes while calculating entropy and partitioning data to build the tree structure. | def RecursiveSplit(classes, node, max_depth, current_depth):
left, right = node["left"], node["right"]
flagLeft, flagRight = True, True
if not left:
flagLeft = False
falseList = list()
node["left"] = TerminateThisSide(falseList, classes)
if not right:
flagRight = False
... |
def extractClass():
file = open("iris1.txt", "r+")
fullData = file.readlines()
dataset = []
classSet = set()
for line in fullData:
line = line.split(',')
dataset.append(line)
classSet.add(int(line[-1]))
return classSet, dataset
def entropyInDataset(dataset, classes):
... | The main task of the code is to construct a decision tree by calculating initial dataset entropy, splitting data recursively based on entropy, and building a tree structure up to a specified maximum depth (6). It initializes class labels and dataset, computes entropy, creates a root node via data splitting, and trigger... | def main():
max_depth = 6
classes, dataset = extractClass()
# print(dataset)
# print()
#makeTree(dataset, classes)
initialEntropy = entropyInDataset(dataset, classes)
root = splitData(dataset, initialEntropy, classes)
print(root)
RecursiveSplit(classes, root, max_depth, 1) |
def entropyInDataset(dataset, classes):
totalData = len(dataset)
# print(totalData)
if totalData == 0:
return 0.0
entropy = 0.0
for value in classes:
occurences = [int(row[-1]) for row in dataset].count(value)
print(occurences)
probability = occurences / totalData
... | This code constructs a decision tree by calculating the entropy of the dataset, splitting the data into nodes, and recursively partitioning subsets to form a tree structure, with the root node printed and further splitting controlled by depth parameters. | def makeTree(dataset, classes):
parentEntropy = entropyInDataset(dataset, classes)
parentNode = splitData(dataset, parentEntropy, classes)
print(root)
RecursiveSplit(classes, parentNode, max_depth, 1) |
def _validate_configuration(self):
if len(self.component_config.get("features", [])) % 2 != 1:
raise ValueError("Need an odd number of crf feature "
"lists to have a center word.")
def _create_dataset(self, examples):
# type: (List[Message]) -> List[List[Tuple[Te... | The code trains a model using provided training data by configuring the component, validating settings, filtering entity examples, creating a dataset from filtered examples, and training the model on this dataset. | def train(self, training_data, config, **kwargs):
# type: (TrainingData, RasaNLUModelConfig) -> None
self.component_config = config.for_component(self.name, self.defaults)
self._validate_configuration()
# checks whether there is at least one
# example with an entity annotation... |
def _from_text_to_crf(self, message, entities=None):
# type: (Message, List[Text]) -> List[Tuple[Text, Text, Text, Text]]
"""Takes a sentence and switches it to crfsuite format."""
crf_format = []
for i, token in enumerate(message.get("spacy_doc")):
pattern = self.__pattern_... | The function extracts entities from a given message using a Conditional Random Field (CRF) model. If the entity tagger (`ent_tagger`) is available, it converts the message text into CRF features, predicts entity labels, and transforms the results into JSON format. If the tagger is unavailable, it returns an empty list. | def extract_entities(self, message):
# type: (Message) -> List[Dict[Text, Any]]
"""Take a sentence and return entities in json format"""
if self.ent_tagger is not None:
text_data = self._from_text_to_crf(message)
features = self._sentence_to_features(text_data)
... |
def getEta(self,t):
return 1/math.sqrt(t) * self.scaleEta
def FW(self,a0,Loss_hat):
'''
a0 is a (L,K) matrix and is the result of the last time step
return: a (L,K) convex combination of several sub-permutation matrices
'''
a=a0
acc=0
for ite in range(1... | The main task of the code is to run an adversarial algorithm that interacts with an environment by selecting actions based on a probability distribution, updating its strategy using the Frank-Wolfe method, accumulating rewards and regret metrics, and logging results for each round. The algorithm adjusts its action prob... | def run_adv(self):
if not self.KNOWN_KAPPA:
reg=0
rews=0
sus=0
Loss_hat=np.zeros((self.L,self.K))
a_t=np.ones((self.L,self.K))/self.K
for t in tqdm(range(self.T)):
self.eta=self.getEta(t+1)
a_t=self.FW(a_t,Lo... |
def legal_king_moves(self, colour: int):
return []
def legal_queen_moves(self, colour: int):
return []
def legal_bishop_moves(self, colour: int):
return []
def legal_knight_moves(self, colour: int):
return []
def legal_rook_moves(self, colour: int):
return []
def legal_pawn_moves... | The function `legal_moves` aggregates all valid moves for a player's pieces on a board by concatenating legal moves generated for each piece type (king, queen, bishop, knight, rook, pawn) based on the given `colour` parameter, returning a combined list of possible moves. | def legal_moves(self, colour: int):
moves = []
moves += self.legal_king_moves(colour)
moves += self.legal_queen_moves(colour)
moves += self.legal_bishop_moves(colour)
moves += self.legal_knight_moves(colour)
moves += self.legal_rook_moves(colour)
moves += self.leg... |
def load_mixup(self, index):
index2 = random.randint(0, self.length - 1)
im, labels = self.load_image(index)
im2, labels2 = self.load_image(index2)
r = np.random.beta(32.0, 32.0)
im = (im * r + im2 * (1 - r)).astype(np.uint8)
if len(labels.shape) == 2 and len(labels2.shap... | This method loads and augments images using techniques like mixup, cutmix, mosaic, applies transformations, pads labels, and returns processed data for training. | def __getitem__(self, index):
index = index % self.length
if random.random() < self.mixup_prob:
image, labels = self.load_mixup(index)
elif random.random() < self.cutmix_prob:
image, labels = self.load_mosaic_4(index)
elif random.random() < self.mosaic4prob:
... |
def wh_question(question):
is_ques = False
for pattern in open_question_partten: # question_pattern:
is_ques = pattern in question
if is_ques:
break
return is_ques
def wh_answer(question, answer, q_entities):
#if wh_question(question):
# named_entities1, nonq = extract_n... | The code performs fact-checking by verifying if a given fact aligns with a user's question or statement. It uses a classifier to assess the fact's validity, trims or processes the fact based on input type, and returns a boolean indicating correctness alongside an answer derived from entity matching and linguistic analy... | def fact_checking(user_input, fact, q_ents, e_ents, dep_text, a_score):
# Append random text as the final value
ran = "ran"
# fact = "Amsterdam is the capital of Netherlands" # LLaMa output
# user_input = "Where is San Francisco?" # "Is Amsterdam capital of Netherlands?" # Question
if user_input in... |
def get_hundred(self, num):
n_100 = (num // 100) * 100
n_1 = int(n_100 / 100)
return self.num_dict['0-9'].get(n_1) + ' ' + self.num_dict['more_than_100'].get(100) + ' ' \
+ self.get_tenth_and_less((num - n_100))
def get_thousand(self, num):
n_1000 = (num // 1000) * 1000
n... | This function converts a number into its verbal representation by separating millions and thousands. It calculates the nearest million, determines the million part's word form using helper methods, appends "million," then processes the remaining thousands using get_thousand. It handles 3-digit, 2-digit, and single-digi... | def get_mill(self, num):
n_mill = (num // 10 ** 6) * 10 ** 6
n_1 = int(n_mill / 10 ** 6)
if len(str(n_1)) == 3:
return self.get_hundred(n_1) + ' ' + self.num_dict['more_than_100'].get(10**6) + ' ' \
+ self.get_thousand(num - n_mill)
elif len(str(n_1)) == 2:... |
def get_hundred(self, num):
n_100 = (num // 100) * 100
n_1 = int(n_100 / 100)
return self.num_dict['0-9'].get(n_1) + ' ' + self.num_dict['more_than_100'].get(100) + ' ' \
+ self.get_tenth_and_less((num - n_100))
def get_mill(self, num):
n_mill = (num // 10 ** 6) * 10 ** 6
... | This function converts a large number into its word representation by breaking it into billions and the remaining part. It calculates the largest billion multiple, determines the appropriate helper function (get_hundred, get_tenth_and_less, or direct lookup) based on the coefficient's digit count, appends the "billion"... | def get_bill(self, num):
n_bill = (num // 10 ** 9) * 10 ** 9
n_1 = int(n_bill / 10**9)
if len(str(n_1)) == 3:
return self.get_hundred(n_1) + ' ' + self.num_dict['more_than_100'].get(10**9) + ' ' \
+ self.get_mill(num - n_bill)
elif len(str(n_1)) == 2:
... |
def get_tenth_and_less(self, num):
if num < 10:
return self.num_dict['0-9'].get(num)
elif 10 < num < 20:
return self.num_dict['11-19'].get(num)
elif num >= 10 and num in self.num_dict['10-90']:
return self.num_dict['10-90'].get(num)
else:
n... | This function converts a number into its word representation based on its magnitude. It checks the length of the number and delegates to specific helper methods for numbers up to 12 digits, returning a predefined message for values exceeding 12 digits. | def display_number(self):
if len(str(self.n)) <= 2:
return self.get_tenth_and_less(self.n)
elif len(str(self.n)) <= 3:
return self.get_hundred(self.n)
elif len(str(self.n)) <= 6:
return self.get_thousand(self.n)
elif len(str(self.n)) <= 9:
... |
def __seg_records(self, pred, gt):
pred, gt, pixelAcc, err = self.__seg_error(pred, gt)
new_mat = confusion_matrix(gt, pred, labels=self.records['labels'])
self.records['conf_mat'] += new_mat
self.records['pixelAccs'].append(pixelAcc)
self.records['errs'].append(err)
def __sn_rec... | This method processes predictions and ground truths for different tasks by delegating to specific record functions based on the task type, such as semantic segmentation, normals, depth, or keypoints/edges, while tracking batch size. | def __call__(self, pred, gt, mask=None):
self.batch_size.append(len(gt))
if self.task == 'segment_semantic':
self.__seg_records(pred, gt)
elif self.task == 'normal':
self.__sn_records(pred, gt, mask)
elif self.task == 'depth_zbuffer':
self.__d... |
def sort_folder(path: Path) -> None:
for item in path.glob("**/*"):
if item.is_file():
cat = get_categories(item)
move_file(item, path, cat)
def delete_empty_folders(path: Path) -> None:
for item in reversed(list(path.glob("**/*"))):
if item.is_dir() and not any(item.iter... | The code's main task is to sort files in a specified folder by categorizing them, delete empty folders, and handle unpacking of archives. It validates the folder path, confirms user intent, organizes files into predefined categories, identifies known/unknown extensions, and provides a summary of sorted files and extens... | def main():
try:
path = Path(sys.argv[1])
except IndexError:
return "/// No path to folder"
if not path.exists():
return f"/// Folder {path} not found."
confirmation = input(f"/// Are you sure you want to sort the files in folder {path}? (Y - Yes, N - No) >>> ")
if conf... |
def get_links(title):
#check if query already has been done, if not get result from wiki and cache it in the db
query = check_db(title, "items")
if query == []:
query = get_wiki_links(title)
insert_db(title, query, "items")
return query
else:
return query["links"]
def f... | This code performs a breadth-first search (BFS) to find a path from a start node to an end node, handling edge cases like dictionary inputs and database errors. It tracks traversal depth, manages parent-child relationships, and returns the discovered route along with the depth. If the end is unreachable within the max ... | def run_search(start, end, max_depth):
dict_passed = False
if type(end) == dict:
dict_passed = True
end[start] = 1
exit_loop = False
if not dict_passed:
print("Finding \"{}\" from \"{}\"".format(end, start))
if start == end:
exit_loop = True
sentinal_n... |
def get_url(self):
return self._url
def image(self):
if self._image is None: self.load()
return self._image
def nchannels(self):
s = numpy.array(self.image().shape)
if s.size == 2:
return 1
else:
return s[2] | The code generates a formatted string containing the object's URL, image information (shape or 'None'), and channel count for display or logging purposes. | def info(self):
txt = ""
txt += "\nurl: %s " % self.get_url()
if self.image() is None:
txt += "\nimage: None"
else:
txt += "\nimage: " + repr(self.image().shape)
txt += "\nchannels: %d" % self.nchannels()
return txt |
def print_hit_board(hit_grid):
board_str = (
"# "
+ "".join(
[f"{letter} " for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[:GRID_SIZE]]
)
+ "#\n"
)
for row_index, row in enumerate(hit_grid):
board_str += f"{row_index} "
for col_index, tile in enumer... | The code's main task is to determine and return the next move coordinates in a game (likely Battleship) by analyzing the hit grid and previous turn status. It updates internal state, prints debug info, uses `make_decision` to evaluate potential moves, records chosen moves, and converts the selected move to a coordinate... | def do_turn(self, hit_grid, last_turn_status) -> (str, int):
self.__last_turn_status = last_turn_status
# self.make_random_board([1, 2, 3])
print_hit_board(hit_grid)
print(self.__last_turn_status)
# TODO Do something clever
move, prob, dict = self.make_decision(
... |
def send_command(self, command: str):
textfsm_template = map_textfsm_template(command, platform="linux")
return self._netmiko_device.send_command(
command,
use_textfsm=(textfsm_template is not None),
textfsm_template=textfsm_template,
)
def is_physical_interf... | The main task of the code is to retrieve and process network interface information from a system by executing the "ip link show" command, parsing its output, and constructing a dictionary of interface details. It handles virtual and physical interfaces differently, extracts attributes like MAC address, MTU, speed, and ... | def get_interfaces(self) -> Dict[str, models.InterfaceDict]:
interfaces: Dict[str, models.InterfaceDict] = {}
output = self.send_command("ip link show")
for record in output:
interface_name = record["interface"]
if "@" in interface_name:
interface_name = i... |
def action_checkout(self, context):
name = self.resource.name.as_string()
user = self.resource.user.as_string()
group = self.resource.group.as_string()
context.change(EnsureDirectory(name, user, group, 0o755))
self.svn(context, "co", self.url, self.resource.name)
return... | This code ensures a Subversion (SVN) working copy is synchronized with a repository by checking out if necessary, then updating the repository root, branch, or revision if they differ from the current state. It handles missing SVN dependencies, logs changes, and returns whether updates occurred. | def apply(self, context, output):
if not context.transport.exists("/usr/bin/svn"):
error_string = "'/usr/bin/svn' is not available; update your configuration to install subversion?"
if not context.simulate:
raise MissingDependency(error_string)
log.info(error_... |
def openShape(matrix, coords):
"""
This function opens the previously saved shapes ( in sample.json file ).
Firstly provides a list of the saved shapes and gives a user to choose which shape to delete ( same as editShape function ).
Lastly opens the shape and prints it on the console
"""... | The main task of the code is to present a menu-driven interface allowing users to select options for handling shapes (Open, Create, Edit, Delete) via letter inputs. It validates user input and invokes corresponding functions (openShape(), createShape(), editShape(), deleteShape()) with parameters X and COORDS based on ... | def main():
"""
This is the starting point of the code.
When the program starts it gives user 4 options:
Open Shapes.
Create New Shapes.
Delete Shapes.
Edit Shapes.
All these option are assigned to different letter which means if the particular... |
def getClassMapping(data,labelName):
class_names = []
for i in data.index:
try:
bboxes = eval(str(data[labelName][i]))
if len(bboxes) > 0:
for bbox in bboxes:
if not bbox["class"] in class_names:
class_names.append(bbox[... | This code trains a YOLOv5 model using a specified dataset, validates its performance, and saves configurations/metrics. It checks for required inputs, prepares data, configures model parameters, trains the model if weights aren't preloaded, evaluates on validation data, and cleans up resources. | def main(args):
if args.save_location == "":
print("No save location specified. Please set flag --save_location")
elif args.data_csv_file == "":
print("No dataset specified. Please set flag --data_csv_file")
else:
dataCSVFile = pandas.read_csv(args.data_csv_file)
config = {}
... |
def copy_item():
try:
version = get_build_version()
location = "" + version + ""
os.path.exists(location)
shutil.copytree(location,"C:\\Users\\dev\\Desktop\\test")
return version
except:
print("File Does not exist")
def upgrade():
try:
versio... | The code prompts the user to select a command (1-4) and executes corresponding actions: copy, upgrade, fresh install, or uninstall. It validates input, calls relevant functions, and handles invalid entries with error messages. | def input_command():
input_rcv = input("Choose a command below : \
1. Copy\
2. Copy and Upgrade\
3.Copy and Fresh Install\
4.Uninstall")
try:
if(int(input_rcv) == 1):
copy_item()
elif... |
def _MakeHardwareStationInterface(
scenario: Scenario,
meshcat: Meshcat = None,
*,
package_xmls: typing.List[str] = [],
) -> Diagram:
builder = DiagramBuilder()
# Visualization
scene_graph = builder.AddNamedSystem("scene_graph", SceneGraph())
plant = MultibodyPlant(time_step=scenario.pl... | Your returnThe function `MakeHardwareStation` constructs a simulation diagram (or hardware communication interface) for a physical robot, incorporating sensors, controllers, and visualization. It uses a `Scenario` configuration to build a `HardwareStation` diagram with a `MultibodyPlant`, `SceneGraph`, default visualiz... | def MakeHardwareStation(
scenario: Scenario,
meshcat: Meshcat = None,
*,
package_xmls: typing.List[str] = [],
hardware: bool = False,
parser_preload_callback: typing.Callable[[Parser], None] = None,
parser_prefinalize_callback: typing.Callable[[Parser], None] = None,
prebuild_callback: t... |
def check_if_exists(input_path):
if not os.path.exists(input_path):
raise Exception(f'{input_path} Path does not exist.')
def create_new_keystore(apk):
logger.info('Creating a new keystore')
alias = input("Whats your alias: ")
validity = input("Keystore Validity: ")
keystore_name = input("Ke... | The code initiates an APK signing process by prompting the user to choose between creating a new keystore, using an existing one, or exiting. If the user selects a new keystore, it generates one; if using an existing one, it requests the keystore path and alias. The process logs actions and handles invalid inputs, ensu... | def start_apk_signing_process(apk):
check_if_exists(apk)
logger.info(f'Starting APK Signing Process for {apk}')
message_prompt = """
Do you want to create a new keystore or use an existing one?
1. Create new keystore
2. Use an existing keystore
3. No thanks, I'm done
"""
user_choice... |
def check_if_exists(input_path):
if not os.path.exists(input_path):
raise Exception(f'{input_path} Path does not exist.')
def run_on_shell(command, nocommand=False):
try:
result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
logger.info(result.stdout)
... | The main task of the code is to align an APK file using the Android SDK's zipalign tool. It verifies the existence of the APK and zipalign tool, processes the filename, constructs an output path, executes the zipalign command, and triggers APK signing if successful. If the zipalign fails, it logs an error. | def start_zipalign_process(apk):
check_if_exists(apk)
check_if_exists(f'{config.ANDROID_SDK_TOOLS}/zipalign')
apk_file_name = os.path.splitext(os.path.basename(apk))[0]
apk_file_name = str(apk_file_name).replace('-unsigned', '')
logger.info(f'Starting zipalign process for {apk}')
output_path = f... |
def check_if_exists(input_path):
if not os.path.exists(input_path):
raise Exception(f'{input_path} Path does not exist.')
def run_on_shell(command, nocommand=False):
try:
result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
logger.info(result.stdout)
... | The function `perform_apk_compiling` compiles decompiled Android APK code into an unsigned APK using APKtool. It verifies the existence of the decompiled directory, generates an output path by removing the `-decompiled` suffix, executes the compilation command with AAPT2, and logs success or failure. If successful, it ... | def perform_apk_compiling(decompiled_code_dir):
logger.info(f'Compiling the Code at {decompiled_code_dir}')
check_if_exists(decompiled_code_dir)
dir_name = os.path.basename(decompiled_code_dir)
dir_name = str(dir_name).replace('-decompiled', '')
output_path = f'output/{dir_name}-unsigned.apk'
ap... |
def choose_initial_centroids(data, k):
"""
:param data: dataset as numpy array of shape (n, 2)
:param k: number of clusters
:return: numpy array of k random items from dataset
"""
n = data.shape[0]
indices = np.random.choice(range(n), k, replace=False)
return data[indices]
def assign_to_... | The code implements the k-means clustering algorithm to group 2D data points into `k` clusters. It initializes centroids, assigns data points to the nearest centroid, recomputes centroids based on cluster memberships, and iterates until centroids stabilize. The function returns cluster labels for each data point and th... | def kmeans(data, k):
"""
Running kmeans clustering algorithm.
:param data: numpy array of shape (n, 2)
:param k: desired number of cluster
:return:
* labels - numpy array of size n, where each entry is the predicted label (cluster number)
* centroids - numpy array of shape (k, 2), centroid f... |
def load_table() -> Optional[Table]:
try:
q_table = np.load('model.npy')
lookup = np.load('lookup.npy', allow_pickle=True).item()
with open('model-info.txt', 'r') as f:
index = int(f.readline())
n = int(f.readline())
return Table(n, q_table=q_table, lookup=loo... | The main task of the code is to implement Q-learning for a grid-based game. It initializes a 4x4 game map, configures learning parameters (learning rate, discount factor, etc.), loads or creates a Q-table, trains the agent over 1000 episodes using the game environment, and evaluates the trained table's performance. The... | def main():
n = 4
settings = QLearningSettings(
learning_rate=0.8,
discount_factor=0.5,
episodes=1000,
epsilon=0.0001,
current_episode=0
)
map = GameMap(n, n)
game = Game(map, [Position(0,0)])
table = load_table()
if table is None:
table = Tab... |
def get_job_links(self):
soup = self.get_page_content()
a_tag = soup.find_all('a', {'class': 'title ellipsis'})
links = [a['href'] for a in a_tag]
return links
def scrape_job(self):
soup = self.get_page_content() # it returns the page content
self.job_heading(soup) # ge... | The main task of the code is to iterate through job links retrieved from a webpage, navigate to each link using a web driver, scrape job data with `scrape_job()`, handle potential HTML inconsistencies or errors (e.g., `AttributeError`), and append valid data to a CSV file. It ensures robustness by skipping problematic ... | def navigate_links(self):
links = self.get_job_links() # It returns the list of all job links in the page
# Iterating through each links
for index, link in enumerate(links):
print(f'scraping link: {index+1}')
self.driver.get(link)
self.job_data = [] # making... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.