dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def defeatEnemy(handle):
if isCorrectPlatform(handle):
clickSpikes(handle)
clickContinue(handle)
return
moveTop(handle)
time.sleep(0.5)
if isCorrectPlatform(handle):
clickSpikes(handle)
return
moveBottom(handle)
time.sleep(0.5)
clickSpikes(handle... | The function `defeatWave` automates defeating enemies in a game wave. It starts by defeating the first enemy, waits, and continues. If the wave is rare, it finishes immediately. Otherwise, it repeatedly defeats four more enemies, waits, and continues. Finally, it finishes the wave, handling both standard and rare wave ... | def defeatWave(handle):
print("Wave started")
#print("Enemy #1")
defeatEnemy(handle)
time.sleep(1)
clickContinue(handle)
if(isRareWave(handle)):
print("Rare wave")
finishWave(handle)
return
for _ in range(4):
time.sleep(1)
#print("Enemy #" + str(i + 2)... |
def getDFWindow():
return win32gui.FindWindow(None, "Adobe Flash Player 32,0,0,465")
def startWave(handle):
click(handle, 600, 400)
time.sleep(3)
def defeatWave(handle):
print("Wave started")
#print("Enemy #1")
defeatEnemy(handle)
time.sleep(1)
clickContinue(handle)
if(isRareWave(han... | The main task of the code is to repeatedly process waves using `startWave` and `defeatWave` functions, incrementing a medal counter until it reaches 9999. It initializes a DataFrame (`dfWind`), takes an initial medal count from the command line, and iteratively updates the count while printing the total medals after ea... | def main():
medals = int(sys.argv[1])
dfWind = getDFWindow()
while medals < 9999:
startWave(dfWind)
defeatWave(dfWind)
medals = medals + 1
print("Total medals: " + str(medals)) |
def _connect_to_socket(self) -> None:
"""
Connect to socket.
"""
self.ws = SocketClient(
self.ws_url
)
self.ws.connect()
self.ws.start_dispatcher()
def _get_camera(self, camera_path: str) -> cv2.VideoCapture:
"""
Get camera.
@... | The code initializes a camera, streams video frames to a socket and queue with specified rates and sizes, handles errors, and maintains an infinite loop to reconnect if the camera disconnects, logging status updates throughout the process. | def start_camera(self) -> None:
"""
Start camera in infinite loop.
"""
self._connect_to_socket()
self.vid = self._get_camera(self.camera_path)
self.logger.info("Started camera...")
frame_stream = self._get_frame_stream(1 / self.frame_rate_camera)
socket_... |
def get_best_split(self, dataset, num_samples, num_features):
best_split = {}
max_information_gain = -float("inf")
for feature_index in range(num_features):
feature_values = dataset[:, feature_index]
possible_thresholds = np.unique(feature_v... | The function recursively constructs a decision tree by splitting the dataset based on information gain. It checks if the current node can split further (based on sample count and depth limits), finds the optimal feature-threshold split, and recursively builds left/right subtrees. If no valid split is found, it returns ... | def build_tree(self, dataset, curr_depth=0):
X, Y = dataset[:,:-1], dataset[:,-1]
num_samples, num_features = np.shape(X)
if num_samples>=self.min_samples_split and curr_depth<=self.max_depth:
best_split = self.get_best_split(dataset, num_samples, num_features)
... |
def load_header(record):
header_file = get_header_file(record)
header = load_text(header_file)
return header
def get_sampling_frequency(string):
value = string.split('\n')[0].split(' ')[2].split('/')[0].strip()
if is_number(value):
value = float(value)
else:
value = None
retu... | The code saves a signal to a record file using the WFDB library, ensuring compatibility with 16-bit integer formats. It extracts header parameters (sampling frequency, units, names, etc.) from the record, validates signal formats, clips and converts the signal to `int16` if all formats are '16', and raises an error for... | def save_signal(record, signal, comments=list()):
header = load_header(record)
path, record = os.path.split(record)
sampling_frequency = get_sampling_frequency(header)
signal_formats = get_signal_formats(header)
adc_gains = get_adc_gains(header)
baselines = get_baselines(header)
signal_units... |
def comm_out_symmetric(targ_id, message):
try:
#Is this line necessary?
message = str(message)
message = encrypt(message.encode('utf-8'), key)
targ_id.send(message)
except ConnectionRefusedError:
print('[-] Connection Refused Error')
def comm_out(targ_id, message):
tr... | This function manages a command-and-control communication loop with a target, handling user input for sending encrypted/Base64-encoded commands, exiting sessions, or setting persistence (registry/cron jobs). It uses symmetric/asymmetric encryption or Base64 encoding based on the target's configuration, terminates conne... | def target_comm(targ_id, targets, num):
while True:
message = input(f'{targets[num][3]}/{targets[num][1]}#>')
if len(message) == 0:
continue
if message == "help":
pass
else:
if targets[num][8] == "Symmetric":
comm_out_symmetric(targ... |
def recipePublisher():
flag = True
while(flag):
recipeStepsRunner("Noodles")
flag = False
def startWashing():
try:
tree = ET.parse("/home/"+user+"/catkin_ws/src/gi_healthcare/washingProcess/wash.xml")
root = tree.getroot()
stepList = list()
for step in root.fi... | The code processes incoming messages to execute specific actions: if the first command parameter is "1", it triggers a recipe publisher; if the second is "1", it starts washing; if both are "0", it initiates a shutdown process. The function splits the message data into parts and uses conditional checks to determine whi... | def callback(msg):
# cooking cmd[0] = 1/0
cmd = msg.data.split(",")
if cmd[0] == "1":
recipePublisher()
# washing cmd[1] = 0/1
elif cmd[1] == "1":
startWashing()
# shutdown cmd[2] = 0/0
elif cmd[0] == "0" and cmd[1] == "0":
shutdownProcess() |
def kin_hip(self, q, dq = None):
if dq is None: dq = np.zeros(3)
x_h = self.l1*sin(q[0])
z_h = self.l1*cos(q[0])
dx_h = self.l1*cos(q[0])*dq[0]
dz_h = -self.l1*sin(q[0])*dq[0]
return x_h, z_h, dx_h, dz_h
def control(self, t, q, dq, parameters):
kp1... | The code simulates a system's state trajectory (xs) and control inputs (us) over T steps using a standard controller, computes swing foot positions (z_swfs), and calculates the displacement (dist) between initial and final hip positions. It initializes the system, applies controls iteratively, and returns xs, us, z_swf... | def compute_control_standard(self, x0, T, params):
#compute xs and us from standard controller
x, us, z_swfs = x0.copy(), [], []
x_h0, _,_,_ = self.kin_hip(x[:3])
for k in range(T):
u = self.control(0, x[:3], x[3:], params)
x = self.step(x, u)
_,z_swf,... |
def set_init_state(self,x0):
self.x0 = x0
def control(self, t, q, dq, parameters):
kp1 = parameters[0];
kp2 = parameters[1];
kd1 = parameters[2];
kd2 = parameters[3];
alpha = parameters[4];
y1 = q[2]-alpha;
y1d = dq[2];
y2 = -q[1]-q[0];
y2... | This function solves a system of differential equations using an initial guess and a control strategy, integrating over time steps with event detection for impacts. It optionally retrained an ILQR controller using initial states, updates the system state after each impact event, and stores the solution trajectory, time... | def solve_eqns(self, q0, dq0, num_steps, parameters, retrain = False, retrain_iter = 5):
#options = odeset('RelTol',1e-5, 'Events', @event_func);
h = self.dT; # time step
tmax = 2; # max time that we allow for a single step
tspan = np.arange(0, tmax, h)
y0 = np.concatena... |
def kin_hip(self, q, dq = None):
if dq is None: dq = np.zeros(3)
x_h = self.l1*sin(q[0])
z_h = self.l1*cos(q[0])
dx_h = self.l1*cos(q[0])*dq[0]
dz_h = -self.l1*sin(q[0])*dq[0]
return x_h, z_h, dx_h, dz_h
def kin_swf(self, q, dq = None):
if dq is No... | The function `analyse` processes a simulation solution (`sln`) to compute kinematic data (positions, velocities) of a system (hip and swing leg), control efforts, and performance metrics (e.g., distance, cost of transport). It iterates through time steps, calculates displacements, velocities, and control inputs, aggreg... | def analyse(self, sln, parameters, to_plot = True, Umax = 30):
x_hs, dx_hs, dx_hs_mean, z_hs, dz_hs = [], [], [], [], []
x_swfs, dx_swfs, z_swfs, dz_swfs = [], [], [], []
qs, dqs, us = [], [], []
t_hs = [] #time index
dts, fs, ds = [], [], [] # time interval for one step,... |
def eval_M(self, q):
q1, q2, q3 = q[0], q[1], q[2]
m1, m2, m3, l1, l2, l3, g = self.m1, self.m2, self.m3, self.l1, self.l2, self.l3, self.g
t2 = q1-q2;
t3 = cos(t2);
t4 = q1-q3;
t5 = cos(t4);
t6 = l1*l3*m3*t5*(1.0/2.0);
M = np.array([l1**2*(m1*(1.0/4.0)... | This function computes the time derivative of a state vector y for a dynamic system, using equations of motion. It calculates inertia (M), Coriolis (C), gravity (G), and input matrices (B), applies control strategies (std, ilqr, qp), and solves for dy[3:] via M⁻¹(-C·dq - G + B·u), returning the state derivative for num... | def eqns(self, t, y, t0, parameters):
q = y[:3]
dq = y[3:]
M = self.eval_M(q)
C = self.eval_C(q, dq)
G = self.eval_G(q)
B = self.eval_B()
if self.control_opt == 'std':
u = self.control(t, q, dq, parameters)
elif self.control_opt =... |
def median_filter(
input: np.ndarray, size: int, dtype: Optional[type] = None
) -> np.ndarray:
"""
Fast 1D median filtering using reflection to
extend the input array beyond its boundaries.
Uses pandas if input and filter size are long, scipy if short.
Parameters
----------
input: ndarr... | The function `noise_std` estimates the standard deviation of noise in input signals using methods like MAD, FFT, or Welch's PSD analysis. It processes multi-dimensional arrays, applies outlier-robust filtering for MAD, computes high-frequency PSD averages for FFT/Welch, and returns a noise estimate. The implementation ... | def noise_std(
x: np.ndarray,
method: str = "welch",
max_num_samples: int = 3072,
noise_range: Tuple[float, float] = (0.25, 0.5),
filter_length: int = 31,
axis: int = -1,
n_jobs: Optional[int] = None,
device: str = "cuda" if torch.cuda.is_available() else "cpu",
) -> Union[float, np.ndar... |
def get_valid_path(self):
temp = []
if self.position[0] - 1 >= 0:
temp.append([self.position[0] - 1, self.position[1], 'up'])
if self.position[1] + 1 < con.COL_COUNT:
temp.append([self.position[0], self.position[1] + 1, 'right'])
if self.position[1] - 1 >= 0:
... | This function navigates through a grid by checking unvisited paths for safety, appending valid moves to tracking lists, and simulating directional key presses. If no safe path is found, it backtracks by reversing the last move. The code handles maze traversal with tracking, backtracking, and directional control based o... | def think_bro_think(self):
valid_path = self.get_valid_path()
unvisited_path = self.get_unvisited(valid_path)
flag = False
for i in range(len(unvisited_path)):
if self.isSafe(unvisited_path[i][0], unvisited_path[i][1]):
flag = True
if unvisited... |
def init_grads(parameters, layer_dims):
L = len(parameters) // 2 # number of layers in the neural network
grads = {}
for l in range(0, L):
grads['dW' + str(l + 1)] = np.zeros((layer_dims[l + 1], layer_dims[l]))
grads['dA' + str(l)] = np.zeros((layer_dims[l], 1))
grads['db' + str(l ... | This code implements a deep neural network with multiple layers using mini-batch gradient descent. It initializes parameters, shuffles data each epoch, computes forward and backward passes, updates parameters, tracks cost and accuracy, and plots the learning curve. The main task is training a multi-layer model to minim... | def L_layer_model(X, Y, layers_dims, learning_rate=1, num_epochs=5, batch_size=10, print_cost=False):
costs = []
parameters = initialize_parameters_deep(layers_dims)
num_batches = (X.shape[1] + batch_size - 1) // batch_size
for i in range(0, num_epochs):
temp = np.concatenate((X, Y), axis=0)
... |
def L_model_forward(X, parameters):
"""returns AL, caches=[((A_prev, W, b), Z)]"""
caches = []
A = X
L = len(parameters) // 2 # number of layers in the neural network
for l in range(1, L):
A_prev = A
A, cache = linear_activation_forward(A_prev, parameters['W' + str(l)], parameters[... | This function trains a deep neural network with multiple layers using mini-batch gradient descent. It initializes parameters, shuffles data each epoch, processes batches, computes forward/backward passes, updates parameters, tracks cost/accuracy, and plots learning curves. It returns total cost and learned parameters. | def L_layer_model(X, Y, layers_dims, learning_rate=1, num_epochs=5, batch_size=10, print_cost=False, file=None):
costs = []
parameters = initialize_parameters_deep(layers_dims)
num_batches = (X.shape[1] + batch_size - 1) // batch_size
for i in range(0, num_epochs):
temp = np.concatenate((X, Y),... |
def get_velocity(self, params):
return _iter_factors(params)
def _get_value(self, key, default, *args, **kwargs):
try:
value = kwargs.get(f'{key}Func')(*args, **kwargs)
except TypeError:
value = kwargs.get(key, default)
finally:
return str(value)
def g... | The main task of the code is to add a musical sample to a parser with calculated parameters. It processes input arguments to determine velocity, MIDI note ranges (Root/LoKey/HiKey), velocity ranges (LoVel/HiVel), and volume. The function constructs a filename using dynamic parameters and adds the sample to the parser w... | def add_sample(self, **kwargs):
params = []
for param in ('rr', 'dyn', 'dir', 'stroke'):
params.append(
(
kwargs.get(f'total_{param}s', 1),
kwargs.get(f'{param}_index', 0)
)
)
vel = self.get_velocity(... |
def drop_down(self):
options = self.df.drop('ztfname', axis=1).columns
def drop_menu(ind):
i_ax = tk.StringVar()
i_ax.set(self.main_graph[0][ind])
i_drop = tk.OptionMenu(self.master, i_ax, *options)
i_drop.grid(row=2, column=int(1 + 3 * ind), rowspan=1, c... | This code initializes a GUI application with a specified window size, background color, and exit protocol. It sets up data visualization parameters, defines graphical elements, and prepares for interactive data analysis using a DataFrame. The class configures plotting settings, dropdown menus, and screen updates to fac... | def __init__(self, df, master=None):
super().__init__(master)
self.master = master
self.master.geometry('1200x600+10+10')
self.master.configure(bg='#6b8ba4')
self.master.protocol('WM_DELETE_WINDOW', self.exit_)
self.df = df
self.target = [None, []]
self.p... |
def gfit(self, x, wave, which='both', params=[]):
model= self.SiII_model[wave] if not params else params
rest_Si_1, rest_Si_2 = self.rest_wl[wave]
md = model[0].params
amp1, vel1, fwhm1 = md['g1_amp'].value, md['g1_vel'].value, md['g1_fwhm'].value
amp2, vel2, fwhm2 = md['g2_amp']... | The main task of the code is to generate a GUI plot displaying spectral flux data and model fits for specific SiII absorption lines (6355Å and 5972Å). It plots the observed flux, fitted Gaussian components, and continuum, annotates velocity measurements, adds labels/legends, and returns the figure/axis objects for visu... | def show_gui(self, figsize):
fig, ax = plt.subplots(figsize=figsize)
ax.plot(self.wave, self.flux, color='blue', label=f'phase: {self.phase:.2f}')
for wave, col in [('6355', 'red'), ('5972', 'green')]:
model, wl_cut, flux_cut, continuum_cut, continuum, v_bounds = self.SiII_model[wave... |
def get_object(self, spec_object):
if type(spec_object) != list:
return spec_object.get_phase(), spec_object.data
else:
phases = np.array([spec.get_phase() for spec in spec_object])
ind = np.abs(phases).argmin()
phase = phases[ind]
data = np.ar... | This code initializes a supernova spectra analysis object by processing input data, setting parameters, and creating models for specific spectral lines (SiII 6355 and 5972). It adjusts wavelengths for redshift, defines constraints, and prepares models for further analysis or fitting, using provided bounds and recursion... | def __init__(self, sn_name, sample, bounds_1, bounds_2, sigma, recursion=[False, False]):
self.name = sn_name
self.redshift = sample.data['redshift'][self.name]
spec_object = sample.get_target_spectra(self.name)
phase, data = self.get_object(spec_object)
self.phase = phase
... |
def update_critic(self, state, action, reward, next_state, terminal):
critic_loss = self.compute_critic_loss(state, action, reward, next_state, terminal)
self.critic_optim.zero_grad()
critic_loss.backward()
self.critic_optim.step()
return critic_loss.item()
def update_actor(self... | This code updates a reinforcement learning agent's critic and actor networks using a batch of experiences from a buffer. It calculates the critic loss and conditionally updates the actor (with target network updates) every 'actor_delay' steps. The function returns both actor and critic losses for monitoring or optimiza... | def update(self, batch_size, step, actor_delay):
state, action, reward, next_state, terminal = self._unpack_batch(self.buffer.sample(batch_size))
self._prepare_update(state, action, reward, next_state, terminal)
critic_loss = self.update_critic(state, action, reward, next_state, terminal)
... |
def get_neighbours(node, edge_vector):
edge_list, to_node_list = get_edge_list_from_node(node)
estate_list = [get_edge_state(e, edge_vector) for e in edge_list]
estate_list = np.array(estate_list)
tnlist = to_node_list * estate_list
nbr_list = tnlist[np.nonzero(tnlist)]
return nbr_list
def get_n... | The function generates all possible network states by iterating over binary assignments of node types to neighbors of a starting node, simulating activation/inhibition propagation through connected nodes, and recording state vectors, type assignments, and active nodes for each configuration. | def perc_motif_2step(edge_vector):
results_list = []
start_node = 0
nbr_list = get_neighbours(start_node, edge_vector)
nb_nbr = len(nbr_list)
if nb_nbr == 0:
state_bvector = 1 # only the starting node is activated
results = dict(state_bvector=state_bvector)
results_list.appen... |
def _track_steps_verbose(self, step_output: Union[dict[str, str], AgentFinish, List[Tuple[AgentAction, str]]]):
if self.verbose:
if 'input' in step_output:
plog(f"> Start: \n{step_output['input']}\n", 'bold')
else:
if isinstance(step_ou... | This method executes a loop up to `max_iterations` to process steps in a sequence, tracking intermediate results. It checks if each step output is an `AgentFinish` (terminating the process) or a tool return (early exit). If neither, it accumulates steps and continues iterating, ensuring controlled execution with step t... | def __call__(self, **kwargs):
intermediate_steps = []
iterations = 0
self._track_steps_verbose(kwargs)
while iterations <= self.max_iterations:
next_step_output = self._take_next_step(intermediate_steps, kwargs)
if isinstance(next_step_output, AgentFinish):
... |
def prep_inputs(self, inputs: Union[Dict[str, Any], Any]) -> Dict[str, str]:
"""Validate and prep inputs."""
if not isinstance(inputs, dict):
_input_keys = set(self.input_keys)
if len(_input_keys) != 1:
raise ValueError(
f"A single string input... | The code processes input data by preprocessing it, generating responses using a model, creating structured outputs, and preparing final results based on the return_only_outputs flag. It handles input transformation, model inference, and output formatting to return structured data efficiently. | def __call__(self, inputs, return_only_outputs: bool = False):
inputs = self.prep_inputs(inputs)
responses = self.generate([inputs])
outputs = self.create_outputs(responses)
final_outputs: Dict[str, Any] = self.prep_outputs(
inputs, outputs[0], return_only_outputs
)
... |
def main_page():
# Comfiguring Streamlit GUI
st.title("Youtube Data Harvesting and Warehousing")
st.subheader("Architectural Diagram of the Project")
image = Image.open('Location of the image ') #keep your image location here
st.image(image, caption='Architectural Daigram')
def Username_Converter()... | The code defines a main function that creates a Streamlit sidebar for page selection, allowing users to navigate between four distinct pages: "Main Page," "Username Converter," "Single Select," and "Multi Select." Based on the selected option, it dynamically renders the corresponding page by calling its dedicated funct... | def main():
# Create a sidebar with page selection
page = st.sidebar.selectbox("Select a Page", ["Main Page","Username Converter", "Single Select","Multi Select"])
# Render the selected page
if page == "Main Page":
main_page()
elif page=='Username Converter':
Username_Converter()
... |
def _maybe_init_user_imports_file(user_imports_path: Path) -> None:
if not user_imports_path.exists():
_maybe_init_user_imports_directory(user_imports_path)
user_imports_path.touch()
user_imports_path.write_text(TEMPLATE_TEXT)
def _read_file_lines_from_user_settings(user_settings_path: str) ... | The function retrieves and processes import statements from a user-specified settings file. It initializes the file if needed, reads its contents, and extracts the imports for further use. | def _get_imports_from_user_settings(user_imports_path) -> list:
_maybe_init_user_imports_file(user_imports_path)
file_lines = _read_file_lines_from_user_settings(user_imports_path)
return _get_imports(file_lines) |
def load_data(self):
headers, regex = self.generate_logformat_regex(self.log_format)
self.df_log = self.log_to_dataframe(os.path.join(self.path, self.logName), regex, headers, self.log_format)
def preprocess(self, line):
for currentRex in self.rex:
line = re.sub(currentRex, '<*>', li... | The code parses a log file by clustering similar log messages into templates using a prefix tree. It preprocesses each log line, searches for matching clusters, creates new clusters when no match is found, or updates existing clusters with new templates. Progress is tracked, and results are saved after processing. | def parse(self, logName):
print('Parsing file: ' + os.path.join(self.path, logName))
start_time = datetime.now()
self.logName = logName
rootNode = Node()
logCluL = []
self.load_data()
count = 0
for idx, line in self.df_log.iterrows():
logID =... |
def get_product_id(id):
try:
conn = session.get(f"https://economy.roblox.com/v2/assets/{id}/details", verify=False)
data = conn.json()
if conn.status_code == 200:
return {
"id": data["ProductId"],
"creator": data["Creator"]["Id"]
}
... | This code monitors the Roblox catalog for items meeting specific criteria, automatically purchasing them when their price is lower than a predefined threshold. It uses session authentication, maintains a cache of purchased items, handles 403 errors by refreshing tokens, and logs activity. The loop runs indefinitely, ch... | def watcher():
global token, session, checks, logs
while True:
try:
headers = {
"x-csrf-token": token,
"cache-control": "no-cache",
"pragma": "no-cache",
}
conn = session.post("https://catalog.roblox.com/v1/catalog/items... |
def sub(mappings, ingredients, steps, templates):
show_mappings(mappings)
for template in templates:
for i in ingredients:
if fuzz.partial_ratio(template[0], i.item.lower()) > 90: #matches first word of template to an ingredient
print(i.item)
i.item = templat... | The function `transform_ingredients` modifies recipe ingredients and steps based on the specified `style` parameter. It applies transformations like converting to vegetarian, scaling recipes, or adjusting difficulty levels using helper functions. Depending on the style, it returns updated ingredients and steps, with sp... | def transform_ingredients(mappings, ingredients, steps, style, scaling_factor=1):
if style == 'to_vegetarian':
return sub(mappings, ingredients, steps, TO_VEGETARIAN)
if style == 'from_vegetarian':
ingredients, steps = sub(mappings, ingredients, steps, FROM_VEGETARIAN)
ingredients.append... |
def do_fall(self):
log.debug("do_fall")
self.image = self.fall.convert()
self.handle_new_image()
self.rect.y = self.original_y + 30
def do_jump(self):
log.debug("do_jump: y={}".format(self.y))
self.image = self.jump[self._get_next_jump_index()].convert()
self.hand... | The code's main task is to update an object's state by executing specific movement actions based on its current status. If falling, it triggers `do_fall`; if jumping, `do_jump`; if sliding, `do_slide`; otherwise, it defaults to `do_run`. This method orchestrates the object's behavior dynamically according to its active... | def update(self):
if self.falling:
self.do_fall()
elif self.jumping:
self.do_jump()
elif self.sliding:
self.do_slide()
else:
self.do_run() |
def bigram_add1_logs(transcript_file):
"""
provide a smoothed log probability dictionary based on a transcript
:param transcript_file: string
transcript_file is the path filename containing unpunctuated text sentences
:return: dict
bg_add1_log_dict: dictionary of smoothed bigrams log pro... | The code computes and prints the log probabilities of given sentences using a bigram language model trained on a generated corpus. It loads a bigram probability dictionary from a training dataset, then evaluates each input sentence's likelihood by calculating its log probability with the model. | def sample_run(sentences):
# sample usage by test code (this definition not actually run for the quiz)
#bigram_log_dict = utils.bigram_add1_logs('transcripts.txt')
bigram_log_dict = bigram_add1_logs(generate_corpus(desc_file='train_clean_corpus.json'))
for sentence in sentences:
print('*** "{}"'... |
def get_blob(data):
line = ""
_branch = data.pop(0)
data = "/".join(data)
if "#L" in data:
data, line = data.split("#L")
if line:
res = f"{data}#L{line}"
else:
res = f"{data}"
return res
def get_commit(org, repo, commit_id, github_token):
if "#diff" in commit_id:
... | The main task of the code is to parse a GitHub URL into its components (organization, repository, and type) and determine the appropriate action based on the URL type (blob, commit, or pull). It uses the GitHub token for authentication and returns results from helper functions like `get_blob`, `get_commit`, or `get_pul... | def parse_url(url, github_token):
res = ""
if "github.com" not in url:
log.debug(f"No match in URL: {url}")
return res
log.info(f"Parsing GitHub url: {url}")
data = url.split("github.com/")[1].split("/")
org = data.pop(0)
repo = data.pop(0)
type_ = data.pop(0)
if type_ ... |
def add_initial_state_constraint(self, prog, x, x_current):
# TODO: impose initial state constraint.
# Use AddBoundingBoxConstraint
a, b = np.shape(x)
for i in range(b):
prog.AddBoundingBoxConstraint(x_current[i],x_current[i],x[0][i])
pass
def add_input_saturation_constraint(self, prog, x, u... | The function `compute_mpc_feedback` solves a Model Predictive Control (MPC) optimization problem to compute the control input `u` based on the current state `x_current`. It sets up a Quadratic Program (QP) with constraints on initial state, input saturation, system dynamics, and a cost function. The QP is solved using ... | def compute_mpc_feedback(self, x_current, use_clf=False):
'''
This function computes the MPC controller input u
'''
# Parameters for the QP
N = 10
T = 0.1
# Initialize mathematical program and decalre decision variables
prog = MathematicalProgram()
x = np.zeros((N, 6), dtype="objec... |
def get_all_time_section(self):
greens = self.practise.all_time.greens
ats = self.practise.all_time.total_ats
percentage = in_percent(greens, ats, 1)
best_chain = self.practise.all_time.best_chain
section = f"""---ALL TIME---
Action tests: {ats}
Greens: {greens} ({percentage}%)
B... | The code's main task is to gather three sections of data (time, session, batches) using specific methods, concatenate them into a single string separated by newlines, and then overwrite the existing content of an info file with this combined string. | def update(self):
sections = [self.get_all_time_section(), self.get_session_section(), self.get_batches_section()]
to_write = "\n\n".join(sections)
self.override_info_file(to_write) |
def determine_section_in_column(self, img, x):
rgb_middle = img.pixel(x, 1)
if Colour.is_quite_green(rgb_middle) and Colour.has_pure_green(rgb_middle):
return self.check_further_for_green(img, x)
rgb_bottom = img.pixel(x, 2)
if Colour.is_mostly_red(rgb_bottom):
re... | This function identifies green and white sections in an image by analyzing each column. It tracks green positions and white start/end points, handling edge cases like white sections ending before green or overlapping. It updates the current AT's position data and alerts users to locating issues, ensuring accurate secti... | def locate_sections(self): # would use refactoring
img = mss().grab(self.bbox)
green_pos = None
white_pos = [None, None] # start and end
for x in range(img.size.width):
section = self.determine_section_in_column(img, x)
if section == ATResult.GREEN:
... |
def setup_new_at(self):
self.current_at = ActionTest()
def wait_to_load_up(self):
attempts = 0
with mss() as sct:
while True:
img = sct.grab(self.bbox)
if self.contains_at(img):
time.sleep(.0275) # a tiny bit for the green to settl... | The code's main task is to process and validate data by initializing a new AT context, waiting for loading, locating sections, monitoring progress, evaluating results, printing the current AT state, and returning it for further use. | def read_at(self):
self.setup_new_at()
self.wait_to_load_up()
self.locate_sections()
self.watch_bar()
self.evaluate_result()
self.current_at.print()
return self.current_at |
def generate_testing_prompt(self, prompt_index=None):
if not prompt_index:
prompt_index = self.prompt_index
self.prompt_index = self.prompt_index % len(self.prompt_generation_prompts)
self.prompt_index + 1
prompt = self.prompt_generation_prompts[prompt_in... | The main task of the code is to evaluate miner responses to a generated prompt by filtering valid replies, comparing them against a validator model's output, and updating miner information with scores. It queries selected miners, collects responses, discards invalid ones, scores valid responses, and updates UID data fo... | def forward(self, call_uids):
uids_to_query = self.uids_info.get_uids_for_category(self.category_name)
testing_prompt = self.generate_testing_prompt()
print("Testing prompt", testing_prompt)
payload = {
'prompt': testing_prompt,
'max_tokens': self.answer... |
def get_metadata(quiet=False):
metadata, len_metadata, metadata_headers, class_to_index, index_to_class, num_classes = rt.load_metadata(
metadata_path,
cols=(COL_ID, COL_PATH),
delimiter=' ',
)
# shuffle at beginning to get random sampling for train, test and validation datasets
... | This code trains a Generative Adversarial Network (GAN) using custom data loaders and PyTorch. It prepares metadata, builds neural networks (generator and discriminator), sets up CUDA optimization, and defines training loops with TensorBoard logging. The code includes placeholder TODOs for checkpointing, metrics, and m... | def run():
print('preparing metadata...')
metadata = get_metadata()
# TODO: remove
torch.autograd.set_detect_anomaly(True)
if not torch.cuda.is_available():
raise Exception("Training GANs on CPU? Aint nobody got time for that.")
print('building main loader')
loader = make_loader... |
def write_dir(hh = [1]):
for h in hh:
title = path+'/Simu_'+datanum+'/Reg%d'%h
if not os.path.exists(title) and MC==1:
os.makedirs(title)
if not os.path.exists(title+'/B') and MC==1:
os.makedirs(title+'/B')
if not os.path.exists(title+'/VIP') and MC==1:
... | The code performs a Monte Carlo simulation to evaluate and compare the predictive performance of multiple regression models (OLS, PCA, PLS, Lasso, Ridge, Elastic Net, Oracle, Group Lasso) on financial data. It iterates over different data configurations (sample sizes, time horizons) and model types, processes standardi... | def MC_simulation(MC = [1], datanum = 100, horizon = [1],model = [1,2]):
### hh is the horizon parameter, e.g. hh=1 means using monthly return as response variable.
### hh=3 is quarterly, hh=6 is Half-year and hh=12 is annually.
start = timeit.default_timer()
write_dir()
for hh in horizo... |
def find_cornerpts(VP, pts):
pts = np.array(pts)
for p1 in range(len(pts)):
bad = False
for idx in range(len(pts)):
if (pts[idx] != pts[p1]).any() and is_right(VP, pts[p1], pts[idx]):
bad = True
break
if not bad:
break
for p2 i... | The function computes perspective transformation matrices to map an image's corners to new points determined by vanishing points (vp1, vp2) and image dimensions. It calculates intersections of lines from vanishing points to image corners, adjusts transformed points based on vp1's position, and enforces a top vanishing ... | def get_transform_matrix(vp1, vp2, image, im_w, im_h, pts=None, enforce_vp1=True, vp_top=None):
if pts is None:
pts = [[0, 0], [image.shape[1], 0], [image.shape[1], image.shape[0]], [0, image.shape[0]]]
vp1p1, vp1p2 = find_cornerpts(vp1, pts)
vp2p1, vp2p2 = find_cornerpts(vp2, pts)
# right sid... |
def get_vp3(vp1, vp2, pp):
focal = np.sqrt(- np.dot(vp1 - pp, vp2 - pp))
vp1_w = np.concatenate((vp1, [focal]))
vp2_w = np.concatenate((vp2, [focal]))
pp_w = np.concatenate((pp, [0]))
vp3_w = np.cross(vp1_w-pp_w, vp2_w-pp_w)
vp3 = vp3_w[0:2]/vp3_w[2] * focal + pp_w[0:2]
return vp3
def get_... | This function detects and transforms license plate (lp) coordinates using a mask and perspective transformations. It generates a masked image, computes vanishing points (vp), applies a warp transformation to locate lps in a warped view, then maps these back to original coordinates. The result is stored in item['lp1'] a... | def get_lp_from_mask(self, item):
item['lp1'] = None
item['lp2'] = None
mask_frame = get_mask_frame(item['box'], self.last_frame, np.array(item['mask']))
_, mask_frame = cv2.threshold(mask_frame, 0.5, 255, cv2.THRESH_BINARY)
del item['mask']
image = np.zeros_like(self.... |
def split_edges(A, cut_off):
pos_E_a, pos_E_b = split_pos_edges(A, cut_off)
neg_E_a, neg_E_b = split_neg_edges(A, cut_off)
return pos_E_a, neg_E_a, pos_E_b, neg_E_b
def construct_adj_matrix(E, n):
E = np.array(E)
A = sparse.csr_matrix((np.ones(len(E)), (E[:,0], E[:,1])),
... | This function splits edges of a sparse matrix into training and validation sets. It calculates a cutoff based on the upper triangular sum of the matrix, partitions edges using this cutoff, and constructs labeled training/validation edge sets with corresponding adjacency matrices for graph-based tasks like link predicti... | def compute_tr_val_split(A, portion):
cutt_off = int(np.sum(sparse.triu(A, 1))*portion)
tr_pos_E, tr_neg_E, val_pos_E, val_neg_E = split_edges(A, cutt_off)
tr_A = construct_adj_matrix(tr_pos_E, A.shape[0])
tr_E = np.vstack((label_edges(tr_pos_E, 1),
label_edges(tr_neg_E, 0)))
... |
def read_vicdata(filename: str, header=3, base=True):
"""
- detectron files are csv files
- the databunch contains 16 3dim positions for all frames
"""
# read the file
vicondata = pd.read_csv(filename, header=header,
dtype=np.float64, skiprows=1)
# transform to ba... | This function reads and processes data files (CSV, JSON) for a specific case by aligning, synchronizing, and unifying them. It uses model type to determine processing mode, then returns the integrated dataset after synchronization and unification steps. | def read_all_data(model, path: str, cur_file: str, verbose=False):
"""
read all datafiles for 1 case, align and sync
"""
base = True if type(model) == BaseModel else False
data = {
'vic': read_vicdata(f'{path}/{cur_file}.csv', base=base),
'dec': read_decdata(f'{path}/{cur_file}.json'... |
def read_all_data(model, path: str, cur_file: str, verbose=False):
"""
read all datafiles for 1 case, align and sync
"""
base = True if type(model) == BaseModel else False
data = {
'vic': read_vicdata(f'{path}/{cur_file}.csv', base=base),
'dec': read_decdata(f'{path}/{cur_file}.json'... | This function analyzes a single data file by loading model data, plotting knee angles (left/right), calculating and printing DEC/IMU error metrics, visualizing models, performing Bland-Altman analysis, and optionally generating a movie GIF if specified. It uses predefined paths and model parameters for analysis. | def run_analysis_by_name(file, movie=False):
"""run analysis of one file"""
basemodel = BaseExtModel()
subpath = 'Gang' if 'Gang' in file else 'Treppe'
path = f'../data/{file[:2]}/{subpath}'
data = read_all_data(basemodel, path, file, verbose=True)
plot_angle(basemodel.get_knee_angles, 'knee'... |
def read_all_data(model, path: str, cur_file: str, verbose=False):
"""
read all datafiles for 1 case, align and sync
"""
base = True if type(model) == BaseModel else False
data = {
'vic': read_vicdata(f'{path}/{cur_file}.csv', base=base),
'dec': read_decdata(f'{path}/{cur_file}.json'... | The main task of the code is to process a single CSV file by reading data, calculating angle measurement errors (MSE), storing results in dictionaries, generating maximum angle values, creating visualizations (plots and movies), and saving outputs based on parameters. It handles both error analysis and data visualizati... | def do_file_job(model, task_res, maxlist, task_path, file, movies=False, save=False):
"""
complete all necessary preparation and calculation for one file
"""
if file.endswith('.csv'):
filename = file.split('.')[0]
# --------------------------------------------------------
data ... |
def start_bloomberg_session(self):
tries = 0
session = None
# try up to 5 times to start a session
while(tries < 5):
try:
# fill SessionOptions
sessionOptions = blpapi.SessionOptions()
sessionOptions.setServerHost(DataConstant... | The main task of the code is to retrieve time series market data from Bloomberg using a provided request. It initializes and manages a Bloomberg session, retries up to five times if the session fails to open, sends a bar data request, waits for responses, processes events, and returns the collected data in a DataFrame.... | def load_time_series(self, market_data_request):
options = self.fill_options(market_data_request)
#if(BBGLowLevelTemplate._session is None):
session = self.start_bloomberg_session()
#else:
# session = BBGLowLevelTemplate._session
try:
# if can't open the... |
def fetch_group_time_series(self, market_data_request_list):
data_frame_agg = None
# depends on the nature of operation as to whether we should use threading or multiprocessing library
if DataConstants().market_thread_technique is "thread":
from multiprocessing.dummy import Pool
... | The main task of the code is to download daily time series market data from a specified data provider, handling multithreading by splitting ticker requests into groups for parallel processing. It aggregates results into a pandas DataFrame, caches the output in memory, and returns the consolidated data. | def download_daily(self, market_data_request, data_vendor):
"""
download_daily - Loads daily time series from specified data provider
Parameters
----------
market_data_request : MarketDataRequest
contains various properties describing time series to fetched, includin... |
def get_data_vendor(self, source):
"""
get_loader - Loads appropriate data service class
Parameters
----------
source : str
the data service to use "bloomberg", "quandl", "yahoo", "google", "fred" etc.
we can also have forms like "bloomberg-boe" separated... | The function fetches time series market data based on parameters in `market_data_request`, handling intraday/tick or daily data retrieval via vendor-specific methods. It dynamically generates tickers if unspecified, applies cache strategies (internet load/mem caching), and returns filtered time series data or `None` on... | def fetch_market_data(self, market_data_request, kill_session = True):
"""
fetch_market_data - Loads time series from specified data provider
Parameters
----------
market_data_request : MarketDataRequest
contains various properties describing time series to fetched, ... |
def popup(text):
tkinter.messagebox.showinfo('stop!', text )
def add_group_todb(arg_grp_name):
conn = sqlite3.connect(db_path)
c = conn.cursor()
c.execute("""INSERT INTO "GroupName" (group_nm)
VALUES (? )""", (arg_grp_name,))
conn.commit()
conn.close()
def refresh():
read_db()
... | The main task of the code is to validate and add a new group name in a UI. It checks if the input name already exists in the 'groups' list or is empty, showing appropriate alerts. If valid, it adds the group to the database, resets the input field, hides the window, and refreshes the UI to confirm the addition. | def add_group_ui():
a= dpg.get_value('grpnm')
if a in groups:
popup ('group name already present ')
return
elif a == '' :
popup ('no name entered for group')
return
else:
add_group_todb(a )
dpg.configure_item("addgrp_win", show=False)
dpg.configur... |
def popup(text):
tkinter.messagebox.showinfo('stop!', text )
def Reset_addedit():
# dpg.configure_item("addscrpt_win", show=False)
# if dpg.get_item_label('addscript_ok')[0] =='A':
# return
dpg.configure_item("addscript_ok", label = 'Add' )
dpg.configure_item("scrnm", default_value = '', rea... | This function updates a script entry in an SQLite database with values from GUI inputs, validates non-empty fields, constructs an SQL UPDATE query, executes the query, and refreshes the UI by hiding windows and resetting inputs. | def Edit_ok():
global script_selection_index
scrnm = script_details [script_selection_index ] [0]
b= dpg.get_value('prjfol')
c= dpg.get_value('scrpath')
d= "-" # dpg.get_value('icopath')
util = dpg.get_value('sel_utl')
grp = dpg.get_value('sel_gr')
if '' in [b,c,d, util, grp] :
... |
def Edit_ok():
global script_selection_index
scrnm = script_details [script_selection_index ] [0]
b= dpg.get_value('prjfol')
c= dpg.get_value('scrpath')
d= "-" # dpg.get_value('icopath')
util = dpg.get_value('sel_utl')
grp = dpg.get_value('sel_gr')
if '' in [b,c,d, util, grp] :
... | The function `add_script_ui` validates and adds a new script via UI inputs. It checks if a script name exists, ensures all required fields are filled, and adds the script to the database if valid. If invalid, it shows error messages. On success, it hides the window, resets UI, and refreshes the interface. | def add_script_ui():
if dpg.get_item_label('addscript_ok')[0]=='S':
Edit_ok()
return
a= dpg.get_value('scrnm')
b= dpg.get_value('prjfol')
c= dpg.get_value('scrpath')
d= '-' # dpg.get_value('icopath')
util = dpg.get_value('sel_utl')
grp = dpg.get_value('sel_gr')
if a in s... |
def main(self):
self.coletaFilePaths()
self.coletaArquivosMaisRecentes()
self.coletaTamanhoFile()
def mainCD(self):
self.filesStatus()
self.createFileListPickle()
self.putSQLStatusFiles()
def mainTamanho(self):
for poi, tamanho in self.dic_video_size.i... | The code's main task is to execute either `self.mainCD()` or `self.mainTamanho()` based on the `boolCD` parameter. If `boolCD` is `True`, it runs `self.mainCD()`; otherwise, it runs `self.mainTamanho()`. The method first calls `self.main()` unconditionally, then conditionally executes one of the two main variants depen... | def run(self, boolCD = False):
self.main()
if boolCD:
self.mainCD()
else:
self.mainTamanho() |
def multiplication_karatsuba(x, y, length, radix):
x = x[1:] if get_sign(x) else x
y = y[1:] if get_sign(y) else y
result = karatsuba_recursive(x, y, length, radix)
return result
def extended_euclidean_algorithm(x, y, radix):
a1 = '1'
a2 = '0'
b1 = '0'
b2 = '1'
while (y[:1] != '-... | The code solves arithmetic exercises (integer or modular) specified in a JSON file at `exercise_location`, determines the operation type, computes the result using corresponding functions, and writes the answer to a JSON file at `answer_location`. It handles operations like addition, subtraction, multiplication, and in... | def solve_exercise(exercise_location: str, answer_location: str):
"""
solves an exercise specified in the file located at exercise_location and
writes the answer to a file at answer_location. Note: the file at
answer_location might not exist yet and, hence, might still need to be created.
"""
#... |
def get_sign(a):
return True if a[0] == '-' else False
def anyBaseToDecimal(string, base):
base = int(base)
integer = 0
for character in string:
assert character in radix_dict
value = radix_dict[character]
assert value < base
integer *= base
integer += value
r... | The function `integer_multiplication_naive` multiplies two integers represented as strings in a given base `r`, handling signs and base conversions. It first determines the sign of the result, strips signs from inputs, converts the first number to decimal, and iteratively multiplies it by each digit of the second numbe... | def integer_multiplication_naive(x: str, y: str, r: int):
# m = len(x)+len(y) (x,y without signs)
radix = r
# m + 1 because index 0 is for the sign
rows = []
ans = '-' if (get_sign(x) and not get_sign(y)) or (get_sign(y) and not get_sign(x)) else ''
x = x[1:] if get_sign(x) else x
... |
def extractDF (resultsA):
df = []
for r in range(len(resultsA)):
res = {"AUC":resultsA[r]["AUC"], "Repeat": resultsA[r]["Repeat"]}
res["Resampling"] = str(resultsA[r]["Params"][0]) # same for all
res["Clf_method"] = str(resultsA[r]["Params"][2][0][0])
res["FSel"] = str(resultsA[r... | The main task of the code is to compute and return multiple evaluation tables (AUC, sensitivity, specificity, and feature agreement metrics) from resampled data using various methods (IoU, CCOR, etc.), by loading datasets, processing results, and generating structured outputs for analysis. | def computeTable (d):
from loadData import Arita2018, Carvalho2018, Hosny2018A, Hosny2018B, Hosny2018C
from loadData import Ramella2018, Saha2018, Lu2019, Sasaki2019, Toivonen2019, Keek2020
from loadData import Li2020, Park2020, Song2020, Veeraraghavan2020
data = eval (d+"().getData('./data/')")
da... |
def get_commits(days: int, commit: Optional[str] = None) -> List[Commit]:
if commit is not None:
return [Commit(sha=commit, date=datetime.datetime.now())]
else:
return get_commits_from_last_n_days(days)
def create_downloader() -> Iterable[MetricDownloader]:
with multiprocessing.Pool() as poo... | The main task of the code is to download CI metrics from recent commits, aggregate durations of key build steps (e.g., LLVM, Rustc stages, test runs), and store them in a structured CSV file. It processes metrics from specified jobs, normalizes test suite durations, and ensures consistent data formatting for analysis. | def download_ci_durations(days: int = 30, commit: Optional[str] = None, jobs: Optional[str] = None,
output: Path = "result.csv"):
"""
Downloads the metrics.json files from the last `days` of master merge commits.
Analyzes the metrics and stores durations of interesting bootstrap st... |
def load_config(yaml_config):
yaml_dict = None
config_stream = io.StringIO(yaml_config)
try:
yaml_dict = yaml.load(config_stream, Loader=yaml.FullLoader)
except yaml.YAMLError as ex:
print(ex)
if yaml_dict is None:
return None, None
return yaml_dict['files_and_buckets_a... | (The main task of the code is to manage BigQuery datasets and views based on a YAML configuration. It deletes existing datasets/views if specified, creates new datasets with metadata, and installs predefined views by formatting SQL queries and applying schema definitions. The process ensures dataset updates or initial ... | def main(args):
if len(args) != 2:
print(" ")
print(" Usage : {} <configuration_yaml>".format(args[0]))
return
print('job started')
#
# Get the YAML config loaded:
#
with open(args[1], mode='r') as yaml_file:
params, steps = load_config(yaml_file.read())
... |
def initialize_network(n_inputs, n_hidden, n_outputs):
network = list()
hidden_layer = [{'weights':[random() for i in range(n_inputs + 1)]} for i in range(n_hidden)]
network.append(hidden_layer)
output_layer = [{'weights':[random() for i in range(n_hidden + 1)]} for i in range(n_outputs)]
network.append(output_lay... | The code performs backpropagation training on a neural network using provided training data, then evaluates the trained model on test data. It initializes a network with specified input, hidden, and output layers, trains it over multiple epochs with a given learning rate, saves the trained model to a file, and returns ... | def back_propagation(train, test, l_rate, n_epoch, n_hidden):
n_inputs = len(train[0]) - 1
n_outputs = len(set([row[-1] for row in train]))
network = initialize_network(n_inputs, n_hidden, n_outputs)
train_network(network, train, l_rate, n_epoch, n_outputs)
pickle.dump(network,open("model.pkl","wb"))
predictions ... |
def count(self):
with open(self.file_path, newline='') as csvfile:
reader = csv.DictReader(csvfile)
return len(list(reader))
def find_by_id(self, id):
return self.find_by_key("id", str(id)) | The code retrieves a random item from a collection. If the collection has fewer than two items, it returns the first item. Otherwise, it generates a random ID, fetches the corresponding item, and recursively retries if the item is invalid, ensuring a valid random item is returned. | def random(self):
count = self.count()
if count < 2: return self.find_by_id(1)
id = randrange(1, count)
res = self.find_by_id(id)
if (res is None):
return self.random()
return res |
def one_step_train(self, x,y,epochs=100, debug=False):
for ind in self.solvers:
ind.fit(x,y,epochs=epochs, debug=debug)
def evolve(self, x, y):
self.evalpop(x, y)
#Get fitness
fitness = self.fitness(self.costs)
bestsoln = np.argmax(fitness)
#Selection strate... | This code trains a model using evolutionary algorithms by iteratively training lower-level solvers, evolving objective functions with test data, and tracking the best performance (lowest cost) over generations. It appends the best cost to 'bestperf' and optionally plots training progress and error curves. The process r... | def train(self,xtrain,ytrain,xtest, ytest,iters, subiters=100, debug_2=False, plot=True, plot_curve = False):
#self.evalpop(xtest, ytest)
#self.bestidx = np.argmin(self.costs)
#self.bestperf.append(self.costs[self.bestidx])
for i in range(iters):
#Train lower level solvers
... |
def checkMove(cur_x, cur_y, ncols, nrows, board):
global deadend
deadend = True
for i in range(DIRECTIONS):
new_x = cur_x + move_x[i] # user coordinates 1 - n
new_y = cur_y + move_y[i] # user coordinates 1 - n
if freeSpot(new_x, new_y, ncols, nrows, board):
board[new_... | The code implements a knight's tour game where the user navigates a knight on a grid, moving to unvisited squares. It validates moves, tracks visited positions, and checks for completion or dead ends. The game ends when all squares are visited or no further moves are possible, displaying the result and number of moves ... | def play_game(start_x, start_y, ncols, nrows):
global win, deadend
board = [[-1 for i in range(ncols)] for i in range(nrows)]
board[start_y-1][start_x-1] = "X"
last_x, last_y = start_x, start_y
warns_board = deepcopy(board)
checkMove(start_x, start_y, ncols, nrows, warns_board)
printBoard(nc... |
def onBoard(x, y, ncols, nrows): # user coordinates 1 - n
if x > 0 and y > 0 and x <= ncols and y <= nrows:
return True
return False
def checkMove(cur_x, cur_y, ncols, nrows, board):
move_x = [2, 1, -1, -2, -2, -1, 1, 2]
move_y = [1, 2, 2, 1, -1, -2, -2, -1]
for i in range(DIRECTIONS):
... | The code initializes a chessboard with user-specified dimensions, validates the knight's starting position, marks it on the board, and calculates/prints possible knight moves. It ensures inputs are positive integers and within bounds, then prepares the board for further move analysis. | def main():
while True:
try:
ncols, nrows = map(int, input(
"Enter your board's dimensions: ").split())
if ncols < 1 or nrows < 1:
raise ValueError
except ValueError:
print("Invalid entry!")
continue
else:
... |
def extract_files(directory, pattern):
# Recursively extract files from a directory based on a pattern
for root, dirs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
file_name = os.path.join(root, basename)
yield file_name
def is_audio_format(ext):
# Check if ... | The code processes audio files in a specified directory to detect their cutoff frequency. It uses command-line arguments to configure parameters like search range, accepted frequency, analysis duration, and downsampling. The script identifies audio files, skips non-audio files, and processes each file to analyze its fr... | def main():
global filecount, debug
parser = argparse.ArgumentParser(description="Detect the cutoff frequency of audio files in a given directory.")
parser.add_argument('folder', help='The folder to search for audio files in')
parser.add_argument('--min-search-hz', type=int, default=10000, help='Start the search ... |
def read_wav(filename, startSecond, endSecond):
try:
wf = wave.open(filename, "rb")
nsamps = wf.getnframes()
fs = wf.getframerate()
if nsamps == 0 or fs == 0:
print(f"[E] while getting basic wav data")
sys.exit(1)
startSample = fs * startSecond
endSample = fs * endSecond
samplesToRead = endSample... | The code analyzes an audio file to compute and plot its BPM (beats per minute) over time. It divides the file into segments, calculates BPM for each using a sliding window, filters results within a specified range, and visualizes the BPM values against timestamps. The output is a graph showing BPM fluctuations, with sk... | def plotBpm(filename, num_samples, sample_length, window_size, min_bpm, max_bpm):
fileLength = int(float(subprocess.check_output("ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 '" + filename + "'", shell=True).decode('utf-8').strip()))
sampleRate = read_wav(filename, 0, 1)[1]
... |
def config(self):
"""Get all persistent configuration options as a dict."""
config = {
"executables": {
"paths": [str(path) for path in self.executables],
"user-choice": str(self.executable),
},
"save_dir": str(self.save_dir)
}
... | This code initializes a GUI application for a simulation tool, setting up exception handling, application directories, configuration loading, and UI components like dock widgets for simulation control, properties, and executable selection. It configures menus, central widgets, and initializes default simulation paramet... | def __init__(self):
super().__init__()
# Exception catching
self.__excepthook__ = sys.excepthook
sys.excepthook = self.excepthook
# Application properties =======================================================================================
first_time_setup = ... |
def promptStopSimulation(self) -> bool:
"""Prompt the user to stop the simulation.
If the user declines, return False. If the user accepts, return True.
"""
prompt = QMessageBox()
prompt.setWindowTitle("Stop simulation?")
prompt.setIcon(QMessageBox.Warning)
prompt... | This code handles the close event of a GUI application by checking if a running simulation needs user confirmation to stop, prompting for unsaved changes, cleaning up output directories, saving configuration data, and either ignoring or accepting the close request based on user input and application state. | def closeEvent(self, event):
if self.simulation.running:
if not self.promptStopSimulation():
event.ignore()
return
# Teminate and process events so onSimulationFinished cleans up
self.simulation.terminate()
QApplication.instance().... |
def gen_circle_obj(min_r,max_r,im_h,im_w,PAD):
r = np.random.randint(min_r,max_r)
# r = 50
cx,cy = np.random.randint(r,im_w-r), np.random.randint(r,im_h-r)
bbox = np.array([cx-r-PAD,cy-r-PAD,cx+r+PAD,cy+r+PAD])
bbox[0] = np.clip(bbox[0],0,im_w)
bbox[1] = np.clip(bbox[1],0,im_h)
bbox[2] = np.... | The code generates a synthetic COCO-format dataset containing images with non-overlapping circles and rectangles. It creates images with random shapes, computes bounding boxes, areas, and annotations, ensuring no object overlaps via IoU checks. Annotations include category IDs, bounding boxes, and metadata, while image... | def gen_dataset(self):
images = []
annotations = []
ann_id_counter = 1 # annotation id needs to start with 1
categories = [{'id': 0, 'name': 'circle'},{'id': 1, 'name': 'rectangle'}]
# categories = [{'id': 0, 'name': 'circle'}]
for image_id in range(1,self.N_IMAGES+1):
... |
def walk_files_directory(entrypoint = None):
if entrypoint is None:
entrypoint = os.getcwd()
file_ext = ".xml"
file_lst = []
with os.scandir(entrypoint) as dirs:
for direc in dirs:
file_lst.extend(find_file(direc, file_ext))
if direc.is_dir():
file... | The code retrieves URLs from files in a directory, downloads data from these URLs, sanitizes the content, and aggregates it into a context. It processes up to 100 files, collects valid URLs, fetches their content, cleans the data, and compiles it into a structured context for further use. | def pull_down_data(data_root):
files = walk_files_directory(data_root)
print(len(files))
urls = []
for x in range(100):
url = find_url(files[x])
if url:
urls.append(url)
data = []
for url in urls:
proj_gut = requests.get(url, stream=True)
data.extend(s... |
def pi_initialise(self):
self.vi_initialise()
self.arrStates = list(self.exploredStates.keys()) # states
numOfStates = len(self.exploredStates)
numOfActions = len(ROBOT_ACTIONS)
self.probabilities = np.zeros([numOfStates, numOfActions, numOfStates]) # t_model
self.reward... | The main task of the code is to implement Policy Iteration for offline planning. It initializes the policy and iteratively improves it until convergence, using `pi_initialise()` and repeated `pi_iteration()` calls within a loop that checks for convergence via `pi_is_converged()`. This method adheres to compatibility co... | def pi_plan_offline(self):
"""
Plan using Policy Iteration.
"""
# !!! In order to ensure compatibility with tester, you should not modify this method !!!
self.pi_initialise()
while not self.pi_is_converged():
self.pi_iteration() |
def pi_initialise(self):
"""
Initialise any variables required before the start of Policy Iteration.
"""
start = time.time()
self.USE_LIN_ALG = True
self.converged = False
self.t_model = np.zeros(
[len(self.states), len(ROBOT_ACTIONS), len(self.state... | The main task of the code is to perform policy iteration for planning in a reinforcement learning context. It initializes the policy and iteratively updates it until convergence, ensuring compatibility with external testing components without modification. | def pi_plan_offline(self):
"""
Plan using Policy Iteration.
"""
# !!! In order to ensure compatibility with tester, you should not modify this method !!!
self.pi_initialise()
while not self.pi_is_converged():
self.pi_iteration() |
def fed_estimate_proj_param(folder):
assert os.path.exists(folder), "Data folder not found!"
files = glob.glob(f"{folder}/client_*")
files = sorted(files)
#print("files = ", files)
assert len(files)>0, "Empty data folder found!"
param_list = None
weight_list = None
for file in fi... | This code initializes a federated learning system by setting up parameters, estimating projection values, loading client data, creating data loaders, and instantiating a central server along with multiple clients. It configures neural network architectures, optimizers, and prepares validation/test datasets for distribu... | def __init__(self, folder, x_dim, layers=[64], c=1.0, alpha_proj=1.0, decay=1e-4, n_batch=32, mp=False, ifgpu=True):
self.x_dim = x_dim
self.layers = layers
self.c = c
self.alpha_proj = alpha_proj
self.n_batch = n_batch
self.mp = mp
self.ifgpu = ifgpu
... |
def phaseOne(self):
self.phase = 1
discovered = self.discoveredInit.copy()
# Run dfs on the reverse graph until all nodes have been inserted into the topological ordering
nextNode = 0
while len(self.topological) < self.nodesCount:
self.dfs(nextNode,discovered,self.reverseGraph)
remaining = list(set(ra... | The code reads input for a directed graph's vertices and edges, constructs adjacency lists and their reverse, applies Kosaraju's algorithm to identify strongly connected components (SCCs), and outputs the number and members of each SCC. It validates inputs and handles errors during edge input. | def __init__(self):
# Accept input for the number of vertices and number of edges from stdin
while self.nodesCount < 0:
numNodes = input('Please input the number of vertices: ')
try:
self.nodesCount = int(numNodes)
except BaseException:
print("Input was an invalid format. Please try again.")
... |
def chooseCalculationMode() -> CalculationMode:
mode = ''
while not mode:
mode_user_input = input("Choose a testing mode: (a)ddition or (m)ultiplication: ")
mode = CalculationMode.getCalculationMode(mode_user_input)
return mode
def getFileName():
return 'results/results.txt'
def startGam... | The code's main task is to initialize and run a game by selecting a calculation mode, retrieving a filename, creating game settings with these parameters and a fixed value (12), then launching the game with those settings. | def runGame():
calculationMode = chooseCalculationMode()
filename = getFileName()
gameSettings = GameSettings(calculationMode, filename, 12)
startGame(gameSettings) |
def features_creation():
global features
global total
general(initial([['-','-','-'],['-','-','-'],['-','-','-']]))
special(total)
for i in range(0,len(total)):
features.append(feature(total[i][0],total[i][1],total[i][2]))
def random_game_sequence(board,ftoplay,game):
play1='x'
play2... | The main task of the code is to generate an evaluation function for a board game by analyzing feature stability and correlation with simulated outcomes. It performs 100 random game sequences, computes feature scores, calculates stability (via variance and average score) and correlation with rollout results, then combin... | def EvalFuncGenerator(board,ftoplay,game):
global features
global total
global svhelper
global EvaluationFunction
Evaluation_Function={}
evalfunctiontemp={}
evaltemp=""
rollresults=[]
avgrollresperseq=[]
rolltemp=0
tempcorel1=0
tempcorel2=0
tempcorel3=0
otemp=0
... |
def epsilon_greedy(self, state, epsilon=None): # modify
if epsilon is None: epsilon = self.epsilon
# with probability epsilon we explore
# otherwise we go greedy
if random.random() < epsilon:
action = self.env.action_space.sample()
else:
action =... | The code trains a reinforcement learning agent over multiple episodes by interacting with an environment, updating the agent's policy using epsilon-greedy exploration and eligibility traces, and periodically evaluating performance while adjusting learning rate (alpha) and exploration rate (epsilon). | def train(self, n_episodes=200, max_steps_per_episode=200): # do not touch
for episode in range(n_episodes):
done = False
s, _ = self.env.reset()
self.traces = np.zeros(self.shape)
for i in range(max_steps_per_episode):
action = se... |
def bootstrap_mean( A , Nbootstrap ):
if Nbootstrap == 0: # bootstrapping is off
SM = np.nanmean(A,axis=0)
SD = 0.
return SM,SD
else: # bootstrapping is on
# 95% confidence intervals from bootstrapping
# A = [samples,features], average bootstrap over samples
if np... | The main task of the code is to compute M-scores and related metrics for cluster features, either using preassigned balances or calculating them dynamically. It processes input cluster labels, raw features, and area weights, applying bootstrap methods to estimate feature means and M-scores. Results are stored in the in... | def get_scores( input , preassigned_balance_flag ):
# find the M score for the input cluster features, either the best fit M
# score and accompanying balances, or the M score for preassigned balances.
# FIX 2/21: MAKE BOTH preassigned and unpreassigned data processed by the same function <-----------------... |
def remove_nans_infs( feature ):
# features is 1d
nan_locs = np.array([],dtype=int) # locations of infs or nans
if np.sum(np.isinf(feature)) > 0:
#print('here1')
#print('np.sum(np.isinf(feature)) = ',np.sum(np.isinf(feature)))
nan_locs = np.append(nan_locs , np.argwhere(np.isnan(feat... | The main task of the code is to load and process oceanographic features (curlCori, BPT, curlTau, curlA, curlB) from files, handle NaNs/inf values, compute a residual term, standardize features if requested, and compile them into a structured data object with spatial coordinates, area weights, and metadata for analysis ... | def get_ECCO_features( file_path, standardize_flag, residual_flag, verbose ):
# grid:
import scipy.io
grid = scipy.io.loadmat(file_path + 'gridVars.mat')
land = grid['land'][:]
#area = grid['vortCellArea'][:] #().flatten('F')
#area = area/np.nansum(np.nansum(area))
area = grid['vortCellArea... |
def combine_clusters( full_labels, full_balance, recursive_labels, recursive_balance, locs ):
# full_ = the full domain results
# recursive_ = the results for re-clustering a particular cluster
# locs = the locations within the full domain of the recursive cluster
nc_full = len(np.unique(full_labels))
... | The code combines two processed datasets (full and recursive) by merging their cluster labels and balance matrices, refines the merged data to group similar sparsity patterns, computes scores and statistical metrics, and prepares the result for visualization with markers/colors, returning a structured data object conta... | def combine_processed_data( data_dicts ):
# combine two sets of processed data for a given
full_data = data_dicts[0]
recursive_data = data_dicts[1]
full_labels = full_data.labels
full_balance = full_data.balance
full_features = full_data.features
recursive_labels = recursive_data.labels
... |
def get_tumor_dynamics_features( path, standardize_flag, data_set_name ):
filename_features = path + 'features.npy'
raw_features = np.load(filename_features)
# standardize:
if standardize_flag == 'on':
features = np.zeros(np.shape(raw_features))
for i in range(0,raw_features.shape[1]):... | The main task of the code is to retrieve and process feature data from specified datasets (e.g., tumor dynamics, boundary layers, ECCO, Stokes) based on the input parameters. It selects the appropriate data-processing function depending on the dataset name, applies standardization/residual calculations where needed, an... | def get_feature_data( path, data_set_name, standardize_flag, residual_flag, verbose ):
# create data.raw_area ? For HDBSCAN...
if data_set_name == 'tumor_dynamics' or data_set_name == 'tumor_angiogenesis':
data = get_tumor_dynamics_features( path, standardize_flag, data_set_name )
elif data_set_n... |
def get_ECCO_features( file_path, standardize_flag, residual_flag, verbose ):
# grid:
import scipy.io
grid = scipy.io.loadmat(file_path + 'gridVars.mat')
land = grid['land'][:]
#area = grid['vortCellArea'][:] #().flatten('F')
#area = area/np.nansum(np.nansum(area))
area = grid['vortCellArea... | The code combines clusters in spatio-temporal data by merging those with area weights below a specified threshold. It updates cluster labels, adjusts balance weights, and modifies data attributes like cluster count and refined balances. The process ensures smaller clusters are consolidated, maintaining statistical prop... | def combine_by_area_threshold( data ):
# the threshold is for combining all clusters that cover an area that is
# less percent of the total spatio-temporal area.
threshold = data.threshold
#threshold = 0.05
combined_labels = np.zeros([data.nc])*np.nan
for j in range(0,data.nc):
if data.... |
def get_scores( input , preassigned_balance_flag ):
# find the M score for the input cluster features, either the best fit M
# score and accompanying balances, or the M score for preassigned balances.
# FIX 2/21: MAKE BOTH preassigned and unpreassigned data processed by the same function <-----------------... | The function computes cluster balances using either 'score' or 'SPCA' methods, normalizing features for SPCA. It deprecates feature removal by trimming unused features if enabled, reclustering data, and reassigning balances. However, this feature removal is marked as deprecated. The primary task is to calculate optimal... | def remove_unused_features( input ):
# should be called get_balances
nf = input.nf # number of features
# assign balances
if input.reduction_method == 'score':
input.refine_flag = False # score the clustered data (not refined data)
input = get_scores( input , preassigned_balance_flag =... |
def read_processed_data( data, feature_path, data_set_name ):
residual_flag = data.residual_flag
read_path = data.read_path
cluster_method = data.cluster_method
reduction_method = data.reduction_method
standardize_flag = data.standardize_flag
NE = int(data.NE)
feature_data = get_feature_da... | This function processes convergence and optimal clustering results from input data, saving key parameters (scores, closures, cluster configurations, feature statistics) as NumPy files. It handles biased/unbiased data, different clustering methods (KMeans, GMM, HDBSCAN), and dimensionality reduction (SPCA), storing conv... | def get_convergence_and_optimal( data, write_path, feature_path, data_set_name ):
# 1) convergence data (meta-data for all parameters, realizations)
data = read_processed_data( data, feature_path, data_set_name )
# 2) save convergence:
np.save(write_path + 'conv_mean_score.npy', data.mean_score)
n... |
def get_alarm_detail(message):
alarm_name = message['AlarmName']
alarms = cloudwatch.describe_alarms(AlarmNames=[alarm_name])
logger.info('describe_alarms: %s', alarms)
if len(alarms['MetricAlarms']) <= 0:
raise UnexpectedMessageException(f'Not a metric alarm: alarm={alarm_name}')
alarm = a... | The main task of the code is to handle AWS CloudWatch Alarm notifications. When an alarm state transitions to "ALARM", it extracts alarm details, sends notifications, and searches logs. If the state is not "ALARM", it logs a debug message. The function processes SNS messages triggered by CloudWatch alarms to enable ale... | def lambda_handler(event, context):
logger.info('Event: %s', event)
message = json.loads(event['Records'][0]['Sns']['Message'])
if message['NewStateValue'] == 'ALARM':
try:
alarm_detail = get_alarm_detail(message)
except UnexpectedMessageException:
logger.warn('Unexp... |
def set_start_and_end(start_point, end_point):
if start_point is not None:
while True: # Keep asking until a valid input is received
change_point = input("What would you like to change? You can enter 'o' for 'origin', 'd' for 'destination', or 'b' for 'both': ")
if change_point == '... | The main task of the code is to determine and display the shortest metro route between two specified points, handling cases where no route exists or maintenance blocks the path. It validates inputs, formats the route instructions, and allows users to request additional routes iteratively. | def new_route(start_point=None, end_point=None):
start_point, end_point = set_start_and_end(start_point, end_point)
if start_point is None or end_point is None:
print("Invalid start or end point.")
return
shortest_route = get_route(start_point, end_point)
if shortest_route is None:
... |
def greet():
global landmark_string
landmark_string = create_landmark_string(landmark_choices)
print("Hi there and welcome to SkyRoute!")
print("We'll help you find the shortest route between the following Vancouver landmarks:")
print(landmark_string)
def new_route(start_point=None, end_point=None):... | The code defines a function `skyroute()` that sequentially executes three tasks: greeting the user, generating a new route, and concluding with a farewell. Its main purpose is to orchestrate a process involving initialization, route creation, and termination, likely for navigation or planning systems. | def skyroute():
greet()
new_route()
goodbye() |
def getvocab(link = 'nil', data = 'nil', from_data = True):
if from_data:
visible_text = data
else:
soup = bs(link)
# visible_text = soup.getText()
visible_text = (" ").join([i.text for i in soup.findAll('p')] + [i.text for i in soup.findAll('li')])
text = re.sub('[... | The function generates a word cloud image from input text when `nclick` is True, using frequencies to determine word size and position. It returns the base64-encoded image and a sorted frequency list. If `nclick` is False, it returns default placeholder data. | def get_word_cloud(nclick, input_text):
if nclick:
plt.rcParams["font.family"] = "serif"
plt.rcParams['figure.dpi'] = 200
vocab, num = getvocab(data=input_text, from_data=True)
data_vocab = get_data(vocab, num)
initial_x = 0.00
initial_y = 0.90
y_step_down = 0... |
def urlParser(url):
protocol = url.split("://")[0]
urldict = {
"protocol" : protocol,
"hostname" : url.strip(protocol+"://").split("/")[0],
"params" : [{ x.split("=")[0] : x.split("=")[1]} for x in url.split("?")[1].split("&")]
}
return urldict
def request_headers():
headers = {"User-Agent" : r... | The code retrieves and decrypts an encrypted M3U8 streaming URL. It parses the input URL, generates encrypted parameters, sends a request to an AJAX endpoint, decrypts the response JSON, and returns the parsed data. The function handles URL parsing, encryption, HTTP requests, and decryption to fetch streaming content d... | def getM3U8url(vodstreamingUrl):
urldict = urlParser(vodstreamingUrl)
USER_AGENT = request_headers()["User-Agent"]
encrypted_params = generate_encrypted_parameters(vodstreamingUrl)
request_url = f"{urldict['protocol']}://{urldict['hostname']}/encrypt-ajax.php?{encrypted_params}"
headers = {"User-Agent" : USER... |
def CreateTextbox(parentWid, iWidth, textString, justify):
lineCount = int(math.ceil(len(textString)/iWidth))
newtextbox = Text(parentWid, height = lineCount, width=iWidth - 30, wrap = WORD, bd =0, padx = 15)
newtextbox.tag_configure("tag_name", justify=justify)
newtextbox.insert(INSERT, textString)
... | The code ranks documents in a corpus based on cosine similarity with a query using three TF-IDF variants (normal, logarithmic, augmented). It clears the UI, loads JSON data, combines titles/abstracts, computes TF-IDF vectors, calculates similarity scores, and displays top 10 results per method in a grid layout with tit... | def rank_corpus(fileName, query, modelframe):
for widget in modelframe.winfo_children():
widget.destroy()
#Open json file
f = open(fileName, 'r', encoding="utf8")
data = json.load(f)
data_after_join = []
#Get all total text for eact document
for index, item in enumerate(da... |
def CreateTextbox(parentWid, iWidth, textString, justify):
lineCount = int(math.ceil(len(textString)/iWidth))
newtextbox = Text(parentWid, height = lineCount, width=iWidth - 30, wrap = WORD, bd =0, padx = 15)
newtextbox.tag_configure("tag_name", justify=justify)
newtextbox.insert(INSERT, textString)
... | The code processes multiple JSON datasets containing biomedical documents, computes TF-IDF vectors using three variants (normal, logarithmic, augmented), calculates cosine similarity between a user query and documents, then displays the top 10 most similar documents with titles/abstracts in a GUI grid, clearing previou... | def All(query, modelframe):
for widget in modelframe.winfo_children():
widget.destroy()
#Open json file
all_path = [r"D:\NCKU\Biomedical Information Retrieval\Homework\HW4\Data\Pubmed_LungCancer.json",
r"D:\NCKU\Biomedical Information Retrieval\Homework\HW4\Data\Pubmed_BrainCancer.json",
... |
def map_data(new_file):
assert not os.path.exists(new_file), "New file must not exist"
old_file = Config.metadata_file
old_conn = sqlite3.connect(old_file)
old_cursor = old_conn.cursor()
old_table = MetadataModule.Metadata(old_cursor)
old_data = old_table.get('*')
old_cursor.close()
old... | The main task of the code is to handle three command-line operations: mapping data, checking duplicates, or updating thumbnails. It processes arguments to execute one task at a time, ensuring mutually exclusive flags (e.g., --map-data vs. --paths). If --map-data is specified, it runs `map_data()`. If --duplicate-check ... | def main(args):
if args.map_data:
assert not args.paths, "Can't specify upload file paths with --map-data"
map_data(args.map_data)
return
if args.duplicate_check:
assert not args.paths
duplicate_check()
return
if args.update_thumbnails:
fnames = [os.... |
def f_force_nms_cpu(frozen_graph):
for node in frozen_graph.node:
if 'NonMaxSuppression' in node.name:
node.device = '/device:CPU:0'
return frozen_graph
def f_replace_relu6(frozen_graph):
return convert_relu6(frozen_graph)
def f_remove_assert(frozen_graph):
remove_op(frozen_graph, 'A... | This function builds a frozen detection graph from a pre-trained object detection model by parsing configuration files, modifying model parameters (e.g., NMS thresholds, input shape), exporting an inference graph, applying optimizations (CPU NMS, ReLU6 replacement, assert removal), and returning the modified frozen gra... | def build_detection_graph(config, checkpoint,
batch_size=1,
score_threshold=None,
iou_threshold=None,
force_nms_cpu=True,
replace_relu6=True,
remove_assert=True,
input_shape=None,
output_dir='.generated_model'):
"""Builds a frozen graph for a pre-train... |
def send_kill_signal(self):
self.update_clients()
for conn, address in self.accepted:
conn.send(b"exit")
def kill_threads(self): # kills the jobs in order to quit
while not self.threads.empty():
self.threads.get()
self.threads.task_done()
def update_clients(s... | This function provides a command-line interface for a reverse shell, allowing users to list active connections, connect to specific clients, send/receive files, or exit. It processes user inputs like 'help', 'list', 'exit', and client numbers to manage communication, handle file operations, and terminate sessions. | def __ui(self):
print("Reverse shell by dbc201")
print("Type help for further info")
while True:
connect = input("->").strip()
if connect.lower() == "exit":
self.send_kill_signal()
self.kill_threads()
self.sock.close()
... |
def movement(self):
# check which keys are pressed
keys = pygame.key.get_pressed()
# changes player angle
if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
self.angle += player_rotation_speed * self.delta_time
if keys[pygame.K_LEFT] or keys[pygame.K_a]:
self.an... | This function updates the game state by calculating time delta, handling movement, checking fruit interactions, creating a trail, and returning updated fruit data. | def update(self, fruits):
self.delta_time = (pygame.time.get_ticks() - self.prev_tics)
self.prev_tics = pygame.time.get_ticks()
self.movement()
fruits = self.check_for_fruit(fruits)
self.make_trail()
return fruits |
def update_window(self):
self.window.fill(pg.Color(self.rgb[0], self.rgb[1], self.rgb[2]))
if self.food.is_eaten(self.snake.head):
self.food.update_food_pos(self.window, self.snake.get_snake_coordinates())
self.snake.add_body()
self.score += 1
self.food.draw_f... | This code implements a Q-learning agent for a snake game. The main task is to run the game loop, update the snake's state based on collisions and food proximity, determine actions (random or optimal), calculate rewards, update the Q-table, and manage game reset upon collision. It uses Pygame for rendering and matplotli... | def play_game(self):
self.food.update_food_pos(self.window, self.snake.get_snake_coordinates())
figure, ax = plt.subplots(figsize = (4,5))
plt.ion()
# reward_plot, = ax.plot(self.episode_rewards)
while True:
if not self.snake.check_collision(self.window):
... |
def velocity_rf_line(lambda_0, lambda_1, vel):
"""get the relative velocity of a feature assuming another line
Parameters
----------
lambda_0 : float
wavelength of the original line [angstrom]
lambda_1 : float
wavelength of the new line [angstrom]
vel : float
the velocit... | The function `ln_prob` computes the log-posterior probability by combining a prior and likelihood. It calculates the prior using `lnprior()` with parameters like velocity range, variance limits, and flux constraints. The likelihood, derived from `lnlike_gaussian_abs()`, models the observed flux data with Gaussian noise... | def ln_prob(
theta,
rel_strength,
lambda_0,
blue_vel,
red_vel,
vel_rf,
norm_flux,
lines=[],
vel_flat=[-1e5, 0],
var_max=1e8,
mu_prior=[],
var_prior=[],
norm_flux_unc=1,
blue_fl=[1, 0.1],
red_fl=[1, 0.1],
free_rel_strength=[],
):
"""log-posterior probab... |
def neg_lnlike_gaussian_abs(
theta,
rel_strength,
lambda_0,
blue_vel,
red_vel,
vel_rf,
norm_flux,
lines=[],
flux_unc=1,
type="gaussian",
free_rel_strength=[],
):
"""negative log-likelihood function"""
lnl = lnlike_gaussian_abs(
theta,
rel_strength,
... | The function `MCMC_emcee_sampler` performs Bayesian parameter estimation using the `emcee` MCMC sampler. It samples posterior distributions for velocity, line profile parameters, and relative strengths, incorporating user-defined priors and likelihoods. The code initializes walkers, runs chains with convergence checks,... | def MCMC_emcee_sampler(
self,
mu_prior=[],
var_prior=[],
vel_flat=[-1e5, 0],
var_max=1e8,
nwalkers=100,
max_nsteps=50000,
nburn=-1,
thin=-1,
initial=[],
normalize_unc="None",
plot_model=True,
plot_mcmc=False,
... |
def genre_present(genre_list, genre_name):
# Looks for genre in the current genre_list. If not found, returns -1.
return genre_list.get(genre_name) is not None
def update_heap(heap, genre_list, element):
pos = genre_list[element['genre']]
# Adds new data to existing genre data.
heap[pos]['score'] +=... | The main task of the code is to either update or add a genre entry in a heap structure within a school dictionary based on whether the genre of the given element already exists in the genre list. If the genre is present, it updates the heap; otherwise, it adds the new genre. The function maintains the heap's integrity ... | def edit_heap(school_dictionary, element):
genre_list = school_dictionary['genre_positions']
heap = school_dictionary['genre_heap']
if genre_present(genre_list, element['genre']):
update_heap(heap, genre_list, element)
else:
add_genre(heap, genre_list, element) |
def share_volume(self):
try:
sv=round((self.value-self.inv_txn_charge())/self.share_bp,-2)
return sv
except ZeroDivisionError as zde:
print('Share purchase price should be greater than: Zero-O',zde)
def inv_rtn_charge(self):
if 1000<=self.sell_value()<100000:
... | The code calculates the expected return on investment (ROI) by determining the net return from selling shares, adjusting for investment charges, purchase residuals, and initial value, then rounding the result. It handles potential ZeroDivisionErrors by alerting users if share purchase price calculations involve divisio... | def expected_ROI(self):
try:
sell_value=self.share_volume()*self.share_sp
net_return= sell_value-self.inv_rtn_charge()
return round(net_return+self.purchase_residual()-self.value,0)
except ZeroDivisionError as zde:
print('Share purchase price should be gre... |
def prediction(features, weights, bias):
return softmax(np.dot(features, weights) + bias)
def error_formula(y, y_hat):
return -y * np.log(y_hat) - (1 - y) * np.log(1 - y_hat)
def update_weights(x, y, weights, bias, learning_rate):
y_hat = prediction(x, weights, bias)
error = y - y_hat
weights += lea... | This code trains a neural network using gradient descent by iterating over epochs, updating weights and bias based on prediction errors, tracking loss and accuracy, and optionally plotting decision boundaries and error trends. | def train(features, targets, epochs, learnrate, graph_lines=False):
errors = []
n_records, n_features = features.shape
last_loss = None
weights = np.random.normal(scale=1 / n_features**.5, size=n_features)
bias = 0
for e in range(epochs):
del_w = np.zeros(weights.shape)
for x, y... |
def writeToLog(input):
"""
write to logfile
"""
if logfileOn:
f = open(logfileName, "a")
f.write(input)
f.close()
def getBlockHeight():
"""
Get blockchain height at this time
"""
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy... | The function `writePeers()` logs details about known peers in a blockchain network. It checks if current peers match previously recorded ones; if not, it updates logs with node-specific peer lists, counts total peers, identifies duplicates, and tracks unique IP addresses. It records timestamps, block heights, and summa... | def writePeers():
"""
Write all peers known to the log file
"""
try:
global prevPeers, writeCounter
if sorted(prevPeers.values()) == sorted(nodePeers.values()): ### For sure the last known one was the same as this current -> dont write
writeToLog(f">No change as of... |
def writeToLog(input):
"""
write to logfile
"""
if logfileOn:
f = open(logfileName, "a")
f.write(input)
f.close()
def getBlockHeight():
"""
Get blockchain height at this time
"""
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy... | (The function `silenceAllNodes` sends a custom RPC command (`silentmode true`) to all nodes in `threadNames` using multithreading, ensuring each node is silenced. It logs failures and sends alerts if any node silencing fails, while handling exceptions to log errors. This is a non-standard Zcash operation specific to Pr... | def silenceAllNodes():
"""
send the slientmode true command to all nodes (NOTE: custom rpc command, not part of standard zcashd, is included in the zcashd of Pranav's observatory nodes)
"""
try:
thread_list = []
results = {} ### ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.