dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def has_started(q, process_q):
""" returns true if start signal received """
new_chunk = q.get()
process_q.append(new_chunk)
if len(process_q) >= SPLIT_CHUNKS:
chunk = to_float_audio(np.hstack(process_q))[0]
process_q.popleft()
data_fft, mags, freqs = fft(chunk)
score = ... | This function synchronizes with a transmitter, collects audio data chunks, performs FFT analysis to detect an end signal, and stops processing when the signal is identified. It records timestamps, aggregates data, and clears buffers while monitoring for termination signals. | def wait_for_end(stopped, q, process_q, all_data, exe_times):
""" thread to record until end signal """
print("waiting for synchronization signal from transmitter...")
while not has_started(q, process_q):
if stopped.wait(timeout=0):
break
print("synchronized with transmitter, receivi... |
def get(self, pos):
if self.is_valid_board_position(pos):
return self.board[pos.x][pos.y]
def set(self, pos, val):
if self.is_valid_board_position(pos):
self.board[pos.x][pos.y] = val
return 1
return 0
def set_empty_spot(self, pos):
self.empty_spot = p... | This function swaps the empty spot in a grid with the value at a specified position. It retrieves the value at the given position, stores the original empty spot, updates the original empty spot with the retrieved value, and sets the new position as the empty spot. It returns the original empty spot position and the ne... | def move_empty_spot_to_new_position(self, pos):
new_val = self.get(pos)
if new_val:
original_empty_spot = self.empty_spot
self.set(original_empty_spot, new_val)
self.set_empty_spot(pos)
return original_empty_spot, pos |
def hash_string(input_string):
sha256 = SHA256.new()
sha256.update(input_string.encode('utf-8'))
return sha256.digest()
def encrypt_file(file_path, encrypt_dir, aes_key):
with open(file_path, 'rb') as f:
data = f.read()
file_info = os.path.splitext(file_path)
file_name = os.path.basena... | The main task of the code is to encrypt a specified file or folder using AES encryption. It allows users to either input a custom password (hashed for the key) or load a pre-existing key from a file. After generating or retrieving the AES key, the script encrypts the target file/folder, saves the key in "key.bin", and ... | def main():
if len(sys.argv) == 2:
while True:
key_string = getpass.getpass("Enter encryption password: ")
confirm_key_string = getpass.getpass("Confirm encryption password: ")
if key_string == confirm_key_string:
aes_key = hash_string(key_string)
... |
def hash_string(input_string):
sha256 = SHA256.new()
sha256.update(input_string.encode('utf-8'))
return sha256.digest()
def decrypt_file(file_path, aes_key):
encrypted_file = file_path + "_encrypted.bin"
with open(encrypted_file, "rb") as f:
file_type_xor = f.read(16)
tag = f.read(... | The code decrypts files or folders using AES encryption. It accepts either a password (hashed) or a key file. If a single file is provided, it decrypts it; if a folder is specified, it decrypts all files within. The decrypted files are saved in the same directory or a 'Decrypted' folder. | def main():
if len(sys.argv) == 2:
key_string = getpass.getpass("Enter encryption password: ")
aes_key = hash_string(key_string)
elif len(sys.argv) == 3:
key_file = sys.argv[2]
if not os.path.exists(key_file):
print(f"Key file '{key_file}' not found.")
s... |
def check_getn(formula):
(passed, returned) = check_valid(formula)
if not passed:
return (passed,returned)
return (returned, determine_n(formula))
def assign(formula):
variables = list(set(num_variables(formula)))
values = {}
for var in variables:
values[var] = random.choice([Fal... | The main task of the code is to implement Schöning's algorithm for solving a Boolean formula. It iteratively checks if a random assignment satisfies the formula, flipping variables in unsatisfied clauses until a solution is found or the maximum iterations (3n) are reached. If a valid assignment is found, it returns the... | def schoning_algo(formula):
(k, n) = check_getn(formula)
count = 0
if not k:
return (False,n)
values = assign(formula)
for index in xrange(3 * n):
count += 1
satisfied, failed = check_solution(formula, values)
if satisfied:
return (values, count)
e... |
def code_to_list(self, code):
return code.split(',')
def convert_or_to_z3_or(self, expression):
if 'or' in expression.lower():
expression = expression.lower().replace(' or ', ',')
expression = "["+ expression+"]"
status = True
else:
status = False
... | The code verifies if all inputs satisfy constraints in a given code snippet using the Z3 solver. It processes each line, declares variables, and separates bounding expressions from others. It adds these to the solver, checks for satisfiability, and returns "sat" with a model if valid. If unsatisfiable, it generates cou... | def for_all(self, code):
# find each line of code
code_steps = self.code_to_list(code)
s = Solver()
# keep track of declared varibles to not dupe
declared_vars = []
bounding_vars = []
bounding_expressions = []
expression_list = []
# declare new... |
def create_mysql_table(user, password, database):
conn = mysql.connector.connect(
host="localhost", user=user, passwd=password, database=database)
cur = conn.cursor()
column_names = session.get('column_names', None)
column_types = session.get('column_types', None)
filename = session.get('fil... | This function handles a POST request to collect database credentials from a form, stores them in the session, and attempts to create tables/collections in MySQL, MongoDB, PostgreSQL, and Couchbase. If all operations succeed, it renders a template for CSV selection; otherwise, it returns an error. For GET requests, it d... | def table_creation():
if request.method == 'POST':
mysql_username = request.form['mysql_username']
mysql_db_name = request.form['mysql_db_name']
mysql_password = request.form['mysql_password']
mongodb_db_name = request.form['mongodb_db_name']
postgresql_username = request.for... |
def create_mysql_table(user, password, database):
conn = mysql.connector.connect(
host="localhost", user=user, passwd=password, database=database)
cur = conn.cursor()
column_names = session.get('column_names', None)
column_types = session.get('column_types', None)
filename = session.get('fil... | The function retrieves database connection details from the session and form data, constructs database-specific connection parameters, creates tables/collections in specified databases (MySQL, PostgreSQL, MongoDB, Couchbase), checks operation success, and renders a template if any operation succeeds, otherwise returns ... | def database_choice_get_queries():
databases = session.get('databases', None)
database_info = {} # to store the information
for database in databases:
info = {}
if database != 'MongoDB':
info['user'] = request.form.get(f'{database}_user')
info['password'] = request.... |
def load_data_celest(file):
orbit_data = np.loadtxt(file, delimiter=',')
time_seconds = orbit_data[:, 0] # julian
position_m = orbit_data[:, 1:4] # gcrs
time_julian = time_seconds / 86400
satellite = Satellite(position=position_m, frame='gcrs',
julian=time_julian, offset=0... | The code's main task is to visualize a celestial object's ground track using loaded data, generate a convex hull, plot the trajectory, mark Toronto's coordinates, and illustrate a linear prediction with error bounds at a specific data point, all within a labeled matplotlib plot. | def do_everything():
sns.set_theme()
data, latitude, longitude = load_data_celest("supernova_data.csv")
# latitude, longitude = set_parameters(0, 500, data) # only get first few points
toronto_lat = [43.6532] # Degrees north
toronto_long = [-79.3832] # Degrees east
fig, ax = plt.subplots()
... |
def plot_ground_track(self, data: np.ndarray, longitude: np.ndarray,
latitude: np.ndarray, hull: ConvexHull, ax: plt.axes) -> None:
"""Plots the ground track, linear approximation of the ground track at a point, and the error of the linear fit
Parameters
----------
... | The code generates a plot visualizing geographical data, including a ground track, convex hull, Toronto's location, a specific data point, and a linear prediction with error. It ensures precomputed data exists, sets plot aesthetics, and annotates the visualization with labels and a title for clarity. | def plot(self):
"""
Generates plots based on precomputed data.
"""
# ensure data has been precomputed
if self.data is None:
raise Exception("Data has not been precomputed.")
sns.set_theme()
fig, ax = plt.subplots()
# Plot the ground track
... |
def form_structure_adjoint(
velocity_primal,
displacement_primal,
temperature_primal,
velocity_adjoint,
displacement_adjoint,
first_test_function,
second_test_function,
structure: Space,
thermal: Space,
param: Parameters,
):
sigma_adjoint = sigma_structure_adjoint(
te... | This function computes the weak form of the adjoint problem for a coupled structural-thermal system, combining terms from mechanical equilibrium, thermal conduction, and objective functional contributions. It integrates test functions with adjoint solutions, time-discretized structural/thermal forms, and strain-based s... | def functional_structure_adjoint(
velocity_primal,
displacement_primal,
temperature_primal,
velocity_primal_after,
displacement_primal_after,
temperature_primal_after,
velocity_adjoint,
displacement_adjoint,
temperature_adjoint,
velocity_adjoint_after,
displacement_adjoint_af... |
def form_thermal_adjoint(
temperature_primal,
temperature_adjoint,
first_test_function,
structure: Space,
thermal: Space,
param: Parameters,
):
form_adjoint = (
param.KAPPA
* inner(
grad(first_test_function),
grad(temperature_adjoint),
)
... | This function computes the weak form of the adjoint problem for a coupled thermal-structural system, combining contributions from thermal conduction, structural deformation, and time-discretized terms. It integrates the adjoint temperature field with test functions, applies parameter-weighted time-stepping schemes, and... | def functional_thermal_adjoint(
velocity_primal,
displacement_primal,
temperature_primal,
velocity_primal_after,
displacement_primal_after,
temperature_primal_after,
velocity_adjoint,
displacement_adjoint,
temperature_adjoint,
velocity_adjoint_after,
displacement_adjoint_afte... |
def get_COGS_proper(to_upper=False):
# Return list of all proper nouns in COGS
# if to_upper=True, convert list to uppercase
with open('COGS/vocab_proper_nouns.txt','r') as fid:
words = fid.readlines()
words = [w.rstrip('\n').strip() for w in words]
words = [w for w in words if len(w)>0]... | This code initializes a dataset handler for a model processing commands and outputs, configuring parameters like data split mode, word permutation rules, and support example settings. It loads COGS dataset files, prepares input/output vocabularies, validates word consistency, and sets up structures for training/evaluat... | def __init__(self, mode, remap_type, support_type='targeted', ns=my_ns_default, inc_support_in_query=True, p_shuffle=0.95, p_make_all_proper=0.01):
# Input
# mode : specifies split to use for queries ['train','test_iid','gen_lexical','gen_structural','dev','dev_tiny']
# remap_type : specifie... |
def readfile_cogs(fn_in, make_output_upper=True):
# Read COGS dataset from text file
#
# Input
# fn_in : filename to read
# make_output_upper (default=True) : convert the output tokens to uppercase, in order to
# break correspondence with identical input tokens
#
# Output
# Pa... | This code initializes a data processor for the COGS dataset, loading task-specific files based on the given mode (train/test). It processes input commands and outputs into sequences, computes maximum lengths for normalization, builds input/output vocabularies, and prepares data pairs for model training/evaluation. The ... | def __init__(self, mode):
# Input
# scan_type : name of scan split
# mode : 'train' or 'test'
# inc_support_in_query : (default=False) include all support examples as queries? If True, it messes up the log-likelihood calculations.
assert mode in ['train','test_iid','gen_lex... |
def goProcess(nameWithoutR, codelines):
imleft = Image.open(nameWithoutR + '.png')
imright = Image.open(nameWithoutR + '-r.png')
imleft = imleft.convert('RGBA')
imright = imright.convert('RGBA')
pixleft = imleft.load()
pixright = imright.load()
assertEq(imleft.size[1], imright.size[1], "we h... | The main task of the code is to process PNG files (excluding those containing '-r') by generating and formatting code from them. It iterates through files, checks for valid PNGs, creates code lines using `goProcess`, shortens the generated text, and prints the formatted result. The code transforms image data into a tex... | def goAll():
for file, short in files.listfiles('.'):
if file.endswith('.png') and not '-r' in file:
print('')
print('/* ' + short + ' */')
codelines = Codelines()
goProcess(short.replace('.png', ''), codelines)
allLines = writeCodelines(codelines)... |
def variables(self):
k=self.k
size = 2*k+1
sigma =0.9
return k,size,sigma
def GAUSS(self,img):
## vytvorenie masku
mask = self.createMaskForGauss()
if self.firstGauss is TRUE:
print(mask)
self.firstGauss=FALSE
img=self.pre... | The main task of the code is to process an image by applying Gaussian and Laplacian filters for edge detection. It loads an image, applies Gaussian blur, computes the Laplacian of the blurred image, displays the result, and returns the processed image data for further use. | def imgConvert(self):
print(str(self.filepath))
if self.filepathExist is TRUE:
## tuna sa len nacitaju premenne
_,size,sigma =self.variables()
## nacita sa zadany obrazok
self.loadedImage = cv2.imread(self.filepath)
... |
def getConfig():
"""Returns json object of configuration file \"config.json\"."""
return __readJSON("config.json")
def getRootDir():
"""Returns the absolute path to the root of the project."""
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def get_status(config):
s = get_status_i... | The main task of the code is to initiate services using configuration parameters. It loads the configuration, starts the welle-cli tool with specified channel and interval settings, and optionally launches EVALUATION.py if trapEnabled is true. All processes run in the background with logging, using subprocess commands.... | def start():
"""It is assumed that the configuration has already been set."""
# Load the configuration
config = getConfig()
root = getRootDir()
# Start SNMP_SERVER.py
#cmd = f"nohup python3 -u {root}/SNMP_SERVER.py 1>/var/log/dabing/SNMP_SERVER.log 2>&1 &"
#subprocess.run(cmd, shell=True)
... |
def find_available_ports(n: int):
available_ports = []
for i in range(n):
try:
port = find_available_port_with_api()
except:
logger.warning('find_available_port_with_api failed')
port = find_available_port_with_socket()
logger.debug('Selected... | The function `complete_resource_information` populates resource details in `inputs_dict`, including ports, scheduler commands (SLURM/PBS), public/private IPs, work directories, and user info. It defaults the job scheduler type, adjusts paths for Windows partitions, and replaces placeholders with resolved values for job... | def complete_resource_information(inputs_dict):
if 'nports' in inputs_dict:
inputs_dict['resource']['ports'] = find_available_ports(int(inputs_dict['nports']))
if 'jobschedulertype' not in inputs_dict:
inputs_dict['jobschedulertype'] = 'CONTROLLER'
if inputs_dict['resource']['name'] == 'us... |
def fit(self, color: Optional[str] = None, name: str = "f(x)") -> go.Figure:
"""Plots Best Curve Fit and Underlying Data with error."""
return plot_fit(self.good, color, name)
def _trace_fit(figure: go.Figure, good: Goodness, color: str, name: str):
# For presentation purposes (due to the nature of ... | The main task of the code is to generate a Plotly figure displaying best-fit curves and error bars for the original function, its first derivative, second derivative, and integral. It uses specified colors to differentiate these components, ensuring at least four colors are provided. The function iteratively updates th... | def fit_all(self, equation: Equation, colors: Optional[List[str]] = None) -> go.Figure:
"""Plot the Best Fit Parameters for the Original Data and given integral and derivatives."""
if colors is None:
colors = px.colors.qualitative.Prism[:]
assert len(colors) > 3, "Must provide at lea... |
def update_last_station_del(self):
'''
Removes last station from a route if it gives a better score.
'''
route_list = self.get_all_routes()
while route_list:
route = random.choice(route_list)
self.graph.routes[route].remove_last_station()
# ... | The code's main task is to optimize a route solution by iteratively improving it through four strategies: removing end stations, shortening routes, merging routes, and adding unused connections. It first trims unnecessary end stations, then eliminates redundant routes, merges routes where beneficial, and finally incorp... | def run(self):
'''
Executes the algorithm.
'''
# Try to get a better solution by removing end stations from routes
self.update_last_station_del()
# Try to get a better solution by removing routes with an increasing length
self.update_short_routes()
# Try... |
def check_status(self):
"""
Checks if the player has won or lost or can still continue to play.
:return: None
"""
there_is_empty_cell = False
for i in range(4):
for j in range(4):
if j < 3 and self.data[i][j] == self.data[i][j + 1] and self.dat... | The code handles player movement in a game by checking the specified direction, attempting to move the player accordingly, and updating the game state if the move was successful. It triggers actions like adding a new number, redrawing the board, and rechecking the game status after a valid move. | def move(self, direction):
"""
Checks where the player wants to move, if the move was possible.
:param direction: Where the player wants to move
:return: None
"""
self.check_status()
changed = False
if direction == "left":
changed = self.move_l... |
def _sanitize_remote_path(self, path: str) -> str:
"""
Sanitizes a remote path for this storage space.
Args:
path: `str` - Path to sanitize.
Returns:
str: Sanitized path.
"""
return path.lstrip("/")
def _get_parts(self, obj: ... | This code defines a `download` method that transfers a file from a remote storage system to a local destination (or buffer), handling progress tracking, overwriting logic, and error management. It initializes a `TransferHandler`, manages concurrent downloading of file parts, and includes cleanup for partial transfers. ... | def download(
self, source: str, destination: Optional[str] = None, force: bool = False
) -> TransferHandler:
"""
Downloads a file from the storage space.
Args:
source: The path to the file to download in the storage space.
destination: The local p... |
def prompt_nonempty(prompt):
global assume_yes
if assume_yes:
raise Exception('Missing required value "{}"'.format(prompt))
value = input(prompt + ': ')
if value:
return value
return prompt_nonempty(prompt)
def get_site_db(basedir, name):
"""
Returns the path to the databas... | This code adds a new site by creating its directory, inserting site details into a database, and handling existing sites with a force option. It prompts for missing parameters, checks for existing sites, and uses a force flag to remove conflicting sites. | def add(args):
site_name = args.name or prompt_nonempty('Site name')
site_dir = os.path.join(args.basedir, site_name)
if os.access(get_site_db(args.basedir, site_name), os.F_OK):
print('\033[31;1mA site named {} already exists at {}\033[0m'.format(site_name, site_dir))
if args.force_dangero... |
def open_site_db(basedir, name, must_exist=True):
"""
Opens a connection to a site's database.
The database is checked for existence and R/W rights if the database is assumed to exist.
If the database is missing or cannot be modified, an error is raised (if must_exist is True) or the database is
cr... | (The code deploys a website by cloning its repository, checking for existing deployments, inserting a new deployment record into a database with a timestamp and revision ID, and activating the deployment. It creates a deployment directory, fetches files, runs post-clone scripts, and triggers cleanup. Key steps include ... | def deploy(args):
"""
Deploys a site.
This function covers the entire deployment procedure:
* clone the repository
* check for matching deployments
* register deployment (if new or previously deleted)
* activate deployment
:param args: the command line arguments
:return: nothing
... |
def feat_eng(X, stat_dict):
feature_list = stat_dict['feature_list']
X_dense = X[:, 0: 13]
X_sparse = []
for row in range(X.shape[0]):
cur_feats = set()
for col in range(0, 26):
t = str(X[row][13 + col])
if t == 'nan':
t = ''
cur_feats... | The code performs feature engineering using a precomputed statistic dictionary, trains a Gradient Boosting Classifier (GBDT), extracts GBDT-derived features, generates FFM (Field-aware Factorization Machines) features, trains an FFM model, and returns final predictions for binary classification. It combines GBDT and FF... | def perform(X_train_src, X_test_src, y_train, y_test):
tmp_folder_name = './tmp'
if not os.path.exists(tmp_folder_name):
os.makedirs(tmp_folder_name)
in_file = open('stat.pkl', 'rb')
stat_dict = cPickle.load(in_file)
in_file.close()
X_train_gbdt = feat_eng(X_train_src, stat_dict)
X... |
def plot_data(samples, centroids, clusters=None):
"""
Plot samples and color it according to cluster centroid.
:param samples: samples that need to be plotted.
:param centroids: cluster centroids.
:param clusters: list of clusters corresponding to each sample.
"""
colors = ['blue', 'green',... | The code loads a dataset of 300 2D points, initializes centroids, runs K-means clustering (with fixed and random initializations), and visualizes the clustering process and centroid evolution over iterations. It demonstrates centroid assignment, iteration progression, and random initialization effects on the final clus... | def main():
datafile = 'data/data2.mat'
mat = scipy.io.loadmat(datafile)
samples = mat['X']
# samples contain 300 pts, each has two coordinates
# Choose the initial centroids
initial_centroids = np.array([[3, 3], [6, 2], [8, 5]])
plot_data(samples, [initial_centroids])
clusters = find_c... |
def burl(u): return f"{BASE_URL}{u}"
def get_images(soup):
images = []
# all_images = soup.find_all("img")
all_images_and_legends = soup.find_all("p", class_="p_Bildlegende")
for i, img in enumerate(all_images_and_legends):
if img.find_all("img"):
src = img.find_all("img")[0]["src"]
... | The main task of the code is to fetch and parse data from a given URL, extracting a victim's first and last name, bio, images, and URL. It uses helper functions to retrieve structured information from HTML content and returns the data in a dictionary format. If parsing fails, it returns False. | def fetch_victim_data(url):
soup = req_handler.get_soup(burl(url))
if not soup: return False
images = get_images(soup)
bio = get_bio(soup)
name = extract_name(url)
return {
"vorname": name[1],
"nachname": name[0],
"bio": bio,
"images": images,
"url": ... |
def update_playing_next(playing_next_list:list):
# what does this do?: This function takes a list of the names of videos playing next and
# updates the next playing visual on the screen
input_string = 'Next Up:\n'
max_items = 5
for index, video_title in enumerate(playing_next_list):
if ... | The code controls live stream visuals by updating on-screen elements like "Next Up" lists and status text based on hardware signals. It processes video data queues, handles cooldown states, and updates OBS sources when videos finish playing, ensuring real-time visual synchronization with hardware processes. | def visuals_process(converter_visuals_conn, hardware_visuals_conn, video_name_q):
# this process should control livestream visuals.
logger.debug(f"Debug mode enabled for {__name__}")
no_video_playing_text = "Nothing currently playing."
## STATE variables & default values
obs_current_status_text =... |
def get_current_session_id():
"""
Return a the current session ID as an integer.
When new sessions are created, the current session ID is incrementeed by 1.
So the current session is simply the max session ID.
"""
conn = get_db_connection()
session = conn.execute(
"SELECT MAX(sess... | The code handles a chatbot's main page by managing user interactions. On POST requests, it captures input text, generates a response, and stores the prompt-response pair in a database with the session ID. On GET requests, it retrieves and displays the chat log for the current session from the database, rendering it in ... | def index():
"""
The main page for the chat bot app
"""
session = get_current_session_id()
# User has sumbitted a prompt
if request.method == 'POST':
input_text = request.form['input']
if not input_text:
flash('Enter a prompt.')
else:
# Query the ... |
def genTopHeader(self, stateName):
print(' - generate topHeader')
header = '<!DOCTYPE html>\n<html lang="en-us" class="theme-cyan" >\n<head>\n <meta charset="utf-8">\n'
header += ' <title>Covid-19: {0}</title>\n'.format(stateName)
headRequire = '<?php require "_inc/coronaMap_header2.p... | The code generates a PHP webpage for a U.S. state by assembling HTML/JavaScript components (headers, navigation, maps, data grids) using state-specific data, then writes the combined content to a file named after the state's code. It handles both structure and dynamic elements like maps and scripts, ensuring state-spec... | def assemblePage(self, stateCode, stateName):
print('assemblePage:', stateCode)
stateCodeLower = stateCode.lower()
head1 = self.genTopHeader(stateName)
head2 = self.genBodyStart()
navigation = self.genNavigation()
highMapsCDN = self.genHighMapsCDN(stateCode)
... |
def compute_flag_delta(old_centroids, new_centroids): # returns True if and only if every delta is less than eps.
flag_delta = True
for i in range(len(old_centroids)):
delta = euclidean_distance(old_centroids[i], new_centroids[i])
if delta >= eps:
flag_delta = False
brea... | The function implements the K-means clustering algorithm, reading data from a file and returning final centroids and cluster assignments. It validates inputs (K > 1, 1 < max_iter < 1000, file existence), initializes centroids with first K data points, iteratively assigns data points to nearest centroids, updates centro... | def k_means_algorithm(K, max_iter, file_path):
flag_K = 1 < K
flag_iter = 1 < max_iter < 1000
flag_file = True # Initialize flag_file here
data_points = []
try:
with open(file_path) as file:
for line in file:
vector = line.rstrip().split(',')
vec... |
def initialize():
# default values
K = 0
flag_K = True
try:
K = int(sys.argv[1])
except ValueError:
flag_K = False
flag_file, flag_iter, data_points, iter = read_file()
return flag_K, flag_iter, flag_file, K, iter, data_points
def check_arguments(flag_K, flag_iter, flag_file,... | The code implements the K-means clustering algorithm. It initializes centroids, assigns data points to clusters, updates centroids iteratively until convergence or max iterations, and outputs final centroids. | def k_means_algorithm():
flag_K, flag_iter, flag_file, K, iter, data_points = initialize()
N = len(data_points)
d = len(data_points[0])
arguments_ok = check_arguments(flag_K, flag_iter, flag_file, K, N, iter)
if arguments_ok: # True if and only if all requirements about the arguments are met.
... |
def get_height(self, current: AVLTreeNode) -> int:
"""
Get the height of a node. Return current.height if current is
not None. Otherwise, return 0.
:complexity: O(1)
"""
if current is not None:
return current.height
return 0
def rebalance(... | This function inserts a key-value pair into an AVL tree, recursively placing the item in the correct position. After insertion, it updates node heights and performs rotations to maintain AVL balance, returning the new root of the subtree. | def insert_aux(self, current: AVLTreeNode, key: K, item: I) -> AVLTreeNode:
"""
Attempts to insert an item into the tree, it uses the Key to insert
it. After insertion, performs sub-tree rotation whenever it becomes
unbalanced.
returns the new root of the subtree.... |
def get_height(self, current: AVLTreeNode) -> int:
"""
Get the height of a node. Return current.height if current is
not None. Otherwise, return 0.
:complexity: O(1)
"""
if current is not None:
return current.height
return 0
def rebalance(... | The code deletes a node with the specified key from an AVL tree, handling cases where the node has no children, one child, or two children. It updates subtree heights, adjusts counts, and rebalances the tree via rotations to maintain AVL properties, returning the new root of the subtree after deletion. | def delete_aux(self, current: AVLTreeNode, key: K) -> AVLTreeNode:
"""
Attempts to delete an item from the tree, it uses the Key to
determine the node to delete. After deletion,
performs sub-tree rotation whenever it becomes unbalanced.
returns the new root of the... |
def browser_opener():
url_builder = ContractFetcher.UrlBuilder()
auth_url = 'https://%s?%s' % (url_builder.base_url, urlencode(url_builder.args))
return webbrowser.open(auth_url)
def check_for_contracts_json():
if os.path.isfile("contracts.json"):
if os.stat("contracts.json").st_size == 0:
... | The main task of the code is to launch a Flask application in a separate thread, open a browser, wait for a JSON file containing contracts to be generated, and then retrieve and merge outstanding contracts from that JSON file. | def contract_fetch():
flask_thread = threading.Thread(target=ContractFetcher.app.run)
ContractFetcher.app.thread = flask_thread
flask_thread.start()
browser_opener()
while True:
is_json = check_for_contracts_json()
if is_json is not False:
... |
def floyd_warshall(self):
next = [[None] * self.n for i in range(self.n)]
distance = list(map(lambda i: list(map(lambda j: j, i)), self.graph))
for i in range(self.n):
for j in range(self.n):
next[i][j] = i
for k in range(self.n):
for i in range(s... | The code calculates the maximum treasure (MaxTreasure) achievable by traversing a graph, using Floyd-Warshall for shortest paths, selecting optimal nodes based on distance and treasure values, and ensuring the path's total distance does not exceed a predefined threshold (Alpha). | def Find(self):
Matrix, n = self.floyd_warshall()
Trophy = self.count(n)
visit = [0 for i in range(self.n)]
nextStop = self.pick(0, Matrix, Trophy, visit)
visit[nextStop] = True
numT = 0
if nextStop >= 0:
if self.Alpha - Matrix[0][nextStop] >= Matrix[n... |
def floyd_warshall(self):
next = [[None] * self.n for i in range(self.n)]
distance = list(map(lambda i: list(map(lambda j: j, i)), self.graph))
for i in range(self.n):
for j in range(self.n):
next[i][j] = i
for k in range(self.n):
for i in range(s... | This method computes the shortest paths between all node pairs using Floyd-Warshall algorithm, then uses the result along with a count value and parameter Alpha to execute a search or analysis operation via the Find method. | def findHelper(self):
Matrix, n = self.floyd_warshall()
Trophy = self.count(n)
self.Find(Matrix, Trophy, self.Alpha) |
def schmit(Q):
nrow = len(Q[0])
d = len(Q)
for i in range(nrow):
for j in range(i):
Q[:, i] -= (Q[:, i] * Q[:, j]).sum() * Q[:, j]
Q[:, i] /= np.sqrt((Q[:, i] ** 2).sum())
return Q
def aggregation_init(Y,args):
ngc, nlc = args['ngc'], args['nlc']
d = len(Y[0][0, :])
... | The function `personalized_pca_dgd` performs a distributed PCA with gradient descent, enabling personalized dimensionality reduction across multiple clients. It initializes basis matrices (`U`, `V`) using random, aggregation, or default methods, then iteratively optimizes local client parameters and globally averages `... | def personalized_pca_dgd(Y, args):
ngc, nlc = args['ngc'], args['nlc']
d = len(Y[0][0, :])
num_client = args['num_client']
rho = args['rho']
vinit = True
if 'randominit' in args.keys() and args['randominit'] == 1:
U_init = np.random.randn(d, ngc)
U_init = schmit(U_init)
... |
def read_card_file(filename):
"""
Args:
filename: the filename of the card file.
Returns:
a list of destination cards: the card text file has the destination cards,
the list has the list of cards in the file.
"""
destination_cards = []
with open(filename, 'r', encoding="utf-8") a... | The function calculates a game score by summing points from routes and destination cards. It reads card and edge files, constructs a graph, checks route validity, enforces a train limit, and accumulates scores while handling errors. | def score_card_set(card_filename, edge_filename):
"""
Args:
card_filename: the filename of the card file.
edge_filename: the filename of the edge file.
Returns:
local_score: score of the game.
"""
destinations = read_card_file(card_filename)
routes = read_edge_file(edge_filename)... |
def adventure_story(beast_1, weapon_1):
"""
Adventure Story makes the beginning of the adventure
game which is telling the story of the adventure ...
:param beast_1: string that represents a random name
of beast that player will fight.
:param weapon_1: string that represents the name of
the ... | The code simulates a text-based adventure game where the player navigates through locations, encounters a randomly chosen beast, and engages in combat or evasion using a randomly selected weapon, with potential upgrades to the weapon during the game. | def play():
"""
Play is where the player is in the center of the game.
"""
# make randomness so the game become more enjoyable ...
beast = random.choice(['troll', 'dragon', 'wicked fairie', 'pirate'])
weapon = random.choice(['tiny dagger', 'tiger claws', 'finger knife'])
# tell the player wh... |
def print_pause(message, delay=0.5):
"""
Print Pause makes displaying more smoothing and colorful
in player screen.
:param message:string that represents significant
information about where player is and which direction
to move next.
:param delay: integer that represents the time to delay
... | The main task of the code is to execute one round of a game by retrieving moves from two players, updating their strategies, determining the winner based on game rules, updating scores, and announcing the result. It stores instance data for future rounds and ensures both players learn from each interaction to adapt the... | def play_round(self):
"""
Perform a round strategy of the game that features of
instance data storage.
:param self: An instance of Game class.
"""
move_1 = self.p1.move() # Get human move
move_2 = self.p2.move() # Get computer move
self.p1.learn(move_1, ... |
def get_component(filepath):
core_files = ["init", "block", "ipc", "kernel", "lib", "mm", "virt"]
fs_files = ["fs"]
driver_files = ["crypto", "drivers", "sound", "security"]
net_files = ["net"]
arch_files = ["arch"]
misc_files = [
"Documentation",
"scripts",
"samples",
... | This function processes a file's addition or deletion by determining its component and calculating source lines of code (SLOC). If the file is a C file, it generates a temporary C file from the blob, computes Java SLOC (possibly a mislabeling), deletes the temporary file, and returns the SLOC count along with the compo... | def handle_added_or_deleted_file(file_path, file_blob, change_type, head_commit_db):
file_logging_loc = 0
component = get_component(file_path)
if is_c_file(file_path):
c_file = generate_c_file_of_blob(file_blob)
file_logging_loc = get_java_sloc(c_file)
delete_if_exists(c_file)
re... |
def is_c_file(file_path: str):
if file_path.endswith(".c"):
return True
else:
return False
def get_component(filepath):
core_files = ["init", "block", "ipc", "kernel", "lib", "mm", "virt"]
fs_files = ["fs"]
driver_files = ["crypto", "drivers", "sound", "security"]
net_files = ["n... | This function processes updated C files between two commits by generating temporary files, calculating lines-of-code (LOC) changes (added, deleted, modified), and updating the log with these metrics for the associated component. | def handle_updated_file(file_diff, head_commit_db):
if is_c_file(file_diff.a_path) and is_c_file(file_diff.b_path):
component = get_component(file_diff.b_path)
c_a_file = generate_c_file_of_blob(file_diff.a_blob)
c_b_file = generate_c_file_of_blob(file_diff.b_blob)
loc_diff = get_ja... |
def handle_added_file(file_diff, head_commit_db):
sloc, component = handle_added_or_deleted_file(
file_diff.b_path, file_diff.b_blob, "ADD", head_commit_db,
)
update_log_loc(component, sloc, 0, 0)
def handle_deleted_file(file_diff, head_commit_db):
sloc, component = handle_added_or_deleted_file(... | The code processes a commit's file differences by inspecting each file's change type (added, deleted, or modified). It routes each file to specialized handlers: `handle_added_file` for new files ("A"), `handle_deleted_file` for removed files ("D"), and `handle_updated_file` for modified or renamed files ("M" or "R" wit... | def diff_inspector(commit_diff, head_commit_db):
for file_diff in commit_diff:
if file_diff.change_type == "A":
try:
handle_added_file(file_diff, head_commit_db)
except:
pass
elif file_diff.change_type == "D":
try:
h... |
def __fetchModelName(self, cluster_size, lower_level_results):
# for each index, If the container has not failed, match the storage name
# (reference of the model in the database)
stored_models=[[] for _ in range(cluster_size)]
# for model in iter(lower_level_results.get, None):
... | The main task of the code is to aggregate lower-level results according to a hierarchical aggregation scheme. It processes each aggregation level, fetches corresponding models, and either invokes a top-level action for final aggregation or recursively aggregates middle levels. The function handles model storage, action... | def __aggregate(self, lower_level_results):
"""
Possible contents of the model info are: (1) "ExecutionError"
(2) 'Compute-Output': storage + ' trained and stored successfully.'
"""
# Determine number of aggregation level
nb_ag_level = len(self.aggregation_scheme)
... |
def __createPackage(self):
metadata = json.dumps({"dataset": self.params['dataset'], "model": self.model['name'], "target": self.params['file'],
"batch": self.batch_size, "epochs": self.epochs, "loss": self.loss, "features": self.params["features"], "db": self.db_url})
pac... | The main task of the code is to process a request by creating a package, training models to obtain results, aggregating those results, and returning the instance. It orchestrates data preparation, model training, and result consolidation in a structured workflow. | def processRequest(self):
# create package
self.__createPackage()
# Create and invoke training containers
training_results = self.__train()
# Create and invoke aggregation Services
self.__aggregate(training_results)
return self |
def prepare_test_img(self, idx):
"""Get testing data after pipeline.
Args:
idx (int): Index of data.
Returns:
dict: Testing data after pipeline with new keys intorduced by \
piepline.
"""
img_info = self.getitem_info(idx)
result... | The main task of the code is to retrieve training or test data based on the `test_mode` flag. If in test mode, it directly returns test data using `prepare_test_img`. For training, it repeatedly fetches data with `prepare_train_img`, re-sampling an index if the data is invalid (`None`), ensuring valid data is returned.... | def __getitem__(self, idx):
"""Get training/test data after pipeline.
Args:
idx (int): Index of data.
Returns:
dict: Training/test data (with annotation if `test_mode` is set \
True).
"""
if self.test_mode:
return self.prepar... |
def get_progress_completion():
return int(os.environ.get('PROGRESS_COMPLETION'))
def _validate_post_survey(user_id, form):
# Get the post_survey information
vision_q = form.vision_q.data
attention_check = form.attention_check.data
prev_survey = form.prev_survey.data
logger.info(f'User {user... | The function validates a user's progress through a multi-step process, checking form inputs to ensure completion criteria are met. It updates user progress, handles validation for initial understanding, post-survey answers, and annotation recording, returning errors if steps fail. It advances progress or sets it to -1 ... | def validate_step(user_id, form):
u = User.get_user(user_id)
err = ""
if not u:
return "Invalid user"
# User completed the process, either successfully (PROGRESS_COMPLETION) or unsuccessfully (-1)
if u.progress == get_progress_completion() or u.progress == -1:
return "User... |
def get_books_from_db(self):
"""Gets all book records.
Yields:
obj: book record
"""
result = session.execute(select(Book))
for book in result.all():
yield book[0]
def opds_page_data(self, page_number, publications):
"""Formats data for one OPDS re... | The code generates an OPDS feed by retrieving books from a database, paginating them, and writing each page as a JSON file. It calculates total pages, iterates through books, converts each to OPDS format, groups them into pages, and saves each page with metadata. | def opds_feed(self):
"""Creates a feed of OPDS data from saved books."""
self.total_pubs = session.query(Book).count()
self.total_pages = ceil(self.total_pubs / self.page_size)
books = self.get_books_from_db()
count = 1
publications = []
page_number = 1
fo... |
def make_data(train_points,noise_param):
return target_func(train_points)+np.random.normal(loc=0,scale=noise_param,size=len(train_points))
def set_up_prior(test_points):
mean = np.array([0]*len(test_points))
covar = np.array(compute_prior_covariance(test_points))
return mean,covar
def metropolis_hasting... | The code performs Bayesian inference using Metropolis-Hastings MCMC on a Gaussian Process (GP) model. It generates training data with noise, sets up a GP prior, samples posterior distributions across multiple chains, computes the posterior mean, and compares it with the true function and analytic mean. It visualizes re... | def main():
mesh_size = 0.05
train_point_count = 6
noise_param = 0.25
train_points = np.linspace(0,1,train_point_count)
y = dict(zip(train_points,make_data(train_points, noise_param)))
samples_per_chain = 2000
burn_in = 1000
n_chains = 10
test_point_count = int(1/mesh_size... |
def prop(xi,layers,mesh_size,plot_all=False):
mesh_count = int(np.round(1/mesh_size)+1)
mesh = np.linspace(0,1,mesh_count)
covar = compute_initial_k(mesh)
u = np.linalg.cholesky(covar)@xi[0]
if plot_all == True:
mesh_count = int(np.round(1/mesh_size)+1)
mesh = np.linspace(0,1,mesh_co... | The code performs Markov Chain Monte Carlo (MCMC) sampling via a Metropolis-Hastings algorithm to generate posterior samples of model parameters. It initializes random parameter states, iteratively proposes new states using a covariance matrix derived from input parameters, computes acceptance probabilities based on li... | def sample_posterior(mesh_size,layers,number_draws,betas,data,gamma):
mesh_count = int(np.round(1/mesh_size)+1)
xi = [np.random.randn(mesh_count) for i in range(layers)]
prediction = prop(xi,layers,mesh_size)
B = get_B(betas)
A = np.sqrt(np.eye(layers)-B**2)
gamma_fac = np.linalg.chole... |
def sample_posterior(mesh_size,layers,number_draws,betas,data,gamma):
mesh_count = int(np.round(1/mesh_size)+1)
xi = [np.random.randn(mesh_count) for i in range(layers)]
prediction = prop(xi,layers,mesh_size)
B = get_B(betas)
A = np.sqrt(np.eye(layers)-B**2)
gamma_fac = np.linalg.chole... | The main task of the code is to compare Bayesian posterior sampling methods (GP and DGP) for approximating three target functions (smooth, step, sine reciprocal). It generates synthetic data with noise, performs MCMC sampling, computes posterior means, and evaluates accuracy via RMSE and convergence using Gelman-Rubin ... | def main():
target_funcs = [sin,step,sin_recip] #sin_recip
mesh_size = 0.01
mesh_count = int(np.round(1/mesh_size)+1)
mesh = np.linspace(0,1,mesh_count)
data_interval = 2
noise_param = 0.1
layers = 2
betas = [0.07]*layers
draws = 3
burn_in = 1
n_chains = 3
... |
def preparing_comp():
# read compustat pulled data
comp = pd.read_csv(resource + "wrds_comp.csv", parse_dates=['datadate'])
# fill the nan in current and long debt data
comp['dlc']=comp['dlc'].fillna(0)
comp['dltt']=comp['dltt'].fillna(0)
# select the columns
comp=comp[['gvkey','datadate','d... | The main task of the code is to prepare and merge financial data from Compustat, CRSP, and CCM sources for years 2005–2008, calculate default probabilities using the `row_dd` function, and save annual results. It processes dates, merges datasets, filters by disclosure periods, integrates FRED interest rates, and output... | def main():
print('preparing compustat...')
comp = preparing_comp()
years = [2005,2006,2007,2008]
for year in years:
print(f'preparing crsp for {str(year)}...')
crsp = preparing_crsp(year)
print('preparing cmm...')
ccm = preparing_ccm(comp)
default_p = crsp.groupb... |
def context_iter(dblp_path):
"""Create a dblp data iterator of (event, element) pairs for processing"""
return etree.iterparse(source=dblp_path, dtd_validation=True, load_dtd=True)
def log_msg(message):
"""Produce a log with current time"""
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), message)
de... | The code processes conference data from CSV files, mapping conferences to their fields and levels, extracts program chair information for conferences between 2000-2015, parses DBLP XML proceedings data, and analyzes chairs' conference involvement before/after specific years, outputting results to a text file. | def main():
ccf = open('conferences_ccf.csv', 'r')
ccfcontent = []
ccf.readline()
while True:
crf = ccf.readline()
if len(crf) == 0:
break
newcontent = crf.split(',')
ccfcontent.append(newcontent)
#print(ccfcontent)
ccf_field_level_dict = {}
conf... |
def get_boxes(self, index):
if self.cfg.SSV2.BOXES_FORMAT == 'detectron2':
return self.get_boxes_detected(index)
elif self.cfg.SSV2.BOXES_FORMAT == 'annotated':
return self.get_boxes_gt(index)
else:
raise NotImplementedError(f'Boxes format {self.cfg.SSV2.BOXES... | This method retrieves video frames, labels, and indexes by loading images, applying transformations (normalization, cropping, flipping), and handling bounding boxes if enabled. It supports training, validation, and testing modes with distinct sampling strategies, adjusts scales/crops based on configuration, and returns... | def __getitem__(self, index):
"""
Given the video index, return the list of frames, label, and video
index if the video frames can be fetched.
Args:
index (int): the video index provided by the pytorch sampler.
Returns:
frames (tensor): the frames of sampl... |
def get_out_path(pbboxes):
path = "epickitchens"
os.makedirs(BASE_DIR, exist_ok=True, mode=0o777)
path = os.path.join(BASE_DIR, path)
return path
def gen_boxes_dict(pbboxes, verbose=False):
"""
pbboxes (str): path to data dir
"""
dboxes = nested_default_dict_list()
dhands = nested_de... | The function generates and saves sorted bounding boxes (bboxes) for the EpicKitchens dataset from input paths (`pbboxes`), either as `.pkl` files or `.h5` files based on the `h5` flag. It checks if output files exist, creates them if missing, and returns the file path or loaded data. The process involves generating bou... | def get_ek_boxes(pbboxes, verbose=False, h5=False):
out_path = get_out_path(pbboxes)
_exists = os.path.exists(out_path)
if h5:
_exists = _exists or os.path.exists(out_path+'.h5')
if not _exists and du.is_master_proc():
if verbose:
logger.info(f"Generating EpicKitchens bboxes ... |
def halveAsString(n):
res = ""
carry = 0
for i in range(len(n)):
d = int(n[i])
if carry == 1:
d = d + 10
carry = d%2
res = res + str(d//2)
return removeFrontZeros(res)
def add1AsString(n):
res = list(n)
for i... | The code computes the minimum number of steps to reduce a string-represented integer `n` to "1" using allowed operations: halving if even, or adding/subtracting 1 if odd, with memoization to optimize recursive calls. | def rec(n, count):
if n in checked.keys():
return checked[n]
if n == "1":
return count
count = count + 1
if n[len(n)-1] in ["0","2","4","6","8"]:
return rec(halveAsString(n), count)
else:
nAdd = add1AsString(n)
resAdd = ... |
def get_game_page(url: str, page_no: int) -> Tag:
"""get_games_page
Retrieve the game list html document from metacritic.
:param page: Desired page on the metacritic game list.
:return: String containing the html document.
"""
r = requests.get(
url, params={"page": page_no}, headers={"U... | The function scrapes user reviews for a specified game from Metacritic, saves them as a CSV file if not already existing, and handles exceptions. It determines the number of review pages, iterates through each page, collects reviews, and writes them to a file with delays to avoid overloading the server. | def get_game_reviews(game: str):
try:
out_file = game.replace("/", "_")
if os.path.exists(f"data/raw/games/{out_file}.csv"):
print(f"Skipping {game}: Already Exists")
return
url = f"https://www.metacritic.com{game}/user-reviews"
first_page = get_game_page(url,... |
def __move_creatures(self):
# each creature picks a move, set old cell as free and new cell as taken by creature
for creature in self.creatures:
possible_moves = self.get_possible_moves(creature)
picked_move = creature.pick_move(possible_moves)
self.get_cell(*(creatur... | The main task of the code is to update a simulation by moving creatures, handling infection processes, and advancing the calendar. The `update` method orchestrates these three private operations: `__move_creatures` updates creature positions, `__handle_infection` manages infection spread or interactions, and `__update_... | def update(self):
self.__move_creatures()
self.__handle_infection()
self.__update_calender() |
def convert_from(shares, counter, exchange, symbol, size):
if shares['VALBZ'] + size > 10 or shares[symbol] -size < -10: return counter
shares[symbol] -= size
shares['VALBZ'] += size
return convert(counter, exchange, symbol, size, "SELL")
def convert_to(shares, counter, exchange, symbol, size):
if s... | The function checks arbitrage opportunities between VALBZ and VALE using best bid/ask prices. It executes trades to balance shares when thresholds are met, adjusting the counter and shares. If best prices differ by more than 1, it buys the cheaper stock and sells the more expensive one to profit from price discrepancie... | def check_ADR(buy_orders, sell_orders, shares, counter, exchange, message):
if 'VALBZ' not in best_prices or 'VALE' not in best_prices: return counter
if best_prices['VALBZ'] == (0,0) or best_prices['VALE'] == (0,0): return counter
if shares['VALE'] >= 8 or shares['VALBZ'] <= -8:
counter = convert_... |
def connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((exchange_hostname, port))
return s.makefile('rw', 1)
def write_to_exchange(exchange, obj):
json.dump(obj, exchange)
exchange.write("\n")
def read_from_exchange(exchange):
return json.loads(exchange.readline())
def pa... | This code interacts with a stock exchange to execute trading strategies. It connects to the exchange, sends a hello message, and processes market data (book/trade messages) to make buy/sell decisions for assets like BOND, VALE, and VALBZ. It maintains order queues, tracks shares, and adjusts positions based on price th... | def main():
exchange = connect()
write_to_exchange(exchange, {"type": "hello", "team": team_name.upper()})
hello_from_exchange = read_from_exchange(exchange)
# A common mistake people make is to call write_to_exchange() > 1
# time for every read_from_exchange() response.
# Since many write messa... |
def initialise(self):
# evaluate initial state of puzzle
self.hn = select_heuristic(self.heuristic, self.search_state, self.goal_state)
# print("Value of h(n):",self.hn)
node = Node(self.search_state)
node.hn = self.hn
node.gn = -1
self.search_nodes.append(node)
d... | This code implements a search algorithm to find a path to a goal state. It initializes a board, iteratively explores nodes, generates new states, checks for goal completion, and manages a priority queue of search nodes sorted by heuristic values. The algorithm tracks paths, evaluates node states, and expands valid move... | def solve(self):
board = Board()
self.initialise()
while True:
if (self.is_exhausted()):
exit(0)
self.path_node() # generate the next node to be evaluated
self.get_stats() # print latest heuristic information
self.mark_evaluated()... |
def markAsAlive(self, thread):
self.threadStatus[thread] = 0
def colorAccordingToResult(self, thread, result):
row = thread%3
column = math.floor(thread/3)
#print ( row , column )
if result == 1:
# Alive, color accordingly
self.tableWidget.setItem(column, ... | This method checks the status of running simulation threads. It iterates through threads, verifies if simulations are active, and evaluates their exit codes. Depending on the return code (e.g., 4294967197, 99), it updates thread status, colors, and miss counts. If a thread exits normally, it marks it as alive; otherwis... | def checkStatus(self):
if self.checkingblocked == False:
#print ( "st1s job current time : {}".format(time.ctime()) )
for thread, (sim, simp) in enumerate(zip(self.simulation, self.simulationP)):
if sim == True:
if simp.poll() is None:
... |
def __handle_disconnect_flag(self, request):
if request.unpack_message['disconnect_flag']:
self.net_pool.disconnect(request.connection)
def __get_neighbours_connections_from_hpn_server_response(self, request):
neighbours_data_list = request.unpack_message['hpn_clients_list']
neighbou... | This function processes HPN server responses by updating server status, checking existing connections, and initiating new requests for unknown connections through streams. It handles disconnections, retrieves neighbor connections, updates last response timestamps, and spawns parallel tasks for untracked connections to ... | def hpn_servers_request(self, request):
self.__handle_disconnect_flag(request)
neighbours_connections = self.__get_neighbours_connections_from_hpn_server_response(request)
self.__update_server_last_response_field(request)
for receiving_connection in neighbours_connections:
if... |
def _create_filename_parts(self):
'''
Helper function that creates a filename based on the configuration file
'''
if isinstance(self.source['name'], str):
self.source['name'] = [self.source['name']]
if 'prefix' in self.sensor:
if isinstance(self.sensor['... | The main task of the code is to process a GEE FeatureCollection of polygons by applying Cloudfree Merging, exporting them individually with customizable parameters. It allows starting from a specified index, limiting the number of polygons, or exporting specific IDs. The function skips large polygons, prepares export s... | def process_datasource(
self, loop_start=0, limit=None, polygon_id_list=None
):
'''
Applies Cloudfree Merging to the polygons in the GEE FeatureCollection and exports them one at a time.
IMPORTANT NOTE: GEE only allows 3,000 exports in your export queue at any one time. Please make ... |
def maxSr(meanreturn,covmatrix,riskfreerate=0,constraintset=(0,1)):
#Focusing on trade off between volatility and return
#minimise the negative SR by altering the weight of portfolio)
#https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize
numstock=len(... | This function calculates optimal portfolios based on mean returns and covariance matrix. It computes (1) the maximum Sharpe Ratio portfolio, (2) minimum volatility portfolio, and (3) efficient frontier. It outputs returns, volatility, asset allocations (as percentages), and efficient frontier data. Constraints and risk... | def calculatedResults(meanreturn, covmatrix, riskFreeRate=0, constraintSet=(0,1)):
#Read in mean, cov matrix, and other financial information. Output:Max SR , Min Volatility, efficient frontier
#Max sharpe Ratio portfolio
maxSR_Portfolio= maxSr(meanreturn,covmatrix)
maxSR_returns,maxSR_std= portfolioPer... |
def createChunks(self, msg):
chunks, chunk_size = len(msg), 100
self.chunks = [msg[i:i + chunk_size] for i in range(0, chunks, chunk_size)]
def sendPacket(self, packet):
try:
self.UDPClientSocket.sendto(packet, self.serverAddressPort)
msgFromServer = self.UDPClientSocket.... | The main task of the code is to send a message in chunks using a protocol that requires acknowledgment. It sends a SYN packet, transmits data packets with sequence numbers, waits for ACK responses, validates packet types and acknowledgment numbers, updates sequence/ack counters, and terminates with a FIN call upon succ... | def sendMsg(self, msg):
self.createChunks(msg)
self.sendPacket(self.SYN())
self.ack += 1
for i in range(0, len(self.chunks)):
packet = self.createPacket(Types.Transmission.value, self.chunks[i], self.ack, self.seq)
response = self.sendPacket(packet)
ti... |
def get_last_id_text(updates):
last_update = get_last(updates)
chat_id =last_update['message']['chat']['id']
update_id = last_update['update_id']
first_name = last_update['message']['from']['first_name']
try:
text = last_update['message']['text']
except:
text = ''
return chat... | The code manages a table tennis bot that waits for user input to start/end sessions, checks for player participation, and sends interactive messages. It loops until 'start' is received, then processes game states, prompts for joining, and concludes with a thank-you message upon 'end'. | def main():
chat_id,text,update_id,first_name = get_last_id_text(get_updates())
# Until the User Presses Start
chat_id,text,update_id,first_name = start(chat_id,text,update_id,first_name)
while text.lower() != 'start':
chat_id,text,update_id,first_name = start(chat_id,text,update_id,first_na... |
def reply_markup_maker(data):
keyboard = []
for i in range(0,len(data),2):
key =[]
key.append(data[i].title())
try:
key.append(data[i+1].title())
except:
pass
keyboard.append(key)
reply_markup = {"keyboard":keyboard, "one_time_keyboard": True}... | The code handles a Telegram bot's main menu interaction. It presents users with two options: "Machine Checker" and "Speed Controller," waiting for their selection. Upon receiving a valid command, it triggers the corresponding function (`machineChecker` for "Machine Checker" or a speed control message for "Speed Control... | def menu(chat_id,text,update_id):
print('User in main menu')
message = 'Select'
commands = ['Machine Checker','Speed Controller']
reply_markup = reply_markup_maker(commands)
send_message(chat_id,message,reply_markup)
print(text)
chat_id,text,update_id = get_last_id_text(get_updates())
w... |
def get_last_id_text(updates):
last_update = get_last(updates)
chat_id =last_update['message']['chat']['id']
update_id = last_update['update_id']
first_name = last_update['message']['from']['first_name']
try:
text = last_update['message']['text']
except:
text = ''
return chat... | The code manages a table tennis bot's interaction flow: it initializes user data, waits for a 'start' command, loops until 'end' is received, handles game session joining with a 'yes' response, sends a green light confirmation, and terminates the session with a thank-you message. | def main():
chat_id,text,update_id,first_name = get_last_id_text(get_updates())
# Until the User Presses Start
chat_id,text,update_id,first_name = start(chat_id,text,update_id,first_name)
while text.lower() != 'start':
chat_id,text,update_id,first_name = start(chat_id,text,update_id,first_name)
... |
def get_last_id_text(updates):
last_update = get_last(updates)
chat_id =last_update['message']['chat']['id']
update_id = last_update['update_id']
try:
text = last_update['message']['text']
except:
text = ''
return chat_id,text,update_id
def get_updates(offset = None):
while T... | The main task of the code is to initialize a bot, retrieve chat and update IDs, start a process, and enter a loop that repeatedly calls a menu function until a 'y' response is received. After exiting the loop, it fetches the latest update and terminates the process. The bot waits for user input, processes commands, and... | def main():
print('Hi, NUSTableTennisBot now launching...')
text = ' '
chat_id, text, update_id = get_last_id_text(get_updates())
chat_id,text,update_id = start(chat_id)
while text.lower() != 'y':
sleep(1)
text = 'start'
menu(chat_id,text,update_id)
print(text ,'at ma... |
def get_data(corpus, device, args):
eval_batch_size = 10
global_batch_size = args.batch_size * args.world_size
train_data = batchify(corpus.train, global_batch_size, device)
val_data = batchify(corpus.valid, eval_batch_size, device)
test_data = batchify(corpus.test, eval_batch_size, device)
retu... | The main task of the code is to perform distributed training of a neural network model using PyTorch. It initializes a process group for multi-GPU training, loads data, sets up the model, optimizer, and training loop with learning rate decay. The code trains the model for a specified number of epochs, evaluates perform... | def main_func(gpu, args):
# Set the random seed manually for reproducibility.
torch.manual_seed(args.seed)
device = torch.device("cuda:{}".format(gpu))
rank = args.nr * args.gpus + gpu
print('rank ', rank)
dist.init_process_group(backend='nccl', init_method=args.dist_url, world_size=args.world_... |
def parse_whitespace(f, c):
while c.isspace():
c = f.read(1)
return f, c
def parse_braces(f, c):
f, c = parse_whitespace(f, c)
bcontent =""
if not c == "{":
print ("open braces with '{'")
exit()
c = f.read(1)
while not c == "}":
if c.isspace():
... | This function parses a field from a file by reading the field name, checking for an equals sign, and then reading the field value based on the subsequent character (brace, quote, alphanumeric, or number). It handles whitespace, commas, and updates the file pointer and current character for further parsing. | def parse_field(f, c):
f, c = parse_whitespace(f, c)
fname = ""
while c.isalpha():
fname += c
c = f.read(1)
fname = fname.lower()
f, c = parse_whitespace(f, c)
if not c == "=":
print(f"expected '=', found '{c}' for {fname}")
exit()
c = f.read(1)
f, c =... |
def parse_whitespace(f, c):
while c.isspace():
c = f.read(1)
return f, c
def parse_cite_key(f, c):
if not is_allowable_in_cite_key(c):
print(f"{c} is not allowable in cite_key")
exit()
cite_key = ""
while is_allowable_in_cite_key(c):
cite_key += c
c = f.read(... | This function parses a structured entry body from a file, extracting a cite key, processing fields with specific formatting (e.g., author/editor names, month), capturing line comments, and returning the key, formatted fields, line comments, and updated file state. It validates syntax and handles whitespace, ensuring pr... | def parse_entry_body(f, c):
if not c == "{":
print(f"Expected body start with '{'{'}', found '{c}'")
c = f.read(1)
f, c = parse_whitespace(f, c)
key, f, c = parse_cite_key(f, c)
f, c = parse_whitespace(f, c)
if not c == ",":
print(f"Expected ',' after key, found '{c}'")
... |
def parse_type(f, c):
if not c == "@":
print ("Type should be of the form '@<type>', instead, we got '{c}' as starting letter")
exit()
# skip over @
c = f.read(1)
if not c.isalpha():
print ("Type should be of the form '@<type>', instead, we got '@{c}' as starting letters")
... | This function parses a BibTeX entry starting with '@', validates its structure, extracts the citation key, fields, and comments, orders fields per a predefined sequence, checks for required fields like 'title', and returns structured data along with remaining input pointers. | def parse_entry(f, c):
if not c == "@":
print ("Entries start with '@'")
exit()
entry_type, f, c = parse_type(f, c)
f, c = parse_whitespace(f, c)
if not c == "{":
print (f"Entry body should start with '{{', got {c} instead")
exit()
cite_key, fields, lcomments, f, ... |
def generateKeys(p, q):
## check if p and q are prime
if not isPrime(p):
raise ValueError("Input must be prime and " + str(p) + " is not prime.")
if not isPrime(q):
raise ValueError("Input must be prime and " + str(q) + " is not prime.")
## define modulus, phi, public exponent (E), and... | The main task of the code is to demonstrate RSA encryption and decryption using example primes (P=83, Q=97) and a sample message. It generates public/private keys, encrypts the message, decrypts the ciphertext, and prints the original message, its ASCII encoding, the ciphertext, and the decrypted result to verify corre... | def main():
## example of functionality
## todo: set an example P,Q, and message
EXAMPLE_P = 83
EXAMPLE_Q = 97
EXAMPLE_MESSAGE = "EXAMPLE MESSAGE"
keys = generateKeys(EXAMPLE_P, EXAMPLE_Q)
EXAMPLE_CIPHERTEXT = encrypt(keys['modulus'], keys['public exponent'], EXAMPLE_MESSAGE)
EXAMPLE_DE... |
def addLeadingBinaryZeros(self, binaryValue, length):
value = binaryValue
while len(value) < length:
value = '0' + value
return value
def hexToBinary(self, hexValue):
return bin(self.hexToDecimal(hexValue))[2:]
def fFunction(self, messageBlock):
cipherText = ''
... | This function performs one round of Blowfish encryption by splitting the 64-bit message block into two halves, applying the fFunction to the first half after XORing with a subKey, then XORing the result with the second half. It combines the outputs to produce the encrypted block, using binary/hex conversions and bitwis... | def encryptionRound(self, messageBlock, subKey):
binaryMessageBlock = self.addLeadingBinaryZeros(self.hexToBinary(messageBlock), 64)
halfBlockSize = int(len(binaryMessageBlock)/2)
if len(binaryMessageBlock) != 64:
print('Error: Blowfish::fFunction given messageBlock wrong si... |
def addLeadingBinaryZeros(self, binaryValue, length):
value = binaryValue
while len(value) < length:
value = '0' + value
return value
def hexToBinary(self, hexValue):
return bin(self.hexToDecimal(hexValue))[2:]
def fFunction(self, messageBlock):
cipherText = ''
... | This function performs a single decryption round in the Blowfish algorithm by splitting the 64-bit message block into two halves, applying the F-function with the subkey to the left half, XORing it with the right half, and swapping the halves to produce the decrypted result. | def decryptionRound(self, messageBlock, subKey):
binaryMessageBlock = self.addLeadingBinaryZeros(self.hexToBinary(messageBlock), 64)
halfBlockSize = int(len(binaryMessageBlock)/2)
if len(binaryMessageBlock) > 64:
print('Error: Blowfish::fFunction given messageBlock too large')
... |
def decimalToHex(self, decimalValue):
return hex(int(decimalValue))[2:]
def stringToAsciiInt(self, string):
numericKey = ''
for x in string:
numericKey = int(str(ord(x)) + str(numericKey))
return numericKey
def encryptPiece(self, messageChunk):
message = messageChunk
... | This code encrypts a message by converting it to a hexadecimal string, padding it to a multiple of 16 bytes, and then encrypting each 16-byte block using a method called encryptPiece, returning the concatenated ciphertext. | def encryptMessage(self, message):
index = 0
plainText = self.decimalToHex(self.stringToAsciiInt(message))
cipherText = ''
while len(plainText)%16 != 0:
plainText = '0' + plainText
while index < len(plainText):
cipherText += self.encr... |
def mag(Lattice,n):
m = 0
for i in range(0,n):
for j in range(0,n):
m+= Lattice[i][j]
return m/(n*n)
def cluster_gen(pos,lat,b,j,h,ant):
cluster = [[pos[0],pos[1]]]
N = len(lat[1])
if ant == False:
for i in cluster:
x=i[0]; y=i[1]; curr=lat[x][y]... | The code performs a Monte Carlo simulation to thermalize a spin lattice using cluster flipping (Wolff algorithm). It updates spins based on energy calculations, with different cluster generation methods depending on the 'ant' parameter. The function tracks average magnetization over steps and returns the updated lattic... | def thermaliseH(Lattice,beta,J,h,MC,ant):
size = len(Lattice[1])
mean_mag = [mag(Lattice, size)]
if ant == False:
for n in range(0,MC):
start = [np.random.randint(0,size),np.random.randint(0,size)]
clust = cluster_gen(start, Lattice, beta, J,h,ant)
if to... |
def log(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def fetch_indiygreg_downloads(
pages: int = 100,
) -> dict[PythonVersion, dict[PlatformTriple, list[IndygregDownload]]]:
"""Fetch all the indygreg downloads from the release API."""
results = {}
for page in range(1, pages):
l... | The main task of the code is to fetch and select the best available downloads for different versions and platform triples from indygreg, then render the curated downloads using the `render` function with `PYPY_DOWNLOADS` as input. The process involves iterating through download options, choosing optimal candidates per ... | def main():
log("Rye download creator started.")
log("Fetching indygreg downloads...")
indys = {}
# For every version, pick the best download per triple
# and store it in the results
for version, download_choices in fetch_indiygreg_downloads(100).items():
# Create a dict[PlatformTriple,... |
def dfa_states(self):
start = self.ep_closure(set([0]))
states = set([start])
comp = set()
while comp != states:
comp = states
for state in states:
for symb in self.letters.replace('@',''):
newstate = self.closure(state, symb)
... | This code converts an NFA to a DFA by computing the DFA's states, transitions, and accepting states using epsilon closure. It constructs a DFA representation from the NFA's components, updating the object's attributes with the new DFA structure, including states, alphabet, transition function, start state, and acceptin... | def nfa_to_dfa(self):
states = self.dfa_states()
letters = self.letters
start = self.ep_closure(set([0]))
trans = self.dfa_trans()
accepts = []
for state in states:
if self.accepts[0] in state:
accepts.append(state)
powdfa = {
... |
def getContextFromSent(sent, dictThreeLex, contextChar, contextPlace, contextObject):
#updating context when needed
whichState = ""
for word in sent:
if word in dictThreeLex:
if dictThreeLex[word] == "character":
word = word.title()
contextChar = word
elif dictThreeLex[word] == "room":
contextP... | The main task of the code is to process a sentence within a narrative context by analyzing lexical tags, determining a numerical value from these tags, generating a response based on the number, and updating the story's context (characters, places, objects, and state) to maintain continuity. It uses dictionaries for le... | def modeThree(sent, characters, rooms, dictThreeLex, dictThreeTag, dictThreeSentence, contextChar, contextPlace, contextObject, contextState):
listTags = []
whichState = ""
contextChar, contextPlace, contextObject, whichState = getContextFromSent(sent, dictThreeLex, contextChar, contextPlace, contextObject)
lis... |
def hydrate(self, c):
satisfied = False
if self.o("water") != None:
self.consume(self.o("water"), self)
satisfied = True
else:
for x in c.environment.rooms:
if (x.state != "unusable") & (x.closed == False):
if x.o("water") != None:
self.consume(x.o("water"), x)
satisfied = True
... | The code manages a character's physical needs (hydration, nutrition, sleep), mental state transitions, and social interactions in a simulation. It updates relationships, triggers actions based on mental states (e.g., depression leads to murder or self-destruction), adjusts states after actions, and logs outcomes. The c... | def act(self, c):
f = open("output_hystory.txt", "a")
#print(self.name)
'''
1 : update sleep hydration and nutrition
2 : relationships passively wear out (not always)
3 : search for food hydration and sleep
4 : update mental state depending on f/h/s
5 : act depending on their mental state and relations... |
def Find_Controls(input_gRNA_df, input_pattern):
# this function will find the gRNA associated with control based on the key word
# input_pattern is a regex expression
return(input_gRNA_df.loc[
input_gRNA_df['Targeted_gene_name'].str.contains(input_pattern, na=False, regex=True),'gRNA'].unique())
def Boots... | This script performs resampling of mice data using bootstrapping, excluding specified samples and sgRNAs. It processes input data, identifies control gRNAs, generates summary statistics for tumor traits, and outputs results in CSV files. Key steps include data filtering, bootstrapping, quantile calculations, and statis... | def main():
parser = argparse.ArgumentParser(description='A function to do resampling of mice')
parser.add_argument("--a0", required=True, help="Address of processed data of Ultra-seq, can take multiple input")
parser.add_argument("--a1", required=False, help="Sample to exclude list address")
parser.add... |
def delete_block(self, code, string):
while string in code:
code = self.delete_annotation_block(code, string)
return code
def delete_annotation(self, code):
sens = code.split("\n")
sens_processed = []
for sen in sens:
if "#" in sen:
index ... | The main task of the code is to preprocess input code by removing multi-line comments (using triple quotes or apostrophes), annotations, import statements, and normalizing whitespace (replacing multiple spaces/newlines with single spaces), ultimately returning a cleaned, simplified version of the code. | def preprocess(self, code):
code = self.delete_block(code, '"""')
code = self.delete_block(code, "'''")
code = self.delete_annotation(code)
code = self.delete_import(code)
code = re.sub("\s+", " ", code).strip()
return code |
def getNewUpdatedGames():
cmd = "rclone sync gog-games: E:\GOG_VERIFIED --size-only --sftp-disable-hashcheck --dry-run -P"
proc = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE,)
lst = proc.communicate()[0].decode("utf8").strip().split("\n")
result = set([ re.search(r'NOTICE: (.*?)/', game).... | The code presents a menu-driven tool for managing GOG game files, offering options to update/sync/delete games with logging, delete cloud-stored older files, clean upload folders, and generate GOG content files while pushing changes to a Git repository. It handles file verification, RAR packing, and log generation for ... | def run():
print("What do you want to do? CHOICES: \n 1- Update, Sync and Delete (WITH LOG FILE)")
print(" 2- Delete older files from cloud (Make sure 1fichier gog folder is mounted (first: 1f:/GOG, then 1f:/GOG_2) and new files are in gog_upload folder, use this before uploading new/updated games to cloud)")
... |
def get_historic_data(self):
symbols = self.get_symbols_list()
symbols_yf = ' '.join(symbols)
df = yf.download(
symbols_yf,
period='100y',
interval='1d',
group_by='ticker',
threads=True,
)
df.to_hdf(self.full_path, key='... | The code updates historic stock data by checking if 50 days have passed since the last update. If so, it retrieves and loads new data. It then downloads recent data from Yahoo Finance, merges it with existing data, removes duplicates, and saves the updated dataset to an HDF file, updating the last pull timestamp. | def update_historic_data(self):
now = datetime.datetime.now()
last_pull_dt = datetime.datetime.utcfromtimestamp(self.last_pull)
days = (now - last_pull_dt).days
if days >= 50:
self.get_historic_data()
return self.load_data()
symbols = self.get_symbols_list... |
def ddm_numpy(data, taus: np.ndarray):
"""_summary_
Parameters
----------
data : np.array
image stack
Returns
-------
np.array
ddm matrix
"""
num_frames, height, width = data.shape
results = []
img_fft = np.fft.fft2(data).astype(np.complex64)
for tau i... | The function `ddm` computes dynamic properties (e.g., diffusion) from time-series data using lag times (`taus`). It handles both NumPy arrays and Dask arrays, leveraging GPU acceleration (via CuPy) if available and requested. If data is a Dask array, it routes computation to `ddm_dask_gpu` (for GPU) or `ddm_dask_cpu` (... | def ddm(
data: Union[dask.array.core.Array, np.ndarray],
taus: np.ndarray = np.arange(0),
bulk: bool = False,
) -> np.ndarray:
"""_summary_
Parameters
----------
data : Union[dask.array.core.Array, np.ndarray]
taus : np.ndarray, optional
array of lag times (in frames), by defaul... |
def rand_data_generator(shape, prec, alt=False):
if prec == 64:
return torch.randn(shape, requires_grad=False, dtype=torch.float64), {}
elif prec == 32:
return torch.randn(shape, requires_grad=False, dtype=torch.float32), {}
elif prec == 16:
if alt:
return torch.randn(sha... | The main task of the code is to generate random data and parameters for kernel operations based on a configuration file. It parses command-line arguments, reads a JSON-like config, generates vectors A and B with specified precision, computes their dot product, and prepares arguments to emit a header file containing the... | def main():
parser = argparse.ArgumentParser(description="Generate data for kernels")
parser.add_argument(
"-c",
"--cfg",
type=pathlib.Path,
required=True,
help="Select param config file kernel",
)
parser.add_argument("-v", "--verbose", action="store_true", help=... |
def rand_data_generator(shape, prec, alt=False):
if prec == 64:
return torch.randn(shape, requires_grad=False, dtype=torch.float64), {}
elif prec == 32:
return torch.randn(shape, requires_grad=False, dtype=torch.float32), {}
elif prec == 16:
if alt:
return torch.randn(sha... | The main task of the code is to generate data for convolutional kernels using a configuration file. It parses command-line arguments, loads parameters from a JSON config, generates random input tensors and zero-initialized matrices, applies zero-padding to input data, executes a 2D convolution operation (fconv2d), and ... | def main():
parser = argparse.ArgumentParser(description="Generate data for kernels")
parser.add_argument(
"-c",
"--cfg",
type=pathlib.Path,
required=True,
help="Select param config file kernel",
)
parser.add_argument("-v", "--verbose", action="store_true", help=... |
def findRoutes(self, area: dict, parentAreaId: int) -> None:
soup = BeautifulSoup(area["HTML"], "html.parser")
routeInfo = list()
for route in soup.find(class_="max-height max-height-md-0 max-height-xs-400").findAll("a"):
if route["href"] == "#":
continue
pageURL = route["href"]
routeId = int(re.se... | This function processes a list of areas by parsing HTML content to identify non-empty areas, checks for routes, scrapes sub-area links, loads pages to detect comments, scrolls to load comments, and recursively processes sub-areas. It exports collected data to JSON, handling timeouts and access issues while maintaining ... | def findSubordinateAreas(self, areas: list[dict], parentAreaId: any([None, int]) = None) -> None:
for area in areas:
currentAreaId = area["AreaId"]
soup = BeautifulSoup(area["HTML"], "html.parser")
subAreaInfo = list()
# Determine if this is an empty area
sidebar = soup.find(class_="mp-sidebar")
if... |
def is_valid_move(self, card, top_card):
# Game logic goes here
return False
def move_card(self, card, tableau):
if card.current_tableau:
card.current_tableau.remove_card(card)
if tableau:
tableau.add_card(card)
card.current_tableau = tableau
... | This code handles the release event of a card on a canvas, attempting to move a selected card to a valid tableau or foundation. It checks if the move is valid, updates the card's position if valid, resets it otherwise, and refreshes the display. It also ensures all cards are deselected and updates the UI for both sourc... | def on_canvas_release(self, event):
if self.last_clicked_card and self.last_clicked_card.face_up:
card = self.last_clicked_card
original_tableau = self.original_tableau
card.current_tableau = original_tableau
# Check if it's a valid move to any tableau or foundat... |
def draw_tile_outline(self, tile):
outline_width = 71
outline_height = 96
self.canvas.create_rectangle(
tile.position_x, tile.position_y, tile.position_x + outline_width, tile.position_y + outline_height,
outline="black", width=2
)
def deal_cards(self):
ta... | The code initializes a Solitaire game window using Tkinter, setting up the canvas, loading and shuffling card images, creating game components (tableaus, foundations, deck, fan), binding mouse events for card interactions, and starting the main event loop to enable gameplay. It prepares the game environment for card de... | def __init__(self):
self.window_width = 825
self.window_height = 625
self.window = tk.Tk()
self.window.title("Solitaire")
self.canvas = tk.Canvas(self.window, width=self.window_width, height=self.window_height, bg="green")
scale_x = 2
scale_y = 2
self.can... |
def random_card():
card_value = values[random.randint(0, (len(values) - 1))]
card_suit = suits[random.randint(0, (len(suits) - 1))]
try:
score.append(int(card_value))
except ValueError:
if card_value.__eq__("jack") or card_value.__eq__("queen") or card_value.__eq__("king"):
... | The code simulates a card game where a player starts with two random cards, draws an additional card ("hits"), calculates the total score, and evaluates the outcome: under 17 is poor, 17-20 is good, 21 is a win, and over 21 is a bust. The function prints feedback based on the score. | def play():
card1 = random_card()
hand = duplicate_card([card1]) # starting hand (two cards)
print()
final_hand = hit(hand)
final_score = calculate_score(score, final_hand)
if final_score < 17:
print(f"yikes... you got {final_score} points.")
if 17 <= final_score <= 20:
p... |
def terminal_test(self, state: GameState) -> bool:
return np.all(state.row_status == 1) and np.all(state.col_status == 1)
def get_utility(self, state: GameState) -> float:
[ny, nx] = state.board_status.shape
utility = 0
# == Count boxes
box_won = 0
box_lost = 0
f... | This function implements the Minimax algorithm with alpha-beta pruning to determine the optimal game move. It recursively evaluates game states, alternating between maximizing (player1) and minimizing (opponent) players. The algorithm returns the best value for the current player by exploring all possible actions, prun... | def get_minimax_value(
self,
state: GameState,
depth: int = 0,
max_depth: int = 0,
alpha: float = -np.inf,
beta: float = np.inf,
) -> float:
if time() >= self.global_time:
raise TimeoutError()
if self.terminal_test(state) or depth == max_d... |
def get_random_action(self, state: GameState) -> GameAction:
if random.random() < 0.5:
return self.get_random_row_action(state)
else:
return self.get_random_col_action(state)
def get_random_col_action(self, state: GameState) -> GameAction:
position = self.get_random_posit... | The function determines the appropriate action based on the game state. If neither all rows nor columns are fully marked, it returns a random action. If all rows are marked, it selects a random column action; otherwise, it chooses a random row action. This logic ensures adaptive decision-making depending on the game's ... | def get_action(self, state: GameState) -> GameAction:
all_row_marked = np.all(state.row_status == 1)
all_col_marked = np.all(state.col_status == 1)
if not (all_row_marked or all_col_marked):
return self.get_random_action(state)
elif all_row_marked:
return self.ge... |
def generate_actions(self, state: GameState) -> List[GameAction]:
row_positions = self.generate_positions(state.row_status)
col_positions = self.generate_positions(state.col_status)
actions: List[GameAction] = []
# TODO: Menambahkan heuristik move ordering
for position in row_po... | The code implements a minimax algorithm with depth-limited search to select the optimal game action. It evaluates all possible moves, calculates their utilities using recursive minimax values, and chooses the action with the highest utility. The loop iterates up to the sum of unfilled rows and columns, applying a timeo... | def get_action(self, state: GameState) -> GameAction:
self.is_player1 = state.player1_turn
selected_action: GameAction = None
self.global_time = time() + TIMEOUT
row_not_filled = np.count_nonzero(state.row_status == 0)
column_not_filled = np.count_nonzero(state.col_status == 0)... |
def read_keyword(root):
"""
A function that search for keywords from the article title of the document
Args:
root (???): the root of the xml tree
Returns:
_type_: _description_
"""
stop_words = set(stopwords.words("english"))
raw_title = read_tag(root, "title-group")
ra... | The function processes XML documents in a directory by parsing each file, extracting keywords, abstracts, and sections. It creates dataframes for word counts in each section, merges them, and saves the combined data as CSV files. | def test_loop_doc():
"""
A function that loops through all the document in the specific directory
"""
file_list = os.listdir()
for docName in file_list:
if os.path.isfile(docName):
tree = ET.parse(docName, etree.XMLParser(recover=True))
root = tree.getroot()
... |
def read_keyword(root):
"""
A function that search for keywords from the article title of the document
Args:
root (xml.etree.ElementTree): the root node of the xml tree
Returns:
[str...]: a list of keywords
"""
stop_words = set(stopwords.words("english"))
raw_title = read_t... | The function processes XML documents by parsing keywords, abstracts, and sections into DataFrames, grouping words by count. It joins these DataFrames on 'word' and exports the combined result as a CSV file, replacing the original XML's file extension. Each XML file is converted to a CSV with the same base name. | def dataframe_join():
"""
A function that loops through all the document for all the process
Output the final DataFrame to a csv file with the initial filename with .csv instead of .xml
"""
file_list = os.listdir()
for docName in file_list:
if os.path.isfile(docName):
tree... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.