dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def testHiddenMessage():
print("Testing hiddenMessage()...", end="")
assert(hiddenMessage("I'm here") == "Ie")
assert(hiddenMessage("Come to office hours") == "Cofr")
assert(hiddenMessage("I") == "I")
assert(hiddenMessage("See May Day") == "Say")
assert(hiddenMessage("Happy Very Yelp Call Yellow... | The code defines a function `testAll()` that sequentially calls multiple test functions: `testHiddenMessage()`, `testLetterFrequency()`, `testOnlyPositive()`, `testRecursiveMax()`, and `testRecursiveCount()`. Its main task is to execute these tests, likely validating the correctness of corresponding implementations (e.... | def testAll():
testHiddenMessage()
testLetterFrequency()
testOnlyPositive()
testRecursiveMax()
testRecursiveCount() |
def testFindMatchingParen():
print("Testing findMatchingParen()...", end="")
expr = "(((X) AND (NOT ((Y) OR (X)))) OR (Y))"
assert(findMatchingParen(expr, 0) == len(expr) - 1)
assert(findMatchingParen(expr, 1) == 28)
assert(findMatchingParen(expr, 2) == 4)
assert(findMatchingParen(expr, 10) == 2... | The code defines a function `week1Tests()` that executes multiple unit tests to validate components of an expression parser. These tests include checking matching parentheses, token boundaries, expression parsing, and validation, ensuring the parser handles syntax and structure correctly. | def week1Tests():
testFindMatchingParen()
testGetTokenBounds()
testParseExpr()
testValidateExpr() |
def testGetLeaves():
print("Testing getLeaves()...", end="")
assert(getLeaves({ "value" : "X", "children" : [] }) == [ "X" ])
assert(getLeaves({ "value" : "Y", "children" : [] }) == [ "Y" ])
assert(getLeaves({ "value" : "AND", "children" : [
{ "value" : "X", "children" : [] },
{ "value" ... | The code defines a function `week2Tests()` that executes four test functions: `testGetLeaves()`, `testGenerateAllInputs()`, `testEvalTree()`, and `testMakeTruthTable()`. Its main task is to validate the correctness of implementations related to tree structures, logical operations, and truth tables, ensuring components ... | def week2Tests():
testGetLeaves()
testGenerateAllInputs()
testEvalTree()
testMakeTruthTable() |
def makeModel(data):
data["expression"] = ""
data["tree"] = None
data["inputs"] = {}
return
def makeView(data, canvas):
expText = "Expression: " + data["expression"]
canvas.create_text(100, 550, text = expText, anchor=SW, font = "Times 12 bold")
if data["tree"] != None:
drawCircuit... | The code runs a simulation GUI with a canvas of size w x h, initializing a model and view, and handling keyboard/mouse events for interaction. | def runSimulation(w, h):
data = { }
makeModel(data)
root = Tk()
canvas = Canvas(root, width=w, height=h)
canvas.configure(bd=0, highlightthickness=0)
canvas.pack()
makeView(data, canvas)
root.bind("<Key>", lambda event : keyEventHandler(data, canvas, event))
root.bind("<Button-1>",... |
def new_number(self, k=1):
free_poss = list(zip(*numpy.where(self.grid == 0)))
for pos in random.sample(free_poss, k=k):
if random.random() < .1:
self.grid[pos] = 4
else:
self.grid[pos] = 2
def draw_game(self):
self.screen.fill(colors['back... | The main task of the code is to run a game loop for a tile-swapping game, handling user input to swipe tiles, updating the grid state, checking for game over conditions, and adding new numbers when the grid changes. It initializes the game, displays the board, processes player commands, and manages game progression unt... | def play(self):
self.new_number(k=2)
for x in range(Z):
for y in range(Z):
self.sScore += self.grid[x][y]
while True:
self.draw_game()
pygame.display.flip()
cmd = self.wait_for_key()
if cmd == 'q':
break... |
def choose_random_subset():
global i_patches
global a_patches
global g_patches
global c_patches
global g_indices
choice = np.random.choice(len(i_patches), 5000, replace=False)
i_patches2 = [i_patches[ii] for ii in choice]
a_patches2 = [a_patches[ii] for ii in choice]
g_patches2 = [g... | The code generates cluster analysis plots for varying K values (2-9) and saves closest visualization data for specified cluster patches. It uses random image subsets from cities like Vegas/Shanghai, applies k-means clustering with a predefined 'good_k', and stores results in numpy files for further analysis or visualiz... | def plots_cluster_patches(get_plots=True, get_cluster_patches=False,good_k=0):
if get_plots:
i_patches, a_patches, g_patches, city_names, g_indices = choose_random_subset()
K = range(2, 10)
save_path = '/home/home1/swarnakr/main/DomainAdaptation/DA_viaBatchNorm/configs/ganDA/train_log/figsDA... |
def fulfills(example, hypothesis):
return more_general(hypothesis, example)
def min_generalizations(h, x):
h_new = list(h)
for i in range(len(h)):
if not fulfills(x[i:i+1], h[i:i+1]):
h_new[i] = '?' if h[i] != '0' else x[i]
return [tuple(h_new)]
def more_general(h1, h2):
mor... | The function generalizes the hypothesis set S by removing elements not fulfilled by x, adding their minimal generalizations, and pruning S to retain only non-redundant hypotheses that are not less general than others. | def generalize_S(x, G, S):
S_prev = list(S)
for s in S_prev:
if s not in S:
continue
if not fulfills(x, s):
S.remove(s)
Splus = min_generalizations(s, x)
S.update([h for h in Splus if any([more_general(g,h)
... |
def get_domains(examples):
d = [set() for i in examples[0]]
for x in examples:
for i, xi in enumerate(x):
d[i].add(xi)
return [list(sorted(x)) for x in d]
def g_0(n):
return ("?",)*n
def s_0(n):
return ('0',)*n
def fulfills(example, hypothesis):
return more_general(hypot... | The code implements the **Candidate Elimination Algorithm** to learn a hypothesis space from labeled examples. It maintains two sets: `G` (general hypotheses) and `S` (specific hypotheses). For each example, it updates `G` and `S` by either generalizing (for positive examples) or specializing (for negative examples), e... | def candidate_elimination(examples):
domains = get_domains(examples)[:-1]
G = set([g_0(len(domains))])
S = set([s_0(len(domains))])
i=0
print("\n G[{0}]:".format(i),G)
print("\n S[{0}]:".format(i),S)
for xcx in examples:
i=i+1
x, cx = xcx[:-1], xcx[-1]
if cx=='Y':
... |
def motif_family_init(motif_path):
list_f = os.listdir(motif_path)
list_f = sorted(list_f)
ptf = list_f[0].split('_')[0]
motif_family_dict = {}
motif_family_list = []
for i in range(len(list_f)):
f_name = list_f[i]
tf = f_name.split('_')[0]
# print(f_name)
if tf =... | The code's main task is to train a model (likely DeepRAM) with fine-tuning on transcription factor (TF) motif families. It initializes a motif family dictionary from a file, loads a TF family tree, trains the model using `train_with_fine_tune`, and saves the resulting scores to a text file. The process involves prepari... | def main():
motif_family_dict = {}
motif_family_dict = motif_family_init(motif_path)
tff = TFFamily('../../../tree')
# tf = tfs_df[0].map(lambda x : x.split('_')[0])
# tf_k = sorted(list(set(tf)))[17:]
# print(tf_k)
test_dict = {}
# print(motif_family_dict['BATF'])
# for k ... |
def set_header():
global bnf_ul
global nf_ul
global bnf_nearest
global nf_nearest
response_text = get_data(url_indices)
data = json.loads(response_text)
for index in data["data"]:
if index["index"] == "NIFTY 50":
nf_ul = index["last"]
print("nifty")
if... | The code defines a function `algo` that executes a trading strategy by initializing headers, retrieving expiry data for options, and triggering an algorithm implementation with parameters like option type, strategy, quantity, and order type, specifically targeting the Nifty index. It processes order execution based on ... | def algo(option, strategy, quantity, normal_order=True):
set_header()
print('\033c')
expiry = print_oi(10, 50, nf_nearest, url_nf)
algo_imp(option, strategy, expiry, "Nifty", nf_ul, nf_nearest, quantity, normal_order) |
def marble_noise(x, y, z, origin, size, shape, bias, sharpnes, turb, depth, hard, basis):
x = x / size
y = y / size
z = z / size
s = shapes(x, y, shape)
x += origin[0]
y += origin[1]
z += origin[2]
value = s + turb * turbulence_vector((x, y, z), depth, hard, basis)[0]
if bias == 1:... | This function generates a 3D landscape using fractal noise algorithms, applying parameters like noise type (multi_fractal, ridged_multi_fractal), height scaling, inversion, and edge falloff. It adjusts terrain based on seed, distortion, strata layers, and clamps values between sea level and plateau levels to create rea... | def landscape_gen(x, y, z, falloffsize, options):
# options = [0, 1.0, 'multi_fractal', 0, 0, 1.0, 0, 6, 1.0, 2.0, 1.0, 2.0, 0, 0, 0, 1.0, 0.0, 1, 0.0, 1.0, 0, 0, 0, 0.0, 0.0]
rseed = options[0]
nsize = options[1]
ntype = options[2]
nbasis = int(options[3][0])
vlbasis = int(options[4][0])
d... |
def sphere_gen(sub_d, size_me, options):
# mesh arrays
verts = []
faces = []
# fill verts array
for i in range (0, sub_d):
for j in range(0, sub_d):
u = sin(j * pi * 2 / (sub_d - 1)) * cos(-pi / 2 + i * pi / (sub_d - 1)) * size_me / 2
v = cos(j * pi * 2 / (sub_d - 1)... | This code generates a landscape mesh (sphere or grid) based on parameters like subdivision, noise settings, and smoothing. It disables undo during mesh creation, deselects objects, and restores undo settings afterward. If AutoUpdate is enabled, it creates the mesh; otherwise, it passes through without changes. | def execute(self, context):
#mesh update
if self.AutoUpdate != 0:
# turn off undo
undo = bpy.context.user_preferences.edit.use_global_undo
bpy.context.user_preferences.edit.use_global_undo = False
# deselect all objects when in object mode
i... |
def pre_query_libc(self) :
if self.libc_list == [] :
self.query_libc()
def determine_the_libc(self) :
if self.libc_list == [] :
print("\x1b[1;31m" +
"[+] No libc satisfies constraints." +
"\x1b[0m")
exit()
elif len(self.l... | The main task of the code is to retrieve the ID of a specified symbol in a libc library. It first prepares a libc query, determines the libc if not already set, then queries the symbol's ID using the libc's ID and the provided symbol name, returning the result. | def dump(self, symbol_name:str) -> int :
self.pre_query_libc()
if self.the_libc is None :
self.determine_the_libc()
return self.query_symbol(libc_id = self.the_libc['id'], symbol_name = symbol_name) |
def compute_movement_score(frames, start_idx, end_idx, SAD_weight=1, homography_weight=1, dx_weight=1, dy_weight=1):
"""
:param end_idx:
:param start_idx:
:param dy_weight:
:param dx_weight:
:param homography_weight:
:param SAD_weight:
:param frames: np.ndarray, dtype=np.uint8, shape=(n... | The function generates short video clips from specified frame ranges in a video, using movement and audio scores to name output files. It also computes and visualizes homographies for each segment, saving results to the given directory. | def create_scene_video_from_breaks(frames, audio_file, breaks, out_dir):
"""
:param audio_file:
:param frames: np.ndarray, dtype=np.uint8, shape=(n, r, c, ch)
the whole video frames
:param breaks: list of tuples (begin, end)
:param out_dir: string
:return:
"""
for i in range(len... |
def compute_scene_cuts(frames, threshold=100, minimum_length=30):
"""
split scenes, return tuple of index (begin, end)
:param minimum_length:
:param threshold: int
:param frames: np.ndarray, dtype=np.uint8, shape=(n, r, c, ch)
:return: list if tuple(begin frame index, end frame index)
"""
... | The function generates a summarized video by analyzing scenes from a combined video, scoring each scene based on movement and audio intensity, normalizing scores, weighting them, selecting top-scoring scenes totaling 100 seconds, and concatenating them into a final video. | def create_summarized_video_from_combined_video(whole_video_frames, combined_video_dir, audio_file_dir, output_dir):
# break scenes and give scene score
audio_file = AudioSegment.from_file(audio_file_dir)
scene_breaks = compute_scene_cuts(whole_video_frames)
scene_scores = []
for i in range(len(scen... |
def create_video_from_frames(frames, out_dir, file_name="frames.mp4"):
"""
create a video from frames image in frames_dir, save to out_dir
:param frames: np.ndarray, dtype=np.uint8, shape=(n, r, c, ch)
:param out_dir: string
:param file_name: string
:return: string, dir of the new video file
... | The code generates a summarized video by combining input frames into a video, merging it with an audio file, and producing a final summarized version. It creates an output directory, constructs a frame-based video, integrates it with audio, and refines the result into a summarized video. Key steps include directory han... | def create_summarized_video(frames, audio_file_dir, output_dir):
try:
os.makedirs(output_dir)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
# combine frames to a video
frame_video_dir = create_video_from_frames(frames, output_dir)
# combine fram... |
def read_frames_from_folder(frames_dir, start=0, end=-1):
"""
read all frames from frames folder
:param frames_dir: string
:return: np.ndarray, dtype=np.uint8, shape=(n, r, c, ch)
image array
"""
frame_names = [img for img in os.listdir(frames_dir)]
# take frame number out from "fra... | The function creates a summarized video by combining frames from a folder into a video, merging it with an audio file, and generating a summarized version. It handles directory creation, frame reading, video/audio combination, and final summarization, returning the result. | def create_summarized_video_2(frames_folder_dir, audio_file_dir, output_dir):
try:
os.makedirs(output_dir)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
# combine frames to a video
whole_video_frames = read_frames_from_folder(frames_folder_dir)
f... |
def create(self):
"""Create the Sudoku challenge grid"""
self.generate_grid() # generate the valid grid to self.grid
self.valid_grid = copy_grid(self.grid) # store the valid grid self.valid_grid
difficulty = 30 # max removed value
# removing the value from grid
while ... | (The code implements a game loop for a grid-based puzzle, allowing users to fill cells with numbers while validating inputs against constraints. It checks for a win condition when the grid matches a predefined valid state, handles restart/quit commands, and manages error states for invalid moves or unsatisfiable positi... | def play(self):
"""Starts the game"""
err = False
sat = True
prev = None
# initiate the game
self.create()
self.removed = dict(sorted(self.removed.items()))
while True:
self.clear()
self.title()
self.display_grid()
... |
def determine_split_candidates(df: pd.DataFrame) -> list[tuple[str, float]]:
'''Given a set of training instances, determine the feature/value pairs we can split on.
Args:
df:
The dataset we are trying to split.
Returns:
A list of (feature, value) tuples that we can split on (ex... | The function `make_subtree` recursively constructs a decision tree by splitting a dataset based on the best feature-value pair. If the dataset is empty or stopping criteria are met, it creates a leaf node labeled with the majority class. Otherwise, it splits the data, builds left/right subtrees recursively, and combine... | def make_subtree(df: pd.DataFrame) -> TreeNode:
print(f"dataset size = {df.shape}")
global stop_criteria_met
node = TreeNode()
best_split_feature, best_split_value = None, None # set later
if not df.empty:
split_candidates = determine_split_candidates(df)
(best_split_feature, best_s... |
def _cpu(self):
self._cpu_general()
self._per_cpu_usage()
self._per_cpu_frequency()
def _memory(self):
memory = psutil.virtual_memory()
swap = psutil.swap_memory()
data = DataReport(
items={
"memory": {
"total": memory.tota... | The main task of the code is to collect system performance data by gathering reports on CPU usage, memory usage, disk information, mount points, temperature sensors, and network status. | def _collect_data_reports(self):
self._cpu()
self._memory()
self._disks()
self._mountpoints()
self._temperature_sensors()
self._networks() |
def checkplaylist(self):
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
isFolder = os.path.isdir(desktop + "\\" + self.getEntryVal())
return isFolder
def createfolder(self):
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
des... | The main task of the code is to load a songlist from a selected text file, check for existing playlists, process each song entry by appending it to a list and triggering an action, create a folder, and notify observers. It handles errors like file not found and cancels if no file is selected. | def loadFile(self):
try:
if self.checkplaylist():
messagebox.showerror(title="Error", message="Songlist name has already existed!!!!!!")
return
filename = filedialog.askopenfilename(initialdir="/", title="Select File",
... |
def filterPart(p_l, p_r, bucket):
pointsLeft = []
pointsRight = []
for point in bucket:
det = LRPoint(p_l, p_r, point)
is_zero = math.isclose(det, 0, abs_tol=1e-5)
if (det > 0 and not is_zero):
pointsLeft += [point]
elif (det < 0 and not is_zero):
p... | This function computes a part of a convex hull using a divide-and-conquer approach. It splits points into left/right subsets, selects the farthest point from a line segment, and recursively constructs hull segments. If no points remain, it returns the base segment. The process combines results from left and right subdi... | def myConvexHullPart(p_l, p_r, points, is_left):
pointsLeft, pointsRight = filterPart(p_l, p_r, points)
if(is_left):
pointsPart = pointsLeft
else:
pointsPart = pointsRight
if(pointsPart.size == 0):
return [[p_l, p_r]]
else:
p_x = maxDistPointLine(p_l, p_r, pointsPa... |
def lower_profit(provider_prices, provider_costs, selected_provider, selected_resource, max_prices, quantities, user_preferences):
isValid, provider_price, provider_cost, user_profits = profit_helper(provider_prices, provider_costs, selected_provider, selected_resource, max_prices, quantities, user_preferences)
n... | The function determines the optimal price for a selected provider/resource by comparing profit scenarios (low, same, high) and returns the corresponding price. It prioritizes the highest profit, defaulting to 'same' profit price if neither low nor high profits are higher. | def updated_price(provider_prices,provider_costs, selected_provider, selected_resource, max_prices, quantities, user_preferences):
low_prof, low_price = lower_profit(provider_prices,provider_costs, selected_provider, selected_resource, max_prices, quantities, user_preferences)
same_prof, same_price = same_profit(p... |
def _run_cps_search(self, connection, session_url, MAX_CPS, MIN_CPS,
threshold, target_failures, test_settings, start_value=0):
test_run_results = []
test_value = start_value
test_iteration = 1
while ((MAX_CPS - MIN_CPS) > threshold):
test_result = ""... | The code's main task is to execute performance tests based on the specified configuration type (`cps` or `tcp_bg`). For `cps`, it runs a search to determine maximum CPS (connections per second) under constraints, while `tcp_bg` runs a background TCP test. It retrieves parameters, invokes internal methods to generate te... | def run(self):
if self.test_config_type == 'cps':
initial_objective = self.url_patch_dict['initial_objective']
MAX_CPS = self.url_patch_dict['MAX_CPS']
MIN_CPS = self.url_patch_dict['MIN_CPS']
threshold = self.url_patch_dict['threshold']
target_failur... |
def _createconfig_ixn(self, settings_dict, no_of_cards):
tb = settings_dict['ixn']
tb_ixn = tb['stateless'][0]
session_assistant = SessionAssistant(
IpAddress=tb_ixn['server'][0]['addr'],
RestPort=tb_ixn['server'][0]['rest'],
UserName=tb["CR"][tb_ixn['server... | This code initializes a network test configuration by setting up traffic generators, adjusting network parameters like ENI counts and IP ranges, configuring session settings, and preparing API endpoints based on the test type (e.g., 'udp_bg' or others). It calculates MAX_CPS values, initializes test iteration counters,... | def __init__(self, create_hero_config, test_config_type, id):
# Configure right traffic generator
self.id = id
self.test_config_type = test_config_type
if self.test_config_type == 'udp_bg':
self.ixnetwork = self._createconfig_ixn(create_hero_config, create_hero_config['num_... |
def do_total(self,xt_o,xr_o,x_s,x_sp):
num_u=10000
y=0
for i in range(num_u):#iterate over u get expectation
yt = self.do_total_per_instance(xt_o,x_s)
yr = self.do_total_per_instance(xr_o,x_s)
y = y + (yt-yr)
ret... | The code computes Shapley values for all possible coalitions of four elements (0-3) by evaluating their contribution using methods specified by 'kind' ('total', 'direct', or 'indirect'). It generates all coalitions, calculates their value via `do_total`, `do_direct`, or `do_indirect`, and stores results in a dictionary... | def compute_shapley(self,xt,xr,kind='direct'):
gc=[0,1,2,3]
ft_map={0:"x1",1:"x2",2:"x3",3:"x4"}
all_coalitions = list(combinations(gc))
val={}
for each_coalition in all_coalitions:
x_s=each_coalition
x_sp=set(gc).difference(x_s)
... |
def authorize(client):
"""Generate new token based on client (1 or 2)credentials and save it to token.dat"""
subprocess.run(f'./petfinder_auth{client}.sh', shell=True, universal_newlines=False)
def petfinder_request(request, client, new_token=False):
"""Make a petfinder API request. Return response dictiona... | The main task of the code is to download cat images from the PetFinder API for a specified ZIP code, handling rate limits, authentication refreshes, and server errors. It saves cat images locally, avoids duplicates, logs progress in 'index.txt', and uses multiple clients to manage API rate limits while iterating throug... | def download_cats(zipcode, n_pages=5, start_page=1, start_client=0):
"""Download n_pages of cats"""
# authorize
client = start_client # start with first client
authorize(client)
count = 0
# document every download to index.txt
for page in range(start_page, n_pages):
request = f'ani... |
def reinforce_train(self, batch):
info = self.model.forward(batch)
# reinforce
l_probs, rewards, entropy = info["l_probs"], info["rewards"], info["entropy"]
rewards = -rewards # minimize rewards
rewards = (rewards - torch.mean(rewards, dim=0, keepdim=True)) / (
to... | The code trains a model (actor-critic) using specified reinforcement learning methods (REINFORCE, A2C, PPO) or supervised learning. It processes batches from a dataset, accumulates actor loss (cla), critic loss (clc), entropy loss (cle), and total loss (cum_loss), then logs these metrics via wandb if enabled. | def train_epoch(self):
self.model.train()
self.critic.train()
train_data = DataLoader(self.datasets[0], self.batch_size, shuffle=True)
cla, clc, cle = 0, 0, 0
cum_loss = 0
for batch in train_data:
if self.train_type == "reinforce":
loss = se... |
def save_model(self, suffix):
os.makedirs("checkpoints", exist_ok=True)
os.makedirs(f"checkpoints/{self.config['timestamp']}", exist_ok=True)
torch.save(
self.model.state_dict(),
f"checkpoints/{self.config['timestamp']}/model_{suffix}.pt",
)
torch.save(
... | The code trains a model for a specified number of epochs, performing training and validation phases each epoch. It initializes a learning rate scheduler (StepLR) but does not use it (commented out). Model checkpoints are saved at the start, after each epoch (if caching is enabled), and at the end of training. The prima... | def train(self):
self.save_model("start") if self.cache else None
scheduler = StepLR(self.model_optimizer, step_size=1, gamma=0.99)
for epoch in range(self.epochs):
self.train_epoch()
self.val_epoch(epoch)
if self.cache:
self.save_model(epoch)
... |
def in_list(text, keywords):
return any(x in text.lower() for x in keywords)
def send_chat_message(channel, text):
client.chat_postMessage(channel=channel, text=text)
def upcoming_events():
#Grab the events url from the database
conn = open_connection()
c = conn.cursor()
events_url = c.execute('... | This code processes incoming messages in a chat application, extracting user input and triggering predefined responses or actions based on keywords. It handles queries about events, updates links in a database (with permission checks), provides information on requirements, rituals, and meetings, filters profanity, and ... | def message(payload):
#Extract all the necessary information from the payload
event = payload.get("event", {})
channel_id = event.get("channel")
user_id = event.get("user")
text = event.get("text")
message_id = event.get("ts")
#Ignore messages from the bot itself
if BOT_ID != user_i... |
def __place_snake(self):
"""
places the snake on the board
:return: -
"""
self.__service.place_initial_snake()
def __place_apples(self):
"""
places the apples on the board
:return: -
"""
self.__service.place_initial_apples()
def print_board... | The main task of the code is to initialize a game by placing the snake and apples on the board, displaying the initial state, and waiting for user input to start the game. Once the user types 'start', it triggers the game's play loop and exits the waiting state. | def run(self):
"""
starts the program
:return: -
"""
self.__place_snake()
self.__place_apples()
self.print_board()
while True:
cmd = input("type 'start' to start the game?")
if cmd == "start":
self.play()
... |
def generate_population(data, num_of_frogs, num_of_clusters, metric):
return [generate_bee(data, num_of_clusters, metric) for i in range(num_of_frogs)]
def update_bee(bee, k, dimensions, data, metric):
new_centroids = generate_new_centroids(bee, k, dimensions)
new_fit = fitness(data, new_centroids, metric)
... | The main task of the code is to perform clustering on input data using an Artificial Bee Colony (ABC) algorithm. It iteratively optimizes cluster centers by simulating bee behavior: workers generate new solutions, onlookers select promising ones probabilistically, and scouts replace stagnant solutions. The algorithm mi... | def abc(data, num_bees=30, num_of_clusters=3, max_iterations=50, metric='euclidean', discard_limit=20):
"""
:param data: the data to be clustered
:param num_bees: the number of bees - this is the number of potential solutions to be considered at one time
:param num_of_clusters: the number of clusters (... |
def get_crypto_data(pair, since):
# Making a call to the API
# The paramater passed is the type of data that we want to query 'OPEN, HIGH, LOW AND CLOSE' which are the different price points on the chart within a certain timeframe
# Within a given time period, we want to accumulate what the open price was... | The code analyzes cryptocurrency price data to determine trading opportunities by comparing current prices with moving averages and predefined thresholds. It checks for upward or downward trends, uses percentage changes to assess price movements, and decides to simulate buy/sell actions based on conditions like price t... | def analyze(pair, since, loop_cycle):
data = get_crypto_data(pair[0]+pair[1], since)
balance = get_fake_balance()
#balance = get_balance() uncomment when you want to trade with real money
last_trade = get_last_trade(pair[0]+pair[1])
available_crypto = float(balance['ANT'])
available_money =... |
def feedforward(self):
self.output = sigmoid(np.dot(self.input, self.weights) + self.bias)
def cost(self):
squared_err = np.square(self.output - self.y)
return squared_err
def backprop(self):
d_weights = np.dot(self.input.T, (2*(self.y - self.output) * deriv(self.output)))
d_bias = 2*(self.y - self.output) * ... | The code's main task is to train a neural network by iteratively performing forward propagation to compute predictions, calculating the cost (error) of those predictions, and applying backpropagation to adjust the model's parameters, minimizing the cost over multiple iterations. | def train(self):
for _ in range(iterations):
self.feedforward()
self.cost()
self.backprop() |
def bestAdjacent(row, col):
#Find all adjacent dirty cells
options = adjacentDirty(row, col)
#If their are no dirty neighbors, return [-1, -1]
if len(options) == 0:
return[-1, -1]
#Initalize best node at 9 dirty edges
min_dirty_edges = 9
#Initalize variable to hold next move
b... | The algorithm directs a Roomba to clean all dirty cells by prioritizing adjacent dirty cells first. If none are adjacent, it identifies the nearest dirty cell and navigates to it. Once all cells are cleaned, it returns to the origin. The loop ensures termination by limiting iterations, avoiding infinite loops. (The mai... | def algorithm():
#Do bestAdjacent - if [-1, -1] is returned, find nearestDirty and go, otherwise if no dirty, go to start position
for i in range(2*len(arr)*len(arr[0])): #In case of infinite loop, will automatically exit loop after a point
next_move = bestAdjacent(roomba_row, roomba_col)
if(nex... |
def findOrigin():
#Iterate through neighboring cells
for r in range(ROWS):
for c in range(COLS):
#If value is roomba value, that is origin
if arr[r][c] == 0:
return [r, c]
return [-1, -1]
def populateDistanceArray():
global roomba_col, roomba_row, dis... | The code computes and returns the path of a roomba navigating a grid, starting from a detected origin. It initializes grid dimensions, locates the origin, populates a distance array, and executes an algorithm to determine the traversal path, which is then printed and returned as a list of coordinates. | def getPath(array):
#Make array globally accessable
global arr
arr = array
#Retrieve size of array
global ROWS, COLS
ROWS = len(array)
COLS = len(array[0])
#Find origin based on input array
global ORIGIN_ROW, ORIGIN_COL
origin = findOrigin()
ORIGIN_ROW = origin[0]
ORIGI... |
def count_frequency(n, main_string):
# Generate a list of n-character long strings from main_string
string_list = [main_string[i:i+n] for i in range(0, len(main_string), n)]
# Create a dictionary to count the frequency of each unique element
frequency_dict = defaultdict(int)
for string in string_li... | This function determines the optimal bit group size for Huffman compression by iterating through possible group sizes, calculating the compressed data size for each, and selecting the group size that yields the smallest compressed size. | def find_opt_bit_group(binary_data_l1, data_length_l1, min_bit_group, max_bit_group):
opt_size = data_length_l1
opt_bit_group = 1
for i in range(min_bit_group, max_bit_group+1):
frequency_dict = count_frequency(i, binary_data_l1)
frequencies, levels = create_huffman_tree(frequency_dict)
... |
def is_valid_move(self, move):
blank_row, blank_col = self.find_blank()
if move == MoveDirection.UP:
return blank_row > 0
elif move == MoveDirection.DOWN:
return blank_row < self.size - 1
elif move == MoveDirection.LEFT:
return blank_col > 0
e... | The main task of the code is to apply a valid move in a sliding puzzle by swapping the blank tile with an adjacent tile in the specified direction. It first validates the move, calculates the target tile's position based on the direction, and swaps their values to update the puzzle state. | def apply_move(self, move):
if not self.is_valid_move(move):
raise ValueError("Invalid move")
blank_row, blank_col = self.find_blank()
if move == MoveDirection.UP:
target_row = blank_row - 1
target_col = blank_col
elif move == MoveDirection.DOWN:
... |
def generatePlayerList():
# Create player list of 1000 players each with lotto numbers
lotto = []
# Create the 2D array and populate it with the players lotto numbers
for i in range(1000):
lotto.append([i] * 6)
# Add 6 numbers to
for x in range(6):
# Currently generated number for player, between 1-30... | The main task of the code is to generate and sort lottery player data and winning numbers. It initializes player lists, sorts each player's numbers using merge sort, separates and sorts primary/supplementary winning numbers (using insertion/selection sort), then recombines them. Finally, it passes processed data to a m... | def main():
# -------------------Initialization stage of system-------------------
# Creates list of players and generates their game-numbers, assigns to list lotto[]
lotto = generatePlayerList()
# Create the list of 8 winning numbers and assign to WinNo variable
WinNo = generateNumbers()
# prints out the winnin... |
def solve(self):
find = self.find_empty()
if not find:
return True
else:
row, col = find
plausible = self.possible(self.grid, find)
for i in range(1, 10):
if plausible[i] == 0:
if self.valid(self.grid, i, (row, col)):
... | This method processes user input events in a Pygame application. It handles window close requests, mouse clicks (to select cells or trigger solving), and keyboard inputs (to enter numbers in selected cells). The function updates the game state by modifying the grid, tracking changes, and managing cell selection, while ... | def playing_events(self): # ui portion
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
# User Clicks
if event.type == pygame.MOUSEBUTTONDOWN:
if self.playingButtons[0].highlighted:
self.... |
def playing_events(self): # ui portion
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
# User Clicks
if event.type == pygame.MOUSEBUTTONDOWN:
if self.playingButtons[0].highlighted:
self.... | The code defines a `run` method that executes a game loop while `self.running` is True. When the game state is "playing," it processes events, updates game logic, and renders graphics via `playing_events()`, `playing_update()`, and `playing_draw()`. The loop terminates when `self.running` becomes False, after which Pyg... | def run(self):
while self.running:
if self.state == "playing":
self.playing_events()
self.playing_update()
self.playing_draw()
pygame.quit()
sys.exit() |
def consulta(query):
response = requests.get("https://core.ac.uk:443/api-v2/search/"+query+"?page=1&pageSize=50&apiKey=ZiykrETNJ0qWQUHoPs5B81A7Reb26YCM")
json_reponse = response.json()['data']
titulos = []
abstract = []
autores = []
topics=[]
for pub in json_reponse:
if (pub['_source... | The code calculates the similarity between a given title, abstract, and topic with existing documents. It processes text using NLP techniques, computes Jaccard and cosine similarities for titles, abstracts, and topics, combines them with weighted scores (0.3, 0.4, 0.3), and returns the top 5 most similar documents with... | def similitud(titulo,abstract,topic):
titulos,abstracts,autores,topics = consulta(titulo)
ttemp = titulos[:]
tabs = abstracts[:]
ttop = topics[:]
_,titulos = nlp(titulos)
listabstracts,abstracts = nlp(abstracts)
topics = [nlpT(tp) for tp in topics]
_,titulo = nlp([titulo])
... |
def main_menu(self) -> bool or None:
while 1:
clear_screen()
self.initialize_values()
table_data = [
["X", "X", "X"],
["1", "TARGET", self.targets],
["2", "OPTIONS", self.options],
["3", "SCAN", "Start Scan"],
... | The code initiates a network scan by checking host status, performing the scan if hosts are alive, saving results to a timestamped JSON file, and displaying status messages. If hosts are unreachable, it notifies the user and pauses before exiting. | def run(self):
"""
Starts the scan
"""
if(not self.main_menu()):
return
print("Checking status of hosts...")
live_hosts = self.is_alive()
if(live_hosts is True):
scan_results = self.perform_scan()
FILE_NAME = dt.now().strftime("... |
def rollout2(instance_path):
"""
Create and print a schedule for every allowed combination of next tasks
:param instance_path: Instance path of the jssp file
:return: None
"""
# Start time of the rollout
start_time = time.time()
# Reading in the data from the instance_path
_, _, all... | The main task of the code is to generate and optimize multiple schedules for job scheduling on multiple machines. It iterates through combinations of jobs, applies a scheduling algorithm to assign tasks, and uses a greedy heuristic to complete schedules. The code evaluates all generated schedules, calculates their make... | def multistep(instance_path, machines):
start_time = time.time()
all_jobs_list, schedules = rollout2(instance_path)
super_schedules = []
super_all_jobs = []
for i in range(len(schedules)):
final_combs = combinations(all_jobs_list[i])
schedules_new = [copy.deepcopy(schedules[i]) f... |
def measure(self, word: str):
word = word.lower()
vc = self.vc(word)
return vc.count("VC")
def contain_vowel_check(self, word: str):
word = word.lower()
word_vc = self.vc(word)
if "V" in word_vc:
if word_vc.find("V") == word_vc.rfind("V") == (len(word_vc)-1):
... | This function implements Step 1b of the Porter stemming algorithm, reducing word endings like "eed", "ed", and "ing" based on vowel count and specific suffix rules, with optional cleanup via helper functions to further simplify the word. | def step_1b(self, word: str):
word = word.lower()
need_to_clean = False
if self.measure(word) > 1:
if word.endswith("eed"):
word = word[:len(word)-1]
elif self.contain_vowel_check(word):
if word.endswith("ed"):
word = w... |
def step_1a(self, word: str):
word = word.lower()
if word.endswith("sses"):
word = word[:len(word)-2]
elif word.endswith("ies"):
word = word[:len(word)-2]
elif word.endswith("ss"):
word = word
elif word.endswith("s"):
word = word... | This code performs word stemming using a multi-step process, applying a series of transformation rules (step_1a to step_5b) to reduce a word to its base or root form. It first converts the word to lowercase, then sequentially applies suffix removal and morphological transformations according to predefined linguistic ru... | def stem(self, word:str):
word = word.lower()
word = self.step_1a(word)
word = self.step_1b(word)
word = self.step_1b_helper(word)
word = self.step_1c(word)
word = self.step_2(word)
word = self.step_3(word)
word = self.step_4(word)
word = self.step... |
def get_all_urls():
"""
this method makes a query on the api containing all the song lyrics of the artist.
it returns a json file in which we extract the link to the lyrics of the designated song
:return: list[string]
"""
page_number = 1
next_page = 1
links = []
while next_page:
... | The main task of the code is to retrieve and process song lyrics by either loading existing data from a JSON file or scraping lyrics from URLs, compiling them into a list, saving the result to the file, and then analyzing the most frequent words (with length ≥7) to display the count. | def get_all_words():
"""
This is the main method, it allows you to store all the song lyrics ( scraping, processing)
in a file if it doesn't exist, but to open it if it does.
:return: none
"""
if Path("lyrics_nena.json").is_file():
with open("lyrics_nena.json", "r", encoding="utf-8") as ... |
def to_catalog(self, dendrogram=None):
"""
Creates a new position-position catalog of leaves in a dendrogram.
This task will overwrite the existing catalog if there is one.
Parameters
----------
dendrogram : `~astrodendro.dendrogram.Dendrogram` object, optional
... | The function calculates the Signal-to-Noise Ratio (SNR) for all sources in a catalog by dividing the peak flux of source pixels by the RMS of background pixels. It uses provided or generated data/cutouts, handles missing inputs by fetching from the instance, and optionally saves SNR values in the catalog and as an inst... | def get_snr(self, source=None, background=None, catalog=None, data=None,
cutouts=None, cutout_data=None, peak=True, save=True):
"""
Return the SNR of all sources in the catalog.
Parameters
----------
source: array-like
Array of source fluxes to use in... |
def to_catalog(self, dendrogram=None):
"""
Creates a new position-position catalog of leaves in a dendrogram.
This task will overwrite the existing catalog if there is one.
Parameters
----------
dendrogram : `~astrodendro.dendrogram.Dendrogram` object, optional
... | The function `plot_grid` visualizes astronomical sources in a grid layout, displaying cutout images with apertures and signal-to-noise ratios (SNR). It uses a catalog to locate sources, applies source and background apertures, filters out rejected sources if specified, and arranges plots using matplotlib's GridSpec. Ea... | def plot_grid(self, catalog=None, data=None, cutouts=None,
cutout_data=None, source_aperture=None, bkg_aperture=None,
skip_rejects=True, outfile=None, figurekwargs={}):
"""
Plot sources in a grid.
Parameters
----------
catalog : astropy.table.... |
def get_core_if_possible(batch):
input_ids, token_type_ids, attention_mask, query, arg_list, context, ids, gold = batch['input_ids'], \
batch['token_type_ids'], batch['attention_mask'], batch['queries'], batch['args'], batch["context"], \
batch["ids"], batch["gold"]
has_core... | The code evaluates a model's performance on NLP tasks (e.g., relation classification) using datasets like CONLL2005/2009/2012. It processes batches, runs the model to predict arguments, adjusts inputs with core argument info if needed, and computes precision, recall, and F1 scores. The function returns these metrics fo... | def evaluation(model, dataloader, amp=False, device=torch.device('cuda'),dataset_tag='', tokenizer=None):
if dataset_tag == 'conll2005' or dataset_tag == 'conll2009':
ARGMS = ['DIR', 'LOC', 'MNR', 'TMP', 'EXT', 'REC',
'PRD', 'PNC', 'CAU', 'DIS', 'ADV', 'MOD', 'NEG']
elif dataset_tag == ... |
def normalize_url(self, url: str, main_url: str=None) -> str:
parse_res = dict(urltools.extract(url)._asdict())
if not parse_res['scheme']:
parse_res['scheme'] = 'http'
if not parse_res['domain'] and main_url:
main_url_parse_res = urltools.extract(main_url)
... | This code extracts and validates RSS feed URLs from a given webpage and common URLs, returning a list of unique valid RSS URLs. It fetches the webpage content, parses HTML for links, filters valid RSS URLs, and supplements with predefined typical URLs if needed, ensuring results are unique and within a specified maximu... | def search(self, url: str, max_results=None) -> typing.List[str]:
url = self.normalize_url(url)
log(url, 'Start process url')
# fetch url content
try:
r = self.loader.fetch(url)
except exceptions.RequestException as e:
log(str(e), url, level=logging.ERROR... |
def corners_solvable(self):
odd_or_even_counter = 0
for number in range(10, 38, 9):
if self.color_at(number) == "yellow" or self.color_at(number) == "white":
odd_or_even_counter = odd_or_even_counter - 1
for number in range(12, 40, 9):
if self.color_at(num... | The method checks if a puzzle is solvable by verifying three conditions: corners and edges have even orientations, and pieces have a valid permutation. If any condition fails, it raises exceptions indicating unsolvable states due to odd orientations or permutations. | def solvable(self):
if not self.corners_solvable():
raise Exception("Corners have an odd orientation.")
if not self.edges_solvable():
raise Exception("Edges have an odd orientation.")
if not self.pieces_permutable():
raise Exception("Pieces have an odd permuta... |
def _one_hot_embedding(labels, num_classes):
"""Embedding labels to one-hot form.
Args:
labels: (LongTensor) class labels, sized [N,].
num_classes: (int) number of classes.
Returns:
(tensor) encoded labels, sized [N, #classes].
"""
y = torch.eye(num_classes).to(device)
retur... | The code computes a loss function based on the gradient magnitudes of predicted and ground truth semantic masks. It applies a thresholded L1 loss to regions where gradients exceed a threshold, combining loss contributions from both predicted and ground truth gradients. The final loss is a weighted average of these comp... | def forward(self, input_logits, gts, ignore_pixel=255):
"""
:param input_logits: NxCxHxW
:param gt_semantic_masks: NxCxHxW
:return: final loss
"""
# input_logits.size() == nb_batch x 6 x w x h
# gts.size() == nb_batch x 1 x w x h
N, C, H, W = input_logits... |
def Clarke_Wright(capacity,lat,long,uploaded_file):
temp_csv=get_csv_temp(lat,long,uploaded_file)
# read node data in coordinate (x,y) format
nodes = pd.read_csv(temp_csv, index_col = 'node')
nodes.rename(columns={"distance to depot":'d0'}, inplace = True)
node_number = len(nodes.index) - 1
nod... | The main task of the code is to generate optimized vehicle routes using the Clarke-Wright algorithm, map indices to geographic coordinates from an Excel file, calculate route distances, and compile results including URLs, route details, and total distance. It processes input data, constructs route strings, computes dis... | def main_1(capacity, lat, long, uploaded_file):
routes=Clarke_Wright(capacity, lat, long, uploaded_file)
print(routes)
df = pd.read_excel(uploaded_file, "Sheet1")
indexinginfile={}
n = df.shape[0]
indexinginfile[0]=(lat,long)
for i in range(n):
indexinginfile[i+1]=(df["Latitude"][i],... |
def check_winner(board):
# Check rows
for row in board:
if row[0] == row[1] == row[2] and row[0] != ' ':
return True, row[0]
# Check columns
for col in range(3):
if board[0][col] == board[1][col] == board[2][col] and board[0][col] != ' ':
return True, board[0][co... | The code implements a Tic-Tac-Toe game where a human player ('X') competes against an AI ('O'). It initializes a 3x3 board, alternates turns, validates human input, and uses an AI's best_move function to determine AI plays. The game loops until a win or tie is detected, then announces the result. | def play_game():
board = [[' ' for _ in range(3)] for _ in range(3)]
player = 'X'
while not check_winner(board)[0]:
print_board(board)
if player == 'X':
row = int(input("Enter the row (0, 1, or 2): "))
col = int(input("Enter the column (0, 1, or 2): "))
... |
def regular_move(self,letter):
global first_player_button_id, first_player_number, first_player_letter
self.config(image=first_player_image, width=65, height=65 )
first_player_button_id.config(image= '', width=9, height=4 )
reaching_end(self,letter)
end_game()
def checking_eating_side(self, letter,... | This code handles checkers piece movement logic, tracking first and second button clicks to determine valid moves. It identifies the player's piece (X/O), checks for regular forward moves, and processes capture moves (eating) based on piece type. For kings, it triggers special movement logic. The function manages game ... | def button_pressed(self, letter, number):
global first_push, first_player_letter, first_player_number, first_player_image,first_player_button_id
if first_push==False: #first push
if self.cget('image')=='':
pass
else:
first_player_letter = letter
first_player_... |
def show_mine(self):
self.cell_btn_object.config(state=DISABLED)
self.cell_btn_object.config(text="\U0001F4A3", bg="#FD5B5F")
for cell in Cell.all_cell:
cell.cell_btn_object.config(state=DISABLED)
cell.cell_btn_object.unbind("<Button-1>")
cell.cell_btn_object.... | This method handles a left mouse click event in a Minesweeper-like game. It decreases the cell count, updates the display, reveals the clicked cell (showing a mine if present or clearing it if empty), and checks for a win condition when all non-mine cells are revealed. If it's the first click, it initializes the game s... | def left_click(self, event):
if Cell.mouse_click != 1:
Cell.cell_number -= 1
Cell.cell_lbl.config(text=f"Cell : {Cell.cell_number}")
if self.is_mine:
self.show_mine()
else:
self.show_cell()
if self.cell_btn_object.cg... |
def print_red(text):
print_bright(colorama.Fore.RED + text)
def get_arc_mode(mode):
if mode == MODE_SEQUENTIAL:
return "-s"
elif mode == MODE_CUDA:
return ""
else:
print_red("Unsupported mode \"{}\", exiting".format(name_str(mode)))
def magenta(text):
return colorama.Fore.MAG... | The code compiles a .coil file using a specified tool, executes it via an interpreter in a given mode, captures execution times, handles errors, and cleans up temporary files. It measures compilation and execution durations, validates outputs, and returns timing metrics along with warm-up, computation, and cooldown pha... | def run_arc(spec, infile, mode):
print("{}: Compiling .coil file...".format(WINDER))
# compile spec
start = time.time()
winder_p = subprocess.Popen([os.path.join(BIN, WINDER), "compile", spec], stdout=subprocess.PIPE)
winder_p.wait()
winder_et = round((time.time() - start)*1000000)
output ... |
def print_bright(text):
print(colorama.Style.BRIGHT + text + colorama.Style.RESET_ALL)
def magenta(text):
return colorama.Fore.MAGENTA + text + colorama.Fore.RESET
def run_tessla(spec, infile):
start = time.time()
print("{}: Running interpreter".format(TESSLA))
with open(TESSLA_OUT, "w") as tessla_o... | The code compares two methods (Tessla and Arc) by executing them with given specifications and input files, measures their execution times, checks for discrepancies in outputs, and records timing metrics. If no differences are found, temporary files are deleted. Results are printed or saved based on the `single_comp` f... | def compare(name, spec, infile, arc_mode, outfile, single_comp):
print_bright("Running comparison for specification {} and input file {}...\n".format(magenta(spec),
magenta(infile)))
tessla_parse_t, tessla_comp_t = run_tess... |
def compare(name, spec, infile, arc_mode, outfile, single_comp):
print_bright("Running comparison for specification {} and input file {}...\n".format(magenta(spec),
magenta(infile)))
tessla_parse_t, tessla_comp_t = run_tess... | This function compares input files (with .in extension) against corresponding specification files (with .tessla extension) in a data directory. It pairs files with matching base names, runs comparisons using the 'compare' function, and collects results. Output is printed to console or written to a specified file, with ... | def compare_all(arc_mode, outfile):
# collect all files in data folder
files = os.listdir(DATA)
input_files = list(filter(lambda a: a.endswith(".in"), files))
spec_files = list(filter(lambda a: a.endswith(".tessla"), files))
all_list = []
for inf in input_files:
pref = inf.split(".")[0]... |
def print_red(text):
print_bright(colorama.Fore.RED + text)
def magenta(text):
return colorama.Fore.MAGENTA + text + colorama.Fore.RESET
def rebuild():
print_bright("Rebuilding...\n")
print("Rebuilding winder...")
# build winder
winder_ec = os.system("cd ../winder; cargo build --release")
#... | The main task of the code is to parse command-line arguments for running and comparing outputs of TeSSLa and winder+arc systems. It handles options for rebuilding binaries, specifying input files, specifications, and execution modes (sequential, CUDA, etc.). The code ensures valid argument combinations, rebuilds binari... | def main():
parser = argparse.ArgumentParser(description="Run TeSSLa and winder+arc and compare outputs")
parser.add_argument("--rebuild", help="Whether to rebuild binaries", action="store_true")
parser.add_argument("-s", "--spec", help="Specification to run the comparison on")
parser.add_argument("-i",... |
def submit_all():
formu = furl.get()
fn = fname.get()
at = token.get()
dbn = dbname.get()
tbln = tname.get()
defaults = default.get()
l1 = list(formu)
l2 = list(fn)
l3 = list(at)
l4 = list(dbn)
l5 = list(tbln)
... | The code validates if the form name from API data matches the one from a submission. If mismatched, it shows an error, sets a flag, and exits. The main task is to ensure form name consistency between submission data and API response, triggering an error for mismatches. | def form_name():
submit_all()
api_request()
api_flatten()
data = api_flatten.final_data
form_name.formname = data["submissions_0_form_name"]
if form_name.formname == submit_all.form_name:
form_name.fname = 0
pass
elif form... |
def dm_download():
submit_all()
file_and_path()
username = submit_all.user_name
url_fixed = file_and_path.full_url
final_wd_path = wd_path()
wdpath = Service(final_wd_path)
options = webdriver.ChromeOptions()
options.add_experime... | The function generates a dictionary mapping column names to SQL data types, primarily 'nvarchar(MAX)', by merging default mappings with specific key-value pairs from prepared data. It ensures compatibility by filtering and combining dictionaries, then adds timestamp fields with the same data type. The result defines a ... | def final_dict():
dm_download()
keys_prep()
values_prep()
column_names = dm_download.df.columns.tolist()
dict_keys = keys_prep.dict_of_keys
dict_values = values_prep.dict_of_values
dict_main = dict.fromkeys(column_names,
... |
def form_name():
submit_all()
api_request()
api_flatten()
data = api_flatten.final_data
form_name.formname = data["submissions_0_form_name"]
if form_name.formname == submit_all.form_name:
form_name.fname = 0
pass
elif form... | The main task of the code is to create SQL tables based on user inputs and predefined checks, handling existing tables by either overwriting or skipping them. It uses conditional logic to execute SQL queries for table creation, manages data types, and sends notifications or emails upon completion, while logging errors ... | def initiate_main_function():
try:
form_name()
if check_url.url == 0 and check_form_name.form == 0 and check_api_token.api == 0 and check_db.db == 0 and check_sql_tbl_name.tbl == 0 and form_name.fname == 0:
res = messagebox.askyesno('Device SQL', 'Do you wan... |
def reset(self):
self.infected = -np.ones(self.n)
self.t = 0
p0 = int(np.random.uniform(0, self.n-0.5))
self.infected[p0] = self.t
self.fixed[:,p0] = 1
self.cases = []
self.recovered = []
def update_verlet(self):
#update the verlet list
self.update... | This code initializes a simulation system with parameters like time, positions, velocities, and infection dynamics. It copies initial states, sets up force matrices, infection tracking (infected/recovered), and fixed particles. The `reset()`, `update_verlet()`, and `update_force()` methods prepare the simulation for dy... | def __init__(self, Time, dt, x, v, box, duration, rate, skin, fixed_rate=0, fmax=float('nan')):
self.T_MAX = Time
self.dt = dt
self.t = 0
self.x = x.copy()
self.v = v.copy()
self.box = box.copy()
self.fmax = fmax
self.dim = self.x.shape[0]
self.n =... |
def update_force(self):
self.f = np.zeros((self.dim, self.n))
for pair in self.verlet:
r_vec = self.x[:,pair[1]]-self.x[:,pair[0]]
r = np.linalg.norm(r_vec)
f_ij = r_vec * self.force(r) / r
self.f[:,pair[0]] -= f_ij
self.f[:,pair[1]] += f_ij
... | This function performs a velocity Verlet integration step for molecular dynamics simulations, updating particle positions and velocities using forces, applying elastic wall boundary conditions, incrementing simulation time, and triggering verlet list updates when particle displacements exceed a threshold. It also calls... | def vv_step(self):
#velocity verlet integration step
self.x = self.x + np.where(self.fixed != 0, self.dt*self.v + 0.5 * self.f * self.dt**2, 0)
self.v = self.v + 0.5 * self.dt * self.f
self.update_force()
self.v = self.v + 0.5 * self.dt * self.f
#increase time
se... |
def remove_existing_nblinks_and_indexfile(tutorial_index_filename):
for file in os.listdir(PATH2DOCSOURCE):
if file.endswith(".nblink"):
os.remove(file)
try:
os.remove(tutorial_index_filename)
except FileNotFoundError:
pass
def generate_nblink_files():
nblink_content... | The main task of the code is to set up tutorial documentation by generating and updating an index file (`tutorial_index.rst`) and a README file (`README.rst`) in the tutorials directory. It cleans existing files, creates Jupyter notebook links, generates content from documentation sources, and writes the structured con... | def setup_tutorials():
# PART 1: Online documentation
tutorial_index_filename = "tutorial_index.rst"
# clean
remove_existing_nblinks_and_indexfile(tutorial_index_filename)
# generate links to Jupyter files
generate_nblink_files()
# generate and write content to rst file
tutorial_page... |
def check_item_manuf(users_input):
## NOTE: 1) return lists of all manufacturers + item-types in inventory
test_manuf, test_type = inventory_item_manuf()
## NOTE: 2) check if user inputted ONE valid manufacturer and item-type
# counts number of valid manufacturers the user inputted; initially zero
... | The main task of the code is to repeatedly query users for item type and manufacturer inputs, validate them against inventory data, and display matching item details along with recommended alternatives. It processes inputs, checks validity, retrieves item information, and prints results until the user enters 'q' to exi... | def query_user():
users_input = []
# while loop queries the user whenever anything but q is inputted, and quits the loop when q is inputted
while users_input != 'q':
## NOTE: 1) get user input
users_input = input(
"Please enter an item type and item manufacturer, or enter 'q' to ... |
def queryTeamDetailsByName(team_name):
my_database = db_connection.cursor()
sql_statement = "SELECT * FROM teams WHERE Team_Name = '" + team_name + "'"
my_database.execute(sql_statement)
result_set = my_database.fetchall()
for team in result_set:
team_details = {"id":team[1], "team_name": te... | The function parses cricket match data from input JSON, extracts structured match information (teams, date, outcome, etc.), processes innings data into detailed ball-by-ball records with team IDs, handles super overs if present, and uploads both match metadata and ball-level data to a database in a transaction. | def parseAndUploadDataToDB(match_data):
# Prepare match info.
match_info = {}
ball_details = []
match_info['Match_SK'] = match_info['match_id'] = match_data['info']['match_id']
match_info['Team1'] = match_data['info']['teams'][0]
match_info['Team2'] = match_data['info']['teams'][1]
matc... |
def get_body_pos(self):
#relevant body points needed
print('Total Number of points: ' + str(len(self.bodyMarkers.markers[0].points)))
#collecting all body points individual based on axis (x, y, z)
#body landmarks used = ['nose', 'neck','right_shoulder','left_shoulder']
upper_tors... | The code calculates FPS using timestamps, updates body marker data, and triggers fall detection if enabled. It processes ROS data to detect falls by analyzing body positions, moving the camera head, and printing fall status. Debug info on torso metrics is commented out. | def callback(self, ros_data):
global new_time
global prev_time
new_time = time.time()
print("FPS: " ,round(1/(new_time-prev_time),3))
self.bodyMarkers = ros_data
#if we want to run fall detection --> calc individual position, move camera head, and detect falls
... |
def configure_job():
"""Construct jobSpec for ML Engine job."""
train_dir = FLAGS.output_dir
assert train_dir.startswith('gs://')
# See documentation:
# https://cloud.google.com/ml-engine/reference/rest/v1/projects.jobs#traininginput
training_input = {
'pythonModule': 'tensor2tensor.bin.t2t_trainer',... | The main task of the code is to launch a T2T trainer on Google Cloud ML Engine by validating configuration flags, preparing job specifications, packaging necessary files (T2T and user directories), and initiating the training job with the specified parameters. It ensures proper setup for distributed training, confirms ... | def launch():
"""Launch t2t_trainer on Cloud ML Engine."""
assert not FLAGS.cloud_tpu
assert not FLAGS.job_dir
assert FLAGS.output_dir.startswith('gs://')
assert FLAGS.data_dir.startswith('gs://')
assert FLAGS.worker_replicas <= 1
assert FLAGS.ps_replicas <= 0
job_spec = configure_job()
job_name = jo... |
def update_prox(mat):
"""returns 'connectivity' of each tile, prox1 shows neighbouring tiles"""
prox1 = neighbour_count(mat)
prox2 = sum_surrounding(prox1)
prox3 = sum_surrounding(prox2)
return [prox1, prox2, prox3]
def choose_loneliest(prbmat, i, j, prox1, prox2, prox3):
"""returns least 'conne... | This function iteratively merges colors in prbmat by identifying and combining "loneliest" elements based on proximity matrices (prox1-3), updating matrices after each valid merge until no isolated elements remain or 100 iterations are reached. It returns the updated prbmat and cmpmat after linking similar color region... | def link_1s(prbmat, cmpmat):
[prox1, prox2, prox3] = update_prox(prbmat)
counter = 0
while 1 in [item for sublist in prox1 for item in sublist] and counter < 100:
for i1 in range(len(prbmat)):
for j1 in range(len(prbmat)):
loneliest = choose_loneliest(prbmat, i1, j1, prox... |
def update_prox(mat):
"""returns 'connectivity' of each tile, prox1 shows neighbouring tiles"""
prox1 = neighbour_count(mat)
prox2 = sum_surrounding(prox1)
prox3 = sum_surrounding(prox2)
return [prox1, prox2, prox3]
def choose_loneliest(prbmat, i, j, prox1, prox2, prox3):
"""returns least 'conne... | The main task of the code is to iteratively merge colors in the `prbmat` matrix based on proximity values (prox1, prox2, prox3) and validity checks. It repeatedly identifies "loneliest" cells with proximity value 2, merges their colors if valid, updates both `prbmat` and `cmpmat`, and recalculates proximity matrices un... | def link_2s(prbmat, cmpmat):
[prox1, prox2, prox3] = update_prox(prbmat)
counter = 0
while 2 in [item for sublist in prox1 for item in sublist] and counter < 100:
for i1 in range(len(prbmat)):
for j1 in range(len(prbmat)):
loneliest = choose_loneliest(prbmat, i1, j1, prox... |
def update_prox(mat):
"""returns 'connectivity' of each tile, prox1 shows neighbouring tiles"""
prox1 = neighbour_count(mat)
prox2 = sum_surrounding(prox1)
prox3 = sum_surrounding(prox2)
return [prox1, prox2, prox3]
def choose_loneliest(prbmat, i, j, prox1, prox2, prox3):
"""returns least 'conne... | The function iteratively merges colors in a matrix (prbmat) by identifying and combining 'loneliest' cells marked with value 3, using proximity matrices (prox1-3) and validation checks. It repeatedly updates the matrix, invokes helper functions (link_1s, link_2s) for further merging, and re-evaluates proximity until no... | def link_3s(prbmat, cmpmat):
[prox1, prox2, prox3] = update_prox(prbmat)
counter = 0
while 3 in [item for sublist in prox1 for item in sublist] and counter < 100:
for i1 in range(len(prbmat)):
for j1 in range(len(prbmat)):
loneliest = choose_loneliest(prbmat, i1, j1, prox... |
def update_prox(mat):
"""returns 'connectivity' of each tile, prox1 shows neighbouring tiles"""
prox1 = neighbour_count(mat)
prox2 = sum_surrounding(prox1)
prox3 = sum_surrounding(prox2)
return [prox1, prox2, prox3]
def choose_loneliest(prbmat, i, j, prox1, prox2, prox3):
"""returns least 'conne... | The function repeatedly merges cells in the prbmat and cmpmat matrices where proximity value 4 is detected, using a loop with a 100-iteration limit. It identifies "loneliest" cells, validates color merges, and updates matrices through merging and subsequent linking operations (link_1s, link_2s, link_3s). The process co... | def link_4s(prbmat, cmpmat):
[prox1, prox2, prox3] = update_prox(prbmat)
counter = 0
while 4 in [item for sublist in prox1 for item in sublist] and counter < 100:
for i1 in range(len(prbmat)):
for j1 in range(len(prbmat)):
loneliest = choose_loneliest(prbmat, i1, j1, prox... |
def get_min_max_years(base_dir, sites_data_paths):
min_year = 2009
max_year = 2018
for filepath in sites_data_paths:
if 'meta' in filepath:
with open(file=os.path.join(base_dir, filepath)) as f:
meta_data = json.load(f)
year_start = int(meta_data['phenocam_sit... | The code aggregates and processes phenophase data from multiple JSON files by extracting metadata, calculating constants, merging data, cleaning NaN values, and saving the result as a CSV file for mapping purposes. | def create_csv():
# get all meta and transition date json filepaths
source_dir = './../../Phenophase_Classification/phenocam_data/'
sites_data = [site_data for site_data in os.listdir(source_dir) if site_data.endswith('_meta.json') or site_data.endswith('_transition_dates.json')]
sitenames = list(set([s... |
def get_location_key(location):
return f"{location['x']}_{location['y']}"
def navigate(location, direction):
if direction == 'north' or direction == '':
next_location, _, next_direction = navigate_north(location)
if next_location is not None:
return next_location, next_direction
... | This code calculates the maximum number of interior steps in a path starting from 'S' in a grid map. It reads input from either test data or a file, navigates in four directions, tracks paths, and returns the interior step count if a loop is found, otherwise 0. | def calculate_score(test: bool) -> int:
if test:
file = test_data4
else:
file = open("input.txt", "r")
start_loc = None
for row_num, line in enumerate(file):
path_map.append(line.strip())
try:
start_loc = {'x': line.index('S'), 'y': row_num}
except Va... |
def navigate_east(location):
next_location = (location[0] + 1, location[1])
if not valid_location(next_location):
return None, None
char = mirror_map[next_location[1]][next_location[0]]
if char in ('.', '-'):
return next_location, "east"
if char == '\\':
return next_location... | The code calculates the maximum number of cells energized by light beams entering a grid of mirrors from all edges, simulating reflections and tracking unique paths to avoid cycles. | def calculate_score(test: bool) -> int:
if test:
file = test_data
else:
file = open("input.txt", "r")
for row_num, line in enumerate(file):
mirror_map.append(line.strip())
if not test:
file.close()
score = 0
x_max = len(mirror_map[0])
y_max = len(mirror_map... |
def preprocessQueries(self, queries, isSpellCheck, isQueryExpansion): # CHANGE AFTER COMPARISON
"""
Preprocess the queries - segment, tokenize, stem/lemmatize and remove stopwords
"""
# Spellcheck on queries
if(isSpellCheck): # Perform spellcheck if isSpellCheck is True
queries = [self.spellcheck.correctQ... | This code evaluates an information retrieval system by preprocessing queries and documents, ranking documents using models like VSM, LSA, and ESA, and computing metrics such as precision, recall, F-score, nDCG, and MAP on the Cranfield dataset. It generates visualizations of these metrics in the output folder to assess... | def evaluateDataset(self):
"""
- preprocesses the queries and documents, stores in output folder
- invokes the IR system
- evaluates precision, recall, fscore, nDCG and MAP
for all queries in the Cranfield dataset
- produces graphs of the evaluation metrics in the output folder
"""
# Read queries
q... |
def is_node(self, node):
return isinstance(node, Node)
def is_edge(self, edge):
return isinstance(edge, Edge)
def add_edges(self, edges):
for edge in edges:
self.add_edge(edge) | The code initializes a graph structure by validating that input nodes and edges are correct, ensuring all edge nodes exist in the node list, and setting up instance variables for nodes and edges. It then calls a method to add the edges to the graph, likely establishing connections between nodes. | def __init__(self, nodes, edges):
assert all([self.is_node(node) for node in nodes]), 'Nodes argument is not list of nodes'
assert all([self.is_edge(edge) for edge in edges]), 'Edges argument is not list of edges'
for edge in edges:
assert edge.node1 in nodes and edge.node2 in nodes... |
def _gather_flat_grad(self):
return torch.cat(
tuple(param.grad.data.view(-1) for param in self._params), 0)
def _weak_wolfe(self, closure, d):
# 0 < rho < 0.5 and rho < sigma < 1
rho = 1e-4
sigma = 0.9
original_param_data_list = self._copy_param()
phi_0 ... | This code implements a single optimization step for the L-BFGS algorithm, computing the gradient descent direction using limited memory updates, performing line search for optimal step size, and checking convergence criteria like gradient tolerance and loss change. It updates model parameters iteratively while tracking... | def step(self, closure):
"""Performs a single optimization step.
Arguments:
closure (callable): A closure that reevaluates the model
and returns the loss.
"""
assert len(self.param_groups) == 1
group = self.param_groups[0]
lr = group[... |
def __slidersVal(self):
values = []
for s in self.sliders:
values.append(s.val)
return values
def __getPoincare(self, y0):
solver = DOP853(self.__odeWrap, 0, y0, self.time_slider.val, max_step=self.maxstep, vectorized=self.vector)
pmap = []
prev_state = y0
... | This function updates dynamic tracks in a visualization by recalculating their positions using sampled slider values. It generates Poincaré maps for each track, updates scatter plot offsets if valid data exists, or removes/reattaches tracks if empty. Finally, it redraws the plot and triggers additional line updates, en... | def __update(self, val):
y0_ar = self.sampling(self.nTracks, self.__slidersVal())
for i in range(int(self.nTracks)):
pmap = self.__getPoincare(y0_ar[i])
if len(pmap) >= 1: self.tracks[i].set_offsets( pmap )
else:
self.tracks[i].remove()
... |
def projection_box(self,encode_inputs):
cls = self.pre_train_model(**encode_inputs)
cls = self.dropout(cls[0][:, 0, :])
center = self.projection_center(cls)
delta = torch.exp(self.projection_delta(cls)).clamp_min(1e-38)
return center,delta
def parent_child_contain_loss(self,pare... | The code computes a composite loss during training by calculating containment losses between parent-child encodings, negative example losses, and regularization terms. It combines these with weighted coefficients to optimize model parameters for relational prediction tasks, returning the total loss and its components f... | def forward(self,encode_parent=None,encode_child=None,encode_negative_parents=None,flag="train"):
if flag == "train":
regular_loss = 0
parent_center,parent_delta = self.projection_box(encode_parent)
child_center, child_delta = self.projection_box(encode_child)
p... |
def get_transcripts(fname_gtf):
### parse all transcripts and store by ID
transcripts = dict()
tx_intervals = dict()
all_pos = dict()
sys.stderr.write('Parsing %s for transcript coordinates\n' % fname_gtf)
for i, line in enumerate(open(fname_gtf, 'r')):
if i > 0 and i % 100000 == 0:
... | The code processes transcript and variant data to generate a personalized transcriptome with a specified tumor mutational burden (TMB). It loads transcript structures, germline, and somatic variants, filters somatic mutations using a random seed to meet the TMB threshold, and outputs modified transcripts and variant po... | def main():
if len(sys.argv) < 8:
sys.stderr.write('Usage: %s <transcripts.gtf> <transcripts.fa> <outname_tag> <outdir> <random_seed> <TMB> <phased_germline_var.vcf-pattern> <somatic_va.vcf-pattern>\n' % sys.argv[0])
sys.exit(1)
fname_gtf = sys.argv[1]
fname_fa = sys.argv[2]
outtag = s... |
def get_today_games_from_team_abbv(team_abbv_name):
today = datetime.datetime.today().date()
# today ="09/07/2021"
team_id = get_team_id_by_abbv_name(team_abbv_name=team_abbv_name)
sched = statsapi.schedule(start_date=today, end_date=today, team=team_id)
return sched
def get_lineups_from_mlbgame(gam... | The function retrieves today's MLB games for a given team abbreviation, fetches lineups for each game, compiles players from both home and away teams, and returns a list of player data. It handles exceptions by printing errors when lineups cannot be retrieved. | def get_mlb_today_lineup_by_team_abbv(team_abbv_name):
"""
Return dic with players from home team and away team
"""
games = get_today_games_from_team_abbv(team_abbv_name)
players = []
# Is a forloop because 1 team can play 2 games in 1 day
for game in games:
try:
home_lin... |
def ele_strk_brdn_DK(self, iLn, **kwargs):
assert kwargs.keys()=={"comp", "T_K"} or kwargs.keys()=={"ne", "T_K"}
_ne = kwargs["comp"].ne if "comp" in kwargs else kwargs["ne"]
T_K = kwargs["T_K"]
prtb = self.prtb_lvl_DK(self.lin.df.loc[iLn, "idx_lLvl"], T_K=T_K) + \
self.prtb_lvl_DK(self.lin.d... | This function calculates total interaction energy using either the DK or Gr method. For DK, it combines residue, van der Waals, electrostatic (from ele_strk_brdn_DK), and ion (from ion_strk_brdn) contributions. For Gr, it directly returns electrostatic results from ele_strk_brdn_Gr. | def loren_brdn(self, iLn, *, comp, T_K, strk_method="DK"):
# assert strk_method == "DK" #TODO
if strk_method=="DK":
ele_strk = self.ele_strk_brdn_DK(iLn, comp=comp, T_K=T_K)
ion_strk = self.ion_strk_brdn(iLn, ele_strk_brdn=ele_strk, comp=comp)
return self.res_brdn(iLn, comp=comp, T_K=T_K) + \
... |
def get_literals(condition):
if isinstance(condition, pddl.Literal):
yield condition
elif isinstance(condition, pddl.Conjunction):
yield from condition.parts
def _get_cover_equivalence_conjunction(self, literal):
"""This is only called for atoms with a predicate for which the
... | This function checks if any delete effect can balance an add effect by constructing a constraint system. It ensures parameters aren't unnecessarily equated, prevents constant binding, and verifies inequalities. If no balancing delete effect exists, it refines candidates and returns True; otherwise, it returns False. | def _add_effect_unbalanced(self, action, add_effect, del_effects,
enqueue_func):
# We build for every delete effect that is possibly covered by this
# invariant a constraint system that will be solvable if the delete
# effect balances the add effect. Large parts of... |
def parse_typed_list(context, alist, only_variables=False,
constructor=construct_typed_object,
default_type="object"):
with context.layer("Parsing typed list"):
result = []
group_number = 1
while alist:
with context.layer(f"Parsing {group... | The function `parse_effect` parses PDDL effect blocks into structured objects (e.g., `ConjunctiveEffect`, `UniversalEffect`, `ConditionalEffect`, `CostEffect`, or `SimpleEffect`). It validates input syntax, recursively processes nested effects, and constructs appropriate effect instances based on tags like "and", "fora... | def parse_effect(context, alist, type_dict, predicate_dict):
if not alist:
context.error("All (sub-)effects have to be a non-empty blocks.", alist)
tag = alist[0]
if tag == "and":
effects = []
for eff in alist[1:]:
if not isinstance(eff, list):
context.err... |
def check_named_block(alist, names):
return isinstance(alist, list) and alist and alist[0] in names
def assert_named_block(context, alist, names):
if not check_named_block(alist, names):
context.expected_named_block_error(alist, names)
def parse_requirements(context, alist):
with context.layer("Pars... | The function `parse_task_pddl` parses a PDDL task description, validating its structure and extracting components like problem name, domain, objects, initial state, goal, and metrics. It iterates through the PDDL input, checks syntax (e.g., "define", ":problem", ":domain"), and yields parsed elements while reporting er... | def parse_task_pddl(context, task_pddl, type_dict, predicate_dict):
iterator = iter(task_pddl)
with context.layer("Parsing task"):
define_tag = next(iterator)
if define_tag != "define":
context.error("Task definition expected to start with '(define ")
with context.layer("Par... |
def parse_typed_list(context, alist, only_variables=False,
constructor=construct_typed_object,
default_type="object"):
with context.layer("Parsing typed list"):
result = []
group_number = 1
while alist:
with context.layer(f"Parsing {group... | The function `parse_action` parses a PDDL action from a list (`alist`), validating its structure and extracting components like the action name, parameters, precondition, and effect. It checks for required tags (e.g., `:action`, `:parameters`, `:precondition`, `:effect`), ensures correct data types, and constructs a `p... | def parse_action(context, alist, type_dict, predicate_dict):
with context.layer("Parsing action name"):
if len(alist) < 4:
context.error("Expecting block with at least 3 arguments for an action.",
syntax=SYNTAX_ACTION)
iterator = iter(alist)
action_tag =... |
def Starter():
"""
checking if all the files that should be exists exist
if not creating include dirs
"""
global Config
global system_os
print("Starting...")
# checking the platform system
system_os = platform.system()
if system_os == "Windows" or system_os == "Linux":
... | The main task of the code is to handle command-line operations for managing and compiling code files. It processes arguments to add new files, compile code (with options for force or rebuild), list files, display help, or change flags. The tool ensures the existence of a file list, validates inputs, and executes corres... | def main():
Starter()
args = sys.argv[1:]
if len(args) == 0:
print("For Help please use the flag --help or -h")
sys.exit("No args has been insert")
# args = input("Option: ").split(" ")
# pass
if not os.path.exists(CODES_FILES_LIST_FILE):
with open(CODES_FILES_... |
def lock(self):
self.locking_level = self.locking_level + 1
if self.locking_level == 1: # went from unlocked to locked, manage area timer
if self.occupancy_timer: # timer is running, store time remaining
self.seconds_left_when_locked = seconds_between(DateTime.now(),self.occu... | This method processes occupancy control commands (LOCK, UNLOCK, CLEARLOCKS, LOG) received from an area's parent system, executes corresponding locking actions, handles timeout parameters, logs status, and propagates commands to child areas via event sending. It parses incoming commands, triggers lock/unlock operations,... | def process_occupancy_control_received_command_event(self,event): # OC event handler for a command from OL to control area locking
log.info("Occupancy Control for area {} received command {}".format(self.name,event.itemCommand))
parts = str(event.itemCommand).split(',')
command = parts [0] ... |
def getPageFromID(idnum):
url = 'https://www.psychologytoday.com/profile/' + idnum
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15'}
mainpagehtml = requests.get(url,headers=headers)
return BeautifulSoup(mai... | The code scrapes therapy directories from psychologytoday.com for a given city and state, filters therapists accepting new clients, and collects their details using additional functions. It constructs a URL, uses headers to bypass restrictions, parses HTML with BeautifulSoup, extracts relevant therapist data, and retur... | def scrapeTherapy(city,state):
url = 'https://www.psychologytoday.com/us/therapists/' + state.lower() + '/' + city.lower()
# headers added after running requests.get(url) by itself returned a 403 status code
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/605.1.15 (KHTM... |
def init_map(self):
"""Intialize the map before each search
"""
self.found = False
self.vertices = []
self.vertices.append(self.start)
def get_new_point(self, goal_bias, goal_region,Flag, Flag2=False, cbest=0):
"""Choose the goal or generate a random point
argumen... | This code implements the Informed RRT* algorithm to find an optimal collision-free path from the start to the goal in a 2D space. It samples points, extends toward the nearest node, checks for collisions, and rewires nodes to minimize path cost. Upon reaching the goal, it continues refining the path. The result include... | def informed_RRT_star(self, n_pts=2000, neighbor_size=20):
'''RRT* search function
arguments:
n_pts - number of points try to sample,
not the number of final sampled points
neighbor_size - the neighbor distance
In each step, extend a new node if possi... |
def uniform_sample(self, n_pts):
'''Use uniform sampling and store valid points
arguments:
n_pts - number of points try to sample,
not the number of final sampled points
check collision and store valide points in self.samples
'''
# Initialize gra... | The code constructs a Probabilistic Roadmap (PRM) graph by sampling points using a specified method (uniform, random, Gaussian, or bridge), connecting them via a kdtree-based nearest-neighbor search, and adding nodes/edges to `self.graph`. It initializes the graph, generates `n_pts` samples, connects vertices within di... | def sample(self, n_pts=1000, sampling_method="uniform", kdtree_d=15):
'''Construct a graph for PRM
arguments:
n_pts - number of points try to sample,
not the number of final sampled points
sampling_method - name of the chosen sampling method
kdtre... |
def print_help():
print("\nCyberpunk 2020 Battle Calculator v1.0.0\n author: wyleg\n\nCommands:\n\
getroundinfo\n\
getcharinfo <character>\n\
nextround\n\
calcinit [ow]\n\
shoot <character> <target> <distance> [preroll=<number>] [ns|nosaveroll] [cm=<modifier>] [f=<fullauto_burst_size>|b|s] [bp=... | This function processes game commands by checking the first argument to determine the action. It handles commands like exiting, displaying help, retrieving round/character info, shooting, advancing rounds, calculating initiative, and skill checks. Each command triggers corresponding functions, with arguments parsed and... | def executeCommand(args):
cmd = args[0]
args_list = args
args_list.pop(0)
if cmd == "exit":
sys.exit(0)
if cmd == "help":
print_help()
elif cmd == "getroundinfo":
getRoundInfo()
elif "shoot" in cmd:
shootParseArgs(args_list)
elif cmd == "nextround":
... |
def additional_interest_on_debt(debt):
interest_rate = 0.05
return debt * interest_rate
def financing_debt(percent_debt, company):
return purchase_price(company) * percent_debt/100
def forgone_interest(cash):
risk_free_rate = 0.04
return cash * risk_free_rate
def financing_cash(percent_cash, company... | The main task of the code is to adjust combined net income values by subtracting calculated interest expenses. For each entry in the combined_net_income dictionary, it deducts additional interest on debt and forgone interest on cash, using financing functions with fixed parameters (30% debt, 70% cash) and the company i... | def pre_tax_minus_interest(combined_net_income, company):
for i in combined_net_income:
combined_net_income[i] -= additional_interest_on_debt(
financing_debt(30, company))
combined_net_income[i] -= forgone_interest(financing_cash(70, company))
return combined_net_income |
def post_tax_net_income(pre_tax_net_income):
tax_rate = 0.25
for i in pre_tax_net_income:
pre_tax_net_income[i] *= (1 - tax_rate)
return pre_tax_net_income
def pre_tax_minus_interest(combined_net_income, company):
for i in combined_net_income:
combined_net_income[i] -= additional_interes... | The code calculates the yearly earnings per share (EPS) after a merger or acquisition by adjusting post-tax earnings based on the combined net income of the buyer and seller, subtracting interest, and dividing by the final shares outstanding. It returns the adjusted EPS values for each period. | def yearly_eps(buyer, seller, percent_cash):
post_tax_earnings = post_tax_net_income(pre_tax_minus_interest(combine_net_income(
project_net_income(buyer), project_net_income(seller)), seller))
for i in post_tax_earnings:
post_tax_earnings[i] /= final_shares_outstanding(
buyer, percen... |
def str_to_bool(df):
"""Convert 'enabled' and 'flex' columns to boolean columns
due to Dash DataTable inability to display booleans"""
for col, dtype in df.dtypes.items():
if col == 'enabled' or col == 'flex':
df[col] = df[col].astype('bool')
return df
def DataFrame_to_dict(df: pd.Da... | (The code processes a DataFrame of vaccination centers by converting boolean columns, filtering enabled centers, running an optimization model with vaccine requirements, parsing the model's output, and applying data transformations to return an optimized DataFrame solution.) | def build(df: pd.DataFrame, vaccines_required: int) -> pd.DataFrame: # takes a csv file address of centres and returns DataFrame of the optimised solution
df = str_to_bool(df) # Convert 'enabled' and 'flex' columns to boolean columns due to Dash DataTable inability to display booleans
centre_vals=DataFrame_to_... |
def display_hand(hand):
"""
Displays the letters currently in the hand.
For example:
display_hand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in ... | The code allows a user to play a hand of letters by entering valid words from the hand. It checks if each input word is valid, updates the hand by removing used letters, and accumulates the score. Invalid words prompt the user to try again. The game continues until the hand is exhausted or the user inputs "!!". The tot... | def play_hand(hand, word_list):
"""
Allows the user to play the given hand, as follows:
* The hand is displayed.
* The user may input a word.
* When any word is entered (valid or invalid), it uses up letters
from the hand.
* An invalid word is rejected, and a message is displayed ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.