dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_exchange(cls):
exchange = cls()
if exchange.id.startswith('bitfinex'):
exchange.rateLimit = 5000
return exchange
def exchange_filter(exchange) -> bool:
return exchange.has['publicAPI'] and exchange.has['fetchOrderBook'] and exchange.has['fetchTrades']
def last_ts():
now = datetime... | The code fetches market data from specified cryptocurrency exchanges, periodically snapping snapshots of base/quote pairs at set intervals. It parses command-line arguments, initializes exchanges, loads market data, and runs a loop to capture snapshots using the `snap` function, handling errors and logging results. | def bdata():
cfg = json.loads(open('config.json').read())
parser = ArgumentParser()
parser.add_argument('--exchange', required=True)
parser.add_argument('--interval', default=300, type=int)
parser.add_argument('--snap_target', type=SnapTarget, choices=list(SnapTarget), default=SnapTarget.TRADE)
... |
def getUrl(env,context):
url=''
if env=='sandpit':
if (context=='Organisation'):
url='https://ws.sandbox.training.gov.au/Deewr.Tga.WebServices/OrganisationServiceV2.svc?wsdl'
elif (context=='TrainingCompnent'):
url='https://ws.sandbox.training.gov.au/Deewr.Tga.Webservices... | The code processes training/qualification data from a web service in auto/manual modes. It parses command-line arguments for rtacode/nrtcode lists, authenticates with credentials, retrieves URLs, and uses SOAP clients to fetch organizational/training component details. Auto mode processes rtacode lists to generate scop... | def main():
user='WebService.Read' # user to add specific to env
password ='Asdf098' # user to add specific to env
env='sandpit' # User to add
parser = OptionParser()
parser.add_option('-a','--auto',type='int', action='store', default=0, help='Automode- Default 0,0->Disable,1->Enable')
parser.ad... |
def compute_all_log_marginal_likelihoods(X, y, max_nonzeros=None,
nested_models=False, **kwargs):
dim = X.shape[1]
if max_nonzeros is None:
max_nonzeros = dim
if nested_models:
num_models = dim
else:
num_models = int(np.sum([sp.special.bin... | The main task of the code is to run a Bayesian variable selection experiment comparing standard Bayesian methods (computing log marginal likelihoods) with BayesBag (a bootstrap-enhanced approach). It iteratively resamples data to stabilize posterior inclusion probabilities, ensuring standard errors fall below a thresho... | def run_single_experiment(seed, X, y, c, a, B, s, a0, b0, sigma0, filepath,
nested_models, max_stderr=0.02):
N, D = X.shape
s = s if s > 0 and s <= D else D
# standard Bayes
bprobs, _, models, bmean, bvar = compute_all_log_marginal_likelihoods(
X, y, s, a0=a0, b0=b0, si... |
def get_name(config, different_nex):
if different_nex:
s = config['baseoutfile'] + '-'
else:
s = ''
s += config['model']
if 'B' in config:
s += '-c-{c}-a-{a}'.format(**config)
return s
def get_base_filepath(odir, config, B):
filename = config['baseoutfile']
if 'B' in ... | This function processes multiple output directories by loading tree probability data from files, organizes them with associated names, identifies a starting index, and analyzes the tree probabilities, optionally comparing results to the first entry. | def standard_analysis(args, config_info):
biparts = []
tree_probs = []
names = []
for i, (odir, config) in enumerate(zip(args.output, config_info)):
name = get_name(config, args.different_nex)
names.append(name)
base_filename = get_base_filepath(odir, config, args.B)
tree... |
def get_name(config, different_nex):
if different_nex:
s = config['baseoutfile'] + '-'
else:
s = ''
s += config['model']
if 'B' in config:
s += '-c-{c}-a-{a}'.format(**config)
return s
def get_base_bootstrap_filepaths(odir, config, B):
filename = config['baseoutfile']
... | The code performs bootstrap analysis on tree probability data from multiple configurations. It loads data, resamples it iteratively, computes overlaps between configurations, and calculates confidence intervals (CI) and median overlaps. Results are printed, showing pairwise comparisons with CI ranges and median non-zer... | def bootstrap_analysis(args, config_info, hdp=.99):
df = pd.DataFrame()
names = []
print('loading data...')
for odir, config in zip(args.output, config_info):
name = get_name(config, args.different_nex)
print(name)
names.append(name)
if 'B' in config:
base_pat... |
def run_single_experiment(seed, X, y, c, a, B, s, a0, b0, sigma0, filepath,
nested_models, max_stderr=0.02):
N, D = X.shape
s = s if s > 0 and s <= D else D
# standard Bayes
bprobs, _, models, bmean, bvar = compute_all_log_marginal_likelihoods(
X, y, s, a0=a0, b0=b0, si... | This function conducts cross-validation experiments on real data, running multiple replications to compute model mismatch and probability metrics. It splits data using KFold or a single split, executes experiments for each fold, saves results to files, and aggregates model mismatch and probability-of-inclusion (PIP) me... | def _run_real_data_experiment(args, a, base_outpath, X, y, seed, D, D0):
if args.k > 1:
splits = KFold(n_splits=args.k, shuffle=True, random_state=seed).split(X)
else:
splits = [(None, np.arange(X.shape[0]))]
files = []
for rep, (_, indices) in enumerate(splits):
filepath = base_... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('output', nargs='+',
help='output directories of results to compare')
parser.add_argument('--results', default='results',
help='results directory to save comparison')
parser.add_argum... | The main task of the code is to validate and compare multiple output directories from experiments by checking their configuration files. It ensures all outputs use the same nexus file (if required) and executes either a standard analysis or bootstrap analysis based on the provided arguments, exiting with errors for inv... | def main():
args = parse_args()
if len(args.output) < 2:
sys.exit('need at least two outputs to compare')
print(args.output)
config_info = []
for odir in args.output:
with open(os.path.join(odir, 'experiment.config'), 'r') as f:
config_info.append(json.load(f))
if not... |
def run_single_synthetic_experiment(mode, seed, rep, c, a, B, D, s, N,
a0, b0, sigma0, base_outpath):
filepath = base_outpath + '-rep-{}.npz'.format(rep)
if not os.path.exists(filepath):
print('rep', rep)
X, y, beta_opt = generate_synthetic_data(mode, seed, D,... | The code conducts synthetic experiments to compare model performance by running multiple repetitions, computing posterior probabilities (pips), and analyzing model mismatch. It handles sparse and non-sparse scenarios, performs statistical tests on pips differences, and generates plots for results comparison and model m... | def run_synthetic_experiment(args, base_outpath, base_figpath, base_a_outpath):
D = args.D
D0 = 3
mark_true = None
if args.mode.startswith('synth-inliers'):
_, _, datatype = args.mode.split('-')
D0 = D/2
mark_true = None
true_inds = []
else:
_, corrtype, spars... |
def _run_real_data_experiment(args, a, base_outpath, X, y, seed, D, D0):
if args.k > 1:
splits = KFold(n_splits=args.k, shuffle=True, random_state=seed).split(X)
else:
splits = [(None, np.arange(X.shape[0]))]
files = []
for rep, (_, indices) in enumerate(splits):
filepath = base_... | This function conducts experiments on real datasets by scaling input data, running parameterized analyses for different 'a' values, and generating comparison plots. It handles model mismatch calculations, stores results, and visualizes outcomes using swarm and strip plots to evaluate performance variations across param... | def run_real_data_experiment(args, base_outpath, base_figpath, base_a_outpath):
if args.mode not in DATASETS:
sys.exit('invalid mode')
Xorig, yorig = DATASETS[args.mode](return_X_y=True)
X = scale(Xorig, axis=0)
y = scale(yorig)
D = X.shape[1]
D0 = 3
seed = 2453
pip_dicts = dict(... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('mode')
parser.add_argument('-B', type=int, default=50,
help='minimum number of bootstrap samples')
parser.add_argument('-r', type=int, default=10,
help='number of experiment repetiti... | The main task of the code is to configure visualization settings, parse command-line arguments, create output directories, generate file paths, and execute either a synthetic or real-data experiment based on the specified mode, saving results and figures accordingly. | def main():
sns.set_style('white')
sns.set_context('notebook', font_scale=1.5, rc={'lines.linewidth': 2})
args = parse_args()
os.makedirs(args.results, exist_ok=True)
os.makedirs(args.figures, exist_ok=True)
as_str = '-'.join(['{}'.format(a) for a in args.a])
base_outpath = os.path.join(ar... |
def generar_padre(genes_iniciales, length):
genes = []
#Se crea una cadena al azar del largo definido
while len(genes) < length:
tamano = min(length - len(genes), len(genes_iniciales))
#Seleccion aleatoria de genes
genes.extend(random.sample(genes_iniciales,tamano))
#Se hace ... | The main task of the code is to search for the optimal solution using a genetic algorithm approach. It iterates through 40 random seeds, varies gene counts from 5 to 14, and performs 1000 mutations per configuration. For each mutation, it evaluates fitness, updates the best solution if improved, and terminates early if... | def get_best_solution(parameters, symbols, variable, genes_iniciales, data):
#Realiza la prueba con 40 seeds diferentes de forma consecutiva
random_seed = 0
while random_seed < 40:
random.seed(random_seed)
random_seed +=1
#La cantidad de genes por seed va desde 5 hasta 15
c... |
def convert_to_matrix(msg):
m = []
for i in range(0, len(msg)):
m.append(aplhabets_to_numbers[msg[i].upper()])
return m
def get_crc(msg, key):
T = convert_to_matrix(msg)
# print(T)
original = get_binary_from_array(T)
# print(original)
return crc_helper(original, len(key) - 1, ori... | The code encrypts a message by padding it to a multiple of 3, converting it into a matrix, transposing and multiplying it with a key matrix (A), computing a CRC value for error checking, and encoding the encrypted data with the CRC for transmission. | def encrypt_data(msg,key):
while len(msg) % 3 != 0:
msg += " "
m = convert_to_matrix(msg)
cols = len(msg) // 3
T_matrix = np.reshape(m, (cols, 3))
T_matrix = np.transpose(T_matrix)
EncData = np.matmul(A, T_matrix)
crc_value = get_crc(msg, key)
send_data = encode_data(EncData... |
def decode_data(c):
matrix, crc = pickle.loads(c.recv(1024))
return matrix, crc
def decrypt_data(m):
m = np.matmul(A_inverse, m)
m = np.transpose(m)
msg = ""
try:
for i in range(len(m)):
for j in range(len(m[0])):
msg += numbers_to_alphabtes[m[i][j]]
r... | The main task of the code is to handle client communication by continuously receiving, decoding, decrypting data, verifying CRC integrity using a key, and responding with error messages or success confirmation. It processes incoming data from a client socket, checks for data integrity, and sends appropriate feedback wh... | def communicate_with_client(c,addr):
while True:
key = '1010'
matrix, crc = decode_data(c)
message = decrypt_data(matrix)
# message+="heyya"
crc_verified = get_crc(message, key)
# print(crc)
# print(crc_verified)
if (crc != crc_verified):
p... |
def mid_term_file_classification(input_file, model_name, model_type,
plot_results=False, gt_file=""):
"""
This function performs mid-term classification of an audio stream.
Towards this end, supervised knowledge is used,
i.e. a pre-trained classifier.
ARGUMENTS:
... | The function evaluates segmentation/classification models on audio files in a directory. It processes `.wav` files, using either `mid_term_file_classification` or `hmm_segmentation` based on the method. It aggregates accuracies, confusion matrices, and computes average/median accuracy, recall, precision, and F1 scores ... | def evaluate_segmentation_classification_dir(dir_name, model_name, method_name):
accuracies = []
class_names = []
cm_total = np.array([])
for index, wav_file in enumerate(glob.glob(dir_name + os.sep + '*.wav')):
print(wav_file)
gt_file = wav_file.replace('.wav', '.segments')
i... |
def moveOnToGrass(self, y, x):
self.map[y][x] = self.map[self.hand[0]][self.hand[1]]
self.map[self.hand[0]][self.hand[1]] = 0
self.hand = (-1, -1)
self.drawMap()
def moveOnToPit(self, y, x):
self.map[self.hand[0]][self.hand[1]] = 0
self.hand = (-1, -1)
self.drawMa... | This code handles left mouse clicks to allow a player to interact with a grid-based game map. It calculates the clicked grid cell, checks if the player can pick up or move a piece, triggers movement or combat actions based on terrain type, updates the game state, switches turns, and triggers AI logic. | def leftHandler(self, event):
if self.gameStarted and self.turn == 0:
print("Left clicked at:", event.x, event.y)
y = int((event.y - self.startY - ((event.y - self.startY) % self.squareSize)) / self.squareSize)
x = int((event.x - self.startX - ((event.x -self.startX) % self.s... |
def run_shaping_agent(seed, save_dir, target_update_frequency):
run_agent(seed, save_dir, target_update_frequency, 38000, create_shaping_agent)
def run_ppr_agent(seed, save_dir, target_update_frequency, decay_factor):
run_agent(seed, save_dir, target_update_frequency, 38000, create_ppr_agent, decay_factor=decay... | The code runs multiple reinforcement learning agents (shaping, PPR, residual, boosted, default, curriculum) with varying hyperparameters and logging settings, using a given seed for reproducibility. Each agent is trained with specific configurations, such as different episode counts, discount factors, policy offsets, a... | def experiment(seed):
run_shaping_agent(seed, "logs/shaping_agent", 4000)
run_ppr_agent(seed, "logs/ppr_agent_0.998", 200, 0.998)
run_residual_agent(seed, "logs/residual_agent_2000", 25, policy_offset=2000)
run_boosted_agent(seed, "logs/boosted_agent", 2000)
run_boosted_agent(seed, "logs/boosted_sha... |
def getConfigItem(Key=None, Default={}):
Value = Default
try:
Config = Domoticz.Configuration()
if (Key != None):
Value = Config[Key] # only return requested key if there was one
else:
Value = Config # return the whole configuration if no key
except KeyError:
... | The code compares the current plugin version with a stored version (Ma.Mi.Pa). It checks for major, minor, or patch upgrades, logs updates, executes specific upgrade methods (e.g., `updateTo1()` for major changes), and updates the stored version if the current version is higher. It returns `can_continue` to indicate if... | def checkVersion(self, version):
"""checks actual version against stored version as 'Ma.Mi.Pa' and checks if updates needed"""
#read version from stored configuration
ConfVersion = getConfigItem("plugin version", "0.0.0")
Domoticz.Log("Starting version: " + version )
logging.info... |
def DumpConfigToLog():
Domoticz.Debug("Parameters count: " + str(len(Parameters)))
for x in Parameters:
if Parameters[x] != "":
Domoticz.Debug("' - " + x + "':'" + str(Parameters[x]) + "'")
#Domoticz.Debug("Settings count: " + str(len(Settings)))
#for x in Settings:
# Domoticz... | The code initializes a Tesla plugin by configuring logging based on debug modes, setting up vehicle devices, and initializing the Tesla server. It checks parameters for version compatibility, processes user credentials, location, and polling intervals, then retrieves vehicle data to create and update devices, ensuring ... | def onStart(self):
self.log_filename = "tesla_"+Parameters["Name"]+".log"
Domoticz.Log('Plugin starting')
if Parameters["Mode6"] == "1":
Domoticz.Debugging(2)
#DumpConfigToLog()
Domoticz.Log('Debug mode')
logging.basicConfig(format='%(asctime)s - %... |
def mergePage(self, pageValues, pageNumber):
canvasPage = self.create_canvas_page(pageValues)
leasePage = self._pdfReader.getPage(pageNumber)
leasePage.mergePage(canvasPage)
return leasePage
def getPageOneValues(self):
pageOneValues = []
if self.tenantData:
tr... | The main task of the code is to generate a new PDF by merging specific extracted content from pages 0–5 with the original PDF's pages. It uses `mergePage()` to combine extracted values with target pages, adds remaining original pages, and writes the result to a `BytesIO` byte stream for return. | def save_pdf(self):
self._pdfWriter.addPage(self.mergePage(self.getPageOneValues(), 0))
self._pdfWriter.addPage(self.mergePage(self.getPageTwoValues(), 1))
self._pdfWriter.addPage(self.mergePage(self.getPageThreeValues(), 2))
self._pdfWriter.addPage(self.mergePage(self.getPageFourValues(... |
def get_flows_client(native_client, resource_server, scopes, file_adapter):
return globus_sdk.FlowsClient(
authorizer=get_authorizer(native_client=native_client,resource_server=resource_server,
scopes=scopes,
file_adapter=file_adapter))
def dict_from(json_str_or_file:'str'='') -> 'dict':
... | This script manages Globus flows via command-line actions (create, delete, list). It uses argparse for input parsing, authenticates with Globus SDK, and interacts with the Flows API to create flows (requiring title/definition), delete flows by ID, or list existing flows with their IDs and titles. Error handling and log... | def main():
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=["create", "delete", "list"])
parser.add_argument("-f", "--flow-id", help="Flow ID for delete")
parser.add_argument("-t", "--title", help="Name for create")
parser.add_argument("-d", "--flow-definition", help="JSON ... |
def get_power_consumption(data):
most_common_values = []
least_common_values = []
for x in range(len(data[0])):
column = get_int_column(data, x)
most_common_values.append(get_significant_value(column, most_common=True))
least_common_values.append(get_significant_value(column, most_... | The code tests the correctness of functions calculating power consumption, oxygen rating, CO2 rating, and life support rating from binary data. It verifies that the power consumption is 198, oxygen rating is '10111', CO2 rating is '01010', and life support rating is 230 using predefined assertions. | def test_1():
data = [
"00100",
"11110",
"10110",
"10111",
"10101",
"01111",
"00111",
"11100",
"10000",
"11001",
"00010",
"01010"
]
power_consumption = get_power_consumption(data)
assert 198 == power_consumpt... |
def listenToClient(self, client, address, chunk_server_no, chunk_id, filenaming):
if not os.access(self.filesystem, os.W_OK):
os.makedirs(self.filesystem)
filename = self.filesystem+"/"+filenaming+"_"+chunk_id
# print(filename)
with open(filename, 'wb') as f:
... | This function handles client-server communication by receiving and processing commands. It processes "upload/download" requests from clients, interacts with chunk servers, and facilitates data swapping between servers. It decodes incoming messages, routes tasks to appropriate methods, and manages file transfers via soc... | def commonlisten(self,client,address):
to_recv=client.recv(400).decode("utf-8")
to_recv=to_recv.split(":")
# to_recv=to_recv.split(":")
if(to_recv[0]=="client"):
if(to_recv[1]=="upload"):
chunk_server_no=to_recv[2]
... |
def listentoChunk(self,client,address,filename,chunkNo,recv_port):
chunkNo=int(chunkNo)
cport=chunk_port[self.replica[(filename,chunkNo)][1]-1]
if cport==int(recv_port):
cport=chunk_port[self.replica[(filename,chunkNo)][0]-1]
cport=str(cport)
client.send(bytes(cport,"... | This function handles client-server communication by processing incoming requests. It routes data to appropriate methods based on the 'the_decision' value (chunkserver/client). For clients, it manages file operations (upload/download), lease/unlease control, file listing, and updates. It maintains active chunk servers,... | def commonlisten(self,client,address):
the_decision,one,two,three=client.recv(1024).decode("utf-8").split(":")
if(the_decision=="chunkserver"):
filename=one
chunk__no=two
recv_port=three
self.listentoChunk(client,address,filename,chunk__no,recv_p... |
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
# Check if somebody has won
print("Checking winner;")
if winner(board) is not None:
print("Winner returned true")
return True
print("Winner is None")
# Check if draw by checking for remaining ac... | The function `minimax` determines the optimal action for the current player on a board using the minimax algorithm with alpha-beta pruning. It checks if the board is in a terminal state, returning the utility value if so. Otherwise, it recursively evaluates possible moves by calling the `solve` function, which explores... | def minimax(board):
"""
Returns the optimal action for the current player on the board.
We will have to call the function itself again
"""
# Get the utility for the board
if terminal(board) == True:
return utility(board)
# Get solve with Alpha -20 & Beta 20
action = solve(boar... |
def subtract_min_values(table):
# for i in range(table.spending_matrix_size):
# row_min_value = table.spending_matrix[i][0]
# for j in range(table.spending_matrix_size):
# if row_min_value > table.spending_matrix[i][j]:
# row_min_value = table.spending_matrix[i][j]
# ... | The code solves a transportation or optimization problem using an iterative algorithm. It copies the initial spending matrix, then repeatedly subtracts minimum values, processes cases, and checks for completion. The loop continues until the problem is fully solved, after which it forms the final solution using the init... | def solve_hm_table(table):
initial_spending_matrix = np.copy(table.spending_matrix)
solving_complete = False
iteration = 1
subtract_min_values(table)
while not solving_complete:
print()
print("ITERATION: {}".format(iteration))
iteration += 1
print()
solve_to_... |
def actual(x):
if printout: print("Actual value: ")
f_x = math.log((math.e**x)+2)
if printout: print(f"f({x}) = {f_x}\n")
return f_x
def actual_error(actual, approx):
error = abs(actual - approx)
if printout: print(f"Error = {error}\n")
def lagrange_interpolating_polynomial(approx_x):
n = le... | The main task of the code is to compute and compare the actual error between a function's true value at x=0.25 and approximations generated by various numerical methods, including Lagrange interpolation, Newton's divided differences, Bezier curves, and least squares polynomials. It prints structured outputs with separa... | def main():
global printout
printout = True
line_len = 35
print("-"*line_len)
print("Actual Value")
print("-"*line_len)
f_x = actual(0.25)
print("-"*line_len)
print("Question 1.1-1.2")
print("-"*line_len)
actual_error(f_x, lagrange_interpolating_polynomial(0.25))
prin... |
def get_tables(self):
ws = datagen.Warning_Singleton()
sql = 'SHOW TABLES;'
records = self.runQuery(sql)
if not records:
return None
records = [item[0] for item in records]
return records
def runQuery(self, sql, options={}):
ws = datagen.Warning_Single... | The code lists database tables and their columns based on specified formats (table/json), handling errors and managing database connections. It retrieves table names via `get_tables()`, fetches column details using `DESCRIBE` queries, constructs structured output matrices, and renders results using `list_table()` or `l... | def list(self, options):
"""List tables."""
try:
ws = datagen.Warning_Singleton()
ws.wprint('Listing tables...', 3)
records = self.get_tables()
if not records:
ws.wprint('No tables available', 1)
return
matrix = ... |
def get_tables(self):
ws = datagen.Warning_Singleton()
sql = 'SHOW TABLES;'
records = self.runQuery(sql)
if not records:
return None
records = [item[0] for item in records]
return records
def runQuery(self, sql, options={}):
ws = datagen.Warning_Single... | This code drops specified database tables or views, handling user confirmation, foreign key constraints, and distinguishing between tables and views. It lists tables, checks options for dropping, executes DROP commands, and manages database transactions with rollback on errors, while logging progress and errors. | def drop(self, options = {}):
"""List tables."""
try:
ws = datagen.Warning_Singleton()
ws.wprint('Dropping tables...', 3)
records = self.get_tables()
records = [] if not records else records
tables_to_drop = []
if options['table'] =... |
def load_python_version(self) -> None:
# Retrieve Python Version
try:
self.version = self.config.get("version", "python")
# No Python Version Specified
except configparser.NoSectionError:
self.version = None
self.warnings = True
warning("N... | The code initializes a configuration by verifying the existence of "pyenvsync.ini", parsing it with a case-sensitive parser, and loading Python version, requirements, and environment variables from the configuration file. | def __init__(self) -> None:
# Verify Config File Exists
if not os.path.exists("pyenvsync.ini"):
raise FileNotFoundError("The pyenvsync.ini configuration file was not found.")
# Config Parser
self.config = CaseSensitiveConfigParser()
self.config.read("pyenvsync.ini")
... |
def create_directories():
train_dir = p_join(DATASET_NAME, 'train')
test_dir =p_join(DATASET_NAME, 'test')
val_dir = p_join(DATASET_NAME, 'valid')
os.makedirs(train_dir, exist_ok=True)
os.makedirs(test_dir, exist_ok=True)
os.makedirs(val_dir, exist_ok=True)
def p_join(dir_1, dir_2):
return o... | The code splits a dataset into training, validation, and test subsets based on specified categories. It loads labels, filters accepted categories, divides data, retrieves annotations/images, copies files, and saves structured labels for each subset. | def split_dataset(categories_path):
create_directories()
print('Loading data and dividing...')
train_labels = load_json(p_join(SOURCE_DIR, 'train.json'))
accepted_cats = load_json(categories_path)['categories']
accepted_cats_ids = [item['oldid'] for item in accepted_cats]
val_labels, test_labels... |
def execute(file_path, data):
file_path= file_path.replace(' ', '_')
subprocess.run(['CCExtractor_win_portable\ccextractorwinfull.exe',file_path,'-o','outputfile1.srt'])
srtfilename = "outputfile1.srt"
mp4filename = file_path
count = 0
cap = cv2.VideoCapture(file_path)
... | The code handles a creation request by validating input data, processing file and search parameters, and either executing a file operation or updating DynamoDB based on the presence of a 'searched_key', returning JSON responses for success or errors. | def create(self, request, *args, **kwargs):
json_data = json.loads(request.body.decode('utf-8'))
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
... |
def empty(self): #O(1)
return (self.len == 0)
def listToArray(self): ## O(n logn)
if self.empty():
return None
else:
listArr= ([self.retrieve(i) for i in range(self.length())]) #create an array and use retrieve to hold the values the list elements
return listArr
def mergeSort(arr): ##helper function for... | The code sorts the elements of an AVL tree using merge sort (O(n log n)) and reconstructs a new AVL tree with the sorted elements, returning the newly created tree with elements in ascending order. | def sort(self): #O(n logn)
if self.empty():
return None
T1= AVLTreeList() ## make a copy of the self tree
arr = self.listToArray() ##store sorter list of elements
mergeSort(arr) #use merge sort algorithm which is O(nlogn)
for i in range (len(arr)):
T1.insert(i, arr[i])
return T1 |
def empty(self): #O(1)
return (self.len == 0)
def listToArray(self): ## O(n logn)
if self.empty():
return None
else:
listArr= ([self.retrieve(i) for i in range(self.length())]) #create an array and use retrieve to hold the values the list elements
return listArr
def shuffle(arr): #O(n)
for i in reversed... | The main task of the code is to generate a random permutation of the elements in the AVLTreeList. It converts the current list to an array, shuffles it, and inserts each element into a new AVLTreeList at sequential positions, returning the shuffled tree with O(n log n) time complexity. | def permutation(self): #O(nlogn)
if self.empty():
return None
T1 = AVLTreeList()
arr = self.listToArray()
shuffle(arr) #O(n)
for i in range(len(arr)):
T1.insert(i, arr[i])
return T1 |
def empty(self): #O(1)
return (self.len == 0)
def setRoot(self,node): #O(1)
self.root = node
def getTreeHeight(self):
return self.root.getHeight()
def length(self): # O(1)
if self.getRoot() == None:
return 0
rootNode= self.getRoot()
sizeTree= rootNode.getSize()
return sizeTree
def getRoot(self): #O(1) ... | This code merges two balanced trees into one while maintaining balance. It handles cases where either tree is empty, or when merging based on height differences, inserting nodes appropriately and rebalancing. The function ensures efficient O(log n) operations by updating heights, sizes, and restructuring nodes when nec... | def concat(self, lst): #O(log n)
if (self.empty() and lst.empty()): # both trees are empty
return 0
elif (self.empty()):
self.setRoot(lst.getRoot())
self.len = lst.length()
return abs(self.getTreeHeight() - (-1))
elif (lst.empty()):
return abs(self.getTreeHeight() - (-1))
lstHeight = lst.getTre... |
def run_insertions():
res = []
trees = []
for i in range(1, 11):
T = AVLTreeList() # create a tree object
total = 0
curr = 0
for j in reversed(range(1, 1500 * (2 ** i))):
num = rd.randrange(0, j)
output = T.insert(curr, num)
total += outp... | The main task of the code is to execute insertion, deletion, and alternating insertion-deletion operations, then compile the results into an Excel file for data analysis or reporting. | def main():
insertion_lst = run_insertions()
deletion_lst = run_deletions(insertion_lst[1])
alternate_insertion_deletion_lst = run_insertions_deletions_alternately()
create_excel_file(insertion_lst, deletion_lst, alternate_insertion_deletion_lst)
pass |
def fetchPlayerKeyMap() -> pd.DataFrame:
# check to see if mtblKeyMap.json exists before proceeding
# if it does, then read it in and return it
# if it doesn't, call subprocess and write it out to a json file
# then return the dataframe
filename = "mtblKeyMap.json"
try:
keyMap = os.path.... | The main task of the code is to retrieve and process fantasy baseball player data from ESPN for a specific league (ID 10998). It checks for a local HTML file containing player data, downloads it if missing, maps player keys using a predefined key map, constructs a player universe dataset, and cleans up temporary files.... | def main():
leagueID = "10998"
espnPlayerRaterURL = "https://fantasy.espn.com/baseball/playerrater?leagueId=" + leagueID
print("\n---Running Fantasy Data Getter---\n")
dfKeyMap = fetchPlayerKeyMap()
# check to see if tempESPNPlayerRater.html exists; if not, download it
if not os.path.exists("t... |
def num_feature(data):
num_feature = [feature for feature in data.keys()]
for feature in data.keys():
for value in data[feature]:
if type(value) == str:
num_feature.remove(feature)
break
return num_feature
def min_max_method(feature):
for value in feat... | The code normalizes a specified numerical column in a dataset using either min-max scaling or z-score normalization. It validates the column's numerical type and the method's validity, applies the chosen normalization, and prints the adjusted maximum and minimum values of the normalized column. | def normalize(data, column, method):
num_attr = num_feature(data)
if column not in num_attr:
raise ValueError('Column must be numerical')
if method == 'min-max':
data[column] = min_max_method(data[column])
print(max(data[column]), min(data[column]))
elif method == 'z-score':
... |
def getServer(name=""):
if name == "":
return PlexServer(token=admin_token)
else:
server = PlexServer(token=admin_token)
try:
user = server.myPlexAccount().user(name)
except NotFound:
return None
return PlexServer(token=user.get_token(server.machin... | The code interacts with a Plex server to select a show's season and apply specified audio/subtitle tracks. It validates a username, prompts for library selection, retrieves a show, lets the user choose seasons, and applies provided track IDs to process media. | def main():
# Usage: python3 [?username]
username = "" if len(sys.argv) < 2 else sys.argv[1]
plex = getServer(username)
if plex is None:
print("Invalid username: %s" % username)
print("Valid Users: \nBlank for admin")
for user in MyPlexAccount(admin_token).users():
p... |
def getServer(name=""):
if name == "":
return PlexServer(token=admin_token)
else:
server = PlexServer(token=admin_token)
try:
user = server.myPlexAccount().user(name)
except NotFound:
return None
return PlexServer(token=user.get_token(server.machin... | The code interacts with a Plex server to process TV show seasons. It retrieves user credentials, selects a show library, chooses a specific show, and processes its seasons (all or specific) with user-selected audio preferences (subtitles or dubbed). It handles input validation and user prompts for library, show, season... | def main():
# Usage: python3 [?username]
username = "" if len(sys.argv) < 2 else sys.argv[1]
plex = getServer(username)
if plex is None:
print("Invalid username: %s" % username)
print("Valid Users: \nBlank for admin")
for user in MyPlexAccount(admin_token).users():
p... |
def get_grid_string(lines):
res = ''
for line in lines:
for c in line:
res += c
res += '\n'
return res[:-1]
def do_cycle(lines):
shift(lines, read_column, write_column)
shift(lines, read_row, write_row)
shift(lines, read_column, write_column, reverse=True)
shift(l... | The main task of the code is to determine the grid state at a specific target cycle by detecting repeating patterns. It tracks encountered grid states, identifies the first occurrence of a cycle, calculates the cycle length, and then uses this to efficiently find the grid state at the target cycle without simulating al... | def part_two(grid):
seen_positions = {get_grid_string(grid): 0}
cycle_count = 0
for i in range(1, TARGET_CYCLE):
cycle_count += 1
do_cycle(grid)
grid_string = get_grid_string(grid)
if grid_string in seen_positions:
break
else:
seen_positions[gr... |
def __extract_text(params: dict) -> str:
""" Extract data from the document and convert it to a string. """
file_path = params['input_file'] # filepath to the file
method = 'PDF_T' if '.pdf' in file_path else 'DEFAULT'
processed_text = TextExtractor(file_path=file_path, method=method)... | The main task of the code is to initialize an Extractor class by extracting structured data from a document. It processes the input document to extract text, divides it into sections, and applies regex rules to extract demographics, emergency data, and medicines. Errors during extraction are logged, and failed data fie... | def __init__(self, **kwargs) -> None:
""" Initializing the Extractor by passing document. """
self.file_path = None # file path of the document passed
try:
self.text = self.__extract_text(kwargs) # text extracted from file
logger.info(f'EXTRACTED TEXT : {self.text}')... |
def createtelegramurl(self, method, parameters={}):
# Define api url
turl = "https://api.telegram.org/bot{}/{}".format(
self.apikey, method)
# Add parameters to the api url
if len(parameters.keys()) != 0:
turl = turl + "?"
for parameter in parameters.... | This function sends a photo to a Telegram channel with a caption. If the photo format is invalid, it falls back to sending the caption as text. It constructs a Telegram API URL, attempts to send the photo, and handles errors by sending text if the 'BadFormat' error occurs and 'backuptotext' is True. | def sendphoto(self, photo, caption, parsemode="HTML", backuptotext=True):
method = 'sendPhoto'
parameters = {
"chat_id": self.telegramchannel,
"caption": caption,
"photo": photo,
"parse_mode": parsemode
}
url = self.createtelegramurl(method... |
def reset():
global symbol_table,operand_table,literal_table,extenal_varibles,pass1_code,pass2_code,relocation_table
global counter,counterloop,counterif,counterEndIf
symbol_table = {}
operand_table = {}
literal_table = {}
extenal_varibles = {}
pass1_code = []
pass2_code = []
reloc... | The main task of the code is to assemble an assembly language file into machine code by processing it through two passes. It initializes operand tables, generates start/stop code, assembles the file, and returns symbol tables, literal tables, external variables, relocation tables, and code from both passes for further ... | def get_results(filename,opcodes):
global operand_table
reset()
operand_table = opcodes
generate_start_code()
assemble_file(filename)
generate_stop_code()
pass2_assemble()
return symbol_table,literal_table,extenal_varibles,relocation_table,pass1_code,pass2_code,counter |
def get_name(array1, array2, searchitem):
i = 0
while i < len(array1):
if array1[i][1] == searchitem:
return array1[i][0]
i += 1
i = 0
while i < len(array2):
if array2[i][1] == searchitem:
return array2[i][0]
i += 1
def divide_into_nd_plot(triangle... | The code generates a hexagonal grid around a specified geographic location using H3 indexing, plotting Distribution Centers (DCs) and Facilities on a Folium map. It creates triangular "Zero-Level Plots" (ZLPlots) connecting DCs/Facilities, saves their coordinates to CSV files, and defines impact zones. The grid alterna... | def plotNumberedGridKMNew(latitude, longitude, radius, n, zoomlevel, zlplotlabel, kring):
""" Determine H3 resolution """
n_to_granularity=[9,8,8,8,7,6,6,6,5,4,3,3,3,2,1,1,1,0]
granularity = n_to_granularity[n];
start_coords = (latitude, longitude)
""" Initialize Map """
folium_map = folium... |
def fix_case(input, firstUpper = True):
output = re.sub(r'(?!^)-([a-zA-Z0-9])', lambda m: m.group(1).upper(), input)
output = re.sub(r'(?!^)_([a-zA-Z0-9])', lambda m: '_' + m.group(1).upper(), output)
if firstUpper:
return ''.join(output[0].upper() + output[1:])
return output
def mkpath(name):
... | The main task of the code is to generate C# files (.cs) for each definition in the input data, creating either enum or struct files based on the definition type, under the specified folder and namespace. It ensures the folder exists, constructs filenames, and writes appropriate code using helper functions `generate_enu... | def generate_defintions(info, folder, namespace):
for definition in info["definitions"]:
name = fix_case(definition["name"])
filename = folder + name + ".cs"
mkpath(folder)
file = open(filename, "wt")
# basic include and namespace
if definition["isEnum"]:
... |
def warm_up(self):
"""
Run the camera to allow exposure adjustment
"""
for frame in range(25):
frames = self.device_manager.poll_frames()
time.sleep(0.1)
def save_intrinsics(self, directory, frames_devices):
"""
Write the intrinsic parameters of ea... | Your returnThe code initializes and configures RealSense cameras for streaming, recording, or snapshots. It sets resolution, frame rate, display/record flags, manages specified devices, validates parameters, configures output directories, warms up cameras, saves intrinsics if needed, and starts streaming or snapshot mo... | def __init__(self, width, height, fps, flip, display, record, lab_monitor, specified_devices,
snapshot_timer, num_snapshots, snapshot_interval, snapshot_mode, save_params):
"""
Manage the RealSense output streams
"""
self.width = width # Resolution
self.height =... |
def handle_video(self, info, req: UfysRequest):
if direct_url := info.get("url"):
return self.handle_direct_url(direct_url, info)
return self.reupload(req.url, req.hash)
def handle_direct_url(self, url: str, info):
if not (width := info.get("width")) or not (height := info.get("heig... | This function processes media requests by extracting information from a URL using YTDLP. It determines if the content is a video or playlist. For videos, it delegates to handle_video. For playlists, it checks entries: if empty, returns an error; if a direct URL exists, processes it; otherwise, attempts the original URL... | def handle_request(self, req: UfysRequest) -> UfysResponse | UfysError:
info = self.ytdl.extract_info(req.url, download=False)
type_ = info.get("_type", "video")
if type_ == "video":
return self.handle_video(info, req)
if type_ == "playlist":
entries = info.get("e... |
def compute_1d(books):
return sum(books)
def compute_2d(books):
books = sorted(books)[::-1]
price = [[-1] * (books[1]+1) for _ in range(books[0]+1)]
v = [0] * 3
for i in range(books[0]+1):
price[i][0] = i
for j in range(books[1]+1):
price[0][j] = j
for i in range(1, books[0]+... | The function `total(arr)` calculates a value based on the input array's dimensions. It initializes a counter array `books` with zeros, then counts element frequencies. Depending on the array's range (dimension), it applies corresponding `compute_nD` functions (1D–5D) to process the counts, multiplies the result by 800,... | def total(arr):
if len(arr) == 0:
return 0
books = [0] * max(arr)
for el in arr:
books[el-1] += 1
if len(books) == 1:
return round(compute_1d(books) * 800)
elif len(books) == 2:
return round(compute_2d(books)[-1][-1] * 800)
elif len(books) == 3:
return rou... |
def slide(line: []):
sections = "".join(line).split("#")
slide_result = ""
for section in sections:
mirror_count = section.count('O')
slide_result += "".join(["O" * mirror_count])
slide_result += "".join(["." * (len(section) - mirror_count)])
slide_result += "#"
return ... | The code processes a grid representing a platform with rocks, calculating the total weight after sliding rocks in each row. It detects repeating platform states to identify cycles, then uses cycle properties to compute the weight after 1,000,000,000 cycles efficiently. It outputs the initial total weight (part 1) and t... | def main():
platform = fh.readFileAsMatrix("Inputs/Day14.txt", True)
rotate = platform.T
total = 0
for line in rotate:
slide_result = slide(line.tolist())
total += weight(slide_result)
counter = 1
platforms_as_bytes = []
weights = []
while True:
platform = cyc... |
def read_sets_from_file(file_path, split_at = None, convert_to_int = False):
parsedLines = []
set = []
with open(file_path) as f:
lines = f.readlines()
for line in lines:
line = line.strip()
if line == "":
parsedLines.append(set)
set ... | The code processes patterns from a file to compute two totals related to mirror symmetries. For each pattern, it identifies vertical/horizontal mirrors using `find_mirror`, contributing to `total` (weighted by axis) and `total2` via `iter_set`. The task involves summing these values for all patterns, with part 1 emphas... | def main():
patterns = read_sets_from_file("Day13.txt")
total = 0
total2 = 0
for pattern in patterns:
np_set = np.array([[char for char in item] for item in pattern])
default_pattern = find_mirror(np_set)
total += default_pattern[1] if default_pattern[0] == Axis.Vertical else 10... |
def is_train_test_file_exists (self)->bool:
try:
logging.info("checking to see if train and test file is available")
is_train_file_exist =False
is_test_file_exist = False
train_file_path = self.data_ingestion_artifact.train_file_path
test_file_path=... | The code performs data validation by checking the existence of train/test files, validating the dataset schema, and detecting data drift. If successful, it creates and returns a `DataValidationArtifact` with file paths and validation status. Exceptions trigger a `HousingException` with error details. | def initiate_data_validation(self)-> DataValidationArtifact:
try:
self.is_train_test_file_exists()
self.validate_dataset_schema()
self.is_data_drift_found()
data_validation_artifact = DataValidationArtifact(schema_file_path= self.data_validation_config.schema_fil... |
def A(self, w=None):
"""State space matrix for an instance of a rotor.
Returns
-------
State space matrix for the rotor.
Examples
--------
>>> rotor = rotor_example()
>>> np.round(rotor.A()[50:56, :2])
array([[ 0., 11110.],
[-... | This method constructs a continuous-time linear time-invariant (LTI) system for a multi-degree-of-freedom (MDOF) system using state-space representation. It derives matrices A, B, C, D from the system's mass (M), stiffness (K), and damping (C) matrices. The LTI system enables analysis of dynamic behavior, including pol... | def _lti(self):
"""Continuous-time linear time invariant system.
This method is used to create a Continuous-time linear
time invariant system for the mdof system.
From this system we can obtain poles, impulse response,
generate a bode, etc.
"""
Z = np.zeros((self... |
def fill_dia(bo):
i = 0
while i < 9:
fill_box(bo, i, i)
i = i + q
def fill_body(bo, i, j):
if j >= 9 and i < 8:
i = i+1
j = 0
if i >= 9 and j >= 9:
return True
if i < q:
if j < q:
j = q
elif i < (9-q):
if j == int(i/q)*q:
... | The code's main task is to fill a Sudoku board's diagonal and main body with values, then remove 'k' digits to create a puzzle. It uses 'fill_dia' for diagonals, 'fill_body' to populate the grid, and 'remove_digi' to erase 'k' entries, preparing a solvable Sudoku challenge. | def fill_values(bo, k):
fill_dia(bo)
fill_body(bo, 0, q)
remove_digi(bo, k) |
def parse_game_meta_data_string_to_columns(df: pd.DataFrame) -> pd.DataFrame:
"""
Split string column with misc game dataframe 'df' into separate columns
Apply correct column names
Sort by date
Convert string columns with bool values to bool
df : input dataframe
return : parsed dataframe
... | The code reads and processes chess game data from a CSV file, cleans and transforms the data, extracts game statistics, and visualizes specific metrics like captures. It handles data in chunks for testing or full processing, parses metadata, standardizes move formats, removes invalid entries, and generates statistical ... | def main():
print(f"Reading file '{FILE_PATH_CHESS_DATA}'...")
chunk_reader = pd.read_csv(
FILE_PATH_CHESS_DATA,
skiprows=4,
sep='###',
engine='python',
chunksize=CHUNK_SIZE)
n_rows_to_process = CHUNK_SIZE
if TESTING:
games = pd.DataFrame(chunk_reader.ge... |
def push(self,value):
self.temp.append(value)
self.top += 1
def isEmpty(self):
return True if self.top == -1 else False
def peek(self):
return self.temp[self.top] if not self.isEmpty() else None
def pop(self):
if self.top !=-1:
self.top -=1
return self.tem... | This code converts an infix mathematical expression to postfix notation (Reverse Polish Notation) using a stack. It processes each character: operands are added directly to the output, parentheses control stack operations, and operators are pushed after popping higher-precedence operators from the stack. Finally, remai... | def infixToPostfix(self,exp):
for i in exp:
if i.isalpha():
self.output.append(i)
elif i =='(':
self.push(i)
elif i == ')':
while(not self.isEmpty() and self.peek() != '('):
self.output.append(self.pop())
... |
def push(self,value):
self.temp.append(value)
self.top += 1
def isEmpty(self):
return True if self.top == -1 else False
def peek(self):
return self.temp[self.top] if not self.isEmpty() else None
def pop(self):
if self.top !=-1:
self.top -=1
return self.tem... | This function converts an infix expression to prefix notation using a stack. It processes the input in reverse, handling operands, parentheses, and operators by pushing/popping from the stack based on precedence. The final output is reversed to form the prefix expression. | def infixToPrefix(self,exp):
for i in exp[::-1]:
if i.isalpha():
self.output.append(i)
elif i ==')':
self.push(i)
elif i == '(':
while(not self.isEmpty() and self.peek() != ')'):
self.output.append(self.po... |
def make_output_dir(out_dir):
if not os.path.exists(out_dir):
os.makedirs(out_dir)
def untar(tar_file, out_dir, out_name=None, gzip=True):
mode = 'r:gz' if gzip else 'r'
with tarfile.open(tar_file, mode) as tar:
tar.extractall(path=out_dir)
if out_name:
if os.path.exists... | The code processes a dataset by extracting files from tar archives, validating their existence, creating output directories, processing data, splitting it into training/validation sets, and cleaning up temporary files, using command-line arguments for configuration and ensuring reproducibility via a random seed. | def main():
args = parser.parse_args()
# Set the random seed for reproducible experiments
random.seed(args.seed)
origin_tar = os.path.join(args.dataset, 'origin.tar')
assert os.path.exists(origin_tar), f'{origin_tar} does not exist.'
assert os.path.isfile(origin_tar), f'{origin_tar} is not a f... |
def __rds_connect(self):
self.conn = None
try:
print('Connecting to PostgreSQL / RDS...')
self.conn = psycopg2.connect(sslmode='require', sslrootcert="./global-bundle.pem", **self.rds_params)
print('Connected OK - now trying to create the engine')
self.eng... | The code's main task is to iterate through all campsites from a search, saving their details and images to both a cloud database (RDS) as JSON and the local filesystem. It tracks progress using a progress bar, processes each campsite via a helper method, and ensures all data is stored before closing the progress tracke... | def save_all_campsite_data(self):
"""Iterate through all campsites found in search, and save details and images to cloud (json) and local filesystem (images)."""
saved_count = 0
self.__rds_connect()
self.progress = tqdm(total=self.campsite_count)
for campsite in self.campsite_lin... |
def print_rules():
'''
The function welcomes the players by printing a welcome statement and the rules.
the function returns the welcome statement.
'''
welcome = print("Hello players, Welcome to Dice-Life:\n Rules\n 1. The game can be played by more than 1 player.\n 2. The players are allowed to rol... | The main task of the code is to simulate a turn-based game (likely involving dice rolls) between a computer and a human player, logging each move, scores, and game status into a text file. It initializes game rules, collects player names, alternates turns, tracks progress, and records the final result once the game con... | def main():
with open("template_behavior_{dice}.txt", "a") as f:
# Variables
trigger = 6
run = True
# Welcome players and inform them of the rules
welcome = print_rules()
print(welcome, file = f)
# Printing out the names of the players
player = no_of_... |
def displayAllFicsInFandom(fandom):
fQuery = getAllFicsInFandomQuery(fandom)
displaySearchResults(fQuery, fandom)
def displayOnlyCompletedFics(fandom):
fQuery = getOnlyCompletedFicsInFandomQuery(fandom)
displaySearchResults(fQuery, fandom)
def displayFicsAccToCateg(fandom, categ):
fQuery = getAllFic... | The main task of the code is to present a menu of options for users to select how they want to view fanfiction entries (fics), such as by category, author, genre, or other filters. It captures user input and executes the corresponding function to display fics based on the selected option, with error handling for invali... | def displayOptions():
click.echo('Choose an option from the list:')
click.echo('Type 1 to Display all fics')
click.echo('Type 2 to Display all completed fics')
click.echo('Type 3 to Display all fics for a particular category/folder')
click.echo('Type 4 to Display all fics for a particular author')
... |
def main():
Art = text2art("PieOrg", font='block', chr_ignore=False)
click.echo(Art)
click.echo('Welcome to PieOrg, your story organiser!\n\n')
def showInsertOption():
insertFic()
def showEditOption():
editOptions()
def showDisplayOption():
displayOptions() | The code's main task is to execute the `main()` function and then route the user to specific options based on the input parameter `a`. If `a` is 'i' or 'I', it calls `showInsertOption()`; if 'e' or 'E', `showEditOption()`; and if 'd' or 'D', `showDisplayOption()`. This structure allows the program to handle user-driven... | def begin(a):
main()
if a == 'i' or a == 'I':
showInsertOption()
elif a == 'e' or a == 'E':
showEditOption()
elif a == 'd' or a == 'D':
showDisplayOption() |
def years(self) -> int:
return self.total_days() // 365
def months(self) -> int:
month_diff = self.today.month - self.birthday.month
if month_diff < 0:
month_diff = month_diff + 12
return month_diff
def days(self) -> int:
day_diff = self.today.day - self.birthday.day
... | This method calculates and returns an object's age in various time units, including years, months, days, and aggregated totals like weeks, hours, minutes, and seconds. It also includes the weekday of the birthday, providing a comprehensive time-based age breakdown. | def age(self) -> dict:
return {
"year": self.years(),
"months": self.months(),
"days": self.days(),
"as_year": self.years(),
"as_months": self.total_months(),
"as_weeks": self.total_weeks(),
"as_days": self.total_days(),
... |
def load_page(self) -> None:
"""Load the base URL into the web driver."""
self.driver.get(self.base_url)
def cookie_trust_handle(self) -> None:
"""
Attempt to handle and dismiss the cookie trust (consent) element.
"""
try:
WebDriverWait(self.driver, timeout=10... | This code runs a web scraper for a specified duration, loads a page, handles cookies, retrieves root categories, and processes them recursively. A timer thread enforces the time limit by triggering cancellation if exceeded. It manages threads, halting execution upon shutdown signal or task completion, ensuring all back... | def run(self, time_limit=60) -> None:
"""
Run the scraper for a given time limit.
:param time_limit: The maximum time to run the scraper in seconds.
"""
self.load_page()
self.cookie_trust_handle()
root_categories = self.get_category_root()
def ti... |
def try_get_item_paginator(self) -> Optional[str]:
"""
Attempt to find the URL for the next page of items.
:return: The URL of the next page or None if not found.
"""
try:
return self.driver.find_element(By.XPATH, '//link[contains(@rel, "next")]').get_attribu... | This function recursively scrapes paginated items from a specified category by navigating through page links, extracting item elements, processing each item's shops, and handling errors or shutdowns. It returns True on success or False if no items are found, pages end, or exceptions occur. | def try_get_page_items_recursive(self, category: Category, paginatorNext: str) -> bool:
"""
Attempt to recursively navigate and scrape items from paginated pages.
:param category: The category for which to scrape paginated items.
:param paginatorNext: The URL of the next page to... |
def try_get_item_paginator(self) -> Optional[str]:
"""
Attempt to find the URL for the next page of items.
:return: The URL of the next page or None if not found.
"""
try:
return self.driver.find_element(By.XPATH, '//link[contains(@rel, "next")]').get_attribu... | This method extracts items from a category's webpage sequentially without concurrency. It navigates to the category URL, retrieves item elements, processes each item to get shop details, and handles pagination recursively. Returns a list of Item objects or None if the operation fails or is interrupted by a shutdown fla... | def get_page_items_root(self, category: Category) -> Optional[List[Item]]:
"""
Extract items from the category's page without using concurrency.
:param category: The category from which to extract items.
:return: A list of extracted Item objects or None if the operation failed.
... |
def get_category_elements(self, parent: Optional[Category]) -> Optional[List[Category]]:
"""
Get category elements from a given parent category.
:param parent: The parent category to search within.
:return: A list of Category objects or None.
"""
try:
... | This function recursively scrapes categories starting from a parent category by navigating its URL, retrieving subcategories, and processing items either concurrently or sequentially based on settings. It returns True on success, False on errors like missing URLs or exceptions, logging issues and halting if the scraper... | def try_get_category_recursive(self, parent: Category) -> bool:
"""
Attempt to recursively navigate and scrape categories starting from the parent.
:param parent: The parent category from which to begin scraping.
:return: True if successful, False otherwise.
"""
... |
def _build_encoder(self):
encoder_input = self._add_encoder_input()
conv_layers = self._add_conv_layers(encoder_input)
bottle_neck = self._add_bottleneck(conv_layers) #return the whole graph of layers
self._model_input = encoder_input
self.encoder = Model(encoder_input, bottle_ne... | The main task of the code is to construct components of a neural network model by initializing an encoder, decoder, and autoencoder. The `_build` method orchestrates this process by sequentially calling `_build_encoder` for the encoder, `_build_decoder` for the decoder, and `_build_autoencoder` to assemble the full aut... | def _build(self):
self._build_encoder()
self._build_decoder()
self._build_autoencoder() |
def get_all_csv_files(run_index: int):
files: list[str] = [file for file in os.listdir(PATH) if file.endswith(".csv")]
router_file: str = [file for file in files if "router" in file][0]
files.remove(router_file)
return [file for file in files if str(run_index) in file.split("_")[-1]], router_file
def ... | The code processes CSV files to analyze and visualize router logs. It retrieves files, trims the router log data, prints the resulting DataFrame, and generates a graph to represent the processed router information. | def run():
files, router_file = get_all_csv_files(RUN_INDEX)
if files and router_file:
router_df = trim_router_log(files[0], router_file)
print(router_df)
plot_router_graph(router_df) |
def get_message_content(self, message):
"""
Returns a string containing the text of a message typed by the user.
The returned message will be converted to lowercase.
Any unneeded punctuation will be removed.
Returns an empty string if the message was sent by Jarvis.
This ... | The code handles user messages to control a bot's behavior, switching between training, testing, and gameplay modes. It processes commands like "training time," "testing time," and "load brain" to initiate learning or testing phases, while "battleship time" triggers a turn-based game where the bot manages ship placemen... | def on_message(self, message):
"""Controls a bot's response to receiving a message."""
message_content = self.get_message_content(message)
# check if training should start
if 'training time' in message_content:
self.action = 'training'
self.send_message("OK, I'm... |
def get_filenames():
"""Get external data files"""
filenames = []
for filename in glob.glob(PATTERN):
filenames.append(filename)
return filenames
def read_file(filename):
"""This function uses the json_read and csv_read functions to read in the
data from both types of files and returns t... | The code compares the accuracy of multiple brain models trained on different datasets by testing each model against all files, calculating average accuracy, and plotting results. It also evaluates a model trained on a specific database (DB_data) and prints its accuracy against the same test files. | def compare_accuracy():
"""Determine accuracy of brain"""
percents = []
all_percents = []
db_accuracy = []
i = 0
for filename in get_filenames():
print(i)
i += 1
data = read_file(filename)
data = list(zip(*data))
brain = fit_brain(data)
if not brai... |
def DB_data():
"""Get data from our database"""
connection = sqlite3.connect(DATABASE_FILE_PATH)
cursor = connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS training_data "
"(txt text, action text)")
# load the data from the database
cursor.execute("SELECT * fr... | The main task of the code is to evaluate how model accuracy improves as the size of training data increases. It iteratively expands the training dataset by adding random files, trains a model, tests its accuracy on all files, records accuracy metrics at each size, and plots the relationship between training data size a... | def compare_sizes():
"""Grow size of training data and test for accuracy on each size"""
data = DB_data()
filenames = get_filenames()
sizes = []
data_names = []
percent = []
percents = []
#grow size of training data
while len(data[0]) < 1000:
brain = fit_brain(data)
... |
def on_message(self, message):
"""Controls a bot's response to receiving a message."""
message_content = self.get_message_content(message)
# check if training should start
if 'training time' in message_content:
self.action = 'training'
self.send_message("OK, I'm... | This function initializes a Slack Real-Time Messaging (RTM) connection using a WebSocket. It constructs a connection URL with an API token, sets up event handlers for messages, errors, and connection closure, and returns the WebSocket instance for real-time communication with Slack. | def initialize_slack_connection(self):
"""This function connects Jarvis to Slack over the RTM API."""
# get the url string
connect_string = f"http://slack.com/api/rtm.connect"
url_string = requests.get(connect_string,
params={'token': API_TOKEN}).json()... |
def get_model(self):
"""Returns the model used in Jarvis' brain."""
pipeline = Pipeline([
('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('clf', SGDClassifier()),
])
params = {
'vect__ngram_range': [(1, 1), (1, 2)],
... | The code initializes a Battleship game environment by setting up attributes for game state management, including a classifier model, database connections, Slack communication, game boards (guess, Jarvis, and player), boat placements, and game control variables. It prepares the system to handle player interactions, trac... | def __init__(self):
self.action = ""
self.channel = ""
self.classifier = self.get_model()
self.db_connection, self.db_cursor = self.initialize_database()
self.ws_connection = self.initialize_slack_connection()
self.play_game = False
self.boats = {'battleship': 0, ... |
def incident_field_camera_plane(nm, nm_obj, nm_img, lamb, mpp, NA, M, z):
"""Calculate the incident field in the camera plane."""
# Devise a discretization plan.
mpp_r, Np, Nq, p, q = discretize_plan(NA, M, lamb, nm_img, mpp)
# Necessary constants.
k_med = 2*np.pi*nm*mpp_r/lamb # [pix**-1]
... | The function simulates the image formed in a camera plane by a spherical scatterer, considering optical parameters like refractive indices, numerical aperture (NA), wavelength, and magnification. It calculates the incident field and the scatterer's field, combines them to generate the image, and optionally crops it. Th... | def image_camera_plane(z, a_p, n_p, nm, nm_obj=1.5, nm_img=1.0, NA=1.45,
lamb=0.447, mpp=0.135, M=100, dim=None,
quiet=True):
'''
Returns an image in the camera plane due to a spherical scatterer with
radius a_p and refractive index n_p at a height z above th... |
def get_img_for_user(dataset, user):
user_json_path = "left_imgs_non_inter_agreement/left_imgs_" + user + ".json"
with open(user_json_path) as f:
left_imgs_parsed_json = json.load(f)
imgs_for_dataset = left_imgs_parsed_json[dataset]
img = {}
if(len(imgs_for_dataset) != 0):
img["file_... | The main task of the code is to retrieve an image for the current user from specified storage directories based on the dataset and dataset_type, encode it in base64, and return it as a JSON response. It handles different dataset types (e.g., "vehicles", "kitti", "eurocity") by searching for the image file in the approp... | def get_img_from_storage(dataset, dataset_type):
try:
print("Getting image for user " + current_user.name)
if(dataset_type == "vehicles"):
img = get_img_for_user(dataset, current_user.name)
else:
img = get_img(dataset, dataset_type, current_user.name)
imgs_pat... |
def remove_img_from_user_list(dataset, img_name, user):
print("Removing image from pending list")
user_json_path = "left_imgs_non_inter_agreement/left_imgs_" + user + ".json"
with open(user_json_path) as f:
left_imgs_parsed_json = json.load(f)
imgs_for_dataset = left_imgs_parsed_json[dataset]
... | This function processes and saves edited JSON annotations by updating database entries, modifying JSON files, and handling sweep data for a specified image and dataset type. It removes the image from a user list if the dataset is "vehicles", retrieves edited JSON data, updates the database with new annotations, and adj... | def save_edited_json(img_name, dataset_type, annotator, selected_dataset):
if (dataset_type == "vehicles"):
remove_img_from_user_list(selected_dataset, img_name, annotator)
# POST request
edited_json = request.get_json()
dict_of_agents = create_edited_agents(edited_json)
edit_db_entry =... |
def download_command(message):
text = get_text(message)
if not text:
bot.reply_to(
message, 'Invalid usage, use `/download url`', parse_mode="MARKDOWN")
return
log(message, text, 'video')
download_video(message, text)
def download_audio_command(message):
text = get_text(... | The function restricts access to commands by checking if a user has started the bot and joined required channels. If not, it prompts them to use `/start` and join channels. Otherwise, it processes commands like `/download`, `/audio`, or `/custom` by calling respective functions. | def restrict_commands(message):
user_id = message.from_user.id
if not user_started.get(user_id) or not user_joined_channels.get(user_id):
bot.reply_to(message, "You must run the `/start` command and join the required channels before using other commands.")
else:
# Handle other commands as us... |
def set(self, AudioOffset='0', TimingPointDensityFactor='1', Elements=[], TimingGroups = []):
self.AudioOffset = AudioOffset
self.TimingPointDensityFactor = TimingPointDensityFactor
self.Elements = Elements
self.TimingGroups = TimingGroups
def lex_timing_group(s):
if not "timinggroup... | This code parses an input string (AffStringLine) by splitting it into timing groups and elements. It extracts header parameters like AudioOffset and TimingPointDensityFactor, processes each element line using lex_main_line, and counts valid elements. The function stores parsed data in instance variables and outputs the... | def load(self, AffStringLine):
t=0
self.set()
headers = []
elements = []
timinggroups = []
# pre-process the timinggroup
timinggroupSplitted = AffStringLine.split("timinggroup")
for i in range(1, len(timinggroupSplitted)):
news = "timinggroup"... |
def __has_https__(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(HTTPSInspector.TIMEOUT_LIMIT)
try:
sock.connect((self.__url_hostname, HTTPSInspector.DEFAULT_HTTP_PORT))
sock.shutdown(socket.SHUT_RDWR)
return True
excep... | This method inspects HTTPS configurations by checking for HTTPS presence, forced HTTP-to-HTTPS redirects, domain consistency of redirects, security headers, certificate details, protocol support, and vulnerabilities. It disables SSL warnings, updates internal flags, and returns the instance for method chaining. | def inspect(self):
urllib3.disable_warnings()
if self.__has_https__():
self.__has_https = True
if self.__has_forced_redirect_from_http_to_https__():
self.__forced_redirect_to_https = True
if self.__is_forced_redirect_to_same_domain__(self.__locati... |
def __get_X_y(self):
""" Return None
Updates class properties X_features and y_features
with appropriate series values
Private Method
"""
w = self.rolling_window_size
features_df = { 'BB_RATIOS' : self.__get_bollinger_ratios(),
'SMA_R... | The code generates a JSON dictionary containing technical analysis and prediction data for stocks, including Bollinger Bands, momentum, SMA ratios, normalized values, and training/test data. It compiles features, predictions, and statistical metrics into a structured format for financial analysis. | def get_json(self):
""" Retrun Dict of stocks exploration
Public method used to get all the stocks
exploration and predictions.
Data returned:
'Symbol'
'BB_Ratios'
'Momentum'
'SMA_Ratios'
'SMA'
... |
def changeAdminValues(self, isAdmin):
self.btnFixImg.setEnabled(isAdmin)
self.btnAddRace.setEnabled(isAdmin)
self.btnAddResult.setEnabled(isAdmin)
self.btnAlterResult.setEnabled(isAdmin)
self.btnDeleteResult.setEnabled(isAdmin)
self.btnLogs.setEnabled(isAdmin)
def defineA... | The code initializes a GUI application by loading a Qt Designer UI, connects database parameters, handles connection errors, sets up UI elements with event handlers, and populates initial data like tracks, drivers, and teams. It prepares the interface for managing races, results, and standings while handling user inter... | def __init__(self):
"""
Initialize the main window.
"""
super().__init__()
loadUi("dab2.ui", self)#Load Ui from the Qt Designer
try:
self.database = Database(self.leHost.text(), self.leUser.text(), self.lePassword.text(), self.leDatabase.text())
... |
def changeAdminValues(self, isAdmin):
self.btnFixImg.setEnabled(isAdmin)
self.btnAddRace.setEnabled(isAdmin)
self.btnAddResult.setEnabled(isAdmin)
self.btnAlterResult.setEnabled(isAdmin)
self.btnDeleteResult.setEnabled(isAdmin)
self.btnLogs.setEnabled(isAdmin)
def loadTra... | The `login` method attempts to establish a database connection using input fields, handles exceptions by displaying errors, and if successful, initializes UI components like tracks, drivers, teams, and standings. | def login(self):
self.database = None
try:
self.database = Database(self.leHost.text(), self.leUser.text(), self.lePassword.text(), self.leDatabase.text())
self.changeAdminValues(self.database.isAdmin())
except Exception as e:
msg = QMessageBox()
m... |
def dither(self, wav):
n = 2*np.random.rand(wav.shape[0])-1
n *= 1/(2**15)
return wav + n
def pre_emphasize(self, wav):
# apply pre-emphasis filtering on waveform
preemph_wav = np.append(wav[0], wav[1:] - self.preemphasis * wav[:-1])
return preemph_wav
def wav_to_frames(s... | The code processes an audio utterance by applying dithering, pre-emphasis, and converting it into filter bank (fbank) features through spectrogram and frame transformations. It optionally normalizes the fbank features and accumulates global statistics if enabled, ultimately returning the processed fbank representation ... | def process_utterance(self, utterance):
wav = self.dither(utterance)
wav = self.pre_emphasize(wav)
frames = self.wav_to_frames(wav)
magspec = self.frames_to_magspec(frames)
fbank = self.magspec_to_fbank(magspec)
if (self.mean_normalize):
fbank = se... |
def _format_record_name(self, record_name):
"""
Format record to canonical form.
:param str record_name: A DNS record name.
:returns: The DNS record name in canonical form.
:rtype: str
"""
if not record_name.endswith("."):
record_name = "{0}.".format(... | The main task of the code is to find the managed zone ID for a given domain by searching through API requests using the provided domain and record name. It generates potential domain name guesses, iterates through them, and returns the first matching domain ID and name. If no match is found, it raises an error indicati... | def _find_domain_id(self, domain, record_name):
"""
Find the managed zone for a given domain.
:param str domain: The domain for which to find the managed zone.
:param str record_name: The record name (typically beginning with '_acme-challenge.').
:returns: The ID of the managed ... |
def _format_record_name(self, record_name):
"""
Format record to canonical form.
:param str record_name: A DNS record name.
:returns: The DNS record name in canonical form.
:rtype: str
"""
if not record_name.endswith("."):
record_name = "{0}.".format(... | This function adds a TXT DNS record to a specified domain using provided details, including formatting the record name, locating the domain's ID, preparing record data, and executing an API request to insert the TXT record with a specified TTL. | def add_txt_record(self, domain, record_name, record_content, record_ttl):
"""
Add a TXT record using the supplied information.
:param str domain: The domain to use to look up the managed zone.
:param str record_name: The record name (typically beginning with '_acme-challenge.').
... |
def _format_record_name(self, record_name):
"""
Format record to canonical form.
:param str record_name: A DNS record name.
:returns: The DNS record name in canonical form.
:rtype: str
"""
if not record_name.endswith("."):
record_name = "{0}.".format(... | The main task of the code is to delete a TXT record from a specified domain using CloudDNS API. It formats the record name, identifies the domain ID, retrieves the record's ID, and sends a DELETE request to remove the record. The function also publishes DNS changes with the provided TTL. Parameters include domain, reco... | def del_txt_record(self, domain, record_name, record_content, record_ttl):
"""
Delete a TXT record using the supplied information.
:param str domain: The domain to use to look up the managed zone.
:param str record_name: The record name (typically beginning with '_acme-challenge.').
... |
def create_2d_matrix(lines, cols, vals):
"""
Create a matrix with sorted data when it depends on two coords
Parameters
----------
lines: list
Lines coords
cols: list
Cols coords
vals: list
Values corresponding to the data
Returns
-------
numpy.ndarray
... | The main task of the code is to generate an xarray Dataset representing a geolocation grid from input metadata (`dictio`) and file paths (`folder_path`). It processes geolocation parameters like longitude, latitude, and height, converting them into 2D arrays with appropriate coordinates, units, and XML paths. The datas... | def create_dataset_geolocation_grid(dictio, folder_path):
"""
Create a dataset for Geolocation Grid
Parameters
----------
dictio: dict
Content of product.xml as a dictionary
folder_path: str
Folder path containing the level 1 files
Returns
-------
xarray.Dataset
... |
def list_xsd_files(xpath, folder_path):
"""
Search for xsd file paths where names are linked with a dataset, thanks to xpaths
Parameters
----------
xpath: str
Xpath describing the hierarchy of a dataset to get its name and its parents
folder_path: str
Folder path containing the ... | The function creates an xarray.Dataset for attitude information by combining timestamped yaw, roll, and pitch data with metadata from XML Schema (XSD) files in a specified folder. It processes each parameter (yaw, roll, pitch) to extract values, associate them with timestamps, and merge attributes from input dictionari... | def create_dataset_attitude_information(
ds_attr, timestamp, yaw, roll, pitch, folder_path
):
"""
Create a dataset for Attitude Information
Parameters
----------
ds_attr: dict
Dictionary of dataset attributes
timestamp: list[datetime64]
Timestamp list of values
yaw: dict... |
def find_doc_in_xsd_files(xpath, interesting_files):
"""
Search dataset variable description in a list of xsd files
Parameters
----------
xpath: str
Xpath describing the hierarchy of a dataset to get its name and its parents
interesting_files: list[list[str]]
Returns
-------
... | The function creates an xarray.Dataset for Doppler Centroid data by combining input parameters with metadata from XML schema files. It constructs DataArrays for variables like ambiguity, coefficients, and confidence, using provided values, time coordinates, and attributes. The dataset is populated with these arrays and... | def create_dataset_doppler_centroid(
ds_attr,
times,
Ambiguity,
AmbiguityConfidence,
CentroidReferenceTime,
CentroidPolynomialPeriod,
CentroidCoefficients,
CentroidConfidence,
folder_path,
):
"""
Create a dataset for Doppler Centroid
Parameters
----------
ds_attr... |
def find_doc_in_xsd_files(xpath, interesting_files):
"""
Search dataset variable description in a list of xsd files
Parameters
----------
xpath: str
Xpath describing the hierarchy of a dataset to get its name and its parents
interesting_files: list[list[str]]
Returns
-------
... | The function `create_dataset_doppler_rate_values` generates an xarray Dataset containing Doppler Rate Values by combining input parameters (`ds_attr`, `rateTime`, `rateCoefficients`) and metadata from XML files in a specified folder. It constructs a DataArray from `rateCoefficients["values"]`, using `rateTime["values"]... | def create_dataset_doppler_rate_values(
ds_attr, rateTime, rateCoefficients, folder_path
):
"""
Create a dataset for Doppler Rate Values
Parameters
----------
ds_attr: dict[str, str]
Dictionary of dataset attributes
rateTime: dict[str, dict | list | str]
RateTime list of val... |
def generate_doc_ds(xpath, folder_path):
"""
Generate a Dataset general documentation found in xsd files from a folder
Parameters
----------
xpath: str
Xpath describing the hierarchy of a dataset to get its name and its parent
folder_path: str
Folder path containing the level 1 ... | The code creates an xarray Dataset for chirp data by converting input parameters into DataArrays with pole coordinates and metadata. It combines provided attributes with documentation generated from a folder path, then aggregates all variables into a single dataset for analysis or processing. | def create_dataset_chirp(
pole,
ds_attr,
replicaQualityValid,
crossCorrelationWidth,
sideLobeLevel,
integratedSideLobeRatio,
crossCorrelationPeakLoc,
chirpPower,
amplitudeCoefficients,
phaseCoefficients,
folder_path,
):
"""
Create a dataset for chirp thanks to its inf... |
def generate_doc_vars(xpath, folder_path):
"""
Generate a Dataset variable documentation found in xsd files from a folder
Parameters
----------
xpath: str
Xpath describing the hierarchy of a dataset to get its name and its parents
folder_path: str
Folder path containing the leve... | This function creates an xarray.Dataset for radar parameters by processing a structured input dictionary. It constructs data arrays with dimensions, coordinates, and metadata from the dictionary, handling special cases like noise level values for Beta, Sigma, and Gamma. Attributes are enriched using metadata from the f... | def create_dataset_radar_parameters(dictio, folder_path):
"""
Create a dataset for the radar parameters
------------------------------------------------
:rtype: xarray.Dataset
:type dictio: dict[str, dict | dict[str, list | TypedDict]]
:param dictio: Content of the useful dataset information a... |
def check_password_length(password):
if len(password) < MIN_LEN:
return 0
return 1
def add(username, password):
if check_duplicate(username):
return 0
hashed = hash_password(password)
user = {username : [hashed[0], hashed[1], 0]}
update_json(user)
return 1
def passwd(userna... | The main task of the code is to manage user account operations via command-line arguments, including adding users with password validation, changing passwords, forcing password changes, and deleting users. It checks for password length and matches, interacts with a JSON file to store passwords, and performs actions bas... | def main():
if not os.path.isfile(ALL_PASSWORDS):
with open(ALL_PASSWORDS, 'w') as f:
f.write(json.dumps({}))
username = sys.argv[2]
if sys.argv[1] == 'add':
password = input()
repeat_password = input()
if password != repeat_password:
... |
def loadImg(path):
return cv2.imread(path)
def ptsCrop(image, side):
pts = np.array(const.pts[side], np.int32)
pts = pts.reshape((-1, 1, 2))
cv2.polylines(image, [pts], True, (0, 255, 0))
rect = cv2.boundingRect(pts)
x, y, w, h = rect
image = image[y:y + h, x:x + w]
return image
def diff... | The code calculates the density difference between a test image and a base image after cropping. It loads images based on the 'side' parameter, crops them, computes their pixel difference, and determines the density of this difference to assess variation or quality. | def getImageDensity(side):
img = loadImg('C:\\Users\\parme\\OneDrive\\Desktop\\TEST_Proj_Final' + side + '.jpg')
baseImg = loadImg('C:\\Users\\parme\\OneDrive\\Desktop\\TEST_Proj_Final\\images\\base' + side + '.jpg')
img = ptsCrop(img, side)
baseImg = ptsCrop(baseImg, side)
canvas = diffImg(img, bas... |
def get_angle(self, rotate_dir):
start = self.head_at_rest
if rotate_dir == 'right':
return max(start - 80, -80)
else:
return min(start + 80, 80)
def rotate_servo(self, servo, target_angle, interval=0.005, speed_multiplier=1):
initial_angle = int(servo.angle)
... | This method rotates the head servo to a direction-specific angle, triggers a number of calls proportional to the input 'times', then resets the head servo to its resting position. | def rotate_caw_times(self, rotate_direction, times):
logger.info(f"rotate_direction: {rotate_direction}, times: {times}")
angle = self.get_angle(rotate_direction)
self.rotate_servo(self.HEAD_SERVO, angle)
self.caw_x_times(times)
self.rotate_servo(self.HEAD_SERVO, self.head_at_res... |
def get_col(theta):
color = [0, 0, 0]
color[int(theta//120)] = int((theta % 120)/8*17)
color[int(theta//120-1)] = int(255-(theta % 120)/8*17)
return hex_col(color)
def get_col_ang(x, y):
try:
theta = math.atan(x/y) * 360 / math.pi
except:
theta = 180
finally:
return t... | The code draws a large circle with radius, using position-dependent colors. At intervals, it creates smaller circles around the main circle, forming a pattern. The nested loops generate multiple concentric or angular shapes, creating a complex, colorful circular design with dynamic color changes based on position. | def major_circle(radius):
tur.pu()
tur.goto(0, -radius)
for i in range(360):
tur.color(get_col(get_col_ang(*tur.pos())))
if i*radius/200 % 60 == 0 and (radius != 0 or i == 0):
for j in range(6):
circle(j*60, 50, tur.pos())
tur.seth(i)
tur.circle(ra... |
def _get_height(root):
if root is None:
return 0
return root.height
def _adjust_balance(self, root):
root_balance = self._get_balance_factor(root)
if root_balance > 1 and self._get_balance_factor(root.left) >= 0:
# inserted node is at the left child of left child... | The main task of the code is to recursively insert data into an AVL tree, update node heights, and maintain balance by calling _adjust_balance after insertion. It handles base cases for empty nodes, inserts data into appropriate subtrees based on comparisons, recalculates node heights, and ensures structural balance to... | def _insert(self, root, data):
if root is None:
return AVLTreeNode(data)
if root.data < data:
root.right = self._insert(root.right, data)
elif root.data > data:
root.left = self._insert(root.left, data)
root.height = max(self._get_height(root.left), ... |
def _find_minimum(self, root):
if root.left is None:
return root
return self._find_minimum(root.left)
def _adjust_balance(self, root):
root_balance = self._get_balance_factor(root)
if root_balance > 1 and self._get_balance_factor(root.left) >= 0:
# inserted node ... | This function deletes a node with specified data from a binary tree, handling cases where the node has no children, one child, or two children. For two children, it replaces the node with its in-order successor and adjusts the tree's balance to maintain structural integrity. | def _delete(self, root, data):
if root is None:
return None
ret = None
if data < root.data:
root.left = self._delete(root.left, data)
ret = root
elif data > root.data:
root.right = self._delete(root.right, data)
ret = root
... |
def view_assigned_patients(self):
query = 'SELECT p.patient_id, p.name AS patient_name, p.age, d.id AS doctor_id, d.name AS doctor_name FROM patients p JOIN doctors d ON p.assigned_doctor_id = d.id WHERE d.id = %s;'
print(self.doctor_id)
print(self.execute_query(query, (self.doctor_id,)))
... | This code provides a menu-driven interface for a doctor to manage tasks like viewing patients, prescriptions, schedules, applying for leave, checking salary, updating schedules, and approving appointments. It loops until the user selects "Exit," handling input to call corresponding methods for each option. | def doctor_module(self):
print("Welcome Doctor!")
while True:
print("1. View Assigned Patients")
print("2. Manage Prescriptions")
print("3. View Schedule")
print("4. Apply for Leave")
print("5. View Salary")
print("6. Update Schedul... |
def value_from_path(data, path):
# Takes string path in form "path/to/value"
return value_from_path(data[path[0]], path[1:]) if path else data
def find_pararms(att, data, id='', params=None):
if dynamic_token(id) and not dynamic_view(att):
return
# Find and return all keys that require input (the model par... | The code generates parameters for each attribute in `attr_paths` by extracting values from `data` using specified paths, creating parameters with `_create_parameters`, and appending them to `model['definitions'][att]['parameters']` to define attribute-specific parameters in a model structure. | def create_parameters(data, attr_paths):
# Use the path associated with each attribute to find all of
# the attribute's parameters
for att, path in attr_paths.items():
params = []
values = value_from_path(data, path.split('/'))
param = find_pararms(att, values)
for id, p in param.items():
p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.