dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def generate_population(coordinates, inital_population_size):
population = []
for i in range(inital_population_size):
ind = generate_individual(coordinates)
population.append(ind)
return population
def evaluate_population(population):
evals = []
for i in range(... | This code implements a genetic algorithm to solve an optimization problem, likely the Traveling Salesman Problem. It generates an initial population, evaluates fitness, selects parents, reproduces offspring via crossover, applies mutation, and iterates through generations to evolve better solutions. The algorithm track... | def genetic_alg(coordinates, pop_size, generations, mutation_rate):
population = generate_population(coordinates, pop_size)
evals = evaluate_population(population)
best = select_best(evals, population)
print('Best solution from inital population: ' + (str(best[1])))
best_by_gen = []
best... |
def capture(self):
cap = cv2.VideoCapture(0)
self.keypoint_features = []
waiting_text = f'Press "s" to start collecting for {self.label}'
try:
while True:
key = cv2.waitKey(1)
capure_and_feed_frames(cap, frame_text=waiting_text)
... | The code's main task is to capture data, check if the collection is complete, and save the results as a CSV file if the collection is finished. | def run(self):
self.capture()
if self.check_collection_complete():
self.save_csv() |
def split_into_m_parts(X, m):
# split the entire dataset into subsets
n = int(X.shape[0] / m)
resShape = [m, n]
if len(X.shape) > 1:
for item in X.shape[1:]:
resShape.append(item)
res = np.zeros(resShape)
for i in range(m):
res[i] = X[i*n:(i+1)*n]
return res
def c... | The function `compute_mse` calculates the mean squared error (MSE) of kernel ridge regression predictions across `m` data splits. It handles real data, integral scenarios, or simulations by adapting predictions (`y_pred_lst`) and test targets (`y_test`). For each split, it computes regression coefficients, predicts out... | def compute_mse(X, y, N, m, params, dist_metric,
X_test = None, y_test = None, real = False, integral = False):
# Key function to compute the mse, real is the parameter indicating if it's
# simulation study or real data
# n = int(N / m)
if (real):
y_pred_lst = np.zeros((m, X_t... |
def get_moves_for(coord):
"""
coord: a tuple (x, y) where x, y is a value between 0-7
"""
moves = []
for dx, dy in RELATIVE_MOVES:
x = coord[0] + dx
y = coord[1] + dy
if is_valid_move(x) and is_valid_move(y) and is_unvisited((x, y)):
moves.append((x, y))
ret... | The code performs a breadth-first search (BFS) to find the minimum number of moves required to reach a target coordinate from a starting point. It processes coordinates in a queue, explores valid moves, tracks steps by incrementing values, and returns the minimum steps when the target is reached. Your return | def find_moves(queue, targetCoords):
"""
1. get the first element from the queue and set to currentCoord
- get the moves for that element
- loop through moves and set a move value
# increment whatever its num value is + 1. So for the first coord, which is 0
- check that coord is unvisited
... |
def get_coord(num):
x = num // 8 # results in the row index
y = num % 8 # results in the column index
return (x, y)
def set_start(coord):
set_coord_value(coord, 0)
def find_moves(queue, targetCoords):
"""
1. get the first element from the queue and set to currentCoord
- get the moves ... | Your return The code calculates the minimum number of moves required for a knight to travel from a starting position (src) to a target position (dest) on an 8x8 chessboard using Breadth-First Search (BFS). It initializes a board to track visited positions, enqueues starting coordinates, and explores all possible knight... | def solution(src, dest):
"""
src: int between 0-63 starting position
dest: int between 0-63 target position
"""
global board
board = [[-1 for y in range(8)] for x in range(8)]
queue = [] # a list of coordinates to check
startCoords = get_coord(src)
targetCoords = get_coord(dest)... |
def core(epsilon, testset=testbed, estimate_method=sample_averaging_estimates, initial_q=0.0,
selection_method_epsilon=True, qstar_registry=np.zeros(1), epsilon_annealing=False):
start = time.time()
print(f'Started at {time.ctime()}')
if qstar_registry.any():
results = [bandit(testset[trial... | This code compares the performance of different epsilon values in a reinforcement learning scenario by plotting average rewards, standard errors, and the fraction of optimal actions taken. It generates two subplots, visualizes results for epsilon = 0.1, 0.01, and 0.0, adds an upper bound reference, saves the figure as ... | def q6():
fig, (ax, ax2) = plt.subplots(2, 1, figsize=figsize)
for epsilon in [0.1, 0.01, 0.0]:
average_rewards, std_error, fractional_optimal_actions = core(epsilon)
plot(average_rewards, std_error, fractional_optimal_actions, ax, ax2, f'epsilon {epsilon}')
plot_upperbound(ax)
# plt... |
def core(epsilon, testset=testbed, estimate_method=sample_averaging_estimates, initial_q=0.0,
selection_method_epsilon=True, qstar_registry=np.zeros(1), epsilon_annealing=False):
start = time.time()
print(f'Started at {time.ctime()}')
if qstar_registry.any():
results = [bandit(testset[trial... | The main task of the code is to compare the performance of different epsilon values (0.1 and 0.0) and initial Q-values (5.0 and 0.0) in a reinforcement learning experiment. It runs simulations, computes average rewards, standard errors, and fractional optimal actions, then plots these results on two subplots. The plots... | def q8a():
epsilons = [0.1, 0.0]
fig, (ax, ax2) = plt.subplots(2, 1, figsize=figsize)
initial_q = [5.0, 0.0]
for epsilon in epsilons:
for q in initial_q:
label = f'Epsilon {epsilon} Initial Q {q}'
average_rewards, std_error, fractional_optimal_actions = core(epsilon, init... |
def core(epsilon, testset=testbed, estimate_method=sample_averaging_estimates, initial_q=0.0,
selection_method_epsilon=True, qstar_registry=np.zeros(1), epsilon_annealing=False):
start = time.time()
print(f'Started at {time.ctime()}')
if qstar_registry.any():
results = [bandit(testset[trial... | This code runs and compares the performance of epsilon-greedy and UCB algorithms in a reinforcement learning context. It generates plots showing average rewards, standard errors, and optimal action fractions for both methods, then saves the visualization as 'q8b_1k.png'. | def q8b():
fig, (ax, ax2) = plt.subplots(2, 1, figsize=figsize)
epsilon = 0.1
average_rewards, std_error, fractional_optimal_actions = core(epsilon)
plot(average_rewards, std_error, fractional_optimal_actions, ax, ax2,
f'Epsilon greedy {epsilon}')
average_rewards, std_error, fractional_opti... |
def read_xml_as_dataframe(xml: str, root_key_list: Optional[List[str]] = None, transpose: bool = False) -> pd.DataFrame:
if transpose:
return pd.DataFrame(get_to_root_in_dict(xmltodict.parse(xml), root_key_list)).T
else:
return pd.DataFrame(get_to_root_in_dict(xmltodict.parse(xml), root_key_list... | This function reads multiple XML files from a ZIP archive, converts each to a DataFrame using specified root elements and transpose settings, and concatenates all resulting DataFrames into a single unified DataFrame with outer joins and reset indices. | def read_xml_files_in_zip_as_dataframe(zip_file: ZipFile, root_key_list: Optional[List[str]] = None, transpose: bool = False) -> pd.DataFrame:
return pd.concat([read_xml_as_dataframe(read_xml_in_zip(zip_file, xml_file), root_key_list, transpose=transpose)
for xml_file in get_files_list_in_zip(... |
def read_xml_files_in_zip_as_dataframe(zip_file: ZipFile, root_key_list: Optional[List[str]] = None, transpose: bool = False) -> pd.DataFrame:
return pd.concat([read_xml_as_dataframe(read_xml_in_zip(zip_file, xml_file), root_key_list, transpose=transpose)
for xml_file in get_files_list_in_zip(... | This function reads XML files from nested zip archives within a main zip file, processes them into DataFrames, and concatenates the results into a single DataFrame. It handles multiple layers of zipping, extracts XML data, and optionally transposes the output structure. | def read_xml_files_in_double_zip_as_dataframe(zip_file: ZipFile, root_key_list: Optional[List[str]] = None, transpose: bool = False) -> pd.DataFrame:
return pd.concat([
read_xml_files_in_zip_as_dataframe(
get_zip_in_zip(zip_file, sub_zip_file),
root_key_list,
transpose=tr... |
def get_zip_file_from_url(zip_url: str) -> ZipFile:
return ZipFile(io.BytesIO(requests.get(zip_url).content))
def get_files_list_in_zip(zip_file: ZipFile, file_extension: str) -> List[str]:
return [x for x in zip_file.namelist() if x.endswith(file_extension)]
def read_xml_files_in_zip_as_dataframe(zip_file: Zip... | This function reads XML data from URLs or local paths, handling nested ZIP archives. It converts XML content into a pandas DataFrame, with options to transpose the data and specify root elements for parsing. | def read_xml(path_or_xml: str, root_key_list: Optional[List[str]] = None, transpose: bool = False, encoding: Optional[str] = None) -> pd.DataFrame:
if urllib.parse.urlparse(path_or_xml).scheme in ['http', 'https']:
if path_or_xml.endswith('.zip'):
with get_zip_file_from_url(path_or_xml) as zf:
... |
def sigmoid(z):
return 1.0/(1.0+np.exp(-1.0*z))
def one_hot_vector(size,pos):
temp=np.zeros(size)
temp[pos]=1
return np.transpose([temp])
def derivative_sigmoid(z):
temp=sigmoid(z)
return np.multiply(temp,1-temp)
def test(self,test_data):
""" Function to calculate the accuracy of the NN over the provided test_d... | This code trains a neural network using stochastic gradient descent to minimize mean squared error. It processes training data in mini-batches, performs forward propagation, backpropagation to compute weight/bias adjustments, updates parameters iteratively, and evaluates accuracy on training/validation data per epoch. | def train(self,training_data,learning_rate=1.0,mini_batch_size=1,n_epochs=10,validation_data=None):
"""
Function which trains the neural network with the provided training data by updating the weights and biases using stochastic gradient descent in order to minimize the mean squared error.
If mini-batch size isn... |
def check(self, ttype: TokenType) -> bool:
if self.tok_end():
return False
return self.peek().type == ttype
def advance(self) -> Token:
if not self.tok_end():
self.cur += 1
return self.previous()
def peek(self) -> Token:
return self.tokens[self.cur] | The function consumes a token of the specified type if present, advancing the parser. If the token type does not match, it raises a ParseErr with the current token and provided message. Its main task is to validate and consume expected tokens during parsing, ensuring syntax correctness by enforcing token type requireme... | def consume(self, token_type: TokenType, message: str) -> object:
if self.check(token_type):
return self.advance()
raise ParseErr(self.peek(), message) |
def advance(self) -> Token:
if not self.tok_end():
self.cur += 1
return self.previous()
def tok_end(self) -> bool:
return self.peek().type == TokenType.EOF
def peek(self) -> Token:
return self.tokens[self.cur] | The code advances through tokens until it encounters one of the specified synchronization tokens (`synch_toks`), at which point it halts. Its main task is to synchronize the parser's position in the token stream by skipping tokens until a recognized synchronization point is reached, ensuring alignment with expected str... | def synchronize(self) -> None:
self.advance()
while not self.tok_end():
ttype: TokenType = self.peek().type
if ttype in self.synch_toks:
return
self.advance() |
def get_img_files(self, img_dir):
self.img_files = sorted(basename(x) for x in iglob(join(img_dir, "*.jpg")))
def _load_existing(self, fname, data, add_to_completer=True):
with open(fname, newline='') as csvfile:
r = csv.reader(csvfile)
try:
header = next(r)
... | This code initializes an object to process image files from a directory, manage a CSV file for species data, and handle loading or creating the file based on existing data. It sets up data structures, checks for image files, applies filters if specified, and prepares for species classification tasks, including handling... | def __init__(self, img_dir, initials, repro=False, filt=False):
self.img_dir = img_dir
self.img_files = None
self.get_img_files(self.img_dir)
if not self.img_files:
raise FileNotFoundError("no .jpg images found in directory {}".format(img_dir))
self.sample = self.i... |
def find_car_multi_scale(img,params, win_size):
bboxes=[]
# print('number of scale use:', len(win_size['use_scale']))
win_scale=win_size['use_scale']
y_start_stop= win_size['y_start_stop']
for x in range(win_size['length']):
if x in win_scale:
scale_0=win_size[f'scale_{x}'][2]
... | The code detects cars in an image using multi-scale methods, generates heatmaps, applies thresholds, filters plates, and visualizes results. It returns the processed image with bounding boxes, labeled heatmaps, and cropped detected regions, along with debug visualizations if enabled. | def run(name,params, win_size, debug=False):
if type(name)!=str:
img=name
else:
img = cv2.imread(name, cv2.IMREAD_COLOR)
img= cv2.resize(img, (1000,500))
img2 = img.copy()
start= time.time()
bbox= find_car_multi_scale(img,params, win_size)
if bbox[0] is None:
return ... |
def print_banner():
os.system("cls" if os.name == "nt" else "clear")
ascii_banner = pyfiglet.figlet_format("klear", font="slant")
print(ascii_banner)
print(" === ======= ======= = ======= === ========= ========")
print(" Clean , light and effective communication. ")
print(" === ======= ======= =... | The main task of the code is to manage user authentication and room connection in a chat application. It checks if a user exists, retrieves their session, and prompts them to join the general room or view other options. If the user is new, it registers them and repeats the process. The code handles input validation, ex... | def main(version):
print_banner()
if version:
print(VERSION)
sys.exit()
if check_if_user_exists():
global session_json
session_json = get_klear_session()
print(Pretty.HEADER + "Welcome back " + session_json["username"] + Pretty.ENDC)
general_room = click.pro... |
def get_json_description_for_api(api):
return json.load(open('./apis/' + api + '.json'))
def get_predicted_paths(sentence, available_paths):
predicted_paths = []
for path in available_paths:
for word in sentence.split():
if get_close_matches(word, [path], cutoff=0.5) and Path(name=path)... | The code processes a user query by predicting potential API requests based on a sentence, generating HTTP requests using an API's JSON description, executing the first predicted request, and logging the interaction. It filters valid paths/verbs, constructs requests, sends them, and stores results in a database with an ... | def query(request, api):
sentence = request.GET.get('sentence')
json_api_description = get_json_description_for_api(api)
predicted_paths = get_predicted_paths(sentence, get_available_paths(json_api_description))
api_base_path = json_api_description['servers'][0]['url']
for predicted_path in predic... |
def get_secret_manager_secret(secret_name):
secretsmanager_client = boto3.client('secretsmanager')
response = secretsmanager_client.get_secret_value(SecretId=secret_name)
return response['SecretString']
def get_parameter_store_checkpoint(parameter_name):
ssm_client = boto3.client('ssm')
try:
... | The main task of the code is to retrieve audit events from the SailPoint IdentityNow API since a specified checkpoint time, handle rate limits, and update the checkpoint to the latest event's timestamp. It fetches events in batches, processes responses, and returns the collected events along with the new checkpoint tim... | def get_events_from_api():
# Get information about IdentityNow from Lambda Environment Vars
parameter_name = 'SailPointOCSFCheckpoint'
org_name = os.environ['SailPointOrganizationName']
identitynow_url = "https://{}.api.identitynow.com".format(org_name)
client_id = os.environ['SailPointClientID']
... |
def getSeasonData(team_id, year):
stats_SOS_pd = pd.read_csv('Data/RegSeasonStats/MMStats_'+str(year)+'.csv')
stats_SOS_pd = handleDifferentCSV(stats_SOS_pd)
ratings_pd = pd.read_csv('Data/RatingStats/RatingStats_'+str(year)+'.csv')
ratings_pd = handleDifferentCSV(ratings_pd)
year_data_pd = reg_seas... | The code generates a training dataset for machine learning by aggregating game features (team statistic differences and home advantage) and outcomes (win/loss) across specified years. It processes regular-season and tournament games, constructs feature vectors, and stores them in matrices `xTrain` and `yTrain`. Team ve... | def createTrainingSet(years, saveYears):
totalNumGames = 0
for year in years:
season = reg_season_compact_pd[reg_season_compact_pd['Season'] == year]
totalNumGames += len(season.index)
tourney = tourney_compact_pd[tourney_compact_pd['Season'] == year]
totalNumGames += len(tourney... |
def del_inves(self, inves, width):
actions = list(self.rules.keys())
for key in actions:
if key in self.rules and self.rules[key] == inves:
# print(">>>>>> del", key, "->", self.rules[key])
self.rm_rule(key,width)
def rm_rule(self, move, width):
... | The function generates a prediction for a given move by either retrieving predefined rules or randomly selecting from available actions. If no valid actions remain, it removes low-scoring rules and recursively retries, ensuring valid moves while updating internal rule sets and scores during execution. | def get_pred(self, move, width, in_eval=False):
if self.rules and move in self.rules.keys():
pred = self.rules[move]
else:
if in_eval:
return 0
pred_buffer = set(range(23,width)) - set(self.rules.values())
# print(">>> buffer", pred_buffer... |
def del_inves(self, inves):
actions = list(self.rules.keys())
for key in actions:
if key in self.rules and self.rules[key] == inves:
# print(">>>>>> del", key, "->", self.rules[key])
self.rm_rule(key)
def update_rules(self, move, target):
investigate ... | The code performs a deduction process using MCTS (Monte Carlo Tree Search) to explore and update logical rules dynamically. It iteratively selects moves, evaluates their validity against existing rules, and adjusts rule scores based on outcomes. When a terminal state is reached, it updates rules, computes scores for mo... | def start_deduction(self, batch, mcts_agent, is_shown=0, temp=1e-3):
self.allpair.init_allpair(batch)
states, mcts_probs, found_in_rules, found_ground_rules, found_in_tgt_rules = [], [], [], [], []
poten_moves = []
moves = []
mcts_agent.mcts.update_rules(copy.deepcopy(self.rule... |
def create_document(document_heading="DFEM Validation Preliminary Report"):
document = Document()
document.add_heading(document_heading, 0)
# changing the page margins
sections = document.sections
for section in sections:
section.top_margin = Inches(1)
section.bottom_margin = Inches... | The code generates a preliminary DFEM validation report by compiling results from gravity, unit, dynamic, and thermoelastic checks into a Word document. It uses input dictionaries to populate sections, inserts screenshots from a specified folder, and saves the final report with a customizable filename. | def create_report(
f06_gravitycheck_dict,
f06_unitcheck_dict,
f06_dynamic_dict,
f06_thermoelastic_dict,
filename="DFEM_Validation_Preliminary_report.docx",
screenshots_folder="./DFEM_Validation/screenshots",
):
doc = create_document(document_heading="DFEM Validation Preliminary Report")
... |
def get_list_GRID(bdf_file):
grid_list = []
CORD2R_added_shift = get_ref_point_coord(bdf_file)
line_count = -1
with open(bdf_file, "r") as f:
lines = f.readlines()
for line in lines:
line_count += 1
if line.startswith("GRID "):
grid_dict = dict.... | The function processes a BDF file to extract finite element grid points (GRID), quadrilateral (CQUAD), and triangular (CTRIA) elements, merges them on node IDs, then filters out nodes linked to RBE, MPC, or "+" entries in the file, returning a cleaned DataFrame of valid element-grid associations. | def get_dfem_elements_df(bdf_file):
df_dfem_grids = pd.DataFrame(data=get_list_GRID(bdf_file))
df_dfem_cquads = pd.DataFrame(data=get_list_CQUAD(bdf_file))
df_dfem_ctria = pd.DataFrame(data=get_list_CTRIA(bdf_file))
df_dfem_elements = pd.concat(
[
df_dfem_cquads[["Element", "prop", "... |
def find_unique_feat(col):
unq = []
for val in col:
if val not in unq:
unq.append(val)
else:
continue
return unq
def get_split_rows(data, feature, value):
left_rows = []
right_rows = []
for r in data:
if is_numeric(value):
answer = get_... | The function determines the optimal feature-value split in a dataset to maximize information gain for decision tree construction. It evaluates all possible splits, calculates their information gain, and returns the split with the highest gain along with the corresponding divided data subsets. | def find_best_spilt(data):
# print('Starting Data', data, sep='\n')
gains = []
ques = []
true_rows = []
false_rows = []
for feat in range(len(data[0])-1):
unq = find_unique_feat([data[k][feat] for k in range(len(data))])
for val in unq:
# print('Is {}... |
def third_cmd(arg1):
buy_categ = YNConfirm_sepa(arg1)
buy_decision = YNConfirmation(buy_categ)
if buy_decision == True:
if arg1 == "True01":
quantity = int(quantity_val())
ttl_price_of_item = quantity*numerical[0]
quan.insert(0, quantity)
usr_total.ins... | The function handles user confirmation to add an item to a cart, modifying global lists based on "yes" or "no" decisions. It validates input, updates cart data, and recursively processes commands (second_cmd → third_cmd → fourth_cmd) to manage cart actions. If "no", it discards the item by removing list elements and re... | def fourth_cmd(arg1):
if arg1 != None:
print("\nWould you like to add this to your cart?\n Yes or No")
while True:
fnl_usr_decision = input("\n> ").lower()
if fnl_usr_decision == "yes":
print("Added!")
return fourth_cmd(third_cmd(seco... |
def get_chall_config(path: str | Path, verify: bool = False) -> Challenge:
if isinstance(path, str):
path = Path(path)
if not is_challenge_folder(path):
raise FileNotFoundError("Challenge does not have chall.yaml or README.md")
with (path / CHALLENGE_CONFIG_FILE).open("r", encoding="utf-8"... | This function adds a challenge from a specified directory to the challenges folder, verifying its validity if required. It checks for existing challenges by name, replacing them if allowed or raising errors for conflicts. If the challenge's target path exists, it ensures no name clashes before moving the challenge to t... | def add_challenge(
folder: str | Path, replace: bool = False, verify: bool = True
) -> None:
"""
Adds a challenge from the specified path to the challenges folder.
If replace is True, will overwrite the challenge if it already exists.
If verify is True, will verify the challenge before adding it.
... |
def usage():
print('Enter: \ng for keygen \ne for encryption \nd for decryption \nf to run all 3 ')
return input()
def keygen():
print('keygen')
print('Input a random number to seed the RNG')
seed = input()
p = genPrime()
# g aka e1
g = 2
# d is random number between 1 < d < p
r... | The code processes command-line arguments to perform cryptographic operations: generating a key (-g), encrypting (-e), decrypting (-d), or all three sequentially (-f). If no valid argument is provided, it outputs an error message. | def main():
try:
userinput = sys.argv[1]
except:
userinput = '-' + usage()
if userinput == '-g':
keygen()
elif userinput == '-e':
encryption()
elif userinput == '-d':
decryption()
elif userinput == '-f':
keygen()
encryption()
decry... |
def use_case():
print("BAD INPUT!\nExpecting: python3 PSU-CRYPT <encrypt/decrypt> <plaintext/cyphertext> <key>")
return -1
def create_Ftable():
global F_TABLE
print("GENERATING FTABLE")
f = open('ftable.txt', 'r')
lines = [line.rstrip('\n').split(',') for line in f]
F_TABLE = lines
retur... | The main task of the code is to perform file encryption or decryption based on command-line arguments. It reads an input file and key, pads the data, and applies the specified mode (encryption/decryption) using a pre-defined Ftable. The operation is determined by the first argument (-e for encryption, -d for decryption... | def main():
input = sys.argv[1]
if input == '-d':
print("Running Decryption")
decrypt = True
elif input == '-e':
print("Running Encryption")
decrypt = False
else:
return use_case()
create_Ftable()
file = sys.argv[2]
file = read_file(file)
file =... |
def gen_subkeys(key):
print("SubKeys Generating")
global G_KEY
G_KEY = key
rounds = 16
four = 4
subkeys = 12
key_array = []
key_array = [[K(((4*j)+(i%4))) for i in range(subkeys)] for j in range(rounds)]
return key_array
def whitening(bit_block, key):
print("whitening")
# s... | This code implements a block cipher encryption/decryption algorithm. It processes input data in 16-byte blocks, applying 16 rounds of transformation using generated subkeys. The function handles both encryption (default) and decryption (via subkey reversal). Each block undergoes whitening, round operations with F-funct... | def mode(input, key, decrypt):
global ROUND
subkey_array = gen_subkeys(key)
if decrypt == True:
subkey_array = subkey_array[::-1]
output = ''
#============================================================
for i in range(int(len(input)/16)):
R = whitening(input[i*16:i*16+16], key)
... |
def use_case():
print("BAD INPUT!\nExpecting: python3 PSU-CRYPT <encrypt/decrypt> <plaintext/cyphertext> <key>")
return -1
def create_Ftable():
global F_TABLE
print("GENERATING FTABLE")
f = open('ftable.txt', 'r')
lines = [line.rstrip('\n').split(',') for line in f]
F_TABLE = lines
retur... | The main task of the code is to perform encryption or decryption based on command-line input flags (-e for encryption, -d for decryption). It reads a hexadecimal file and a key, pads the file data, and executes the specified mode using the provided key and file content. The process involves creating necessary tables, h... | def main():
input = sys.argv[1]
if input == '-d':
print("Running Decryption")
decrypt = True
elif input == '-e':
print("Running Encryption")
decrypt = False
else:
return use_case()
create_Ftable()
file = sys.argv[2]
file = read_hex_file(file)
fi... |
def get_laser_ranges(self):
rospy.wait_for_service('/get_distance')
try:
req = GetDistanceRequest()
req.dir_name = ''
req.obstacle_name = ''
get_data = rospy.ServiceProxy('/get_distance', GetDistance)
resp = get_data(req)
... | This code navigates a robot towards a target point by continuously sensing the environment using LIDAR data, calculating the optimal direction (teta) via the Vector Field Histogram (VFH) algorithm, and executing movement commands. The loop repeats until the robot reaches its goal, avoiding obstacles by dynamically adju... | def navigate_to_point(self):
# rospy.loginfo(ranges)
while True:
ranges = self.get_laser_ranges()
if ranges != None:
teta = self.calculate_vfh(ranges)
self.move(teta) |
def hash_func(matrix):
res = 0
for i in range(20):
res += matrix[i//4][i%4] * 10**(i)
return res
def add_moves_new(current_state, frontier):
gap1 = current_state.gap1
gap2 = current_state.gap2
check_gap_simple_moves_new(current_state, frontier, gap1)
check_gap_simple_moves_new(curren... | The code performs an A* search by initializing a frontier with possible moves from the initial state, tracking explored states, and returning the result of the a_search function which processes the frontier to find an optimal path. | def run_a_search(initial):
explored = {} # dictionary containing number->State
res = []
frontier = []
current_state = Path_State_A_Search(initial, [])
explored[hash_func(initial)] = current_state
add_moves_new(current_state, frontier) #do first move
return a_search(frontier,explored) |
def utility_f(state):
k = 0
for y in range(8):
for x in range(8):
ch = state[y][x]
if ch == 'b':
if (x == 7) or (x == 0) or (y == 0) or (y == 7):
k-=0.1
k -= 1
elif ch == 'B':
k -= 2
elif ... | This function implements alpha-beta pruning for game tree search, optimizing decision-making by evaluating possible states. It recursively explores actions, using a depth limit and pruning non-optimal branches via alpha/beta values. The 'explored' set caches previously computed utilities to avoid redundant calculations... | def alpha_beta(current_state, alpha, beta, player_max, depth, explored):
best_state = current_state
if depth == 12:
return utility_f(current_state), best_state
if terminal(current_state, player_max):
if terminal(current_state, player_max) == 1:
return float('inf'), best_state
... |
def translate_input(file_name):#check_queue [[first priority], [second priority],...]
with open(file_name) as f:
ln = f.readline()
sum_row = [int(i) for i in [*ln[:-1:]]]
ln = f.readline()
sum_column = [int(i) for i in [*ln[:-1:]]]
ln = f.readline()
ships = ([int(i) f... | The code processes an input file to determine ship placements and capacities, applies constraints, computes the solution using the function f_s, and writes the resulting grid to an output file. | def run_s(input_name, output_name):
ships, horizontal_list, vertical_list = translate_input(input_name)
capacity_list = apply_constraints(ships, horizontal_list, vertical_list)
res = output(f_s(ships, capacity_list, horizontal_list, vertical_list))
f = open(output_name, 'w')
for l in res:
f.... |
def extractPairsOfDataPoints(dataPoints):
pairs = []
for i in range(0, len(dataPoints)-1):
for j in range(i+1, len(dataPoints)):
# We are only looking for documents with same id
if dataPoints[i].qid != dataPoints[j].qid:
break
# If docume... | The main task of the code is to train a neural network model (likely RankNet) by iterating through pairs of data points, propagating input features forward, performing backpropagation to adjust weights, tracking error rates of misordered pairs across epochs, and saving the trained model weights. The process runs for a ... | def train(self, iterations = 20):
pairs = extractPairsOfDataPoints(self.dataPoints)
errorRate = []
startTime = time.time()
for it in range(iterations):
print("*** Epoch {0} ***" .format(it+1))
for pair in pairs:
self.propagate(pa... |
def find_liberty(self,board, i, j):
ally_members = self.ally_dfs(board,i, j)
for member in ally_members:
neighbors = self.detect_neighbor(board,member[0], member[1])
for piece in neighbors:
# If there is empty space around a piece, it has liberty
i... | This function checks if placing a piece of a given type at position (i,j) on a Go board is valid by verifying boundaries, ensuring the spot is empty, testing for liberties after placement, removing opponent's dead pieces, and applying the KO rule to prevent repeated board states. | def valid_place_check(self,board, i, j, piece_type, test_check=False):
# Check if the place is in the board range
if not (i >= 0 and i < len(board)):
return False
if not (j >= 0 and j < len(board)):
return False
# Check if the place already has a piece
i... |
def findTables(numTables):
tables = []
find = False
for num in range(numTables):
nameTable = ""
i = 1
while True:
for letter in letters:
temp = nameTable + letter
payload = f"tom' AND SUBSTRING((SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' LIMIT 1 OFFSET {num}),1,{i... | The main task of the code is to identify and update the 'PASSWORD' column in the 'USER' table by enumerating all columns of relevant tables, filtering for the 'USER' table, locating the password column, and applying updates. It involves database exploration, column identification, and targeted table modification. | def main():
#findDBversion()
#findNumberOfBaseTables(122)
#####FIRST SOLUTION#####
#bruteForcePassword()
#####SECOND SOLUTION ENUMERATING ALL COLUMNS OF ALL TABLES#####
#tables = findTables(24)
#newTables = filterTables(tables, 'USER')
#tablesAndColumns = findAllColumns(newTables)
#tablePasswordColumn = fi... |
def assemble(node_arr, elem_arr, phi, f, symbolic):
# initalize matrices and determine if they need to be a symbolic representation
N_n, N_e = len(node_arr), len(elem_arr)
mlocal = np.zeros((N_n,N_n))
klocal = np.zeros((N_n,N_n))
F = sp.zeros(N_n,1)
if symbolic:
M = sp.zeros(N_n, N_n)
... | The code simulates a partial differential equation (PDE) using the finite element method (FEM) with Forward or Backward Euler time integration. It assembles mass (M), stiffness (K), and force (F) matrices, applies boundary conditions, and computes the numerical solution over time. The analytical solution is compared to... | def main ():
x = sp.Symbol('X')
t = sp.Symbol('t')
f = (sp.pi*sp.pi - 1)*sp.E**(-t)*sp.sin(sp.pi*x)
u = sp.E**(-1)*sp.sin(sp.pi*x)
bc_arr = [] # array that holds the values of the boundary conditions
# gather user input
print("Welcome to the Finite Element Simulator")
print("Please fill ... |
def generate_k_mat(spring_const, condition, num_masses):
num_springs = len(spring_const)
A_t = create_A_t(condition, num_masses, num_springs)
C = create_C(spring_const)
A = A_t.transpose()
K = np.zeros((num_masses, num_springs))
if condition == 0:
K = np.matmul(np.matmul(A_t,C),... | The main task of the code is to simulate a mass-spring system by gathering user inputs for boundary conditions, mass weights, and spring constants. It constructs a stiffness matrix, computes displacements, elongations, and internal stresses, then outputs results for each mass and spring. The simulation supports three b... | def main ():
# gather user input
print('Welcome to the Mass-Spring Simulator')
print("Choose either Fixed-Free, Fixed-Fixed, or Free-Free boundary condition (enter the number of the condition): ")
print("[0]: Fixed Free")
print("[1]: Fixed Fixed")
print("[-1]: Free Free")
print()
conditi... |
def get_background_color(element):
# Traverse up the ancestor chain to find a parent element with a style attribute
parent = element.parent
while parent:
if parent.has_attr('style'):
# Extract the background-color property from the CSS styles
background_color_match = re.searc... | This code detects HTML elements with insufficient text-background color contrast by parsing HTML content, extracting text and background colors, calculating contrast ratios, and identifying elements failing accessibility standards (e.g., WCAG 4.5:1 for normal text). It returns a list of non-compliant elements with thei... | def detect_unsufficient_color_contrast(html_content):
soup = BeautifulSoup(html_content, 'html.parser')
text_elements = soup.find_all(text=True)
text_background_colors = {}
for element in text_elements:
background_color = get_background_color(element)
print("background color " + str(back... |
def question(question_list):
print("You got " + str(len(question_list)) + " suggestions")
print("Select most applicable number or list suggestions.")
def filter_romantic_youth_comedies(filter_2_1):
romantic_youth(filter_2_1)
question(filter_2_1)
while True:
answer_2_1 = int(input("1.Heartfel... | The code defines a function to filter or suggest romantic comedy movies based on user input. It presents a dictionary of movies with ratings, prompts the user to choose between filtering for youth-focused, non-youth-focused, or general romantic comedies, and calls respective functions to display results. The main task ... | def filter_romantic_comedies():
romantic_comedies = {'To All the Boys Ive Loved Before': 97, 'To All the Boys: P.S. I Still Love You': 75,
'Tall Girl': 44, 'The Last Summer': None, 'The Half of It': 96, 'The Kissing Booth': 17,
'Sierra Burgess Is a Loser': 61, 'The ... |
def na_na(list_5_4):
remove_list_5_4 = ['Sextuplets', 'Unbreakable Kimmy Schmidt: Kimmy vs the Reverend', 'The Ridiculous 6',
'The Polka King', 'Bad Moms', 'A Futile and Stupid Gesture', 'Wine Country',
'The Meyerowitz Stories', 'The Land of Steady Habits', 'Paddleton',... | The main task of the code is to configure buttons in a GUI application to handle different filtering options for a movie dataset, including "Independent," "Youth," "N/A," and "List suggestions." Each button is linked to a specific function that processes the data based on the selected category, while also updating the ... | def filter_na_na(filter_5_3_2):
na_na(filter_5_3_2)
question(filter_5_3_2)
btn1.config(text="Independent", command=lambda: na_na_independent(filter_5_3_2))
btn2.config(text="Youth", command=lambda: na_na_youth(filter_5_3_2))
btn3.config(text="N/A", command=lambda: na_na_na(filter_5_3_2))
btn4.co... |
def na_witty(list_5_3):
remove_list_5_3 = ['Sextuplets', 'Unbreakable Kimmy Schmidt: Kimmy vs the Reverend', 'The Ridiculous 6',
'The Package', 'The Polka King', 'Bad Moms', 'Between Two Ferns: The Movie',
'War Machine', 'Dude', 'Private Life', 'Win It All', 'Pee-wees B... | The code configures buttons to trigger specific functions for categorizing or processing data (e.g., humorous, emotional, dark-comedy, cerebral) and suggesting movies, using the `filter_5_3_1` parameter. It initializes a filtering process by calling `na_witty` and `question`, then sets up interactive options for user i... | def filter_na_witty(filter_5_3_1):
na_witty(filter_5_3_1)
question(filter_5_3_1)
btn1.config(text="Humorous", command=lambda: na_witty_humorous(filter_5_3_1))
btn2.config(text="Emotional", command=lambda: na_witty_emotional(filter_5_3_1))
btn3.config(text="Dark-comedy", command=lambda: na_witty_dark... |
def question(question_list):
intro1.config(text="You got " + str(len(question_list)) + " suggestions")
intro2.config(text="Select most applicable genre or list suggestions.")
def christmas_family(list_4_1):
remove_list_4_1 = ['Christmas Inheritance', 'Let It Snow', 'A Christmas Prince']
for key in remov... | The function initializes a dictionary of Christmas comedies with ratings, configures buttons to categorize them into "Children & Family", "N/A", or suggest movies, and hides specific UI elements. Its main task is to organize and filter Christmas comedy movies based on user-defined categories through button interactions... | def filter_christmas_comedies():
christmas_comedies = {'Christmas Inheritance': 43, 'Let It Snow': 81, 'A Christmas Prince': 73,
'A Christmas Prince: The Royal Wedding': 50, 'A Christmas Prince: The Royal Baby': 33,
'The Knight Before Christmas': 68, 'The Christma... |
def question(question_list):
intro1.config(text="You got " + str(len(question_list)) + " suggestions")
intro2.config(text="Select most applicable genre or list suggestions.")
def action_goofy(list_3_1):
remove_list_3_1 = ['The Hitmans Bodyguard', 'Shaft', 'Spenser Confidential']
for key in remove_list_3... | The function `filter_action_comedies` initializes a dictionary of action-comedy movies with ratings, configures buttons to handle user interactions (e.g., categorizing movies as "Goofy," "N/A," or suggesting titles), and removes specific UI elements. It prepares the interface for filtering or processing movie data base... | def filter_action_comedies():
action_comedies = {'The Do-Over': 5, 'Murder Mystery': 44, 'True Memoirs of an International Assassin': None,
'Coffee and Kareem': 20, 'Game Over, Man!': 19, 'The Hitmans Bodyguard': 43, 'Shaft': 32,
'Spenser Confidential': 38}
question(a... |
def romantic_not_youth_humorous(list_2_2_1):
remove_list_2_2_1 = ['Falling Inn Love', 'Home Again', 'Holiday in the Wild', 'Isnt It Romantic',
'Nappily Ever After']
for key in remove_list_2_2_1:
del list_2_2_1[key]
def question(question_list):
intro1.config(text="You got " +... | This function configures UI buttons to filter romantic, non-youth/humorous movies. It calls initial filtering and question functions, then sets buttons for "Witty" (triggering witty-specific filtering), "N/A" (no filter), and "List suggestions" (generating movie recommendations) using lambda functions with the provided... | def filter_romantic_not_youth_humorous(filter_2_2_1):
romantic_not_youth_humorous(filter_2_2_1)
question(filter_2_2_1)
btn1.config(text="Witty", command=lambda: romantic_not_youth_humorous_witty(filter_2_2_1))
btn2.config(text="N/A", command=lambda: romantic_not_youth_humorous_na(filter_2_2_1))
btn3... |
def romantic_youth(list_2_1):
remove_list_2_1 = ['Ibiza', 'Love Wedding Repeat', 'Set It Up', 'The Incredible Jessica James', 'Always Be My Maybe',
'Someone Great', 'The Breaker Upperers', 'When We First Met', 'Falling Inn Love',
'Home Again', 'Holiday in the Wild', 'Is... | The code configures a UI with buttons to filter romantic youth comedies by user-selected traits (Heartfelt, Humorous, N/A) and suggests movies based on the choice. It binds buttons to functions that process the `filter_2_1` parameter for tailored recommendations. | def filter_romantic_youth_comedies(filter_2_1):
romantic_youth(filter_2_1)
question(filter_2_1)
btn1.config(text="Heartfelt", command=lambda: romantic_youth_heartfelt(filter_2_1))
btn2.config(text="Humorous", command=lambda: romantic_youth_humorous(filter_2_1))
btn3.config(text="N/A", command=lambda... |
def heartfelt_humorous(list_1_2):
remove_list_1_2 = ['The Main Event', 'Sandy Wexler', 'The Half of It', 'To All the Boys Ive Loved Before',
'To All the Boys P.S. I Still Love You', 'The Last Summer', 'Tall Girl',
'Love Wedding Repeat', 'Falling Inn Love', 'Holiday in t... | The code configures buttons to filter heartfelt humorous comedies based on user input, linking each button to specific functions that handle youth, non-youth, N/A categories, and movie suggestions. The main task is to enable interactive filtering of movie data through a UI with dynamic button commands. | def filter_heartfelt_humorous_comedies(filter_1_2):
heartfelt_humorous(filter_1_2)
question(filter_1_2)
btn1.config(text="Youth", command=lambda: heartfelt_humorous_youth(filter_1_2))
btn2.config(text="Not Youth", command=lambda: heartfelt_humorous_not_youth(filter_1_2))
btn3.config(text="N/A", comm... |
def heartfelt_romantic(list_1_1):
remove_list_1_1 = ['The Fundamentals of Caring', 'The Two Popes', 'Otherhood', 'The Last Laugh', 'Unicorn Store',
'Dolemite Is My Name', 'Like Father', '#realityhigh', 'Dumplin', 'Deidra & Laney Rob a Train',
'The Main Event', 'Sandy We... | The code defines a function to configure a UI with buttons for filtering heartfelt romantic comedies. It sets up options to handle youth-related filters, non-youth filters, and movie suggestions, linking each button to specific processing functions. The final line hides a button, likely part of a dynamic interface adju... | def filter_heartfelt_romantic_comedies(filter_1_1):
heartfelt_romantic(filter_1_1)
question(filter_1_1)
btn1.config(text="Youth", command=lambda: heartfelt_romantic_youth(filter_1_1))
btn2.config(text="Not Youth", command=lambda: heartfelt_romantic_not_youth(filter_1_1))
btn3.config(text="List sugge... |
def intro():
print("I will give you Netflix Original Comedy Movie suggestion")
print("Select most applicable number you like to watch.")
def filter_heartfelt_comedies():
heartfelt_comedies = {'The Fundamentals of Caring': 78, 'The Two Popes': 89, 'Otherhood': 25, 'The Last Laugh': 53,
... | The code's main task is to allow users to select a comedy movie genre (Heartfelt, Romantic, Action, Christmas, or N/A) via input, then display filtered movies of that type using corresponding functions. It includes an introductory message, validates user input, and provides Rotten Tomatoes score information and a frien... | def main():
intro()
while True:
answer = int(input("1.Heartfelt 2.Romantic 3.Action 4.Christmas 5.N/A: "))
print("")
# Heartfelt Comedy Movies
if answer == 1:
filter_heartfelt_comedies()
break
# Romantic Comedy Movies
elif answer == 2:
... |
def question(question_list):
intro1.config(text="You got " + str(len(question_list)) + " suggestions")
intro2.config(text="Select most applicable genre or list suggestions.")
def na_goofy(list_5_1):
remove_list_5_1 = ['The Package', 'The Polka King', 'Bad Moms', 'Between Two Ferns: The Movie',
... | The code defines a function to filter and categorize a list of comedy movies based on attributes like "Goofy," "Humorous," "Witty," and "N/A," using buttons that trigger specific filtering functions. It processes a dictionary of movies with numerical ratings and None values, allowing users to explore or suggest movies ... | def filter_na_comedies():
na_comedies = {'Sextuplets': 14, 'Unbreakable Kimmy Schmidt: Kimmy vs the Reverend': None, 'The Ridiculous 6': None,
'The Package': 42, 'The Polka King': 66, 'Bad Moms': 58, 'Between Two Ferns: The Movie': 74,
'A Futile and Stupid Gesture': 61, 'Wine C... |
def romantic_not_youth(list_2_2):
remove_list_2_2 = ['To All the Boys Ive Loved Before', 'To All the Boys: P.S. I Still Love You', 'Tall Girl',
'The Last Summer', 'The Half of It', 'The Kissing Booth', 'Sierra Burgess Is a Loser',
'The Perfect Date', 'Candy Jar']
fo... | The code defines a function that configures buttons to filter romantic comedies excluding youth-oriented ones. It sets up three buttons: one to apply a humorous filter, one for "N/A" responses, and one to suggest movies, each linked to specific functions that process the input data. | def filter_romantic_not_youth_comedies(filter_2_2):
romantic_not_youth(filter_2_2)
question(filter_2_2)
btn1.config(text="Humorous", command=lambda: filter_romantic_not_youth_humorous(filter_2_2))
btn2.config(text="N/A", command=lambda: romantic_not_youth_na(filter_2_2))
btn3.config(text="List sugge... |
def question(question_list):
intro1.config(text="You got " + str(len(question_list)) + " suggestions")
intro2.config(text="Select most applicable genre or list suggestions.")
def filter_heartfelt_romantic_comedies(filter_1_1):
heartfelt_romantic(filter_1_1)
question(filter_1_1)
btn1.config(text="You... | The code defines a function to display and filter a list of heartfelt comedies via buttons, allowing users to categorize movies as romantic, humorous, or N/A, and generate suggestions. It uses a dictionary of movies with ratings/values, configures buttons to trigger filtering/suggestion functions, and hides a fifth but... | def filter_heartfelt_comedies():
heartfelt_comedies = {'The Fundamentals of Caring': 78, 'The Two Popes': 89, 'Otherhood': 25, 'The Last Laugh': 53,
'Unicorn Store': 64, 'Dolemite Is My Name': 97, 'Like Father': 46, '#realityhigh': 40,
'Dumplin': 85, 'Deidra & Lan... |
def question(question_list):
intro1.config(text="You got " + str(len(question_list)) + " suggestions")
intro2.config(text="Select most applicable genre or list suggestions.")
def filter_romantic_youth_comedies(filter_2_1):
romantic_youth(filter_2_1)
question(filter_2_1)
btn1.config(text="Heartfelt",... | The code defines a function that initializes a dictionary of romantic comedy movies with ratings, sets up GUI buttons to filter these movies by "Youth" or "Not Youth" categories, and provides a suggestion feature. It configures button commands to trigger further filtering or suggestion functions, while hiding other but... | def filter_romantic_comedies():
romantic_comedies = {'To All the Boys Ive Loved Before': 97, 'To All the Boys: P.S. I Still Love You': 75,
'Tall Girl': 44, 'The Last Summer': None, 'The Half of It': 96, 'The Kissing Booth': 17,
'Sierra Burgess Is a Loser': 61, 'The ... |
def log(self, text):
if not self.logging: return
# handles logging if present
t = time.time()
if self.printlogs:
print('{}: {}'.format(t, text))
self.logs.append('{}: {}'.format(t, text))
def on_home_network(self) -> bool:
'''
Returns true if ... | This function controls a smart plug by setting it to 'on' or 'off' states using either the python Kasa module (preferred) or TPLinkCmd.exe, depending on enabled flags. It checks network connectivity, verifies the current state, and returns status codes (0 for success, -1 for failure, -2 for network issues) while loggin... | def set_plug(self, on=False, off=False, use_pykasa=True, use_tplink=True) -> int:
'''
Sets the smart plug on or off.
`use_pykasa` : Allowed to use the python Kasa module
`use_tplink` : Allowed to use TPLinkCmd.exe
Attempts to set the plug first using the Kasa module (if allowe... |
def testing():
botcreds = SCRIPT_CONFIG['email_bot_account_creds']
eb = EmailBot('smtp.gmail.com', botcreds[0], botcreds[1])
print('Sending')
eb.sendEmail('Testing', 'Hello World', 'xfojd@example.com')
print('SENT')
def started_notif():
send_notification('Headless Battery Monitor', 'Battery moni... | The code monitors battery levels using command-line arguments for configuration, triggers alerts based on user-defined thresholds, controls a smart plug, and sends notifications via email. It initializes logging, parses input parameters, and runs a battery monitoring loop, handling errors and exiting gracefully with st... | def main():
global SCOUT
global BATTERY_FLOOR
global BATTERY_CEILING
global ALERT_PERIOD
global MAX_ATTEMPTS
global HEADLESS
global SMART_PLUG_CONTROLLER
global SLEEP_CONTROLLER
global EMAILBOT
SCOUT = ScriptOutputStream.getInstance(logFileAddr=LOG_FILE_ADDR, enableLogs=False, ... |
def load_data(input_data_sheet_path):
# Read excel data into dataframe
return pd.read_excel(input_data_sheet_path)
def load_ontology():
global bfo_onto, iof_annotation_onto, iof_core_onto, functional_breakdown_onto, asset_list_onto, maintenance_activity_onto, work_order_onto, maint_activity_classification_r... | The main task of the code is to populate an ontology with data from a specific row of an Excel dataset, using command-line arguments to specify the row index and whether to save merged data. It reloads the ontology each run to avoid caching issues, processes the selected data row, and saves the populated ontology as an... | def main():
print("Starting Population Script")
input_data_sheet_path = "data.xlsx"
data_frame = load_data(input_data_sheet_path)
i = int(sys.argv[1]) # cannot loop because of owlready caching.
save_merged = bool(sys.argv[2]) if len(sys.argv) >= 2 else False
load_ontology() # reload ontolog... |
def readFileContent(path: str) -> str:
f = open("users.txt", "r")
lines = f.readlines()
f.close()
return lines
def computeSolution(file_content: str) -> (int, str):
required_keys = {"usr", "eme", "psw", "age", "loc", "fll"}
nvalid_users = 0
last_valid_username = ""
user_data_chunks = ge... | The main task of the code is to read data from a file named "users.txt", process it using a computation function, and output the results. The `main()` function orchestrates these steps: reading input, computing a solution, and printing the outcome. | def main():
content = readFileContent("users.txt")
results = computeSolution(content)
printResults(results) |
def get_run_status(self):
""" Return the status of the run, that is the trello card where it needs to be placed
"""
demux_started = self._is_demultiplexing_started() # True if demux is ongoing
demux_done = self._is_demultiplexing_done() # True if demux is done
sequencing_done = s... | The main task of the code is to check if all demultiplexing (demux) jobs for a HiSeq run are completed. If all demux jobs are done, it aggregates the results, initializes a RunParser, and renames undetermined samples. It examines each demux job's status by checking for a completion file, logs progress, and triggers agg... | def check_run_status(self):
"""
This function checks the status of a run while in progress.
In the case of HiSeq check that all demux have been done and in that case perform aggregation
"""
run_dir = self.run_dir
dex_status = self.get_run_status()
#in this ca... |
def _set_sequencer_type(self):
self.sequencer_type = 'HiSeqX'
def _set_run_type(self):
self.run_type = 'NGI-RUN'
def _copy_samplesheet(self):
ssname = self._get_samplesheet()
ssparser = SampleSheetParser(ssname)
indexfile = dict()
# Loading index files
try:
... | The code initializes a HiSeqX_Run instance by calling the parent class constructor with `run_dir` and `samplesheet_folders`, then sets the sequencer type, run type, and copies the samplesheet to prepare for processing. | def __init__(self, run_dir, samplesheet_folders):
super(HiSeqX_Run, self).__init__( run_dir, samplesheet_folders)
self._set_sequencer_type()
self._set_run_type()
self._copy_samplesheet() |
def clear_frame(self,frame):
"""
:return: clears all data in a frame
"""
for widgets in frame.winfo_children():
widgets.destroy()
def num_of_planets(self, players):
"""
:param players: a int value 2,4,6,8 number of players
:return: generates the number... | The code generates game assets by gathering user inputs, creating two lists (p_lst for planet details and l_lst for positions), and updating the UI with icons, campaign details, and card data. It separates lists for easier modification, adjusts fleet numbers, maps regions, and clears previous UI data before rendering n... | def generate(self):
"""
function gathers user input and generates the play assets into 2 lists
p_lst (planet list) is the name, vp and details of the asset
l_lst(location list) is the x,y co ord amended onto the p_lst
the lists are seperate to make modifing them later eaiser
... |
def prep_batch(self, train_data):
try:
if self.params.get('ndata') == "mnist":
self.inputs, self.labels = (train_data[0].view(-1, 28 * 28)).to(self.device), train_data[1].to(
self.device)
else:
self.inputs, self.labels = train_data[0].t... | The code trains a multi-level model by iterating through training data, initializing counters for accuracy and samples, performing optimization cycles via `mgopt_cycle`, and collecting statistics periodically. It handles data preparation, triggers statistics collection at specified intervals, and exits early if `prep_b... | def train(self, epoch, params):
self.trainloader_iter = iter(self.trainloader)
for i in range(self.num_levels):
self.train_total[i] = 0
self.train_correct[i] = 0
for train_data in self.trainloader_iter:
if not self.prep_batch(train_data):
sel... |
def initialize_parameters_random(self):
for l in range(1, self.num_layers + 1):
self.weights.append(
np.random.rand(self.num_nodes_layers[l], self.num_nodes_layers[l - 1]))
def forward_propogation(self, x):
# dim of A vector: (no. of hidden nodes * num_data) *(no. of layers)... | This code trains a neural network using mini-batch gradient descent. It initializes parameters, performs forward/backward propagation, updates weights, tracks training/validation loss, and implements early stopping if validation loss stagnates for 5 epochs. The function returns arrays of training and validation losses ... | def model(self):
mini_batch = int((self.num_data) / (self.batch_size))
self.initialize_parameters_random()
# if self.activation_function == "linear":
# self.initialize_parameters_random()
# elif self.activation_function == "sigmoid" or self.activation_functi... |
def percent_data_missing(df):
df = pd.DataFrame(df)
sorted_index_list = np.argsort(np.sum(df == 0))
return sorted_index_list
def predictContinuousFeature(train_data, test_data, isFeatureReal_train, isFeatureReal_test, col_to_predict, predicted_indexes, x_testing):
m, k = train_data.shape
isF... | This code imputes missing values in training and test datasets by iteratively predicting missing entries for each feature. It starts with the column having the least missing data, removes rows with missing values in that column, then predicts missing values for subsequent columns. Continuous features use predictContinu... | def model(X_prime_train, X_prime_test, isFeatureReal_train, isFeatureReal_test, categoricalFeatures):
# identify col with least percent of missing data.
sorted_index_list = percent_data_missing(X_prime_train)
first_col = sorted_index_list[0]
# remove rows with first_col missing
m, k = X_prime_trai... |
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 code returns a dictionary containing an object's age in various time units (years, months, days, etc.) and related details, including the birthday's weekday. It aggregates values from methods like `years()`, `total_months()`, and `today_seconds()` to provide a comprehensive age breakdown in different formats. | 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 crop(self, percentage):
x_min = int(self.image.shape[1] * percentage)
x_max = int(self.image.shape[1] * (1 - percentage))
y_min = int(self.image.shape[0] * percentage)
y_max = int(self.image.shape[0] * (1 - percentage))
self.image = self.image[y_min:y_max, x_min:x_max]
def p... | This code processes an image by loading, cropping, converting to grayscale, applying preprocessing (blurring), edge detection, and contour analysis. It isolates a specific color (e.g., pink) using a color mask, compares the area of the color region to the total contour area, and calculates the percentage of color cover... | def __init__(self, name, blur = 5, method = 'Gaussian', lower_bound = 120, upper_bound = 250, central_percentage = .2):
path = os.path.join('Sample_Images/Original_Images', name)
self.original_image = cv2.imread(path)
self.name = name
self.image = np.copy(self.original_image)
s... |
def get_input(query: str = "",
numOnly: bool = False,
numMin=None,
numMax=None,
acceptBlank: bool = False,
rawStr: bool = False):
if not rawStr:
query += ": "
while True:
try:
inp = input(query)
if not ... | This function deletes a POI (Point of Interest) entry by taking a user-input ID, searching for it in a dataset, and removing the corresponding entry if found. It first validates the input ID as a non-negative number, checks if the POI exists using `search_poi`, and deletes the record if located. If the POI is not found... | def user_delete_poi():
id = get_input("Enter a poi ID to delete", numOnly=True, numMin=0)
lineNum = search_poi(id, useLineNum=True)
if lineNum == -1:
print("Query not found")
else:
delete_line(lineNum)
print(f"Successfully deleted POI {id}") |
def disp_options():
print("Selection an option from the list below:")
print("0) Exit\n1) Add POI\n2) Search POI\n3) List all POIs\n4) Search POI name\n5) Delete POI\n6) Make enquiry\n7) Answer enquiry")
choice = get_input("Enter option", numOnly=True, numMin=0, numMax=8)
return choice
def add_poi() -> N... | The code defines a menu-driven POI (Point of Interest) management application. It loops to display options for adding, searching, listing, deleting POIs, and handling inquiries. User choices trigger corresponding functions like `add_poi()`, `user_search_poi()`, `list_poi()`, etc., with option 0 exiting the loop. The ma... | def run():
print("POI application")
choice = None
while True:
choice = disp_options()
print()
match choice:
case 0:
return
case 1:
add_poi()
case 2:
user_search_poi()
case 3:
... |
def stored(bb, ostrm):
bln = bb.getbyte() | (bb.getbyte() << 8)
nln = bb.getbyte() | (bb.getbyte() << 8)
if (~bln & nln) != nln:
raise Exception("Bad length value for stored block")
while bln:
ostrm.append(bb.getbyte())
bln -= 1
def fixed(bb, ostrm):
lengths = []
lengths... | The function `inflate` decompresses data by processing blocks of compressed data. It reads bitstreams using `BitReader`, identifies block types (stored, fixed, or dynamic), and delegates decompression to corresponding helper functions (`stored`, `fixed`, `dynamic`). Each block is processed iteratively until the end of ... | def inflate(data):
global blockcount
bb = BitReader(data)
ostrm = ByteBuffer()
bfinal = 0
while not bfinal:
bfinal = bb.getbits(1)
bb.dropbits(1)
btype = bb.getbits(2)
bb.dropbits(2)
#print(f"last block {bfinal}")
#print(f"block type {btype} o... |
def read16(handle, avance=True):
r = handle.read(2)
if len(r) != 2:
raise Exception(f"not a marker (read <> 2) {r}")
if not avance:
handle.seek(handle.tell() - 2)
return r[0] << 8 | r[1]
def findcomponent(jpg, n):
j = 0
for c in jpg.components:
if c.id == n:
... | The function parses the JPEG SOS (Start Of Scan) marker, validating component IDs, setting DC/AC Huffman tables, and configuring scan parameters. It checks for valid component counts, spectral ranges, and progressive scan settings. If non-progressive, it skips bytes or decodes directly; if progressive, it prepares for ... | def parseSOS(handle, jpg):
position = handle.tell()
r = read16(handle)
s = ord(handle.read(1))
if s != 1 and s != 3:
raise Exception("bad number of components")
component = None
print(f"SOS: number of components {s}")
corder = []
for i in range(s):
c = ord(handle.read(... |
def read16(handle, avance=True):
r = handle.read(2)
if len(r) != 2:
raise Exception(f"not a marker (read <> 2) {r}")
if not avance:
handle.seek(handle.tell() - 2)
return r[0] << 8 | r[1]
def parseAPP0(handle, jpg):
position = handle.tell()
r = read16(handle)
s = handle.read(... | The function parses JPEG image segments from a file handle by reading and processing markers like SOF, DQT, DHT, SOS, and EOI. It updates the JPG object with image metadata, handles progressive and interleaved formats, and returns the parsed image data once all segments are processed, raising exceptions for unsupported... | def parsesegments(handle):
jpg = JPG(handle)
while True:
try:
m = read16(handle)
except:
if jpg.decoded:
print("end of input")
return jpg
raise
s = ""
if m in markers:
s = markers[m]
print(f... |
def show_Online(client):
client.send("Online Users:\n".encode())
for key in clients:
client.send(f"(({clients[key][0]})) AKA '{clients[key][1]}'\n".encode())
client.send("\n1-Enter [R] to return to the Menue \n".encode())
client.send("\n2-Enter [/Close!] to Close the Application \n".encode())
... | The code displays a menu of options to a client in a P2P chat application, allowing them to view online users, create/join chat rooms, change nicknames, or logout. It processes user input by calling corresponding functions like show_Online, create_chat_room, etc., until the user logs out, breaking the loop. | def Show_Menue(client):
while True:
# client.send(str(Fore.WHITE+"Welcome To the Local P2P Chatting Application\n").encode())
client.send("Welcome To the Local P2P Chatting Application\n".encode())
client.send("1- Press [1] To See Online Users\n".encode())
client.send("2- Press [2] ... |
def Login_or_register(client):
# client.send(str(Fore.WHITE+"Welecome To the Local P2P Chatting Application\n").encode())
client.send("Welcome To the Local P2P Chatting Application\n".encode())
client.send("1- Enter [login] to login\n".encode())
client.send("2- Enter [Register] if You are New!\n".encod... | This function handles client connections by authenticating users, collecting nicknames, broadcasting online status, and managing client sessions. It registers clients, sends welcome messages, displays menus, and handles disconnections by cleaning up resources and notifying other clients of status changes. | def Handle_Client(client,address):
while True:
try:
Username = Login_or_register(client)
print(f"Connected with {str(address)}")
client.send('Choose Your Nickname'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
clients[client]=[Use... |
def show_Online(client):
message = Fore.RESET + "Online Users:\n"
for key in clients:
username = clients[key][0]
nickname = clients[key][1]
online_user_info = f"{Fore.CYAN}{username}{Style.RESET_ALL} AKA '{Fore.GREEN}{nickname}{Style.RESET_ALL}'\n"
message += online_user_info
... | The main task of the code is to display a menu for a P2P chat application, allowing users to view online users, create/join chat rooms, change nicknames, or logout. It sends options to the client, processes their input, and routes them to corresponding functions like show_Online, create_chat_room, or Logout, maintainin... | def Show_Menue(client):
while True:
# client.send(str(Fore.WHITE+"Welcome To the Local P2P Chatting Application\n").encode())
client.send(f"Welcome '{clients[client][1]}'To the Local P2P Chatting Application\n".encode())
message = "1- Press [" + Fore.YELLOW + "1" + Style.RESET_ALL + "] To "... |
def Login_or_register(client):
# client.send(str(Fore.WHITE+"Welecome To the Local P2P Chatting Application\n").encode())
client.send("Welcome To the Local P2P Chatting Application\n".encode())
client.send("1- Enter [login] to login\n".encode())
client.send("2- Enter [Register] if You are New!\n".encod... | This code handles client connections by authenticating users, assigning nicknames, broadcasting online status, and managing disconnections. It maintains a client registry, notifies other users of connection changes, and ensures proper cleanup when clients disconnect. | def Handle_Client(client,address):
while True:
try:
Username = Login_or_register(client)
print(f"Connected with {str(address)}")
client.send('Choose Your Nickname'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
clients[client] = [U... |
def Login_or_register(client):
# client.send(str(Fore.WHITE+"Welcome To the Local P2P Chatting Application\n").encode())
client.send("Welcome To the Local P2P Chatting Application\n".encode())
message = "1- Enter [" + Fore.GREEN + "login" + Style.RESET_ALL + "] to login\n"
client.send(message.encode())
... | This function handles client connections by authenticating users, assigning nicknames, broadcasting online status, and managing disconnections. It stores client data in a dictionary, sends welcome messages, and handles errors like disconnections by notifying other users and cleaning up resources. | def Handle_Client(client, address):
try:
while True:
try:
Username = Login_or_register(client)
message = "Connected with " + Fore.GREEN + f"{str(address)}" + Style.RESET_ALL
print(message)
message = Fore.YELLOW + "Choose your Nickna... |
def _print_build(self, message: str) -> None:
"""Print wrapper to print only when the `show_build` flag is `True`.
Prints the given message to the console.
"""
if self._show_build:
print(message)
def read(self) -> None:
"""Reads the data provided as the `filepath`.
... | This code initializes a configuration object with widgets, loading data from either provided input or a file. It sets up hooks for widgets, enabling dynamic data binding, and configures save-on-change behavior. The class manages data storage, hook construction via a loader if provided, and triggers callbacks for data c... | def __init__(
self,
name: str,
widgets: list[QWidget],
data: Optional[dict] = None,
filepath: Optional[str] = None,
loader: Optional[QConfigDynamicLoader] = None,
*,
recursive: bool = True,
allow_multiple_hooks: bool = False,
save_on_change... |
def do_contours_make_square(contours, tolerance=0.05):
if len(contours) > 4:
print('This function does not support more than 4 contours')
sys.exit(1)
centers = []
for co in contours:
centers.append([co.cX, co.cY])
d1 = calc_distance(centers[0], centers[1]) # top left & top rig... | The function checks if three conditions are met: whether triangle contours form a square, align with a 'plus' shape, and contain the plus. It returns True if all conditions are satisfied, printing "TARGET FOUND!" otherwise. | def is_target_found(plus, triangles):
print('-----')
found = do_contours_make_square(triangles, tolerance=0.1) and \
do_contours_align_to(triangles, plus, tolerance=16.0) and \
does_plus_lie_in_triangles(plus, triangles)
if found:
print("TARGET FOUND!")
return found |
def find_ME_dot(M_BH):
"""
Input: BH mass in g
return: Accretion rate at Eddington luminosity in g/s
"""
return 1.4e18 * M_BH / M_sun
def find_MBH_dot(ME_dot, eddington_ratio):
"""
Input:
ME_dot: Accretion rate at Eddington luminosity in g/s
edding... | The code initializes a class to model a black hole accretion disk system, calculating key physical parameters such as mass accretion rates (ME_dot, MBH_dot), bolometric luminosity (L_bol), disk emission (Fnu_average), optical depth (tau), and infall scaling factor (sf_inf). It uses input values like black hole mass (M_... | def __init__(self, t0: float, M_BH: float, lam: np.ndarray, edd_ratio: float, rng):
self.lam = np.asarray(lam)
self.t0 = t0
self.rng = np.random.default_rng(rng)
self.ME_dot = self.find_ME_dot(M_BH)
self.MBH_dot = self.find_MBH_dot(self.ME_dot, edd_ratio)
self.Fnu_averag... |
def _goToStartOfPacket(self):
# Need to read TWO sync bytes, then you are at the start of a packet
syncByteCode = 0xaa
maximumBytesBeforePacketSync = 200 # to prevent this test from running forever
bytesRead = 0
while(bytesRead < maximumBytesBeforePacketSync):
receiv... | The code tests incoming packets by repeatedly reading and validating each packet's payload and checksum until a specified number of packets are processed. It initializes a counter, loops while the counter is less than the target number of packets, resets the packet position, reads a packet's data and checksum, verifies... | def testIncomingBytes(self):
numberOfTestedPackets = 0;
while(numberOfTestedPackets < numberOfPacketsToTest):
self._goToStartOfPacket();
payloadBytes, checkSum = self._readOnePacket();
self._checkPacket(payloadBytes, checkSum);
numberOfTestedPackets += 1 |
def read_data():
train_input = []
train_target = []
dev_input = []
dev_target = []
test_input = []
with open('train.csv', 'r') as training_file:
training_read = csv.reader(training_file)
training_read.__next__()
for line in training_read:
line = [int(line[i])... | The main task of the code is to train a neural network with specified parameters (10 layers, 4 units, learning rate 0.0001) using a custom optimizer, applying L2 regularization (λ=0.01) on the training data for 100 epochs. It evaluates the model's performance by generating predictions on the test dataset after training... | def main():
max_epochs = 100
batch_size = 32
#test teh best learning rate
learning_rate = 0.0001
num_layers = 10
num_units = 4
lamda = 0.01 # Regularization Parameter
train_input, train_target, dev_input, dev_target, test_input = read_data()
net = Net... |
def read_data():
dev = pd.read_csv('dev.csv')
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
train_target = np.array(train.iloc[:,0])
train_target = one_hot(train_target)
dev_target = np.array(dev.iloc[:,0])
dev_target = one_hot(dev_target)
train_input = np.array(t... | The main task of the code is to train a 2-layer neural network with 8 units per layer using Adam optimizer and L2 regularization (λ=0.1) on a dataset. It performs 128 epochs of training with batch size 32, validates on a development set, and generates predictions for the test set. Hyperparameters include learning rate ... | def main():
max_epochs = 128
batch_size = 32
learning_rate = 0.0001
num_layers = 2
num_units = 8
lamda = 0.1 #egularization Parameter
train_input, train_target, dev_input, dev_target, test_input = read_data()
net = Net(num_layers, num_units)
optimizer = Optimizer(learning_rate, ba... |
def masked_minmax(self, x, axis):
if not x.mask.any():
return self.minmax(x, axis)
# report min of max, whichever has greater abs value
a = x.squeeze()
mx = np.expand_dims(np.ma.max(a, axis=axis), axis=axis)
mn = np.expand_dims(np.ma.min(a, axis=axis), axis=axis)
... | This code initializes a data processing class to compute and save statistical differences (e.g., max, min, mean, median) between two datasets over specified time periods (annual, monthly, bimonthly). It validates inputs, selects relevant species data, defines statistical operations, and processes files to generate outp... | def __init__(self, fname1, fname0, oname, period='annual', thres=None):
self.fname0 = fname0
self.fname1 = fname1
if period not in ('annual', 'monthly', 'bimonthly'):
raise ValueError(f'period: {period}')
self.period = period
# get species to process
spc = [_... |
def my_max(self, x, axis):
myfnc = [np.amax, np.ma.max][x.mask.any().astype(int)]
o = myfnc(x, axis=axis)
self.drop_edges(o)
return o
def my_avr(self, x, axis):
myfnc = [np.average, np.ma.average][x.mask.any().astype(int)]
o = myfnc(x, axis=axis)
self.drop_edges(o... | The main task of the code is to initialize an object for processing climate or data files, identifying a specific species from the filename, configuring statistical calculations (maximum, mean, median, count) based on the specified period (annual/monthly/bimonthly), and saving the computed statistics to an output file.... | def __init__(self, fname, oname, period='annual', thres=None):
self.fname = str(fname)
if period not in ('annual', 'monthly', 'bimonthly'):
raise ValueError(f'period: {period}')
self.period = period
# get species to process
spc = [_ for _ in known_spc if _ in self.f... |
def get_class():
title_text()
print('Choose Class:\n\nWarrior Ranger\n')
valid_response = False
while not valid_response:
call()
try:
user.assign_class(user_response)
valid_response = True
except ClassCreationError:
print('Please choose a ... | The code defines a `setup` function that initializes a system or application by sequentially calling three helper functions: `get_class()` to retrieve or define a class, `get_name()` to obtain or set a name, and `intro()` to handle introductory logic or setup steps. The primary task is to orchestrate initialization pro... | def setup():
get_class()
get_name()
intro() |
def print_condition(enemy):
clear()
print(f'Your health: {user.hp} / {user.max_hp}\n'
f'Poison: {user.poison}\n\n'
f'{enemy.name}\'s health: {enemy.hp} / {enemy.max_hp}\n'
f'Poison: {enemy.poison}\n')
def call():
global user_response
user_response = input('> ').strip().lowe... | This function presents a user menu in a game where the player can choose to use moves or items against an enemy. It validates input, allows selecting moves (via 'm') or items (via 'i'), handles 'back' navigation, applies move effects, uses health potions (if available), and manages invalid inputs with error messages an... | def user_menu(enemy):
print_condition(enemy)
valid_response = False
while not valid_response:
print_condition(enemy)
print('Moves or Items\n')
call()
try:
if 'm' == user_response[0]:
valid_response2 = False
while not valid_respons... |
def user_menu(enemy):
print_condition(enemy)
valid_response = False
while not valid_response:
print_condition(enemy)
print('Moves or Items\n')
call()
try:
if 'm' == user_response[0]:
valid_response2 = False
while not valid_respons... | The code initiates a turn-based battle between the user and an enemy. It resets the user's HP and poison status, then enters a loop where the user selects actions via `user_menu`, while the enemy randomly chooses a move. The enemy's move is executed, and the battle continues until either the user or enemy dies, trigger... | def initiate_battle(enemy):
user.hp = user.max_hp
user.poison = 0
try:
while True:
user_menu(enemy)
used_move = enemy.moves[rand.randint(0, len(enemy.moves) - 1)]
print_condition(enemy)
print(f'{enemy.name} uses {used_move.name}')
time.slee... |
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
def initiate_battle(enemy):
user.hp = user.max_hp
user.poison = 0
try:
while True:
user_menu(enemy)
used_move... | The function `run_location` processes a game location by displaying scene descriptions, prompting user input, and initiating battles or shop scenes based on the `place` index, with specific enemies (goblin, elf, etc.) or shop interactions triggered for different locations. | def run_location(place):
clear()
print(location_list[place] + '\n')
input('PRESS ENTER TO CONTINUE')
clear()
if place == 0:
print('A goblin jumps out of the trees and attacks you!\n')
input('PRESS ENTER TO BATTLE!')
initiate_battle(goblin)
if place == 1:
shop()
... |
def isEnd(self, currBlack, currWhite):
currentBoard = self.createBoard(currBlack, currWhite)
white = self.isWhiteWinner(currentBoard)
if white != 0:
return white
return self.isBlackWinner(currentBoard)
def evaluation(self, currBlack, currWhite, maximizer):
value = 0
for e in currBlack:
value += (e[0... | This function implements the Alpha-Beta pruning algorithm for a two-player game, recursively evaluating all possible moves up to a specified depth. It alternates between maximizing and minimizing players, calculating the best move by comparing evaluation scores and pruning non-optimal branches. The function returns the... | def alphaBetaPlayer(self, depth, currBlack, currWhite, maximizer, alpha, beta, maxDepth):
if depth == maxDepth or self.isEnd(currBlack,currWhite):
return self.evaluation(currBlack, currWhite, maximizer)
if maximizer:
best = -1000000
all_valid_moves = self.findAllMoves(currBlack,currBlack,currWhite,maximize... |
def reset(self, seed=None):
if seed is not None:
self.seed = seed
self.random = np.random.RandomState(self.seed)
self._respawn()
self.steps = 0
self.countdown = 0
self.done = False
return self._obs()
def _respawn(self):
target_pad = list(... | The code implements a step function for an environment where an agent navigates a grid. It updates the agent's position based on the action, checks boundaries, tracks a sequence of pads stepped on, and rewards the agent if the sequence matches a target. If the episode ends, it resets; otherwise, it returns the observat... | def step(self, action):
if self.done:
return self.reset()
self.steps += 1
self.done = self.done or (self.steps >= self.length)
if self.countdown:
self.countdown -= 1
if self.countdown == 0:
self._respawn()
else:
... |
def clr_screen():
goto(-175, -310)
down()
fillcolor('blue')
begin_fill()
for i in range(2):
forward(30)
left(90)
forward(350)
left(90)
end_fill()
up()
return
def set_X(row, column):
mycross = turtle.Turtle()
mycross.hideturtle()
mycross.speed(2... | This code handles a turn-based grid game, tracking player moves on a board. When a cell is clicked, it updates the board with 'X' or 'O' based on the turn, switches turns, and checks game outcomes. It also uses an AI to place 'O' at the best move. The game ends when all cells are filled, displaying "GAME END". | def clicked_grid(x, y):
global next_turn
if next_turn == 0:
next_turn = next_turn + 1
print(next_turn)
print("You clicked", int(x), ",", int(y), "in clicked grid")
if x in range(-300, 300) and y in range(-300, 300):
row = int((300 - y) // width)
column = int((x + 300) // wid... |
def easy(self, gameModel, moveList):
choice = random.choice(moveList)
# Don't play queen on turn 1
while gameModel.turnNum == 1 and 'Q' in choice[:3]:
choice = random.choice(moveList)
print(choice)
return choice
def medium(self, gameModel, moveList):
return se... | The function `bestMove` determines the optimal move in a game by selecting a strategy based on the given difficulty level. It retrieves valid moves from the game model, handles edge cases like no available moves, and delegates move calculation to `easy`, `medium`, or `hard` methods. It also validates the difficulty inp... | def bestMove(self, gameModel, difficulty=0, maxTime=None, maxDepth=None):
# print('bestMove')
validMoves = gameModel.validMoves()
moveList = [p for p in validMoves.split(";") if p != '']
if len(moveList) == 0:
return "pass"
if "" in moveList:
print(moveLis... |
def pauseAPScheduler():
scheduler.pause_job(id=SEARCH_AND_PREDICT)
return 'Scheduler Paused', 200
def vectorize_payload(payload):
vec_255 = [0]*255
vectorizer = CountVectorizer(analyzer='char', ngram_range=(1, 1))
vectorized = vectorizer.fit_transform([payload])
mapped = list(zip(vectorizer.get_... | The code's main task is to analyze network payload data for anomalies by: (1) loading and preprocessing log data, (2) vectorizing payloads and applying PCA for dimensionality reduction, (3) computing mean-shifted features and covariance maps, (4) establishing thresholds using statistical properties, and (5) detecting a... | def search_and_predict():
pauseAPScheduler()
df = pd.read_csv(r'anomalous.csv', sep=',', error_bad_lines=False, index_col=False, dtype='unicode')
# df = pd.read_json(r'2021-10-06.json', convert_dates=True, lines=True)
#Should have atleast 2 logs
if len(df) >= 2:
df_reduced = df.iloc[:100000]
df_reduced = df_... |
def pauseAPScheduler():
scheduler.pause_job(id=SEARCH_AND_PREDICT)
return 'Scheduler Paused', 200
def vectorize_payload(payload):
vec_255 = [0]*255
vectorizer = CountVectorizer(analyzer='char', ngram_range=(1, 1))
vectorized = vectorizer.fit_transform([payload])
mapped = list(zip(vectorizer.get_... | The main task of the code is to reduce the dimensionality of network payload data using PCA (Principal Component Analysis) on frequency features, compute statistical properties (mean, variance, covariance) of compressed data, and save these results for further analysis or prediction tasks. It processes a CSV dataset, f... | def search_and_predict():
pauseAPScheduler()
df = pd.read_csv(r'norm.csv', sep=',', error_bad_lines=False, index_col=False, dtype='unicode')
if len(df) >= 2:
df_reduced = df.iloc[:1000]
df_reduced = df_reduced[df_reduced['payload'].notnull()].copy()
number_of_observations = len(df_reduced)
# Vectorizing a... |
def _move_to_device(
cls,
_input,
device: torch.device,
dtype: torch.dtype = None):
if not torch.cuda.is_available() and not device == torch.device('cpu'):
warnings.warn("CUDA not available! Input remains on CPU!", Warning)
if isinstance(_inpu... | The code upsamples a sequence of image pairs by generating intermediate frames using optical flow, then saves the resulting frames and their timestamps to specified directories and files. It processes each image pair, computes flow fields, applies adaptive upscaling, sorts output frames by time, and writes them as imag... | def upsample_sequence(self, sequence: Sequence, dest_imgs_dir: str, dest_timestamps_filepath: str):
os.makedirs(dest_imgs_dir, exist_ok=True)
timestamps_list = list()
idx = 0
for img_pair, time_pair in tqdm(next(sequence), total=len(sequence), desc=type(sequence).__name__):
... |
def makeset(v):
v.pi = v
v.height = 0
def find(v):
if not v.isEqual(v.pi):
v.pi = find(v.pi)
return v.pi
def union(u,v):
# find the roots of the trees for u and v
ru = find(u)
rv = find(v)
if ru == rv:
return
# make shorter set point to taller set
if ru.height >... | The code implements Kruskal's algorithm to construct a Minimum Spanning Tree (MST). It initializes disjoint sets for each vertex, iterates through edges, and adds an edge to the MST if it connects two disjoint sets, then unites those sets. This ensures the MST includes the smallest edges without cycles. | def kruskal(adjList, edgeList):
# initialize all singleton sets for each vertex
for vertex in adjList:
makeset(vertex)
mst = []
for edge in edgeList:
# if the min edge crosses a cut, add it to MST
u, v = edge.vertices
if not find(u).isEqual(find(v)):
mst.app... |
def bbox_to_xyz(lon_min, lon_max, lat_min, lat_max, z):
x_min, y_max = latlon_to_xyz(lat_min, lon_min, z)
x_max, y_min = latlon_to_xyz(lat_max, lon_max, z)
return(floor(x_min), floor(x_max),
floor(y_min), floor(y_max))
def createdir(identifier):
"""
Create directories for storing tiles an... | The function `calldownloadfun` downloads and georeferences map tiles for a specified geographic area at a given zoom level. It converts bounding box coordinates to tile indices, creates directories, iterates over tile ranges, downloads tiles from a Google server, and georeferences each tile. It returns temporary and ne... | def calldownloadfun(zoom_level, lon_min, lon_max, lat_min, lat_max, identifier, boundary=False):
"""
zoom_level: zoom level int
lon_min: min longitude
lon_max: max longitude
lat_min, lat_max: min & max latitude
"""
x_min, x_max, y_min, y_max = bbox_to_xyz(lon_min, lon_max, lat_min, lat_max, ... |
def make_list(var):
if type(var) is not list:
var = [ var ]
return(var)
def ingest_teams(self):
#pull json data from API
r = requests.get(
'https://api.collegefootballdata.com/teams'
).json()
df = pd.DataFrame(r)
df['logos'] = df['l... | The main task of the code is to ingest sports-related data (teams, venues, schedules, rankings, talent, player usage) for specified years into a database, then export all tables in the 'sports' schema to CSV files for data storage or analysis. | def ingest_all(self, year_list, current_season_year):
year_list = make_list(year_list)
self.ingest_teams()
self.ingest_venues()
self.ingest_schedule(year_list)
#self.ingest_rankings_old_method(year_list)
self.ingest_rankings(year_list)
self.ingest_talent(... |
def __merge_rankings_into_schedule_data(self, schedule_df, rankings_df):
#temp_df1 is the schedule data
temp_rank_df1 = schedule_df.copy()
#temp_df2 is the ranking data
temp_rank_df2 = rankings_df.copy()
#temp_df3 is where temp_dfs 1 and 2 get combined
#start with merg... | This method aggregates multi-year college football schedules, rankings, and poll data for all teams, merges rankings into schedules, filters for latest season/week rankings, flags watch-listed teams, and generates detailed per-team schedules with game status indicators, next/last game info, and matchup history for each... | def GetMultiYearScheduleAllTeams(self):
#set up a coupleof empty dataframes
self.df_multi_yr_schedule_all_teams = pd.DataFrame()
self.all_ranking_data = pd.DataFrame()
self.all_poll_data = pd.DataFrame()
#for all years in range
for year_item in range(self.curre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.