dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def check_fireball(self, obj):
if config.fireball is 1:
self.dfs(obj, self.x, self.y)
def dfs(self, obj, a, b):
if(a<2 or b<2 or b>73):
return
if(obj.Matrix2[a][b]==1):
return
if((obj.Matrix[a][b]==(Fore.RED + "X")) or (obj.Matrix[a][b]==(Fore.RED + "Y"))):
logging.warning("reached red area dont d... | The function checks ball collisions with walls, paddle, and bricks in a game. It reverses ball direction on wall hits, handles paddle interactions to adjust bounce angles, destroys bricks, updates score/lives, spawns powerups, and triggers game events like UFO damage or win conditions. It also manages ball deletion whe... | def ball_collision_check(self, obj, obj1, obj2):
if(self.x < 3):
self.vx = (-1) * (self.vx)
if(self.y < 3 or self.y > 72):
self.vy = -1 * self.vy
if(self.x > 30):
logging.info('initial balls before reduction %d ', config.no_of_balls)
logging.debug("ball crossed reducing no of ball by 1")
config.n... |
def setup_board(self):
players_num = self.get_num_players()
if players_num == 2:
self.board.add_player(Player('Player 1', 'red'))
self.board.add_player(Player('Player 2', 'green'))
elif players_num == 3:
self.board.add_player(Player('Player 1', 'red'))
... | The main task of the code is to run a game loop that initializes the game board, processes user inputs (like quitting or pressing keys), updates game state (e.g., dice rolls and player turns), and continuously renders the game elements (pieces, dice, background) on the screen at a controlled frame rate until the game e... | def run_game(self):
self.setup_board()
while self.running:
self.clock.tick(self.tick)
self.screen.fill((0, 0, 0))
self.screen.blit(self.background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
... |
def threads_to_mail_set(threads):
for value in threads:
if isinstance(value, list):
for sub_value in threads_to_mail_set(value):
yield sub_value
else:
yield value
def fetch_mails_info(imap_account, mail_set=None, decode=True, limit=None):
"""Retrieve infor... | The main task of the code is to generate an indented string representation of email threads using an IMAP account, recursively processing nested threads and formatting mail information with specified indentation levels. It fetches mail metadata if not provided, then yields formatted strings for each message in the hier... | def display_mail_tree(imap_account, threads, mail_info_by_uid=None, depth=0,
format_thread=None):
"""Generate indented string representing threads.
.. versionadded:: 0.5
:param imap_account: imaplib.IMAP4 or imaplib.IMAP4_SSL instance
:param threads: List containing other list or... |
def create_search_criterion(address=None, date=None, size=None, subject=None,
tags=None, text=None, operator='AND'):
"""Create a list for all search criterion
Wrapper helping developer to construct a list of search criterion with
a single method.
.. versionadded:: 0.2
... | The main task of the code is to retrieve and display emails from an IMAP server based on user-specified criteria (date, subject, tags, etc.), either as individual messages or threads. It uses configuration files for connection and display settings, processes command-line arguments, formats results dynamically, and outp... | def main():
args = docopt.docopt('\n'.join(usage.split('\n')), version=const.VERSION)
logging.basicConfig(
level=logging.DEBUG if args['--verbose'] else logging.INFO,
stream=sys.stdout,
)
connect_conf = config.new_context_from_file(args['--config-file'],
... |
def process_multi_field_query(query):
words = query.split(' ')
local_dict = {}
for i in words:
if ':' in i:
tag, w = i.split(':')
local_dict[tag] = [w.casefold().strip()]
else:
local_dict[tag].append(i.casefold())
return local_dict
def process_field_query(tag, words):
ex = re.compile... | The main task of the code is to process multiple search queries, handling both multi-field and normal queries. It splits each query into a number and a query string, checks for field-specific prefixes, processes them using dedicated functions, retrieves top-k documents, and records execution time and time-per-document ... | def search_queries():
global outputs, queries
li = ['t:', 'i:', 'b:', 'c:', 'l:', 'r:']
for q in queries:
# outputs.append(q)
num,qu = q.split(',',1)
num = int(num)
qu = qu.strip()
start = timeit.default_timer()
## check for field query
if any(val in qu for val in li):
... |
def generate_grid(self):
grid = np.ones((self.size, self.size), dtype=int) # Open grid
start, goal = self._initialize_start_target(grid)
# Add obstacles, ensuring there is a path from start to goal
obstacles_to_add = random.randint(1, self.size * self.size // 4)
while obstacles... | The main task of the code is to reset the environment's state by regenerating the grid, agent, and target positions, obtaining observations and info, rendering if needed, and returning the observation and info for the next episode. | def reset(self, seed=None, options=None):
# We need the following line to seed self.np_random
super().reset(seed=seed)
# Regenerate the grid and the start/goal locations
self._grid, self._agent_location, self._target_location = self.generate_grid()
observation = self._get_obs()... |
def pe_from_pg(self, t, pg, get_fe = False):
dif = 1.1
pe = self.init_pe_from_pg(t, pg) # Init Pe assuming only H and increase it 10%
ope = pe
it = 0
while((abs(dif) > self.prec) and (it < 250)):
pe = (ope + pe)*0.5
ope = pe
pe,... | The function computes gas pressure (pgas) from density (rho) and temperature (temp) using iterative adjustments. It calculates initial parameters, iteratively refines pressure (Pe) and density (irho) until convergence, then derives final pgas from the adjusted Pe. The process involves temperature-dependent coefficients... | def pg_from_rho(self, temp, rho):
xna = (rho / self.avw)
if(temp > 8000): a = 0.5;
elif(temp > 4000): a = 0.1;
elif(temp > 2000): a = 0.01;
else: a = 0.001;
xne = a * xna /(1.0 - a)
pgas = (xna+xne)*self.BK*temp
Pe = self.pe_fro... |
def forward(self, x_input, activation = 'relu'):
with tf.variable_scope('input', reuse=tf.AUTO_REUSE):
input_standardized = per_image_standardization(x_input)
x = self._conv('init_conv', input_standardized, 3, 3, 16, self._stride_arr(1))
strides = [1, 2, 2]
activate_befo... | The code builds a neural network model for training/evaluation, computes cross-entropy loss, accuracy, and gradients. It implements Integrated Gradients (IG) attribution methods, calculates regularization terms using KL divergence and attribute shifts, and combines them with loss for outer minimization. The model also ... | def _build_model(self, m, lamb, approx_factor, create_saliency_op):
assert self.mode == 'train' or self.mode == 'eval'
"""Build the core model within the graph."""
with tf.variable_scope('input'):
self.input = tf.placeholder(
tf.float32,
shape=[None, ... |
def max_info_gain(self, df, target, givens=None):
"""find the most info gained from a list of cols"""
if givens is not None:
for col, value in givens:
df = df[df[col] == value]
df = df.drop(columns=[col])
info_gains = [(self.info_gain(df, column, targe... | This function recursively builds a decision tree by splitting the dataset based on information gain. For each unique value of the parent node's feature, it filters the data, determines the best feature to split next, and creates new nodes. If no further splits are possible, it adds a leaf node with conditional probabil... | def _recursive_fit(self, df, target, parent_node):
"""Call from fit using a head node in order to keep adding more nodes to
the tree"""
s = df[parent_node.name].unique()
for i in s:
new_df = df[df[parent_node.name] == i].drop(columns=parent_node.name)
gain_name = ... |
def init(self):
for i, j in self.rho:
self.vel[i, j][0] = 0.0
self.vel[i, j][1] = 0.0
self.rho[i, j] = 1.0
self.mask[i, j] = 0.0
for k in ti.static(range(9)):
vel = self.vel[i, j]
rho = 1.0
self.f_upd[i, ... | This code implements a parallel LBM (Lattice Boltzmann Method) solver for fluid dynamics simulations using MPI. It performs collision-streaming steps, boundary condition application, and macroscopic variable updates across distributed processes. The rank-0 process visualizes vorticity and velocity fields via a GUI, dis... | def solve(self):
if self.mpi_rank == 0:
gui = ti.GUI('lbm solver', (self.nx + 2, 2 * self.ny))
self.init()
st = time.perf_counter()
for i in range(self.steps):
reqs = self.mpi_commit_border_transfer()
self.collide_and_stream_bulk()
self.mpi... |
def fillDiagonal(self):
for i in range(0, self.N, 3):
self.fillBox(i, i)
def fillRemaining(self, i, j):
# Check if we have reached the end of the gridrix
if i == self.N - 1 and j == self.N:
return True
# Move to the next row if we have reached the end of the curr... | The code generates a Sudoku puzzle by first filling the diagonal elements of a matrix, then populating the remaining blocks, and finally removing a specified number of digits to create an incomplete game grid. | def fillValues(self):
# Fill the diagonal of SRN x SRN matrices
self.fillDiagonal()
# Fill remaining blocks
self.fillRemaining(0, 3)
# Remove Randomly K digits to make game
self.removeKDigits() |
def Deciding_Between_Getting_All_Data_Or_Only_Getting_Some():
print("-----------------------------------")
print("1.All Data")
print("2.Filter out data via conditionns")
print("-----------------------------------")
Answer = int(input("Choice: "))
if Answer == 1:
ReadingAllData()
elif... | This code defines a menu-driven interface for database operations, allowing users to read, add, update, or delete data, or exit. It loops until the user selects "Exit," directing choices to corresponding functions like reading, inserting, updating, or deleting data, with error handling for invalid inputs. | def Decision():
stop = False
while stop == False:
print("---------Menu---------")
print("1.Read Data")
print("2.Adding Data")
print("3.Updating Data")
print("4.Deleting Data")
print("5.Exit")
print("----------------------")
Decision = int(input("Ch... |
def clean_up_df(self):
self.df = self.df.iloc[5:len(self.df) - 2]
self.df.columns = self.col_names
del(self.df['NaN'])
def convert_in_df(self):
for i in self.col_convert:
self.df[i] = self.df[i].apply(lambda x: convert_to_seconds(x))
def make_columns_numeric(self):
nu... | The code initializes a class to process an Excel file by defining column names, converting specific columns to numeric types, cleaning data, and creating copies of the DataFrame for employee and labels data, preparing it for further analysis or output. | def __init__(self, path_name, month, output_path_name):
self.col_names = ['Agent', 'NaN', 'Queue', 'NaN', 'TotalLoggedInTime', 'CallsAnswered', '%CallsServiced',
'CallsAnsweredPerHour', 'RingTimeTotal', 'RingTimeTotalMean', 'TalkTimeTotal', 'TalkTimeMean']
self.col_convert = ['... |
def select_employee_df(self, column_name, filter_condition):
df_list = self.create_employee_dataframes()
main_df = df_list[0]
main_df = main_df.append([d for d in df_list[1:]])
cleaned_df = main_df[main_df[column_name].str.contains(filter_condition)]
cleaned_df = cleaned_df[clean... | This function generates a bar chart displaying 'CallsAnswered' per agent for a specified month, cleans agent names, annotates bar heights, saves the plot as a PNG, and inserts both the chart and processed data into an Excel sheet. It uses pandas for data handling, matplotlib for visualization, and openpyxl for Excel ou... | def create_employee_total_df(self):
df = self.select_employee_df('Agent', 'total')
df['Agent'] = df['Agent'].apply(lambda x: strip_name(x))
title = f'CallsAnswered per person in {self.month}'
ax = df.plot(x='Agent', y='CallsAnswered', kind='bar', title=title, rot=20, figsize=(17, 7), co... |
def get_employees_list(self):
return list(dict.fromkeys(self.employee_df['Agent'].tolist()))
def remove_zero_calls_labels(self):
label_to_remove = 'MatchQ'
labels = self.get_filtered_labels(label_to_remove)
for l in labels:
if self.labels_df[self.labels_df['Queue'] == l]['Cal... | The main task of the code is to generate a dictionary mapping employee-label combinations (with non-zero call counts) to their respective call data. It processes each employee's call statistics across filtered labels, aggregates results, and stores non-zero entries in a structured format for further analysis or visuali... | def create_data_labels(self):
data_dict = {}
employees = self.get_employees_list()
labels = self.remove_zero_calls_labels()
for emp in employees:
emp_data = []
for l in labels:
try:
result = self.labels_df[(self.labels_df['Agent... |
def create_overall_frequency_df(self) -> pd.DataFrame:
df_list = self.create_dataframes_by_day()
temp_df_list = [self.create_frequency_dataframe(d) for d in df_list]
main_df = temp_df_list[0]
main_df = main_df.append([d for d in temp_df_list[1:]])
return main_df
def group_frequen... | The main task of the code is to generate and save Excel files containing frequency data visualizations. It creates an overall frequency DataFrame, groups data by days, generates grouped and single-day plots, and saves them into an Excel sheet named with the specified month. | def write_data_to_excel(self) -> None:
overall_df = self.create_overall_frequency_df()
df_to_use = self.group_frequency_by_days(overall_df)
sheet_name = f'Frequency calls {self.month}'
self.create_grouped_days_plot(df_to_use, sheet_name)
self.create_single_days_plot(overall_df, s... |
def create_data_labels(self):
data_dict = {}
employees = self.get_employees_list()
labels = self.remove_zero_calls_labels()
for emp in employees:
emp_data = []
for l in labels:
try:
result = self.labels_df[(self.labels_df['Agent... | The main task of the code is to generate a stacked bar chart visualizing "CallsAnswered per label" for a specific month, using data from `create_data_labels()`. It processes labels, sorts data, plots the chart with custom colors, saves the plot as a PNG, and exports both the plot and underlying data to an Excel sheet. ... | def create_labels_plot(self):
color_list = [
'#e6194B', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4', '#42d4f4', '#f032e6', '#bfef45',
'#fabed4', '#469990', '#dcbeff', '#9A6324', '#800000', '#aaffc3', '#808000', '#ffd8b1',
'#000075', '#a9a9a9', '#ffffff', '#000000'
... |
def append_dataframes_to_list(self):
df_list = []
for t in self.filter_list:
df_to_append = self.df[self.df["Queue"].str.contains(t)]
result_dict = self.get_results_in_dict(df_to_append, t)
df_to_append = df_to_append.append(result_dict, ignore_index=True)
... | This function combines multiple dataframes into one and optionally generates and saves plots (calls, ring time, talk time) in an Excel file. If create_missed_calls is True, it also creates a missed calls plot. The final Excel file is saved with the generated charts. | def write_dataframes_to_excel(self, create_plots=True, create_missed_calls=False, path_name_missed_calls=None):
df_list = self.append_dataframes_to_list()
main_df = df_list[0]
for i in df_list[1:]:
main_df = main_df.append(i)
if create_plots:
# Creating the call... |
def ensure_model_folder_exists(model_directory, auto_update=True):
metadata_file = os.path.join(model_directory, "metadata.json")
local_etag = get_local_metadata(metadata_file)
s3_etag = get_s3_file_etag(s3_url)
if s3_etag is None:
return # Exit if there's no internet connection or other issues... | (The code defines a command-line interface for a sensitive information detection tool using a BERT model. It processes text inputs via a direct prompt or file, outputs results in HTML, and supports GPU acceleration, confidence thresholds, and line-by-line processing. The tool identifies entities, displays labels/confid... | def main():
parser = argparse.ArgumentParser(description="Sensitive Information Detector.")
parser.add_argument(
"-p", "--prompt", type=str, help="Direct text prompt for recognizing entities."
)
parser.add_argument(
"-f", "--file", type=str, help="Path to a text file to read prompts from... |
def get_drink_obj(drink_name):
return data.MENU[drink_name]
def restart_coffee_machine():
start_coffee_machine()
def get_resources_obj():
return data.resources | The function `process_coins` handles payment for a selected drink by prompting the user to insert coins, calculating the total amount, and verifying if it meets the drink's cost. If insufficient, it refunds and restarts the machine; otherwise, it updates the machine's resources with the drink's cost and provides change... | def process_coins(drink_name):
drink = get_drink_obj(drink_name)
print("Please insert coins.")
money = float(input("how many quarters?: ")) * QUARTERS
money += float(input("how many dimes?: ")) * DIMES
money += float(input("how many nickles?: ")) * NICKLES
money += float(input("how many pennies?... |
def get_drink_obj(drink_name):
return data.MENU[drink_name]
def check_enough_resources(drink_name):
drink = get_drink_obj(drink_name)
not_enough_resource = ''
if 'water' in drink['ingredients'].keys() and data.resources['water'] < drink['ingredients']['water']:
not_enough_resource = 'water'
... | The code's main task is to prepare and dispense a specified drink by checking resource availability, processing payment, deducting resources, and restarting the coffee machine. It handles the full workflow from validating ingredients to delivering the drink and resetting the system for the next use. | def make_drink(drink):
drink_obj = get_drink_obj(drink)
check_enough_resources(drink)
print(f"{drink} cost is a ${drink_obj['cost']}")
process_coins(drink)
decrease_resources(drink)
print(f"Here is your {drink} ☕️. Enjoy!")
restart_coffee_machine() |
def get_tensor_from_list(name: str, list: List[tf.Tensor]) -> Optional[tf.Tensor]:
"""
Pick a tensor from a list, using it's name
:param name: name of the tensor
:param list: list of tensor where to pick
:return: tensor
"""
ll = [t for t in list if t.name == name]
if len(ll) > 0:
... | The code performs feature engineering by transforming raw numerical and categorical features into engineered tensors. It calculates L1 distance for coordinates, embeds path information via bucketization, encodes categorical 'company' data with embeddings, and applies bucketized embeddings for day_of_week and minutes_si... | def feature_engineering(
numerical_features_list: List[tf.Tensor],
categorical_features_list: List[tf.Tensor],
configs: Dict,
) -> List[tf.Tensor]:
"""
Feature engineering
:param feature_list: list of raw features as created by tf.keras.Input
:param configs: dict of config values
:retu... |
def serif_json_seralizer(serif_doc):
ret = dict()
ret["doc_id"] = serif_doc.docid
ret["sentences"] = list()
ret["entity_relations"] = list()
ret["mention_id_to_mention_loc"] = dict()
ret["event_mention_id_to_event_mention_loc"] = dict()
timestamp = int(time.time())
for sent_no, sentence ... | The function processes a document using an A2T template and annotations. It retrieves input data, modifies the serif document with unary markings, applies the template, generates new annotations, resolves conflicts with existing adjudicated data, and returns updated extraction results and the modified document in JSON ... | def rescore_using_latest_template():
a2t_template_dict = flask.request.json.get("a2t_template", None)
if a2t_template_dict is None:
a2t_template_dict = a2t_default_config_dict
adjudicated_extraction = flask.request.json.get("a2t_extraction", dict())
unary_marking_extraction =... |
def sample_and_store(self):
s = self.agent
a = self.select_action(s, policy=self.policy, epsilon=self.epsilon, temp=self.temp)
s_next, r, terminated, truncated, info = self.env.step(a)
done = terminated or truncated
if done:
s_next, info = self.env.reset()
self... | The code trains a reinforcement learning agent by running multiple episodes, collecting experiences in a replay buffer, and performing training updates when the buffer is sufficiently filled. It tracks total steps and rewards, updates target network weights periodically, and terminates early if the agent achieves a rew... | def play(self):
total_steps = 0
steps_over_500 = 0
for episode in tqdm(range(self.episodes)):
reward = 0
while True:
done = self.sample_and_store()
reward += 1
total_steps += 1
self.factor_decay()
if len(self.replay... |
def roll_dice(self, num):
print(f"Rolling {num} dice...")
roll = self._roller(num)
print(",".join([str(i) for i in roll]))
return roll
def got_zilch(self, roll):
initial_score = self.calculate_score(roll)
if initial_score == 0:
print("Zilch!!! Round ove... | The main task of the code is to manage a single round of a dice game. It rolls dice, checks for "zilch" (no valid keepers), allows the player to choose to roll again, bank points, or quit, updates the round score accordingly, and displays the final score for the round. The loop continues until the player banks points, ... | def start_round(self, round, num_dice=6):
print(f"Starting round {round}")
round_score = 0
while True:
roll = self.roll_dice(num_dice)
if self.got_zilch(roll):
break
keepers = self.handle_keepers(roll)
roll_again_response = i... |
def wake(self):
self.wakeup = True
self.snoozed = False
self.seconds = 0
self.minutes = 0
def generate_datapoint():
data = DrowsyData()
data.add_datapoint(str(datetime.now()), 0, 3)
data.save_data_to_file(data_filename)
del data
def snooze(self):
i... | This code initializes a Tkinter GUI frame for an alarm/alert system, setting up a background image, displaying a falling-asleep warning label, and adding "Wake Up" and "Snooze" buttons. The "Wake Up" button triggers wake-up logic, data recording, and navigation to a recording window, while "Snooze" initiates a snooze a... | def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
background_image = tk.PhotoImage(file=background_IMAGE)
BGlabel = tk.Label(self, image=background_image)
BGlabel.image = background_image
BGlabel.place(x=0, y=0, width=no... |
def update_viewport(window, width, height):
global pix2angle
pix2angle = 360.0 / width
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(70, 1.0, 0.1, 300.0)
if width <= height:
glViewport(0, int((height - width) / 2), width, width)
else:
glViewport(int((width - ... | The code initializes an OpenGL viewport for rendering, sets up depth testing, creates 2D grids for control points and Bezier surface coordinates, randomizes control points, and computes the Bezier surface. It prepares the environment for 3D graphics rendering of a Bezier mesh. | def startup():
global control_points
global bezier
update_viewport(None, 400, 400)
glClearColor(0.0, 0.0, 0.0, 1.0)
glEnable(GL_DEPTH_TEST)
control_points = [[[0, 0, 0] for _ in range(N)] for _ in range(N)]
bezier = [[[0, 0, 0] for _ in range(bN)] for _ in range(bN)]
randomize_control_p... |
def calculate_bezier():
global bezier
global bN
for i in range(bN):
for j in range(bN):
bezier[i][j] = bezier_point(i, j)
def axes():
glBegin(GL_LINES)
glColor3f(1.0, 0.0, 0.0)
glVertex3f(-5.0, 0.0, 0.0)
glVertex3f(5.0, 0.0, 0.0)
glColor3f(0.0, 1.0, 0.0)
glVert... | The code renders a 3D Bezier surface with interactive camera controls. It adjusts view angles (theta, phi) via mouse input, modifies control points or camera distance (R) based on MODE, calculates eye coordinates using trigonometry, sets the camera with gluLookAt, and draws axes, control points, and the surface. It han... | def render(time):
global theta
global phi
global R
global control_points
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
if left_mouse_button_pressed:
theta += delta_x * pix2angle
phi += delta_y * pix2angle
if phi > 180:
phi -= 360
... |
def startup():
update_viewport(None, 800, 800)
glClearColor(0.0, 0.0, 0.0, 1.0)
glEnable(GL_DEPTH_TEST)
global vertices
u_arr = [i/(N-1) for i in range(N)]
v_arr = [i/(N-1) for i in range(N)]
for i, u in enumerate(u_arr): #u
for j, v in enumerate(v_arr): #v
vertices[i][j... | The main task of the code is to create a GLFW window for rendering a spinning Sierpinski pyramid using OpenGL. It initializes GLFW, sets up a window with a framebuffer size callback, enters a rendering loop calling `render4()` to draw the 3D fractal, and handles events until the window closes. The loop updates the view... | def main():
if not glfwInit():
sys.exit(-1)
window = glfwCreateWindow(800, 800, __file__, None, None)
if not window:
glfwTerminate()
sys.exit(-1)
glfwMakeContextCurrent(window)
glfwSetFramebufferSizeCallback(window, update_viewport)
glfwSwapInterval(1)
startup()
... |
def startup():
global RAND_SEED
RAND_SEED = random.randint(0, 10000)
print("random seed:", RAND_SEED)
update_viewport(None, 800, 800)
glClearColor(0.1, 0.1, 0.3, 1.0)
def render4():
random.seed(RAND_SEED)
glClear(GL_COLOR_BUFFER_BIT)
sierpinski_rect(-90, -90, 180, 180, color_mode='C... | The code initializes a GLFW window for OpenGL rendering, sets up a rendering loop to display a Sierpinski rectangle fractal, and handles window events until closure. It includes GLFW initialization, window creation, viewport updates, and rendering with specific functions, terminating resources upon exit. | def main():
if not glfwInit():
sys.exit(-1)
window = glfwCreateWindow(800, 800, "lab2", None, None)
if not window:
glfwTerminate()
sys.exit(-1)
glfwMakeContextCurrent(window)
glfwSetFramebufferSizeCallback(window, update_viewport)
glfwSwapInterval(1)
startup()
... |
def startup():
# global RAND_SEED
# RAND_SEED = random.randint(0, 10000)
update_viewport(None, 800, 800)
glClearColor(0.1, 0.1, 0.3, 1.0)
def render(time):
random.seed(0)
glClear(GL_COLOR_BUFFER_BIT)
# glBegin(GL_TRIANGLES)
# glColor3f(1.0, 0.0, 0.0)
# glVertex2f(-50.0, -50.0)
#... | The code initializes a GLFW window for OpenGL rendering, sets up a rendering loop with vsync, handles window events, and performs startup/shutdown tasks. It continuously renders frames using the current time, swaps buffers, and processes events until the window is closed, ensuring proper resource cleanup. | def main():
if not glfwInit():
sys.exit(-1)
window = glfwCreateWindow(800, 800, __file__, None, None)
if not window:
glfwTerminate()
sys.exit(-1)
glfwMakeContextCurrent(window)
glfwSetFramebufferSizeCallback(window, update_viewport)
glfwSwapInterval(1)
startup()
... |
def update_viewport(window, width, height):
global pix2angle
pix2angle = 360.0 / width
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(70, 1.0, 0.1, 300.0)
if width <= height:
glViewport(0, int((height - width) / 2), width, width)
else:
glViewport(int((width - ... | The code initializes OpenGL settings for 3D rendering, configures lighting and material properties, generates a parametric surface's vertices and normals, and fixes color artifacts by flipping seam indices. It sets up a viewport, enables depth testing, defines light and material parameters, computes surface geometry, a... | def startup():
update_viewport(None, 400, 400)
glClearColor(0.0, 0.0, 0.0, 1.0)
glEnable(GL_DEPTH_TEST)
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient)
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse)
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular)
glMaterialf(GL_FRONT, GL_SHININESS, mat_s... |
def startup():
global control_points
global bezier
update_viewport(None, 400, 400)
glClearColor(0.0, 0.0, 0.0, 1.0)
glEnable(GL_DEPTH_TEST)
control_points = [[[0, 0, 0] for _ in range(N)] for _ in range(N)]
bezier = [[[0, 0, 0] for _ in range(bN)] for _ in range(bN)]
randomize_control_p... | This code creates a GLFW window for OpenGL rendering, initializes event callbacks for input and window resizing, and runs a rendering loop that updates the scene using the current time. It handles user interactions, maintains the rendering context, and properly cleans up resources upon exit. | def main():
if not glfwInit():
sys.exit(-1)
window = glfwCreateWindow(400, 400, __file__, None, None)
if not window:
glfwTerminate()
sys.exit(-1)
glfwMakeContextCurrent(window)
glfwSetFramebufferSizeCallback(window, update_viewport)
glfwSetKeyCallback(window, keyboard_k... |
def startup():
update_viewport(None, 400, 400)
glClearColor(0.0, 0.0, 0.0, 1.0)
glEnable(GL_DEPTH_TEST)
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient)
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse)
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular)
glMaterialf(GL_FRONT, GL_SHININESS, mat_s... | This code initializes a GLFW window for rendering, sets up input callbacks for keyboard and mouse events, and runs a rendering loop that updates the viewport, processes events, and renders frames until the window is closed. It ensures proper GLFW initialization and cleanup, including startup/shutdown routines and vsync... | def main():
if not glfwInit():
sys.exit(-1)
window = glfwCreateWindow(400, 400, __file__, None, None)
if not window:
glfwTerminate()
sys.exit(-1)
glfwMakeContextCurrent(window)
glfwSetFramebufferSizeCallback(window, update_viewport)
glfwSetKeyCallback(window, keyboard_k... |
def read_string_list(infile):
result = []
strlen = read_int32(infile)
while strlen > 0:
result.append(str(infile.read(strlen)))
strlen = read_int32(infile)
return []
def read_int32(infile):
return struct.unpack('>i', infile.read(4))[0]
def read_blocks(infile, is_loadfile):
resul... | This function parses a hunk file (Header or Unit type) by reading metadata like library names, hunk sizes, or unit names. It processes file blocks into hunks, then conditionally prints detailed disassembled code, an overview, or dumps code based on input flags. | def parse_hunkfile(hunkfile, disassembled, dump_code, detail):
"""Top level parsing function"""
with open(hunkfile, 'rb') as infile:
id = infile.read(4)
# can be Header or Unit
is_loadfile = True
if id == HUNK_BLOCK_HEADER:
print("Hunk Header (03f3)")
lib... |
def log_barrier(x, f, ineq_constraints, t):
phi, d_phi, h_phi = phi_calc(x, ineq_constraints)
f_x, grad_x, hess_x = f(x)
log_barr_f = (t * f_x) + phi
log_barr_g = (t * grad_x) + d_phi
log_barr_h = (t * hess_x) + h_phi
return log_barr_f, log_barr_g, log_barr_h
def newton(x_p,hessian_p):
I =... | This function implements the Newton method with a log barrier for constrained optimization. It iteratively computes search directions using Newton steps, adjusts step lengths via line search, and checks convergence based on a stopping criterion. The method handles equality and inequality constraints by constructing aug... | def newton_method(x0, f, ineq_constraints, t, n_equ_const, A, epsilon, init_step_len, slope_ratio,back_track_factor, count, max_iter=100):
outer_obj = []
obj = []
success = False
xk = x0
xs = [xk]
for k in range(max_iter):
log_barr_f_xk, log_barr_g_xk, log_barr_h_xk = log_barrier(xk... |
def draw_rand_card(self):
deck_dict = self.shoe.get_cards_unused()
if self.shoe.numberofcards_remaining_actual > 0:
pulled_card = random.choice(list(deck_dict))
while deck_dict[pulled_card] == 0:
pulled_card = random.choice(list(deck_dict))
self.shoe.u... | The hit method adds a random card to the agent's hand, updates the hand's total value and soft status, and returns the current game state if the hand value is under 21. If the hand value reaches 21 or higher, it triggers the stand action instead. | def hit(self):
new_card = self.draw_rand_card()
self.agent_hand.append(new_card)
self.agent_hand_value, self.agent_hand_is_soft = get_total_and_soft_from_hand(self.agent_hand)
if self.agent_hand_value < 21:
return self.agent_hand, self.dealer_hand_hidden, \
... |
def stand(self):
##
# Agent Cannot Win, so it busted
##
if self.agent_hand_value > 21:
self.game_over = True
return self.agent_hand, self.dealer_hand_hidden, \
self.shoe.numberofcards_remaining_actual, \
[self.game_over, "Bu... | This code processes a game action (stand, hit, double down, or additional bet) in a card game, updates the game state, calculates a reward (including a participation bonus and a proximity-to-21 bonus), and returns the reward, current state, and whether the game is finished. It supports reinforcement learning by providi... | def step(self, action):
if action == 0:
p_hand, d_hand, cards_remain, result_list = self.stand()
elif action == 1:
p_hand, d_hand, cards_remain, result_list = self.hit()
elif action == 2:
p_hand, d_hand, cards_remain, result_list = self.double_down()
... |
def create_data_profile_df(self):
try:
conn_string = "DRIVER={ODBC Driver 17 for SQL Server}; SERVER=AWS-PROD-SQL\Sockeye; DATABASE=Elmer; trusted_connection=yes"
sql_conn = pyodbc.connect(conn_string)
sql_statement = "select * from data_portal.census_data_profile({}, '{}', '... | The code generates Excel workbooks for specified geography groups (State-County-MSA, City, CDP) by creating one workbook per group. It uses data profiles, excludes CDP for 'acs1' census data, and exports files with structured naming. Error handling is included for robustness. | def create_workbooks(self):
"""
Create Excel workbooks for all geography groups (State-County-MSA, City, and CDP).
Exports one workbook per geography group.
"""
try:
self.create_data_profile_df()
df = self.df
# short_title = self.short_title
... |
def search_by_title(self):
"""
Search self.gis for layers with a given title (self.title),
which is of the same type (Shapefile or tabular CSV) as self,
and which is also owned by the current user.
Return the first layer that is an exact match.
If no match is found, returns the string "no item"
"""
try... | The code's main task is to check if a resource is already published on a data portal. If it exists, it deletes the existing resource and republishes it as new, using spatial or standard methods based on the resource type. If not found, it publishes the resource as new. Error handling is included to capture and re-raise... | def export(self):
"""
check if self is already published on the data portal.
If yes then delete resource, then publish as new
If no then publish as new
"""
try:
found_item = self.search_by_title()
if found_item != "no item":
if self.is_spatial:
self.republish_spatial()
else:
self... |
def get_ticker_symbol():
print('Please press Q if you want to exit at any point...')
#ticker symbol is gotten from user and stored in variable symbol
symbol = input('Enter the ticker symbol ')
#Quit
if symbol == 'Q' or symbol == 'q':
sys.exit('Quitting')
nw_chk, msg = cv.nw_check("h... | The code retrieves stock ticker data and date ranges, fetches historical financial data, and outputs it if available. If data is empty, it recursively re-tries the process to ensure valid data retrieval and display. | def command_line_operations():
symbol, ticker_data = get_ticker_symbol()
start_date, end_date = get_date_range()
ticker_hist = get_ticker_data(ticker_data, start_date, end_date)
if ticker_hist.empty == False:
output(ticker_hist, symbol)
else:
command_line_operations() |
def check_True_facts(row, facts, vars):
for f in facts:
i = 0
while i < len(vars):
if vars[i] == f:
break
i += 1
if row[i] == 0:
return(1)
return(0)
def calculate_rules(rpn_rules, vars, row):
result = []
binary_vars = get_binary... | The code generates all possible truth assignments for variables in `dic['vars']`, filters out invalid assignments based on `dic['facts']`, evaluates logical rules using `dic['rpn_rules']`, collects valid assignments in a matrix, and passes it to `make_decision` for further processing. | def cnf(dic):
matrix = []
for row in product('01', repeat=len(dic['vars'])):
row = [int(item) for item in row]
if dic['facts']:
if check_True_facts(row, dic['facts'], dic['vars']) == 1:
continue
result = calculate_rules(dic['rpn_rules'], dic['vars'], row)
... |
def gridtoValues(self,grid):
"""
Module to convert the string of values of variables in sudoku to a dictionary
with values filled with domain values for the unfilled variable"
Parameters:
-----------
grid: String of values with '.' for unfilled v... | The code solves a puzzle by converting the grid into a value dictionary, reducing it using constraints, and applying backtracking with a specified variable order to find a solution. | def solvePuzzle(self,grid,constraint, var_order):
gridValDict = self.gridtoValues(grid)
reduced_puzzle = self.reduceGridVal(gridValDict,constraint)
soln = self.backtrack(reduced_puzzle, constraint, var_order)
return soln |
def _get_colormap(cmap):
if isinstance(cmap, list) and len(cmap) == 1:
cmap = cmap[0]
return cmap
def update_axes(self):
if self.get_opt('trange', None) is not None:
self.axes.set_xlim(pd_to_datetime(self.get_opt('trange')))
self.axes.xaxis_date()
if self.get_opt... | This function generates a spectrogram image from input data by rasterizing time-frequency data with configurable log scales, colormaps, and axis ranges. It prepares data, adjusts ranges, creates a rasterized image, plots it on axes, sets limits, adds a colorbar, and updates visualization parameters according to user-de... | def buildfigure(self):
data = self.data
x = data.time.values
t = pd_to_datetime(x)
y = data.coords['spec_bins'].values
z = data.values
ylog = self.get_opt('ytype', 'linear') == 'log'
zlog = self.get_opt('ztype', 'linear') == 'log'
# prepare for data to b... |
def epoch(self):
total_fid = 0
total_real_error = 0
total_fake_error = 0
total_generator_error = 0
total_real_correct = 0
total_fake_correct = 0
total_generator_correct= 0
for (real, _) in tqdm(self.dataloader, leave=False):
real_error, fake_e... | The main task of the code is to train a model (likely a GAN) by iterating through epochs, computing metrics like FID, loss, and accuracy for generator and discriminator, logging these metrics, and periodically saving model checkpoints, generated images, and training statistics for monitoring and evaluation. | def train(self, current_epoch):
for epoch in range(current_epoch, self.epochs):
total_fid, total_real_error, total_fake_error, total_generator_error, total_real_correct, total_fake_correct, total_generator_correct = self.epoch()
# metric calculation
real_accuracy = total_fake... |
def exists(self, tree: Tree) -> bool:
for elem_ferme in self.ferme:
if elem_ferme.noeud.equals(tree.noeud):
return True
return False
def creersuccesseur(self, n: Tree):
res: list[Tree] = []
if n.noeud.depart():
left = Tree(Noeud(self.max_x, 0))
... | This function performs a pathfinding algorithm by iterating through nodes in an open list, checking if each node matches the target. If not, it generates successors and adds them to the graph. Upon finding the target node, it constructs the path using the graph and returns the list of nodes in the path. | def proceder(self) -> list[Noeud]:
resultat: list[Noeud] = []
while len(self.ouvert) > 0:
n = self.ouvert.pop(0)
if not self.exists(n):
self.ferme.append(n)
if n.noeud.x == self.but:
Carafe.chemin(self.graphe, self.but, resultat)
... |
def gram_schmidt(self, f_list):
'''run gram-schmidt orthogonalization on list of functions.
see wikipedia for pseudo-code: https://en.wikipedia.org/wiki/Gram–Schmidt_process.'''
f_orth_list = []
f_orth_list_norm = []
k_eff = 0 # keep track of number of non-zero orthogonal functions
for k in tqdm(range(len(f... | The code orthogonalizes a library of functions using Gram-Schmidt, computes projections of receptive fields (RFs) onto this basis, and plots the orthogonalized RFs or library functions based on the dimensionality (Dx=1 or 2). It handles 1D and 2D cases separately, visualizing results as "rf_orth_functions" or "lib_orth... | def set_rf_orth(self, ollie=True):
print('Running GS on library...')
self.lib_orth_list = self.gram_schmidt(self.lib_list)
print('Getting projections of RFs wrt library...')
self.get_alpha_proj()
if self.Dx==1:
self.plot_rf_d1(self.x_grid, self.Phi_orth_lib(self.x_grid), nm='rf_orth_functions')
elif sel... |
def set_rf(self):
self.w_in = self.fac_w * np.random.randn(self.Dr, self.Dx)
self.b_in = np.random.uniform(low=0, high=2*np.pi, size= (self.Dr, 1))
# self.w_in = np.random.uniform(low=-self.fac_w, high=self.fac_w, size= (self.Dr, self.Dx))
# self.b_in = np.random.uniform(low=-self.fac_b, high=self.fac_b, size=... | The function `fit_data` computes and fits multiple models using random features (RF) and libraries for function approximation. It calculates RF and library matrices, performs ridge/lasso regression with CVX or regularized least squares, and generates predictions. It also conducts joint learning by combining L1-regulari... | def fit_data(self, use_cvx=False):
self.set_rf()
### Compute libraries
print('Computing Phi and Library matrices...')
nplot = min(500, self.Nx)
Phi = self.Phi_lib(self.x_norm.T).T
self.plot_rf_seq(Phi.T[:nplot], nm='rf_seq')
try:
# these "truth" segments are specifically for inspecting L63 cases
t... |
def normalize_data(self):
self.x_norm = self.scaleX(self.x, save=True)
self.y_norm = self.scaleY(self.y, save=True)
def fit_data(self, use_cvx=False):
self.set_rf()
### Compute libraries
print('Computing Phi and Library matrices...')
nplot = min(500, self.Nx)
Phi = self.Phi_lib(self.x_norm.T).T
self.pl... | The code's main task is to normalize data, fit a model, attempt to plot results (with error handling), and print evaluation metrics. It processes data through normalization and model fitting, visualizes outcomes if possible, and outputs performance metrics. | def run(self):
# self.make_data()
self.normalize_data()
self.fit_data()
try:
self.plot_fits()
except:
pass
self.print_eval() |
def summaryurl(t):
return f"https://finance.yahoo.com/quote/{t}"
def reboot(self):
"""Reboot driver."""
self.driver.quit()
self.sleep(600) # rest for 10 minutes
self.init_driver()
self.signin()
def parse(self, tr):
"""Parse row element from table into column and value... | The code crawls summary and statistics data for given stock symbols from web pages, parses HTML content using BeautifulSoup, handles exceptions by rebooting the driver, and saves extracted data into a dictionary. It retries up to max_trial times per symbol, storing results or saving them to symbol_summary.csv if fully ... | def crawl_summary(self, symbols):
"""Crawl data to get saved in symbol_summary.csv."""
for symbol in symbols:
data = {"Date" : tools.get_today(), "Symbol" : symbol}
# [Summary, Statistics]
result = [False, False]
for _ in range(self.max_trial):
... |
def statisticsurl(t):
return f"https://finance.yahoo.com/quote/{t}/key-statistics?p={t}"
def sleep(self, t=6):
"""Sleep crawler."""
return time.sleep(t)
def reboot(self):
"""Reboot driver."""
self.driver.quit()
self.sleep(600) # rest for 10 minutes
self.init_driver()
... | The main task of the code is to crawl and save financial statistics data for a given stock symbol from a webpage. It uses Selenium to load the page, BeautifulSoup to parse HTML content, and extracts key metrics like fiscal year, profitability, and financial statements. The function also attempts to download quarterly v... | def crawl_statistics(self, symbol):
"""Crawl statistics.csv."""
result = [False, False]
data = {}
self.driver.get(statisticsurl(symbol))
self.sleep(3)
for _ in range(self.max_trial):
name = "tmp"
if not self.debug and path.exists(tools.get_path(nam... |
def player_menu2():
"""
Purpose: Allows player 1 to choose their position piece
:return: Yell_leader icon and position of Yell Leader
"""
width, height = 1120, 490
screen = pygame.display.set_mode((width, height))
menu_2 = pygame.image.load('player 1 selection.png') # background image for m... | This code implements a turn-based game between a player and a computer opponent using Pygame. It initializes game elements, alternates turns for card selection and movement, checks for a win condition (reaching position 71), and displays a victory screen for the winner with appropriate graphics. The player chooses card... | def computer_mode():
"""
Executes the game code by combining fundamental functions
:return: nothing
"""
player1_icon1 = player_menu2()[0]
player1_icon = pygame.transform.scale(player1_icon1, [40, 40])
computer_icon = pygame.image.load('Computer_icon.png')
computer_icon = pygame.transform... |
def player_menu2():
"""
Purpose: Allows player 1 to choose their position piece
:return: Yell_leader icon and position of Yell Leader
"""
width, height = 1120, 490
screen = pygame.display.set_mode((width, height))
menu_2 = pygame.image.load('player 1 selection.png') # background image for m... | This function simulates a turn-based board game where a player and computer take turns moving pieces based on randomly drawn cards. It initializes game elements, alternates between player and computer moves, updates positions, checks for reaching the winning position (71), and displays the appropriate victory screen wh... | def computer_mode_random():
"""
Executes the game code by combining fundamental functions
:return: nothing
"""
player1_icon1 = player_menu2()[0]
player1_icon = pygame.transform.scale(player1_icon1, [40, 40])
computer_icon = pygame.image.load('Computer_icon.png')
computer_icon = pygame.tr... |
def player_menu2():
"""
Purpose: Allows player 1 to choose their position piece
:return: Yell_leader icon and position of Yell Leader
"""
width, height = 1120, 490
screen = pygame.display.set_mode((width, height))
menu_2 = pygame.image.load('player 1 selection.png') # background image for m... | The main task of the code is to execute a turn-based game where a player and a computer (using a basic AI) take turns moving pieces on a board based on randomly drawn cards. The game continues until either the player or computer reaches position 71, at which point a win screen displays the winner's icon and a correspon... | def computer_mode_dumb():
"""
Executes the game code by combining fundamental functions
:return: nothing
"""
player1_icon1 = player_menu2()[0]
player1_icon = pygame.transform.scale(player1_icon1, [40, 40])
computer_icon = pygame.image.load('Computer_icon.png')
computer_icon = pygame.tran... |
def player_menu2():
"""
Purpose: Allows player 1 to choose their position piece
:return: Yell_leader icon and position of Yell Leader
"""
width, height = 1120, 490
screen = pygame.display.set_mode((width, height))
menu_2 = pygame.image.load('player 1 selection.png') # background image for m... | The code implements a two-player board game where each player takes turns drawing cards to move their piece across a board. The game continues until one player reaches position 71, triggering a victory screen displaying the winner's icon. It handles game initialization, turn-based movement, win condition checks, and gr... | def two_player():
"""
This code executes the game for two player mode. It is very similar to computer v player with a few differences
:return: nothing
"""
menu_response = player_menu2()
player_icon1 = menu_response[0]
player1_icon = pygame.transform.scale(player_icon1, [40, 40])
grey_pos... |
def computer_mode_dumb():
"""
Executes the game code by combining fundamental functions
:return: nothing
"""
player1_icon1 = player_menu2()[0]
player1_icon = pygame.transform.scale(player1_icon1, [40, 40])
computer_icon = pygame.image.load('Computer_icon.png')
computer_icon = pygame.tran... | Your return
The code displays a menu for selecting computer difficulty levels in a game, using Pygame. It loads images, tracks mouse input, and highlights options. Users choose between three modes (standard, dumb, random) by clicking on designated areas. The menu loops until a selection is made or the user exits, tra... | def computer_difficulty_menu():
"""
Purpose: Have the user decide two player or computer mode
Executes the code for either
"""
width, height = 1120, 490
screen = pygame.display.set_mode((width, height))
menu1_image = pygame.image.load('Computer difficulty.png')
menu1_image = ... |
def jenkins_response(self,url):
"""_summary_
Call jenkins Job specific Api and returns repsonse
Args:
url (_type_): Jenkins Job server URL
Returns:
_type_: Success return bool depending on jenkins response
"""
success = False
r... | The main task of the code is to collect and compile current build status and related information (e.g., next/previous builds) for Jenkins jobs specified in `SERVER_URLS` and `JOB_NAMES`. It uses authentication credentials (`self.username`, `self.build_token`) to query Jenkins, processes responses, and structures the da... | def call_jenkins(self):
"""_summary_
Generate data containing all job current status and additional information
Returns:
_type_: dict
"""
data = {'current_build': []}
if self.username and self.build_token:
for index, url in enumerate(SE... |
def main_menu():
global Map_Size
global Tile_Size
global Number_Of_Tiles
menu_size = 350
half = menu_size // 2
quarter = half // 2
eighth = quarter // 2
screen = pygame.display.set_mode((menu_size, menu_size))
pygame.display.set_caption('Main Menu')
font = pygame.font.Font('frees... | The main task of the code is to run a maze-solving game where a player navigates from a start to an end point using movement keys, with options to trigger a bot solution or display the solution path. It initializes the game screen, generates a maze via recursive division, handles user input for movement and bot functio... | def game_running():
global Map_Size
global Tile_Size
global Number_Of_Tiles
# Initialize the screen
pygame.init()
main_menu()
screen = pygame.display.set_mode((Map_Size, Map_Size))
pygame.display.set_caption('Buttons: {wasd & arrows} = Movement; b = Bot; n = Solution; m = Quit;')
# ... |
def test(model, L, noise_level=15, vec_t=None, model_out_type='pred_xstart'):
E = model(L, noise_level, vec_t=vec_t, model_out_type=model_out_type)
return E
def test_pad(model, L, modulo=16, noise_level=15, vec_t=None, model_out_type='pred_xstart'):
h, w = L.size()[-2:]
paddingBottom = int(np.ceil(h/mod... | This function executes different testing modes for a model, selecting between normal testing, padding, splitting, or scaling strategies based on the 'mode' parameter. It dispatches to specific test functions (e.g., test_split, test_x8) and returns results accordingly, enabling flexible evaluation of model performance u... | def test_mode(model_fn, model_diffusion, L, mode=0, refield=32, min_size=256, sf=1, modulo=1, noise_level=0, vec_t=None, \
model_out_type='pred_xstart', diffusion=None, ddim_sample=False, alphas_cumprod=None):
'''
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Some testing modes
# ^^^^^^^^^^^^^^^^^... |
def move_paddle(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and self.paddle.left > 0:
self.paddle.left -= self.PADDLE_SPEED
if keys[pygame.K_RIGHT] and self.paddle.right < constants.SCREEN_WIDTH:
self.paddle.right += self.PADDLE_SPEED
def move_ball(self)... | This code runs a game loop using Pygame, handling events (like quitting), updating game elements (paddle and ball movement), rendering the game state, and maintaining a 60 FPS frame rate until the user exits. | def run(self):
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
self.move_paddle()
self.move_ball()
self.draw()
self.clock.tick(60)
pygam... |
def image(self, data, num):
image = {}
img = utils.img_b64_to_arr(data["imageData"])
height, width = img.shape[:2]
img = None
image["height"] = height
image["width"] = width
image["id"] = num
image["file_name"] = data["imagePath"].split("/")[-1]
s... | This code converts Labelme JSON annotations into a structured dataset format by parsing shape labels, organizing annotations with corresponding category IDs, and ensuring consistent label ordering across data splits for model training. | def data_transfer(self):
for num, json_file in enumerate(self.labelme_json):
with open(json_file, "r") as fp:
data = json.load(fp)
self.images.append(self.image(data, num))
for shapes in data["shapes"]:
label = shapes["label"].split... |
def create_discipline():
disciplines_list = []
for discipline in disciplines:
name = disciplines[discipline]['name']
classes = disciplines[discipline]['classes'].split(';')
importance = disciplines[discipline]['importance']
disciplines_list.append(Discipline(name, classes, import... | The main task of the code is to create a list of School objects by populating them with data from predefined lists of disciplines, directors, and secretaries. It iterates through a schools dictionary, matches director/secretary names to corresponding objects, constructs School instances, and appends them to a list. Fin... | def create_schools():
schools_list = []
disciplines_list = create_discipline()
directors_list = create_directors(disciplines_list)
secretaries_list = create_secretaries()
for school in schools:
name = schools[school]['name']
email = schools[school]['email']
address = schools... |
def calc_n_sub_plots(self):
n_expr = 0 if not self.args.expr else len(self.args.expr)
n_piped = len(self.piped_cols)
if self.args.subf:
ret = len(self.data)
if len(self.piped) > 0: ret += 1
return ret
if self.args.c:
mult ... | The code generates a multi-subplot visualization based on input data and command-line arguments, dynamically adjusting subplot layouts (2x1, NxN) for surface/scatter plots. It handles data column selection, overrides with user-specified columns, plots data from multiple files, adds legends, processes piped data, and ev... | def plot_all(self):
# set up sub plot stuff
sp_kw = {}
if self.args.surf: sp_kw["projection"]="3d"
len_data = len(self.data)
n_subs = self.calc_n_sub_plots()
#print(f"n_sub_plots = {n_subs}")
if self.args.subf or self.args.subc:
if n_subs < 3:
... |
def get_piped(self):
if sys.stdin.isatty(): return
self.piped = genfromtxt(sys.stdin, dtype=np.double, comments=self.line_comment)
print(f"piped in data shape: {self.piped.shape}")
if self.args.p:
self.piped_cols = self.args.p
def read_all_data(self):
if not self.args... | The code defines an `__init__` method for a class that parses command-line arguments to customize data plotting with matplotlib. It handles file inputs, column selections, axis settings, error bars, histograms, scatter plots, and custom data readers. The parser supports options for log scales, binning, labels, and form... | def __init__(self, arg_str=None):
self.parser = argparse.ArgumentParser(description='Plot data from files with matplotlib. Data can also be piped through stdin.')
self.parser.usage = f"{sys.argv[0]} FILE1 [columns to plot] FILE2 [columns to plot] ... [options]"
p = self.parser.add_argument
... |
def connect(db=""):
creds = rds_credentials.get_secret()
rdshost = creds["host"]
rdsport = creds["port"]
rdsusername = creds["username"]
rdspassword = creds["password"]
if db == "":
mydb = mysql.connector.connect(
host=rdshost,
port=rdsport,
user=rd... | The code defines a function `summarizeTables` that connects to a database, retrieves all table names, and iterates through each table to summarize its contents using the `sampleTable` function, printing progress messages for each table processed. | def summarizeTables(dbName=""):
with connect(getDBName(dbName)) as db:
cur = db.cursor()
cur.execute("SHOW TABLES")
for x in cur:
t = x[0]
print("Summarizing table {}".format(t))
sampleTable(dbName=dbName,tableName=t)
print("\n") |
def getVersion(string):
version = int(string[:3], 2)
print("version", version)
return version
def isNumberPacket(string):
return getType(string) == 4
def getPacketLength(packetString):
if isNumberPacket(packetString):
index = 6
lastGroup = False
while lastGroup == False:
currentGroup = packe... | The function calculates the sum of version numbers from a hexadecimal-encoded packet string by recursively processing sub-packets. It checks packet type (number or operator), extracts version numbers, and processes sub-packets based on length type (fixed or variable). For operators, it handles nested packets by either ... | def calculatePacketVersion(packetString):
print("packetString", packetString)
if len(packetString) < 11:
return 0
version = getVersion(packetString)
if isNumberPacket(packetString):
packetLength = getPacketLength(packetString)
version += calculatePacketVersion(packetString[packetLength:])
else:
... |
def readFile(filepath):
f = open(filepath, "r")
content = f.readlines()
return content[0]
def letterToBinary(letter):
map = {
"0": "0000",
"1": "0001",
"2": "0010",
"3": "0011",
"4": "0100",
"5": "0101",
"6": "0110",
"7": "0111",
"8": "1000",
"9": "1001",
"A": "1010",... | The code reads a file, converts its characters to a binary string, calculates the packet version from this binary data, and returns the version. | def first(filepath):
input = readFile(filepath)
binaryString = "".join([letterToBinary(x) for x in input])
print("binaryString", binaryString)
version = calculatePacketVersion(binaryString)
return version |
def readFile(filepath):
f = open(filepath, "r")
content = f.readlines()
return content[0]
def letterToBinary(letter):
map = {
"0": "0000",
"1": "0001",
"2": "0010",
"3": "0011",
"4": "0100",
"5": "0101",
"6": "0110",
"7": "0111",
"8": "1000",
"9": "1001",
"A": "1010",... | The function reads a file's content, converts each character to its binary representation, concatenates these binaries into a single string, and computes a packet value from this binary string. | def second(filepath):
input = readFile(filepath)
binaryString = "".join([letterToBinary(x) for x in input])
return calculatePacketValue(binaryString) |
def match_labels(self):
labels_em = np.argmax(self.posteriors, axis=1)
labels_atlas = np.argmax(self.atlas_map, axis=1)
order = {}
for label in np.unique(labels_atlas):
labels, counts = np.unique(labels_em[labels_atlas == label], return_counts=True)
order[label] =... | This code implements the Expectation-Maximization (EM) algorithm for clustering, initializing model parameters via specified methods (random, kmeans, tissue models, etc.), computing posteriors, and iterating through EM steps to fit a probabilistic model to input data. It handles different initialization strategies, upd... | def fit(self, x: np.ndarray):
""" Runs the EM procedure using the data provided and the configured parameters.
Args:
x (np.ndar ray): Datapoints 2D array, rows=samples, columns=features
"""
self.training = True
self.x = x
self.n_feat = x.shape[1] if np.ndim(x)... |
def __findlastdate(self, file):
"""
Finds and returns the latest date in the file uploaded from the CS3070.
:param str file:
:rtype: str
:return: Finds the latest date in the scanned file.
"""
with open(file, 'r') as f:
lines = f.read().split... | The code processes a CSV file to scan barcodes, handle inventory commands (e.g., delete all, adjust scan groups), and flag potential errors. It deletes existing data for the latest date, parses each line, sends API requests to track scans, adjusts inventory settings, and outputs structured JSON results to the specified... | def processCSV(self, file, outfile):
latestdate = self.__findlastdate(file)
#if this list already exists, delete it.
payload, status = self.__apiquery('POST','/bc/deleteall',**{'scandate': latestdate})
self.scangroup=0 #
previousline=None #
previousgr... |
def __addlineitem(self, line, invoicedate):
"""
Converts a static line from the incoming arinvoice.xls file to a structured dict and uploads to the API.
:param line: A line read from the incoming csv file.
:param invoicedate: Date of invoice.
:rtype: None
"""
l... | The main task of the code is to read an ARinvoice .xls file line by line, sanitize data (e.g., removing invalid characters, fixing dollar amounts >999.99), extract the invoice date, and send processed data to an API. It identifies product lines, cleans formatting, and triggers helper methods for barcode checks, price c... | def processCSV(self, inputfile):
"""
Reads the ARinvoice .xls file line by line and sends to API.
This function will sanitize strings for undesirable characters as well as cleanup dollar amounts >999.99.
This will also extract the invoice date from the file.
:param inputfile: F... |
def grab_tortillas(ingrQty): # refill the taquero's tortillas with the tortillas made from the tortilera
while ingrQty['tortillas'] < 500:
time.sleep(.5)
with lock:
ingrQty['tortillas'] -= 500
return 500
def create_taco(tacos, currentTaco, ingrQty, tortillas):
madeTacos = 0
whil... | The code simulates a "taquero" thread processing taco orders by managing a queue of suborders, coordinating with a tortillera thread to produce tortillas, and using a switch mechanism to handle order prioritization. It tracks order steps (start, resume, pause, complete), ensures taco production, and updates order statu... | def taquero(queue, answersList, ingrQty): # Each "taquero" represents a thread
threadTortillera = Thread(target=produce_tortillas, args=(ingrQty, queue), daemon=True) # Creates thread tortillera, produces the tortillas
threadTortillera.start()
tacos = 2 # Amount of tacos that a "taquero" can make at a ti... |
def _get_device_from_message(self, message):
device = message.data.get("entity", "")
LOG.info(f"Device: {device}")
device_id = self._get_device_id(device)
LOG.info(f"Device ID: {device_id}")
return device, device_id
def _get_device_info(self, device_id):
return [x for x i... | This function retrieves and reports the brightness of a specified device. It extracts device info from the message, checks for brightness data, converts it to a percentage, and responds via dialog. If brightness is unavailable or the device isn't found, it provides corresponding feedback. | def handle_get_brightness_intent(self, message):
LOG.info(message.data)
device, device_id = self._get_device_from_message(message)
if device and device_id:
brightness = self._get_device_info(device_id).get("attributes", {}).get("brightness")
LOG.info(brightness)
... |
def _get_device_from_message(self, message):
device = message.data.get("entity", "")
LOG.info(f"Device: {device}")
device_id = self._get_device_id(device)
LOG.info(f"Device ID: {device_id}")
return device, device_id
def _get_device_info(self, device_id):
return [x for x i... | This function increases a device's brightness by 10% using Home Assistant integration. It retrieves the device and its current brightness, calculates the new value, and triggers a "turn_on" command with updated brightness. If brightness data is unavailable or the device isn't found, it provides appropriate feedback thr... | def handle_increase_brightness_intent(self, message):
device, device_id = self._get_device_from_message(message)
if device and device_id: # If the intent doesn't understand the device, you'll get a device_id but no device
brightness = self._get_device_info(device_id).get("attributes", {}).g... |
def _get_device_from_message(self, message):
device = message.data.get("entity", "")
LOG.info(f"Device: {device}")
device_id = self._get_device_id(device)
LOG.info(f"Device ID: {device_id}")
return device, device_id
def _get_device_info(self, device_id):
return [x for x i... | This function decreases a device's brightness by 10% using Home Assistant value conversions. It retrieves the device from the message, checks its brightness status, calculates the reduced percentage, constructs a function call to "turn_on" with the new brightness value, emits a system message, and acknowledges the acti... | def handle_decrease_brightness_intent(self, message):
device, device_id = self._get_device_from_message(message)
if device and device_id: # If the intent doesn't understand the device, you'll get a device_id but no device
brightness = self._get_device_info(device_id).get("attributes", {}).g... |
def getDate(self):
return [self.getYear(), self.getMonth(), self.getDay()]
def getDayOfWeek(self):
return self.BCDToDec(self.getReg(DS3231_REG_WEEKDAY))
def getTime(self):
return [self.getHour(), self.getMinute(), self.getSecond()] | The code's main task is to concatenate the date, day of the week, and time into a single list. It calls `getDate()` for date components, `getDayOfWeek()` for the weekday name, and `getTime()` for time components, then combines them sequentially in a list format. This aggregates temporal data into a structured output fo... | def getDateTime(self):
return self.getDate() + [self.getDayOfWeek()] + self.getTime() |
def embedding_with_mask(self):
story_embedding = tf.nn.embedding_lookup(self.Embedding, self.story)
query_embedding = tf.nn.embedding_lookup(self.Embedding, self.query)
story_mask = tf.get_variable(
'story_mask',
[self.sequence_length, 1],
initializer = tf.con... | The code performs inference by processing input through an embedding layer with masking, applying either a bidirectional LSTM or BOW encoder based on `use_bi_lstm`, generating hidden states via an RNN, and producing logits through an output module. | def inference(self):
self.embedding_with_mask()
if self.use_bi_lstm:
self.input_encoder_bi_lstm()
else:
self.input_encoder_bow()
self.hidden_state = self.rnn_story()
logits = self.output_module()
return logits |
def input_module(self):
"""encode raw texts into vector representation"""
story_embedding = tf.nn.embedding_lookup(self.Embedding, self.story)
story_embedding = tf.reshape(
story_embedding,
(
self.batch_size,
self.story_length,
... | The code's main task is to perform an inference process by sequentially executing four modules: input processing, question handling, episodic memory management, and answer generation. It returns logits from the answer module, likely for classification or prediction tasks. Each module processes data step-by-step to deri... | def inference(self):
self.input_module()
self.question_module()
self.episodic_memory_module()
logits = self.answer_module()
return logits |
def instantiate_weights(self):
"""define all weights here"""
with tf.variable_scope('output_module'):
self.H = tf.get_variable(
'H',
shape = [self.dimension, self.dimension],
initializer = self.initializer,
)
self.R = tf... | This code initializes a TensorFlow model for sequence classification, setting hyperparameters, placeholders for input data (story, query, answers), and training components (learning rate decay, global step). It defines the model's architecture, loss function, and optimizer, preparing for training on sequence data with ... | def __init__(
self,
num_classes,
learning_rate,
decay_steps,
decay_rate,
sequence_length,
story_length,
vocab_size,
embed_size,
hidden_size,
block_size = 20,
initializer = tf.random_normal_initializer(stddev = 0.1),
... |
def instantiate_weights(self):
"""define all weights here"""
with tf.variable_scope('gru_cell'):
self.W_z = tf.get_variable(
'W_z',
shape = [self.embed_size, self.hidden_size],
initializer = self.initializer,
)
self.U_z ... | This code initializes a neural network model for text processing, setting hyperparameters like learning rate, sequence length, and vocabulary size. It defines placeholders for input data (story, query, answers) and initializes weights, loss functions, and training operations. The model includes learning rate decay, gra... | def __init__(
self,
num_classes,
learning_rate,
decay_steps,
decay_rate,
sequence_length,
story_length,
vocab_size,
embed_size,
hidden_size,
num_pass = 2,
use_gated_gru = True,
decode_with_sequences = False,
... |
def generate_prime(bits):
while True:
prime_candidate = getLowLevelPrime(bits)
if isMillerRabinPassed(prime_candidate):
return prime_candidate
def gcd(a, b):
while b:
a, b = b, a % b
return a
def mod_inverse(a, m):
m0, x0, x1 = m, 0, 1
while a > 1:
q = a /... | This code generates an RSA key pair by selecting two prime numbers, computing their product and Euler's totient function, choosing a public exponent, and calculating the private exponent to return public and private keys. | def generate_keypair(bits):
p = generate_prime(bits)
q = generate_prime(bits)
# print(p,q)
n = p * q
phi = (p - 1) * (q - 1)
e = random.randrange(2, phi)
while gcd(e, phi) != 1:
e = random.randrange(2, phi)
d = mod_inverse(e, phi)
return ((e, n), (d, n)) |
def generate_prime(bits):
while True:
prime_candidate = getLowLevelPrime(bits)
if isMillerRabinPassed(prime_candidate):
return prime_candidate
def gcd(a, b):
while b:
a, b = b, a % b
return a
def mod_inverse(a, m):
m0, x0, x1 = m, 0, 1
while a > 1:
q = a /... | The code generates an RSA key pair by selecting two prime numbers of specified bit length, computing their product (n) and Euler's totient (φ), choosing a public exponent (e) coprime to φ, and calculating the private exponent (d) as the modular inverse of e. It returns the public key (e, n) and private key (d, n) for e... | def generate_keypair(bits):
p = generate_prime(bits)
q = generate_prime(bits)
# print(p,q)
n = p * q
phi = (p - 1) * (q - 1)
e = random.randrange(2, phi)
while gcd(e, phi) != 1:
e = random.randrange(2, phi)
d = mod_inverse(e, phi)
return ((e, n), (d, n)) |
def generate_prime(bits):
while True:
prime_candidate = getLowLevelPrime(bits)
if isMillerRabinPassed(prime_candidate):
return prime_candidate
def gcd(a, b):
while b:
a, b = b, a % b
return a
def mod_inverse(a, m):
m0, x0, x1 = m, 0, 1
while a > 1:
q = a /... | This code generates an RSA key pair consisting of a public key (e, n) and a private key (d, n). It selects two large primes p and q, computes their product n, calculates Euler's totient φ(n), chooses a public exponent e coprime to φ(n), and determines the private exponent d as the modular inverse of e modulo φ(n). | def generate_keypair(bits):
p = generate_prime(bits)
q = generate_prime(bits)
# print(p,q)
n = p * q
phi = (p - 1) * (q - 1)
e = random.randrange(2, phi)
while gcd(e, phi) != 1:
e = random.randrange(2, phi)
d = mod_inverse(e, phi)
return ((e, n), (d, n)) |
def encrypt(public_key, plaintext):
e, n = public_key
encrypted = [mod_pow(ord(char), e, n) for char in plaintext]
return encrypted
def feistel_network_encrypt(plain_text, num_rounds, key):
left_half, right_half = plain_text[:len(plain_text)//2], plain_text[len(plain_text)//2:]
subkeys = generate_su... | The function compares RSA and hybrid (Feistel network) decryption times across multiple samples. It encrypts messages using both methods, measures decryption durations, and plots the results. The graph visualizes how decryption time varies with sample size, highlighting performance differences between RSA and the hybri... | def plot_comparison_graph_decryption(public_key, private_key, key, num_rounds, message, num_samples):
rsa_times = []
hybrid_times = []
encrpypted_key = encrypt(public_key, key)
for i in range(num_samples):
cypher_text_rsa = encrypt(public_key, message[i])
cypher_text_hybrid = feiste... |
def list_dir_contents(self):
Content = {}
c = 1
for i in os.listdir(self.DIR):
print(c, ". "+i)
Content[c] = i
c += 1
return Content
def speak(audio):
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice',... | The code implements a command-line interface for file system navigation and management. It processes user queries to list directory contents, change directories, delete files/folders (by number), and exit. The loop continuously prompts for actions, validates input, and executes corresponding operations like listing ite... | def Start(self):
query = ""
while(True):
if("list contents" in query):
self.list_dir_contents()
elif("change directory" in query):
content = self.list_dir_contents()
content[len(content.keys())+2] = 'Go back...'
spea... |
def load_data_types(self, repository):
# <fixr:datatypes>
# <fixr:datatype name="NumInGroup" baseType="int" added="FIX.4.3">
# <fixr:mappedDatatype standard="XML" base="xs:positiveInteger" builtin="0">
# <fixr:annotation>
# <fixr:documentation purp... | The code initializes an object by parsing an XML file specified by 'filename', extracting its root element, and loading various data components (data types, code sets, fields, components, groups, messages) from the XML structure into the object's attributes. | def __init__(self, filename = None):
if filename == None:
return
self.filename = filename
tree = ET.parse(filename)
repository = tree.getroot()
self.load_data_types(repository)
self.load_code_sets(repository)
self.load_fields(repository)
self.l... |
def create_xml_metadata(self, root):
# <fixr:metadata>
# <dc:title>Orchestra</dc:title>
# <dc:creator>unified2orchestra.xslt script</dc:creator>
# <dc:publisher>FIX Trading Community</dc:publisher>
# <dc:date>2019-03-12T10:11:48.582-05:00</dc:d... | The code generates an XML structure for a FIX protocol repository. It registers namespaces, creates a root element with version/name attributes, and populates it with metadata, data types, code sets, fields, components, groups, and messages via helper methods. The final XML tree is returned as the root element. | def to_xml(self):
# <?xml version="1.0" encoding="UTF-8"?>
# <fixr:repository xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:functx="http://www.functx.com" xmlns:fixr="http://fixprotocol.io/2020/orchestra/repository" xmlns:dc="http://purl.org/dc/elements/1.1/" name="FIX.4.2" version="FIX.4.2" specUrl... |
def parse_csv(filename):
"""parses csv"""
csv_list = []
train_dataset_dict = {}
with open(filename, newline='') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
for row in csv_reader:
csv_list.append(row)
csv_list[0][-1] = CLASS_LABEL
for index_x, label in... | The main task of the code is to build and evaluate a decision tree model. It parses training and test data from CSV files, trains a decision tree (with optional depth parameter), visualizes the tree structure, and applies the model to predict test data outcomes, returning statistically significant results. | def main(arguments):
if len(arguments) < 2:
print("Not enough arguments given")
return -1
csv_train = parse_csv(arguments[0])
csv_test = parse_csv(arguments[1])
if len(arguments) == 3:
depth = arguments[2]
root_node, statistically_highest = fit(csv_train, depth)
else:... |
def loadBrain(self, filename):
if self._verboseMode: print( "Loading brain from %s..." % filename, end="" )
start = time.process_time()
self._brain.restore(filename)
if self._verboseMode:
end = time.process_time() - start
print( "done (%d categories in %.2f second... | The main task of the code is to initialize a system by loading a brain file, learning from specified files, executing commands, and managing the working directory. It starts a timer, loads the brain if provided, changes directories if needed, processes learning files and commands, reverts directory changes, and prints ... | def bootstrap(self, brainFile = None, learnFiles = [], commands = [],
chdir=None):
start = time.process_time()
if brainFile:
self.loadBrain(brainFile)
prev = os.getcwd()
try:
if chdir:
os.chdir( chdir )
if isinstance... |
def _addSession(self, sessionID):
if sessionID in self._sessions:
return
self._sessions[sessionID] = {
self._inputHistory: [],
self._outputHistory: [],
self._inputStack: []
}
def getPredicate(self, name, sessionID = _globalSessionID):
try: ... | The main task of the code is to process input text by splitting it into sentences, maintaining a session-specific conversation history, generating responses for each sentence, and returning the encoded concatenated response. It ensures thread safety using a lock, manages history size limits, and handles encoding/decodi... | def respond(self, input_, sessionID = _globalSessionID):
if len(input_) == 0:
return u""
try: input_ = self._cod.dec(input_)
except UnicodeError: pass
except AttributeError: pass
self._respondLock.acquire()
try:
self._addSession(sessionID)
... |
def switch_driver_handle(driver):
# record window handle of pensioner inquiry page
driver.switch_to.window(driver.window_handles[1])
pensioner_inquiry_handle = driver.current_window_handle
print(pensioner_inquiry_handle)
# switch frames to main
return pensioner_inquiry_handle
def refresh_page(d... | The code automates entering SIN data from a DataFrame into a web form, switches browser frames, performs searches, navigates to member results, and invokes a function to handle downloads. It iterates through each entry, inputs values, triggers searches, clicks result links, and manages driver handles for multi-window o... | def enter_info(driver, search_data_df, home_page_handle):
# loops through all SIN values, inputting them and downloading their associated pdfs
for i in range(0, len(search_data_df)):
# switched to appropriate frame
pensioner_inquiry_handle = switch_driver_handle(driver)
driver.switch_to.... |
def find_search_bar(driver):
# record window handle of I&TS home page
home_page_handle = driver.current_window_handle
print(home_page_handle)
# STEP ONE: Navigate to 'Benefit Payments'
menu = driver.find_element_by_id('mainmenu_bp').click()
# Click on 'Pensioner Information Inquiry'
hidden_s... | This function automates login to a web application by locating username/password fields, inputting credentials, and clicking the login button. It then waits for the homepage, locates a search bar, and calls another function to input data from a DataFrame. The code includes pauses for stability and contains a commented ... | def enter_login_info(driver, search_data_df):
# Find the username field by its id in the HTML markup - will look like [id="uid"]
username = driver.find_element_by_id("j_username")
password = driver.find_element_by_id("j_password")
time.sleep(3)
# ADD PAUSES BETWEEN STEPS
# enter in your personal... |
def update_mini_batch_matrix_based(self, mini_batch: List[tuple], eta):
"""
Update the network's weights and biases by applying gradient descent
using backpropagation to a single mini batch
"""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape... | The main task of the code is to train a neural network using mini-batch stochastic gradient descent. It shuffles training data, splits it into mini-batches, and updates model parameters via either matrix-based or vector-based methods depending on the `speedUp` flag. After each epoch, it evaluates performance on test da... | def SGD(self, training_data: List[tuple], epochs, mini_batch_size, eta, test_data=None):
"""
Train the neural network using mini-batch stochastic gradient descent
"""
for j in range(epochs):
random.shuffle(training_data)
mini_batches = [training_data[k:k + mini_ba... |
def findStartAndEnd(self, contourPoints, targetPoint, startPoint, endPoint):
w, h = targetPoint
wStart, hStart = startPoint
wEnd, hEnd = endPoint
left = -1
right = self.inWidth
startIndex = -1
endIndex = -1
index90Degree = []
for i in range(len(contou... | The code deforms a contour by applying rotations and transformations using upper/lower control points, midpoints, and Bezier curves. It maps original contour points to rotated positions, interpolates between points, and generates refined contours for upper, middle, and lower sections, returning transformed coordinates ... | def deform(self, contourPoints, lineUpper, lineLower, angleUpper, angleLower, isLeft):
#upper control points
lineUpperStart, lineUpperEnd = lineUpper
#find mid point of lineUpper
wLineUpperMid = int((lineUpperStart[0] + lineUpperEnd[0]) / 2)
hLineUpperMid = int((lineUpperSt... |
def create_url():
# Replace with user ID below
user_id = get_id(username)
return "https://api.twitter.com/2/users/{}/mentions".format(user_id)
def get_params():
# Tweet fields are adjustable.
# Options include:
# attachments, author_id, context_annotations,
# conv... | The main task of the code is to execute a series of steps: generate a URL, retrieve parameters, connect to an API endpoint using those parameters, and return the resulting JSON response. The function `main()` orchestrates these operations to fetch and deliver data from a specified endpoint. | def main():
url = create_url()
params = get_params()
json_response = connect_to_endpoint(url, params)
return json_response |
def read_adj_matrix(file_path):
with open(file_path, 'r') as f:
lines = f.readlines()
n = len(lines)
adj_matrix = [[0] * n for _ in range(n)]
for i in range(n):
row = lines[i].split()
for j in range(n):
adj_matrix[i][j] = int(row[j])
return adj_matrix
def is_isomo... | The main task of the code is to check if two graphs, represented by adjacency matrices from input files, are isomorphic. If not, it attempts to modify the first graph using a permutation and rechecks isomorphism. The code outputs whether isomorphism exists directly or requires adjustment, along with the permutation, or... | def main():
if len(sys.argv) != 3:
print("Usage: python main.py data1.txt data22.txt")
return
adj_matrix1 = read_adj_matrix(sys.argv[1])
adj_matrix2 = read_adj_matrix(sys.argv[2])
is_iso, perm = is_isomorphic(adj_matrix1, adj_matrix2)
if is_iso:
print("Isomorphism exists w... |
def rainbowCycle(strip, wait_ms=10, iterations=5):
"""Draw rainbow that uniformly distributes itself across all pixels."""
for j in range(256 * iterations):
for i in range(strip.numPixels()):
strip.setPixelColor(strip.numPixels() - (i + 1), wheel(
(int(i * 256 / strip.numPixe... | The main task of the code is to control an LED strip (PixelRing) to display time-based animations, including startup effects, hour/minute transitions with specific patterns, and continuous clock updates. It initializes the LED configuration, handles time checks, triggers animations (e.g., "flavortown," "crisscross"), a... | def main():
DEBUG = False
#parse arguments here (if any alowed)
#params = read_settings() from yaml
if DEBUG:
#print(help(PixelStrip))
pass
# Default LED strip configuration:
# any parameters that for sure don't need to be changed by settings can be defaulted in the ... |
def event_loop(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
self.pan_input(event)
self.selection_hotkeys(event)
self.menu_click(event)
self.obje... | This method updates game elements and renders the current state. It processes events, updates animations and objects, clears the screen, draws the game level, origin marker, grid lines, and the UI menu, all within a single frame using the provided delta time (dt) for smooth animation and timing. | def run(self, dt):
self.event_loop()
self.animation_update(dt)
self.canvas_objects.update(dt)
self.object_timer.update()
self.display_surface.fill("grey")
self.draw_level()
pygame.draw.circle(self.display_surface, "red", self.origin, 10)
... |
def __all_times(list_box: Listbox) -> None:
""" Create new windows with an time overview of 'both' failed and succeeded interactions"""
(filename, path) = __get_filename_path(list_box)
if filename is None or path is None:
return
__text_in_new_window('All times', filename, get_times(get_summaries... | This function creates six buttons in a Tkinter GUI, each linked to specific callback functions that process or display data from a listbox. Buttons like "All Times" and "Success Logs" trigger actions such as showing all entries, success/failure logs, or counts, with red/green colors for visual distinction. The buttons ... | def __create_function_buttons(window: TkinterDnD.Tk, list_box: Listbox) -> None:
"""" Create buttons with corresponding callback functions """
all_times_button = Button(window, text="All Times",\
command=lambda: __all_times(list_box))
all_times_button.pack(expand=True, side="left", padx=5, pady=5)
... |
def persistence(log_file):
# Persistence menu
while True:
if (log_file is not 0):
log_file.flush()
print("Persistence")
print("1. Find process dlls")
print("2. Find running processes")
print("3. Find scheduled tasks")
print("4. Find all local users")
... | The main task of the code is to provide a menu-driven interface for logging system actions, creating directories, and executing forensic/artifact-related operations (e.g., persistence checks, file inspections, hash functions). It initializes logging if enabled, manages output directories, displays an ASCII banner, and ... | def main():
log_path = ""
log_file = 0
if (args.logging):
# Open the log in the global log variables so other functions can write to it
now = str(datetime.datetime.now())
now = now.replace('.', '')
now = now.replace(':', '')
now = now.replace('-', '')
log_path... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.