dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_conn_cursor() -> psycopg2.extensions.cursor:
conn = psycopg2.connect(
host=os.env['rds_link'],
database="final_project",
port='5432',
user="postgres",
password=os.env['password_pgql'])
cur = conn.cursor()
return conn, cur
def check_user_exists(username):
s... | The code creates a new user in a database by hashing the provided password with SHA-256, checking if the username already exists, and inserting the user if unique. It returns True on success or False if the user exists, logging the activity afterward. | def create_user(username,password):
hashed_password =str(hashlib.sha256(password.encode()).hexdigest())
print(hashed_password)
conn, cursor = get_conn_cursor()
user_exists = check_user_exists(username)
if(user_exists):
return False
insert_user_sql = f'''INSERT INTO public.users(username,... |
def mutate(self, x, gene_pool, pmut):
if random.uniform(0, 1) >= pmut:
return x
n = len(x)
g = len(gene_pool)
c = random.randrange(0, n)
r = random.randrange(c, n)
first_gene = x[c]
second_gene = x[r]
templist = []
for i in range(len(... | This code implements a genetic algorithm to evolve a population of individuals over multiple generations. It iteratively selects, recombines, and mutates individuals to optimize fitness, returning the first individual meeting a threshold or the fittest after max generations. | def genetic_algorithm(self, population, fitness_fn, gene_pool, f_thres=None, ngen=500, pmut=0.02):
"""[Figure 4.8]"""
for i in range(ngen):
population = [self.mutate(self.recombine_ordered(*self.select(2, population, fitness_fn)), gene_pool, pmut)
for i in range(len... |
def G(in_w = (w_hei, w_wid, 1), in_c = (height, width, 3), scale=1):
C = Input(shape=in_c, name='C')
W = Input(shape=in_w, name='W')
w_code = wm_enc(W, scale, 'wm_enc_')
w_code = Reshape(target_shape=(128,128,3), name='wm_code3')(w_code)
w_code = conv_block(w_code, scale, prefix='wm_code_3_encode_... | The code defines a StegoGAN model for watermark embedding, combining a generator (G), reconstructor (R), and two discriminators (D1, D2). It constructs three training models: GR (generates watermarked images and reconstructs watermarks), GD1 (adversarial training with D1), and GD2 (adversarial training with shuffled in... | def stegoGAN(in_w=(w_hei, w_wid, 1), in_c=(height, width, 3)):
G_model = G()
R_model = R()
D1_model = D1()
D2_model = D2()
C = Input(shape=in_c, name='C')
W = Input(shape=in_w, name='W')
M = G_model([C, W])
## models for traning
# a. G connected to R
W_prime = R_model(M)
GR... |
def _run_initial_turn(self) -> None:
"""
Runs logic for the first turn of the human and the bot.
"""
def end_chat(self):
# print('Chat is done')
self.ended_chat = True
# self.chat_done = True
# Save the final chat data
self.final_chat_data = self.get_final... | The main task of the code is to manage a turn-based dialogue between an agent and a bot. It handles initial setup, collects actions from both participants, processes annotations or end-of-dialogue signals, updates the conversation state, and progresses the turn index. It ensures proper message logging, observation shar... | def parley(self):
# print(f'{self.__class__.__name__}:{self.tag}: is at turn {self.task_turn_idx}, with {self.num_turns} pairs of turns needed...')
if self.task_turn_idx == 0:
self._run_initial_turn()
self.task_turn_idx += 2
return
# print(f'{self.__class__.... |
def pixel_length_correction(self, element):
num_total_points = element.area
skeleton = element.image
_, num_diag_points = self.find_structure(skeleton, 'diag')
_, num_mid_points = self.find_structure(skeleton, 'mid')
num_adj_points = num_total_points - num_diag_points - num_mid_p... | This function calculates curvature metrics (mean and median) for each labeled element in an image, using a specified window size and resolution. It corrects pixel length for diagonal measurements, computes Taubin curvature, filters outliers, and returns curvature values alongside element length in millimeters. If enabl... | def analyze_each_curv(self, element, window_size_px, resolution, output_path, name, within_element, fiblog):
"""Calculates curvature for each labeled element in an array.
Parameters
----------
element : Iterable
A list of RegionProperties (most importantly, coordinates) from... |
def filter_curv(self, file, output_directory, save_img, fiblog):
_, fn = os.path.split(file)
img = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
filter_img = skimage.filters.frangi(img)
if save_img:
img_inv = skimage.util.invert(filter_img)
imgname = fn.split('.')[0] + ... | The code performs curvature analysis on an input image by sequentially filtering, binarizing, cleaning, skeletonizing, pruning, and analyzing the image. It processes the image through multiple steps to extract curvature data, ultimately returning a dataframe containing the analyzed curvature results. The function logs ... | def curvature_seq(self, input_file, output_directory, resolution, window_size, window_unit, save_img, within_element, fiblog):
_, fn = os.path.split(input_file)
fiblog.handlers.clear()
fiblog = self.get_logger('fiblog')
fiblog.info('Curvature analysis for {} has been started'.format(fn))... |
def around_cells(self, button):
info = button.grid_info()
mine_count = 0
checked_cells = []
for row in range(3):
for col in range(3):
try:
side_button = self.board.grid_slaves(info["row"]+row-1,info["column"]+col-1)
side... | The main task of the code is to recursively reveal cells and their adjacent cells in a Minesweeper-like game. It checks the clicked cell's surrounding mines, displays the count, and automatically opens all neighboring cells if the count is zero. This process continues recursively for each newly opened cell with zero ad... | def cell_search(self, button):
checked_cells, mine_count = self.around_cells(button)
self.opened_cells.append(button)
self.show_number(button, mine_count)
if mine_count == 0:
self.open_all(button)
for cell in checked_cells:
if cell not in self.opened_cel... |
def cell_search(self, button):
checked_cells, mine_count = self.around_cells(button)
self.opened_cells.append(button)
self.show_number(button, mine_count)
if mine_count == 0:
self.open_all(button)
for cell in checked_cells:
if cell not in self.opened_cel... | This function handles opening a cell in a Minesweeper game. It checks if the cell is flagged (already marked as a mine) and exits if true. If the cell is not a mine, it performs a search and checks for a win. If it is a mine, it reveals all mines. The function prevents interacting with flagged cells and manages game st... | def open_cell(self, button):
if button['background'] == self.flag:
return
if button not in self.mines:
self.cell_search(button)
self.check_win()
else:
self.show_mines() |
def reset_board(self):
self.game_start = False
self.game_end = False
self.timer_enabled = False
self.time = 0
self.used_flags = 0
self.board_cells = []
self.opened_cells = []
self.mines = []
self.flag_counter.configure(text=f'0{self.mine_co... | This code initializes a Minesweeper game interface by setting up the board size, mine count, and UI elements. It creates a top bar with a flag counter, timer, and reset button, then generates a grid of interactive cells for gameplay. | def start_game(self, event, mine_count, board_size):
self.cover.pack_forget()
self.mine_count = mine_count
self.board_size = board_size
self.geometry(f"{self.board_size[0]*(self.cell_size+6)}x{self.board_size[1]*(self.cell_size+6)+50}")
i = tk.PhotoImage(width=1, height=1)
... |
def print_transactions(transactions: list):
print("| {:^10} | {:^10} | {:^10} | {:^20} | {:^10} | {:^20} |".format(
"Transaction Id", "Date", "Amount", "Description", "Type", "Category"
))
print("*" + "-" * 101 + "*")
for transaction in transactions:
transaction_id, date, amount, de... | This function retrieves a user's transactions, allows editing by ID, adjusts the balance based on the original transaction type, updates the transaction details, and recalculates the balance with new data. | def edit_transaction(connection, user_id):
transaction_query = """
SELECT t.TransactionId, t.Date, t.Amount, t.Description, t.Type, c.Name
FROM Transactions t
JOIN Categories c ON t.CategoryId = c.CategoryId
WHERE t.User... |
def clear_shell():
return os.system("cls" if os.name == "nt" else "clear")
def print_menu(menu: dict):
for option, text in menu.items():
print(f"[{option}] {text}")
def enter_transaction(connection, user_id: int) -> list:
date = ch.check_date()
transaction_type = ch.check_transaction_type() ... | This function provides a menu-driven interface for managing user transactions, allowing actions like adding/editing transactions, viewing by category/date, creating categories, and displaying transaction history. It retrieves the user's balance, executes selected operations via database queries, and updates the balance... | def transaction_menu(connection, user_id: int):
get_balance_query = "SELECT Balance FROM Wallets WHERE UserId=?;"
while True:
clear_shell()
last_balance = db.get_data(connection, get_balance_query, (user_id,))[0][0]
print(f"Actual balance: {last_balance}")
print("+--------------... |
def clear_shell():
return os.system("cls" if os.name == "nt" else "clear")
def print_menu(menu: dict):
for option, text in menu.items():
print(f"[{option}] {text}")
def log_in_user(connection):
clear_shell()
# Check if there are any users in the database
query = "SELECT COUNT(*) FROM Users;"... | The main task of the code is to provide a menu-driven interface for a virtual wallet system, allowing users to log in, sign up, or exit. It connects to a database, displays options, processes user input, validates choices, and executes corresponding actions (login/signup) while maintaining the connection until exit. Th... | def main():
connection = db.connect_database("Virtual-Wallet.db")
while True:
clear_shell()
print("+----------------+\n| Virtual Wallet |\n+----------------+")
print_menu(MENU_OPTIONS)
option = ch.check_number("int", "Select and option from the menu: ")
if optio... |
def get_user_phone(prompt: str = 'Enter your phone number in the form 256772111333\n:\t'):
""" Used to get the user phone number"""
phone = input(prompt)
while True:
if len(phone) == 12:
return phone
else:
phone = input(prompt)
def check_number(phone: str):
"""use... | The main task of the code is to enable money transfer between users by verifying the receiver's phone number, prompting for the amount, executing the transfer, updating transaction records, and providing feedback on the transfer status and updated balances. | def transfer(phone: str):
"""used to send money from one user to another"""
receiver = get_user_phone('Enter the reciever number:\t')
verification = check_number(receiver)
if verification:
amount = int(get_user_string('Enter the amount to send:\t'))
money_transfer = transfer_money(phone,... |
def home_file():
file_path = ""
if len(readme_package_names) > 0:
if "nwg-shell" in readme_package_names:
file_path = readme_path("nwg-shell")
elif "nwg-readme-browser" in readme_package_names:
file_path = readme_path("nwg-readme-browser")
else:
file_p... | The function `go_home` checks if a home directory exists, attempts to load its README file, and updates a status label if successful. It accepts variable arguments, retrieves the home path via `home_file()`, verifies its existence, and conditionally executes `load_readme_file()` and `update_status_label()` based on the... | def go_home(*args):
home = home_file()
if home:
if load_readme_file(home):
update_status_label() |
def readme_path(name):
if isinstance(name, str) and name:
if os.path.isfile(f"{config['doc-dir']}/{name}/README.md"):
return f"{config['doc-dir']}/{name}/README.md"
if os.path.isfile(f"{config['doc-dir']}/{name}/readme.md"):
return f"{config['doc-dir']}/{name}/readme.md"
... | This function handles the activation of a flowbox item by retrieving the package name from the clicked item, clearing the webview history, updating global variables to track the last accessed package and its README file path, and attempting to load the README file. If successful, it updates the status label to reflect ... | def on_child_activated(fb, child):
# on flowbox item clicked
package_name = child.get_name()
webview.load_uri("about:blank") # clear history
file_path = readme_path(package_name)
global last_file_path, last_package_name
last_file_path = file_path
last_package_name = package_name
if loa... |
def home_file():
file_path = ""
if len(readme_package_names) > 0:
if "nwg-shell" in readme_package_names:
file_path = readme_path("nwg-shell")
elif "nwg-readme-browser" in readme_package_names:
file_path = readme_path("nwg-readme-browser")
else:
file_p... | This code creates a GUI application for browsing README.md files of software packages. It filters packages based on command-line arguments (internal/config), lists them in a searchable interface, and previews selected READMEs in a webview. The app uses GTK for the UI, WebKit for rendering, and includes features like se... | def main():
GLib.set_prgname('nwg-readme-browser')
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--version", action="version",
version=f"%(prog)s version {__version__}")
parser.add_argument("-i", "--internal", action="store_true",
help="o... |
def fillIdentifiers(self, filename):
line_number = 0
with open(filename, "r") as file:
for line in file:
line_number += 1
for token in self.GetTokensFromLine(line.strip(), separators):
if self.IsIdentifier(token) and token not in reserved +... | The Tokenize method processes a file by tokenizing its content, categorizing tokens into reserved words, operators, separators, identifiers, or constants. It populates a Program Intermediate File (PIF) with codified representations of tokens, referencing identifier and constant tables. Unknown tokens trigger exceptions... | def Tokenize(self, filename):
self.fillIdentifiers(filename)
line_number = 0
with open(filename, "r") as file:
for line in file:
line_number += 1
for token in self.GetTokensFromLine(line.strip(), separators):
if token in reserved +... |
def get_current_date_in_miliseconds():
return math.floor(time.time() * 1000)
def get_formatted_date_as_miliseconds(string_date: str, format: str):
datetime_object = datetime.datetime.strptime(string_date, format)
date_int = math.floor(datetime_object.timestamp() * 1000)
return date_int
def create_and_store_mu... | The function validates and processes CSV data to create APIModel instances, ensuring fields like 'name', 'dni', and 'birth_date' meet specific criteria (non-empty, length, format). It raises exceptions for invalid entries, converts birth_date to milliseconds if needed, and stores valid entities. | def store_entities_from_csv(csv_file: UploadFile):
# Transform the binary file into a text file for the csv reader
text_file = io.TextIOWrapper(csv_file.file, encoding='utf-8')
reader = csv.DictReader(text_file, delimiter=',')
data: list[APIModel] = []
for index, row in enumerate(reader):
creation_date... |
def get_all_possible_moves(self):
moves = []
for r in range(len(self.board)):
for c in range(len(self.board[r])):
turn = self.board[r][c][0]
piece = self.board[r][c][1]
if (turn == 'w' and self.white_move) or (turn == 'b' and not self.white_mov... | This function generates valid chess moves by checking if each potential move leaves the king in check. It iterates through all possible moves, simulates each, checks for check status, removes invalid moves, and determines checkmate/stalemate if no valid moves remain. It temporarily stores and restores enpassant coordin... | def get_valid_moves(self):
temp_enpassant = self.enpassant_coordinates
moves = self.get_all_possible_moves()
for i in reversed(range(len(moves))):
self.make_move(moves[i])
#make move swaps moves, but we need to still check the move players, so we switch it back
... |
def _create_cells(self):
for i in range(self.__num_rows):
self._cells.append([])
for j in range(self.__num_cols):
self._cells[i].append( Cell(
self.__x1 + i*self.__cell_size_x,
self.__y1 ... | This code initializes a maze structure by setting up its dimensions, cell sizes, and window. It creates cells, breaks walls to form paths, sets entrance/exit points, and prepares the maze for solving. The constructor also handles random seed initialization for reproducibility, ensuring the maze is ready for traversal o... | def __init__(
self,
x1,
y1,
num_rows,
num_cols,
cell_size_x,
cell_size_y,
win=None,
seed=None
):
self.__x1 = x1
self.__y1 = y1
self.__num_rows = num_rows
self.__num_col... |
def _resync(self, pts):
self.container = av.open(self.filename)
self.container.gen_pts = True
self.container.streams.video[0].thread_type = "AUTO"
#self.container.streams.video[0].thread_count = 4
self.container.streams.audio[0].thread_type = "AUTO"
self.container.seek(pt... | This code decodes video/audio frames from a container, handling errors by skipping invalid frames, resynchronizing timestamps, and yielding video frames paired with audio peaks. It manages a queue to align audio with video, using seek operations to bypass corrupt data, and ensures smooth frame iteration with error logg... | def frames(self) -> iter:
fail = 0
vs = self.container.streams.video[self.streams.get('video', 0)]
iter = self.container.decode(**self.streams)
while True:
try:
frame = next(iter)
if fail:
log.debug(f"Resync'd after {fail} s... |
def move(self, frames=0, seconds=0, abs=None):
seconds += frames/self.player.frame_rate
if abs is not None:
seconds += abs
else:
seconds += self.position
seconds = max(0, min(seconds, self.player.duration))
self.prev_frame_time = seconds - 1/self.player.f... | This code creates a GUI application for editing video scenes, allowing users to navigate, tag segments (e.g., commercials, intros), and visualize timelines. It initializes a Tkinter window with video controls, scene tagging buttons, timeline maps, and a scroller for precise positioning, enabling editing of video conten... | def __init__(self, video, scenes:list[Scene]=[], logo:tuple=None):
tk.Tk.__init__(self)
self.title("pycommflag editor")
self.player = Player(video, no_deinterlace=True)
self.result = None
self.scenes = scenes
self.position = 0
self.prev_frame_time = 0
sel... |
def website_open():
global driver
options = webdriver.ChromeOptions() # allows for use of ChromeDriver without exceptions flagging up or other bugs that are yet to be removed.
#options.headless = True ... | The code initiates data collection by initializing variables and processing URLs from Agency Central. It opens a website, loads cookies, extracts agency URLs, navigates through pages, and stores collected URLs in a list for later Excel export. The function handles pagination by retrieving next-page URLs and quits the b... | def initiate_data_collection():
global x, agency_url_list
x = 0
agency_url_list = [] # blank list to contain all collected URL's. Will be added to excel at a later stage.
ac_url_list = ["https://www.agencycentral.c... |
def gz(a, b, c):
return pz(a, b, c) * qz(a, b, c)
def df_dz (n, a, apos, b, bpos, c, cpos):
'''
partial f / partial z
f = (c-b)^T (a-b)
apos is the index of a into the 1D grid vector
a is [a_x, a_y, a_z]
'''
gr = np.zeros(n)
gr[apos] = c[2] - b[2]
gr[bpos] = (2 * b[2]) - a[2] - c... | The function `dw_dz` computes the derivative of the quotient `fz(a,b,c)/gz(a,b,c)` using the quotient rule, returning `[(gz * df_dz - fz * dg_dz) / (gz²)]`, where `df_dz` and `dg_dz` are partial derivatives of `fz` and `gz` with respect to `z`, and `a, b, c` with their positions are input parameters. | def dw_dz(n, a, apos, b, bpos, c, cpos):
return ((gz(a, b, c) * df_dz(n, a, apos, b, bpos, c, cpos))
- (fz(a, b, c) * dg_dz(n, a, apos, b, bpos, c, cpos))) / (gz(a, b, c) * gz(a, b, c)) |
def get_vertices(xf, yf, zf):
# list of coordinates of each triangle
return np.array(list(zip(xf, yf, zf)))
def get_curvature(vertices, t_of_v):
'''
return an array containing the curvature at each vertex in vertices
'''
return np.array([vertex_curvature(v, t_of_v, vertices) for v in range(len(v... | The function `generate_surface` optimizes a surface's z-coordinates (`zf`) to match a target curvature (`kappa`) using gradient descent with momentum. It initializes `zf` randomly, adjusts it iteratively to minimize a composite objective function balancing curvature accuracy and smoothness (controlled by `smooth_pen`).... | def generate_surface(smooth_pen, rate, momentum, kappa, xf, yf, t_of_v, niter = 1000, verbose = False, hmap=[0]):
'''
generate the surface that matches the curvature given by kappa
kappa: desired curvature at each point of the mesh - 1D array
smooth_pen: the weight applied to non-smoothness;
... |
def get_triangle_vertices(triangles, xf, yf, zf):
# this is the actual mesh we will plot
return np.array([np.array([[xf[T[0]], yf[T[0]], zf[T[0]]],
[xf[T[1]], yf[T[1]], zf[T[1]]],
[xf[T[2]], yf[T[2]], zf[T[2]]]]) for T in triangles])
def ge... | The main task of the code is to generate a smoothed 3D surface from input curvature data using graph-based regularization. It processes a grid of curvature values, constructs a triangular mesh, computes a Laplacian matrix for smoothing, and iteratively optimizes the surface shape with parameters like smooth_pen and nit... | def main(data, smooth_pen=5, niter=20, hmap=[0]):
global L3
global cmap
global gridsize
# print("\n\ndata")
# print(data)
# df = pd.read_json(json_data)
# csv_string = df.to_csv()
# refc = pd.read_csv(r'python/surface/Data/mark_us_curv.csv', index_col = 0)
# print("\n\nCSV STRING"... |
def get_available_slots(wall: list) -> list[int]:
"""Get the valid slots to drop a token.
Args:
----
wall (list): 2D array of zeros
Returns:
-------
list: list of valid locations
"""
return [col for col in range(COLUMNS_COUNT) if is_slot_available(wall, col)]
def is_final_node(wall... | The code implements the **Minimax algorithm with Alpha-Beta Pruning** to determine the optimal move in a turn-based game (e.g., Connect Four). It evaluates game states by recursively exploring possible moves, alternating between maximizing and minimizing players. The function returns the **best column to play** and its... | def minimax(
wall: list,
depth: int,
alpha: int,
beta: int,
maximizing_player: bool,
) -> tuple[int, int]:
"""Minimax algorithm.
Args:
----
wall (list): 2D array of zeros
depth (int): depth of the search
alpha (int): alpha value
beta (int): beta value
maximizing_play... |
def chunk_text(self, text: str, chunk_size):
startingSentence = 0
wordsInChunk = 0
chunks = []
sentences = sent_tokenize(text)
for i in range(0, len(sentences)):
words = sentences[i].split()
wordsInSentence = len(words)
if wordsInChunk + words... | The code generates question-answer pairs from input text by splitting it into chunks, rephrasing each chunk, and creating contexts from adjacent chunks to form pairs. It removes whitespace, processes each chunk with rephrasing, generates questions from rephrased sentences, and combines them with contextual text for QA ... | def qa_pair_rephrase(self, text):
conext_q_a_pairs = []
text = re.sub(r'[\t\n]', '', text)
chunks = self.chunk_text(text, REPHRASE_CHUNK_SIZE)
for i in range(len(chunks)):
qa_pairs = []
answers = sent_tokenize(self.rephrase(chunks[i]))
if i == len(chun... |
def chunk_text(self, text: str, chunk_size):
startingSentence = 0
wordsInChunk = 0
chunks = []
sentences = sent_tokenize(text)
for i in range(0, len(sentences)):
words = sentences[i].split()
wordsInSentence = len(words)
if wordsInChunk + words... | The code generates question-answer (QA) pairs from an article by splitting it into chunks, summarizing each chunk, and creating QA pairs from the summaries. It returns a list of these QA pairs for use in training or testing QA systems. | def qa_pair_summarize(self, article):
context_q_a_pairs = []
chunks = self.chunk_text(article, SUMMARIZE_CHUNK_SIZE)
for chunk in chunks:
summary = self.summarize(chunk)
context_q_a_pairs += self.question_gen_summaries(summary)
return context_q_a_pairs |
def get_connection_details(line, match):
return {
"usr": match.group(0),
"ip_addr": re.search('((\d+\.)+\d+)', line).group(0),
"date": re.search('[A-Z]\w{2}\s{1,2}\d{1,2}', line).group(0),
"time": re.search('(\d{2}:\d{2}:\d{2})', line).group(0),
}
def print_entry(ip, usr, date, time, msg):
print(f... | This function processes log entries to handle SSH connection attempts. It extracts IP, user, date, and time from input data, then prints connection details based on entry type (attempt, success, failure). For unauthorized access, it checks/blocklists IPs using external methods, terminating connections if necessary. | def handle_new_entry(line, match, entry_type, tail_mode):
conn_info = get_connection_details(line, match)
ip = conn_info['ip_addr']
usr = conn_info['usr']
date = conn_info['date']
time = conn_info['time']
print('\n\n')
if entry_type == 0:
print_entry(ip, usr, date, time, 'tried to connect as')
ch... |
def _update_solver(self, word, states):
def word_breakdown(word, states):
breakdown = {}
for i in range(self.game.word_length):
letter = word[i]
state = states[i]
if letter not in breakdown:
breakdown[letter] = []
... | This code automates solving a Wordle game by initializing a solver, applying constraints from prior guesses, and iteratively generating optimal guesses until the game concludes. It uses historical game data to refine strategies, displaying initial guesses if no prior attempts exist. | def auto_solve(self):
from autosolver import WordleSolver
self.solver = WordleSolver(self.game)
if self.game.guesses > 0:
print('Adding constraints')
for guess in range(self.game.guesses):
word = self.game.history[guess]
states = self.game... |
def set_header(self):
header_font = font.Font(size=15, family='Helvetica')
# txt = f'Word: {self.game.answer}'
print(self.game.answer)
txt = 'Welcome to XY\'s Wordle rip-off'
header = tk.Label(
self.root,
text=txt,
)
header.grid(row=0, colu... | The code initializes and starts a GUI application by setting up interface elements (header, input fields, labels, help row) and launching the main event loop with `root.mainloop()`, enabling user interaction and rendering the graphical window. | def start(self):
self.set_header()
self.create_input()
self.generate_labels()
self.create_help_row()
self.root.mainloop() |
def get_input() -> tuple:
# SCREEN
SCREEN = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption('Connect 4')
# Texts on the Customization
texts = {
"title_text": 'Connect 4 Customization',
"instructions_text": 'Default Values Are Already Selected',
"row_text": '... | The code implements a Connect Four-style game with a graphical interface using Pygame. It initializes the game board, handles player/AI moves, checks for winning conditions, and displays results. The main loop processes input, updates the board, animates pieces, and manages game states, supporting both player vs player... | def main():
global BOARD, ROWS, COLUMNS, WIN_COUNT, WIDTH, HEIGHT
# Board
ROWS, COLUMNS, WIN_COUNT, MODE = get_input()
BOARD = zeros((ROWS, COLUMNS), dtype=int)
# SCREEN
WIDTH = SQUARE_SIZE * COLUMNS
HEIGHT = SQUARE_SIZE * (ROWS + 1)
SCREEN = pg.display.set_mode((WIDTH, HEIGHT))
... |
def identity_map(self, size):
idnty_map = self.Tensor(size[0],2,size[2],size[3])
idnty_map[0,0,:,:].copy_(torch.arange(0,size[2]).repeat(size[3],1).transpose(0,1))
idnty_map[0,1,:,:].copy_(torch.arange(0,size[3]).repeat(size[2],1))
return idnty_map
def find_neural_best_buddies(self, corr... | This code computes and visualizes correspondences between two images A and B using a multi-level neural network algorithm. It extracts features at different scales, identifies best-buddies matches, processes correspondences through clustering and thresholding, and saves results as images and text files. The process inv... | def run(self, A, B):
assert(A.size() == B.size())
image_width = A.size(3)
print("Saving original images...")
util.mkdir(self.save_dir)
util.save_final_image(A, 'original_A', self.save_dir)
util.save_final_image(B, 'original_B', self.save_dir)
self.A = self.Tensor(... |
def handle401(self):
self.send_response(401)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write(bytes("Not Authenticated.", "utf-8"))
def end_headers(self):
self.sendCookie()
self.send_header("Access-Control-Allow-Origin", self.headers["Ori... | This function retrieves a song by ID for authenticated users. It checks if the user is logged in (via sessionData), fetches the song from the database, and returns it as JSON if found. If unauthorized, it returns a 401 error; if the song isn't found, it triggers a 404 response. | def handleGetSongsMember(self, song_id):
if "userId" not in self.sessionData:
self.handle401()
return
db = SongsDB()
oneSong = db.getOneSong(song_id)
if oneSong != None:
# response status code:
self.send_response(200)
# respons... |
def loadSession(self):
# load the cookie data and check for existance of the session ID cookie
self.loadCookie()
if 'sessionId' in self.cookie:
# load the session data for the sessionID
sessionId = self.cookie['sessionId'].value
self.sessionData = SESSION_STOR... | This method handles HTTP GET requests by parsing the URL path to determine the collection name and member ID. It retrieves songs data for a specific member if an ID is provided, or lists all songs otherwise. If the collection isn't "songs", it returns a not-found response. | def do_GET(self):
self.loadSession()
path_parts = self.path.split("/")
if len(path_parts) == 3:
collection_name = path_parts[1]
member_id = path_parts[2]
else:
collection_name = path_parts[1]
member_id = None
if collection_name == ... |
def loadSession(self):
# load the cookie data and check for existance of the session ID cookie
self.loadCookie()
if 'sessionId' in self.cookie:
# load the session data for the sessionID
sessionId = self.cookie['sessionId'].value
self.sessionData = SESSION_STOR... | This method handles HTTP DELETE requests by parsing the URL path to identify a collection name and member ID. If the collection is "songs," it deletes the specified song using `handleDeleteSong`; otherwise, it returns a "Not Found" response via `handleNotFound`.) | def do_DELETE(self):
self.loadSession()
path_parts = self.path.split("/")
if len(path_parts) == 3:
collection_name = path_parts[1]
member_id = path_parts[2]
if collection_name == "songs":
self.handleDeleteSong(member_id)
else:
self.... |
def _get_package(package):
"""Normalize a path by ensuring it is a string.
If the resulting string contains path separators, an exception is raised.
"""
module = _resolve(package)
if not hasattr(module, '__path__'):
raise TypeError("{!r} is not a package".format(package))
return module
... | This function checks if a given name corresponds to a file (not a directory) within a specified package. It normalizes the path, verifies the name exists in the package's contents, and confirms it is a file using is_file(). | def is_resource(package, name):
"""True if name is a resource inside package.
Directories are *not* resources.
"""
package = _get_package(package)
_normalize_path(name)
try:
package_contents = set(contents(package))
except OSError as error:
if error.errno not in (errno.ENOEN... |
def rot_l(field):
field_cp=field.copy()
res=field.copy()
# Reverse each line of the field...
for i in range(len(field_cp)):
field_cp[i]=field_cp[i][::-1]
# ...and transpose that field
res=row_to_collumn(field_cp)
return res
def left(field):
for line in field:
points=shif... | The function `up(field)` simulates an upward movement in a game grid by first rotating the field left, then shifting it left (which may involve merging or scoring points), and finally rotating it back right. It returns the updated field configuration and the points earned during the left shift operation. | def up(field):
# Rotate the field to the left, shift the field left and
# rotate it to the right
field=rot_l(field)
(field,points)=left(field)
field=rot_r(field)
return (field,points) |
def rot_r(field):
# Just rotate the field to the left three times
res=field.copy()
for i in range(3):
res=rot_l(res)
return res
def left(field):
for line in field:
points=shift_left(line)
return (field,points)
def rot_l(field):
field_cp=field.copy()
res=field.copy()
#... | The code performs a sequence of operations on a game field: first rotating it right, then shifting it left (which may involve moving pieces and calculating points), and finally rotating it left again. The main task is to simulate a downward movement of game elements, combining rotations and a left shift to update the f... | def down(field):
# Rotate the field to the right, shift the field left and
# rotate it to the right
field=rot_r(field)
(field,points)=left(field)
field=rot_l(field)
return (field,points) |
def __sort_league_table(self, index):
_list = self.__get_standings_as_list_of_lists()
if index != 1:
_list.sort(key=lambda e: int(e[index]), reverse=self.teams_sort_info[index])
else:
_list.sort(key=lambda e: e[index], reverse=self.teams_sort_info[index])
was_re... | This method creates a GUI league table with sortable columns (Pos., Team, Pts, etc.) and a top scorers section. It initializes labels, buttons for sorting, and populates data using external methods to display standings and top scorers for a default league and season. | def __create_league_table(self):
Label(self.league_table_frame, text="League table",
font=(MainGUI.DEFAULT_APP_FONT, MainGUI.HEADING_SIZE, "bold"),
bg=MainGUI.APP_BLUE_COLOR, fg=MainGUI.APP_GREEN_COLOR).grid(row=2, column=1, columnspan=10)
Label(self.league_table_frame, text=... |
def __initialize_menu_bar(self):
self.menu = Menu(self.root)
self.filemenu = Menu(self.menu, tearoff=0)
self.filemenu.add_command(label="Export league table as excel file", command=self.__export_xlsx)
self.filemenu.add_command(label="Export league table as .txt file", command=self.__expo... | This code initializes a GUI component for a sports application, setting up data structures (standings, scorers) and interface elements (frames, menus, scrollbars). It configures default season values, organizes layout elements, and prepares interactive widgets for league and country selection, enabling dynamic display ... | def __init__(self, root):
self.current_standings = []
self.current_top_scorers = []
self.teams_sort_info = [False for _ in range(self.STANDINGS_INFO_LENGTH)]
self.current_season = MainGUI.DEFAULT_SEASON
self.root = root
self.main_frame = Frame(self.root, bg=MainGUI.APP_G... |
def get_valid(board):
valid_locations = []
for col in range(COLUMN_COUNT):
if is_valid(board, col):
valid_locations.append(col)
return valid_locations
def end_state(board):
return check_win(board, PLAYER_PIECE) or check_win(board, AI_PIECE) or len(get_valid(board)) == 0
def check_win(board, piece):
# Check... | This function implements the alpha-beta pruning algorithm for a game, likely Connect Four, to determine the optimal move for the AI player. It recursively evaluates game states, considering valid moves and terminal conditions, while pruning non-optimal branches to improve efficiency. The function returns the best colum... | def alpha_beta_prune(board, depth, alpha, beta, maximizingPlayer):
valid_locations = get_valid(board)
is_terminal = end_state(board)
if depth == 0 or is_terminal:
if is_terminal:
if check_win(board, AI_PIECE):
return (None, 10000000000000)
elif check_win(board, PLAYER_PIECE):
return (None, -100000000... |
def get_valid(board):
valid_locations = []
for col in range(COLUMN_COUNT):
if is_valid(board, col):
valid_locations.append(col)
return valid_locations
def end_state(board):
return check_win(board, PLAYER_PIECE) or check_win(board, AI_PIECE) or len(get_valid(board)) == 0
def check_win(board, piece):
# Check... | This code implements the Minimax algorithm for a turn-based game, recursively evaluating all possible moves up to a given depth. It determines the optimal column for the AI or player to place a piece by maximizing/minimizing the resulting score, considering terminal states (win/loss/draw) and heuristic evaluations of t... | def mini_max_search(board, depth, score, maximizingPlayer):
valid_locations = get_valid(board)
is_terminal = end_state(board)
if depth == 0 or is_terminal:
if is_terminal:
if check_win(board, AI_PIECE):
return (None, 100000000000000)
elif check_win(board, PLAYER_PIECE):
return (None, -10000000000000)... |
def create_board():
board = np.zeros((ROW_COUNT, COLUMN_COUNT))
return board
def draw_board(board):
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
pygame.draw.rect(screen, BLUE, (c * SQUARESIZE, r * SQUARESIZE + SQUARESIZE, SQUARESIZE, SQUARESIZE))
pygame.draw.circl... | The code implements a Connect Four game loop with AI opponents. It handles player moves, AI strategies (random, blocking, alpha-beta, state-space search), win/draw detection, and real-time board updates using Pygame. The main task is to manage game flow, AI decision-making, and user interaction for a turn-based Connect... | def play():
game_over = False
game_turns = 0
turn = 0
board = create_board()
screen = pygame.display.set_mode(size)
draw_board(board)
pygame.display.update()
print("In play method - ai_type = " + str(ai_type))
NotValidCols = set()
while not game_over:
for event in pygame.... |
def download_by_organisation(experts_folder, grid_id_csv, base_url = 'https://pub.orcid.org/v3.0/') :
'''
Download the experts ids by the organisations they belong to
'''
by_organisation_file = experts_folder+'by_organisation.json'
if os.path.exists(by_organisation_file) :
print('by_organisa... | The main task of the code is to download and process ORCID data for experts. It creates necessary directories, retrieves ORCID IDs from a grid CSV, downloads corresponding XML records, converts them to JSON format, and maps ORCID IDs to expert names, organizing data into structured files for further analysis or use. | def main_download_orcid() :
orcid_folder = base_data_folder + '/orcid/'
experts_folder = orcid_folder + 'experts/'
grid_id_csv = orcid_folder + 'grid_id/grid.csv'
for folder in [orcid_folder, experts_folder] :
if not os.path.exists(folder) :
os.mkdir(folder)
all_orcid, _ = down... |
def gen_city(self, city_prior_dist: Optional[Dict[str, float]] = None) -> str:
"""Generate a random city according to some distribution."""
if not city_prior_dist:
city_prior_dist = self.city_dist
return sample_item(city_prior_dist)
def adjust(dist: Dict[K, float], to_remove: Union[... | The code generates a trip by selecting a starting city (random if unspecified), adjusting city distances to avoid the start city, choosing a destination city, generating merchandise items, and returning a `Trip` object with these details. | def gen_trip(self, from_city: Optional[str] = None) -> Trip:
"""Generate a trip."""
if not from_city:
from_city = self.gen_city()
new_dist = adjust(self.city_dist, from_city)
to_city = self.gen_city(new_dist)
merch_len = self.merch_len_sampler.gen()
merch... |
def debug_print(message):
if debug:
print(f"{Fore.GREEN}Debug: {message} {Fore.RESET}")
def new_game():
print("\nChoose a team:")
# Enumerate Teams and Print them
for i, team_name in enumerate(TEAM_NAMES, 1):
print(f"{i}. {team_name}")
while True:
choice = input("[New_Game] ... | The main task of the code is to display a basketball simulator's main menu, allowing users to choose between starting a new game, loading a saved game, accessing settings, or quitting. It loops until a valid choice is made, executing corresponding functions like `new_game()` or `load_game()` and breaking the loop when ... | def main_menu():
while True:
debug_print(f"{Fore.GREEN}Debug Mode is Enabled{Fore.RESET}")
print(f"{Fore.LIGHTYELLOW_EX}Welcome to the Basketball Simulator!{Fore.RESET}")
print("1. Start a new game")
print("2. Load a saved game")
print("3. Settings")
print("4. Quit")
... |
def show_score(self):
print(f"Current Score:{self.score}")
def in_game_menu(self, team1, team2):
while True:
print(
f"{Fore.CYAN}\n{'*' * 30} IN-GAME MENU {'*' * 30}\n"
f"{Fore.YELLOW}\nChoose what to do:\n"
f"1. Change Strategy\n"
... | The main task of the code is to simulate a sports game with four quarters, allowing user input for strategy choices, tracking scores, and handling overtime if needed. It prints match details, updates scores after each quarter, displays team stats, and determines the game result. The function manages game flow, user int... | def simulate_game(self):
print(
f"\n\nMatch for today : {self.team1.name}, Ovr: {self.team1.get_team_overall()} v.s {self.team2.name} {self.team2.get_team_overall()}\n{self.team1.name}'s star player: {self.team1.get_star_player().name} = Ovr: {self.team1.get_star_player().get_player_overall()}\n{sel... |
def simulate_quarter(self):
if self.ai_vs_ai == False:
debug_print(f"Team1 Active players")
for player in self.team1.players:
debug_print(f"\nPlayer: {player}")
while self.quarter_time > 0: # Checking quarter's Reamaining Time
if self.quarter_time < ... | This code simulates a sports game between two teams, displaying team stats, simulating four quarters with scoring updates, handling overtime if scores are tied, and outputting final results. It manages game flow, including pauses, score tracking, and post-game actions. | def quick_simulate(self):
print(
f"\n\nSimulating : {self.team1.name}, Ovr: {self.team1.get_team_overall()} v.s {self.team2.name} {self.team2.get_team_overall()}\n{self.team1.name}'s star player: {self.team1.get_star_player().name} = Ovr: {self.team1.get_star_player().get_player_overall()}\n{self.te... |
def writeInt(file, val: ctypes.c_int):
file.write(struct.pack('i', val))
def writeUlong(file, val: ctypes.c_ulong):
file.write(struct.pack('Q', val))
def writeString(file, text: str):
length = len(text)
writeLEB128(file, length)
file.write(text.encode())
def writeBool(file, val: bool):
file.writ... | This function serializes a dictionary's data into a file by writing specific fields in a structured format: StreamVersion (int), VTable (unsigned long), Name (string), Size (conditional int with a preceding boolean flag), and RTTI (unsigned long), adhering to a predefined binary structure for data storage. | def writeType(file, val: dict):
writeInt(file, val["StreamVersion"])
writeUlong(file, val["VTable"])
writeString(file, val["Name"])
if val["Size"] != 0:
writeBool(file, True)
writeInt(file, val["Size"])
else:
writeBool(file, False)
writeUlong(file, val["RTTI"]) |
def writeInt(file, val: ctypes.c_int):
file.write(struct.pack('i', val))
def writeUlong(file, val: ctypes.c_ulong):
file.write(struct.pack('Q', val))
def writeBool(file, val: bool):
file.write(struct.pack('?', val))
def writeString(file, text: str):
length = len(text)
writeLEB128(file, length)
f... | The function serializes a dictionary `val` into a binary file by writing specific fields: `StreamVersion`, `Begin`, `End`, `ShortName` (with a boolean flag indicating presence), `FullName` (with a boolean flag), and `Id`. It uses helper functions to write integers, unsigned longs, booleans, and strings, handling option... | def writeFunc(file, val: dict):
writeInt(file, val["StreamVersion"])
writeUlong(file, val["Begin"])
writeUlong(file, val["End"])
if val["ShortName"] != "":
writeBool(file, True)
writeString(file, val["ShortName"])
else:
writeBool(file, False)
if val["FullName"] != "":
... |
def readInt(file) -> ctypes.c_int32:
return struct.Struct("i").unpack_from(file.read(4))[0]
def readUlong(file) -> ctypes.c_ulong:
return struct.Struct("Q").unpack_from(file.read(8))[0]
def readString(file):
length = readLEB128(file)
s = []
for i in range(length):
s.append(readChar(file)... | The code parses structured data from a file into a dictionary with keys "StreamVersion", "VTable", "Name", "Size" (conditionally), and "RTTI", extracting values of specific types (int, ulong, string) and handling optional fields based on a boolean flag. | def parseType(file) -> dict:
t = dict()
t["StreamVersion"] = readInt(file)
t["VTable"] = readUlong(file)
t["Name"] = readString(file)
if readBool(file):
t["Size"] = readInt(file)
else:
t["Size"] = 0
t["RTTI"] = readUlong(file)
return t |
def readInt(file) -> ctypes.c_int32:
return struct.Struct("i").unpack_from(file.read(4))[0]
def readUlong(file) -> ctypes.c_ulong:
return struct.Struct("Q").unpack_from(file.read(8))[0]
def readBool(file) -> bool:
return struct.Struct("?").unpack_from(file.read(1))[0]
def readString(file):
length = read... | The function `parseFunc` reads data from a file and constructs a dictionary with specific keys. It extracts integers, unsigned longs, and strings, conditionally adding `ShortName` and `FullName` based on boolean flags. The dictionary includes `StreamVersion`, `Begin`, `End`, `Id`, and optional names. | def parseFunc(file) -> dict:
f = dict()
f["StreamVersion"] = readInt(file)
f["Begin"] = readUlong(file)
f["End"] = readUlong(file)
if readBool(file):
f["ShortName"] = readString(file)
else:
f["ShortName"] = ""
if readBool(file):
f["FullName"] = readString(file)
el... |
def writeInt(file, val: ctypes.c_int):
file.write(struct.pack('i', val))
def writeType(file, val: dict):
writeInt(file, val["StreamVersion"])
writeUlong(file, val["VTable"])
writeString(file, val["Name"])
if val["Size"] != 0:
writeBool(file, True)
writeInt(file, val["Size"])
else... | The code serializes a dictionary's structured data into a binary file. It writes the StreamVersion, iterates through FileVersion entries, records TypesCount followed by each Type, and writes FunctionsCount with corresponding Functions, using helper functions like writeInt, writeType, and writeFunc to handle specific da... | def writeBin(path, val: dict):
with open(path, "wb") as file:
writeInt(file, val["StreamVersion"])
for v in val["FileVersion"]:
writeInt(file, v)
writeInt(file, val["TypesCount"])
for t in val["Types"]:
writeType(file, t)
writeInt(file, val["FunctionsC... |
def readInt(file) -> ctypes.c_int32:
return struct.Struct("i").unpack_from(file.read(4))[0]
def parseType(file) -> dict:
t = dict()
t["StreamVersion"] = readInt(file)
t["VTable"] = readUlong(file)
t["Name"] = readString(file)
if readBool(file):
t["Size"] = readInt(file)
else:
... | The main task of the code is to read a binary file, parse its structured data (including version numbers, type definitions, and function entries), and return the parsed information as a dictionary with keys like "StreamVersion," "Types," and "Functions". The function reads integers, unpacks binary data using `struct`, ... | def readBin(path) -> dict:
with open(path, "rb") as file:
streamVersion = readInt(file)
fileVersion = struct.Struct("iiii").unpack_from(file.read(4*4))
typesCount = readInt(file)
types = []
for i in range(typesCount):
types.append(parseType(file))
... |
def get_dimensions(blocks, debug):
# get block limits
xmin, xmax, ymin, ymax = get_limits(blocks)
if debug > 0:
print(f"xmin: {xmin} xmax: {xmax} ymin: {ymin} ymax: {ymax}")
# {xpos,ypos} coordinates are based on the top-center point
# of the doc **iff there are no text boxes**. When you add... | The function converts a list of blocks into an SVG document by determining dimensions, writing SVG headers, rendering strokes and text from specific block types, and adding interactive elements like a clickable rectangle for page navigation. It handles different block classes, outputs warnings for unsupported types in ... | def blocks_to_svg(blocks: Iterable[Block], output, debug=0):
"""Convert Blocks to SVG."""
# we need to process the blocks twice to understand the dimensions, so
# let's put the iterable into a list
blocks = list(blocks)
# get document dimensions
svg_doc_info = get_dimensions(blocks, debug)
... |
def get_time_from_header(self, data):
t = data.header.stamp
t = t.secs + t.nsecs*1e-9
if self.collect_t < 0:
self.collect_t = t
return t
def get_range(self, a, b):
self._debug(a, prefix="a: ")
self._debug(b, prefix="b: ")
self._debug(self.theta, prefix... | This function processes LiDAR range data by extracting specific angular ranges (a_deg and b_deg) from the input data. If the time difference since the last collection is within a sync window, it appends the measured ranges to lists (self.a, self.b). When the sync window expires, it calculates the average of collected r... | def get_range_wrapper(self, data):
t = self.get_time_from_header(data)
if t - self.collect_t < self.sync_time:
#TODO: static!
a_idx = int((180.+self.a_deg)/360.*len(data.ranges))
b_idx = int((180.+self.b_deg)/360.*len(data.ranges))
a, b = data.ranges[a_id... |
def build_check_panel(self) -> None:
return Panel(
self.get_panels(),
title="[bold default]" + ("Checking"),
border_style="bold blue",
padding=(2, 2),
)
def determine_file_or_archive(self, f):
return Path(f).suffix in [".zip", ".7z"]
def get_node(s... | The code processes a list of ROM files by checking if they match entries in a DAT file, handling archives by extracting them, updating progress, and generating a report. It uses live updates or a progress bar, processes each ROM, validates matches, and cleans up temporary files, finally displaying statistics and a repo... | def check(self) -> None:
self.console.print("[+] Started check operation..", style="bold yellow")
self.console.print(f"[*] Found {len(self.roms)} files..", style="bold yellow")
check_panel = self.build_check_panel()
if self.args.live:
display_mgr = Live(
che... |
def is_final_solution(self):
"""
Returns True if every element is valid. Should only be used to check condition of the final filled matrix.
Will return False if matrix contains any empty elements.
"""
if 0 in self.matrix:
return False
for i in range(... | This code implements a recursive backtracking algorithm to solve a Sudoku puzzle. It attempts numbers 1-9 in an empty cell (i,j), checks validity, and recursively proceeds to the next empty cell. If no solution is found, it backtracks by resetting the cell. The function returns True upon finding a valid solution, ensur... | def find_solution(self, i, j):
"""
Recursive backtracking algorithm to find a valid solution for the Sudoku matrix.
Returns True if a solution is found.
"""
# Base case
if 0 not in self.matrix:
# Only need to check full validity if no empty cells are present ... |
def reset(self):
"""
Resets the board to the original starting matrix, and removes all green and red borders.
"""
for i in range(constants.ROWS):
for j in range(constants.COLS):
self.current_matrix[i, j] = self.start_matrix[i, j]
self.squares[i... | The code solves a Sudoku puzzle via a GUI by resetting the grid, locating the next empty cell, and invoking a backtracking algorithm to find a valid solution. | def solve_gui(self):
"""
Solves the sudoku puzzle.
"""
self.reset()
start_i, start_j = self.next_loc(0, 0)
self.find_solution(start_i, start_j) |
def __get_selected_range(self) -> tuple[list[int], list[int]]:
"""Get the currenly selected range from the buffer.
Returns:
tuple[list[int], list[int]]: The first position and second position of the
selected range
"""
pos1 = strings_to_ints(self.__nvim.funcs.... | The main task of the code is to extract text from a specified range in a buffer. It retrieves the selected range's start and stop positions, validates them, fetches the text within that range, and returns the text along with its boundaries if successful. Error handling logs issues if the range or text retrieval fails. | def __extract_text_from_buffer(self):
"""Extract selected text from a buffer."""
start, stop = self.__get_selected_range()
if not start or not start:
self.__log(LogLevel.INFO, "Exiting due to error in getting selected range.")
return
text = self.__get_text_from_r... |
def __extract_text_from_buffer(self):
"""Extract selected text from a buffer."""
start, stop = self.__get_selected_range()
if not start or not start:
self.__log(LogLevel.INFO, "Exiting due to error in getting selected range.")
return
text = self.__get_text_from_r... | The main task of the code is to evaluate the selected text as an expression, replace it with the result if different, and handle formatting. It extracts text from the buffer, preprocesses it, evaluates the expression, logs results, and replaces the original range with the formatted output if the evaluation changes the ... | def calculate(self, args):
"""Entrypoint to the plugin.
Will extract the text from the currently selected range,
evaluate it, and then replace the currently selected range with the result.
"""
extract_result = self.__extract_text_from_buffer()
if extract_result:
... |
def __extract_text_from_buffer(self):
"""Extract selected text from a buffer."""
start, stop = self.__get_selected_range()
if not start or not start:
self.__log(LogLevel.INFO, "Exiting due to error in getting selected range.")
return
text = self.__get_text_from_r... | This function extracts a number from a buffer, formats it using a specified or default format, and replaces the original text in the buffer if successful. If extraction or formatting fails, it logs errors and leaves the text unchanged. | def format_number(self, float_format):
"""Extract a number from the buffer and format it with user specified format.
If formatting fails, the text is not replaced.
"""
extract_result = self.__extract_text_from_buffer()
if extract_result:
text, start, stop = extract_r... |
def get_word28(self):
word28 = self.content[self.current_index: self.current_index + 4]
self.current_index += 4
return word28
def parse_bytes(self, k):
result = 0
shift_amt = 0
for i in k:
result |= (i << shift_amt)
shift_amt += 7
return re... | This function parses a symbol table from a binary format by reading the number of entries, iterating through each entry to parse individual symbols, and returning a dictionary containing the count of entries and the list of parsed symbols. | def parse_symbol_table(self):
num_entries = self.get_word28()
num_entries = self.parse_bytes(num_entries)
symbols = []
for i in range(num_entries):
# todo: change
s = self.parse_symbol()
symbols.append(s)
return {
"num_entries": num... |
def get_text7(self):
result = ""
while True:
if self.content[self.current_index] == 0x00:
self.current_index += 1
return result
result += chr(self.content[self.current_index])
self.current_index += 1
def get_filetype(self):
retu... | The function parses an ORC file's structure by reading headers, determining the file type, checking for an entry point, and parsing symbol, relocation, section, and segment tables. It aggregates these parsed components into a dictionary and returns them, representing the file's structural metadata for further processin... | def parse_orcfile_struct(self):
header = self.get_text7()
_type = self.get_filetype()
has_entry_point = self.get_bool()
entry_point = ""
if has_entry_point == 0x01:
entry_point = self.get_word28()
symbol_table = self.parse_symbol_table()
relocation_ta... |
def round_time(tm, mins=15):
discard = datetime.timedelta(
minutes=tm.minute % mins, seconds=tm.second, microseconds=tm.microsecond,
)
tm -= discard
if discard > datetime.timedelta(minutes=mins/2):
tm += datetime.timedelta(minutes=mins)
return tm
def reformat_modvels(startTime, modVe... | The main task of the code is to interpolate model ionospheric velocity data onto DMSP satellite observation points over a specified time interval. It processes input files, preprocesses data, performs spatial interpolation using LinearNDInterpolator, and prepares arrays of interpolated east/north velocity components fo... | def main(
startTime, endTime, sat, potFnFmt, velFnFmt, satFnFmt,
):
assert startTime.day == endTime.day, 'Cannot handle multi-day events yet'
modTime = round_time(startTime + (endTime - startTime) / 2) # time for plotting the model
# Filenames
potFile = os.path.expanduser(startTime.strftime... |
def initializeFirstGenereation(self):
for i in range(50):
self.env.append(self.genereteDNA())
def isGoalGen(self,gen):
if self.utilityFunction(gen):
return True
return False
def crossOverAndMutant(self):
for i in range(1,len(self.env),2):
firstGen = se... | The code implements a genetic algorithm (GA) to find a solution by evolving generations. It initializes the first generation, iterates through each, and checks if the goal is met. If not, it repeatedly applies crossover, mutation, and selection to generate new generations. The loop continues until the goal is achieved,... | def solveGA(self):
self.initializeFirstGenereation()
for gen in self.env:
if self.isGoalGen(gen):
return gen
count = 0
while True:
self.crossOverAndMutant()
self.env = self.makeSelection()
count +=1
if self.goalI... |
def factorize_delay(self, joint_df):
# fix DelayFactor to numeric
self.delay_factor = joint_df['DelayFactor'].factorize()
joint_df['DelayFactor'] = self.delay_factor[0]
return joint_df
def remove_outliers(joint_df):
entries_before = joint_df.shape[0]
joint_df = joint_df[abs(joint... | The main task of the code is to preprocess and clean a combined dataset (X and y) by factorizing delay categories, removing outliers, and integrating weather data from the specified path, returning a cleaned DataFrame ready for training. | def clean_up_train(self, path_to_weather, X, y):
joint_df = X.join(y)
joint_df = self.factorize_delay(joint_df)
joint_df = remove_outliers(joint_df)
joint_df = clean_up_data(joint_df, path_to_weather)
return joint_df |
def print_help():
print('This script parses the trials in the specified folder and outputs a json file with the parsed data.')
print('The script can be run in two modes: per default the user is asked for every trial if it should be included in the output file.')
print('Alternatively, the user can specify th... | The main task of the code is to process XML trial files from a specified directory, map them into structured data, and selectively save accepted trials to a JSON file. It supports flags for remapping, specifying output files, limiting trials, and resuming from previous sessions. The script checks for valid input paths,... | def main():
if len(sys.argv) < 2:
print_help()
return
if '-h' in sys.argv:
print_help()
return
# get path
path = sys.argv[-1]
if not os.path.exists(path):
print('Path does not exist')
return
if not os.path.isdir(path):
print('P... |
def MsgToDictionary(msg, name, data):
try:
dataTmp = dict()
for s in type(msg).__slots__:
val = msg.__getattribute__(s)
MsgToDictionary(val, str(s), dataTmp)
data[name] = dataTmp
except:
if isinstance(msg, list):
listTmp = list()
da... | The code processes ROS bag messages by parsing topic structures, extracting nested message fields, and organizing data with timestamps. It flattens hierarchical data, outputs JSON/CSV based on command-line flags, and returns the structured, flattened dataset for further analysis or storage. | def Analysis(topic, bag):
if '_/' in topic:
topicTmp = topic.split('_/')
topicMember = topicTmp[-1].split('/')
topicMember = filter(None, topicMember)
topicMember[0] = topicTmp[0] + '/' + topicMember[0]
else:
topicMember = topic.split('/')
topicMember = filter(Non... |
def add_embedding_layer(self,input):
# Embedding layer
with tf.variable_scope('embedding',reuse=tf.AUTO_REUSE):
wordVectors = tf.get_variable('word_vectors', initializer=self.wv_initial,trainable=self.fine_tune_word_embedding)
embedded_words = tf.nn.embedding_lookup(wordVectors... | This code builds a neural network model that processes multiple text fields by embedding words, extracting sentence-level features, and combining them into document-level representations. It reshapes inputs, computes features with sentence and document-level functions, concatenates results, and builds a document predic... | def build(self):
features = []
doc_features = []
for i, name in enumerate(self.text_field_names):
input_embedded_words = self.add_embedding_layer(self.input_doc[i])
sentence_input = tf.reshape(input_embedded_words, [-1, self.max_sent_length[name], self.word_embedding_si... |
def add_embedding_layer(self,input):
# Embedding layer
with tf.variable_scope('embedding',reuse=tf.AUTO_REUSE):
wordVectors = tf.get_variable('word_vectors', initializer=self.wv_initial,trainable=self.fine_tune_word_embedding)
embedded_words = tf.nn.embedding_lookup(wordVectors... | This code builds a document-level model by processing each text field through sentence-level feature extraction, applying masks for variable sentence lengths, and combining results for prediction. It constructs embeddings, reshapes tensors, masks sequences, and concatenates features across fields before generating docu... | def build(self):
features = []
doc_features = []
for i, name in enumerate(self.text_field_names):
input_embedded_words = self.add_embedding_layer(self.input_doc[i])
sentence_input = tf.reshape(input_embedded_words, [-1, self.max_sent_length[name], self.word_embedding_si... |
def generate_initial_population(self):
population = []
for i in range(self.N):
x = []
for j in range(self.D):
x.append(random.randint(0, 1))
population.append(x)
# create array contain ony 0's
zero = [0] * self.D
population[0] =... | This code implements a population-based optimization algorithm (likely Cuckoo Search) to find the optimal solution by iteratively improving a population through levy flights, selection of the best solution, and probabilistic replacement. It generates initial solutions, updates them using random perturbations and best-s... | def process(self):
start = time.time()
self.population = self.generate_initial_population()
for iteration in range(self.maxiter):
u = np.random.normal(0, self.sigma, self.D)
v = np.random.normal(0, 1, self.D)
S = u / abs(v) ** (1 / self.beta)
# fi... |
def break_lines(self):
lines = 0
for i in range(1, self.height):
zeros = 0
for j in range(self.width):
if self.field[i][j] == -1:
zeros += 1
if zeros == 0:
lines += 1
for i1 in range(i, 1, -1):
... | This method freezes the current figure by placing its blocks on the game field, clears completed lines, spawns a new figure, and checks for game-over conditions if the new figure collides with existing blocks. | def freeze(self):
for i in range(4):
for j in range(4):
if i * 4 + j in self.figure.image():
self.field[i + self.figure.y][j + self.figure.x] = self.figure.color
self.break_lines()
self.new_figure()
if self.intersects():
self.st... |
def intersects(self,igap=0):
intersection = False
for i in range(4):
for j in range(4):
if i * 4 + j in self.figure.image():
if i + self.figure.y + igap > self.height - 1 or \
j + self.figure.x > self.width - 1 or \
... | The code attempts to rotate the figure, checks for collisions, and adjusts its position if necessary. If rotation causes a collision, it moves left, then right, reverting rotation if all adjustments fail. Finally, it resets the shadow to reflect the new state. | def rotate(self):
old_rotation = self.figure.rotation
self.figure.rotate()
if self.intersects():
self.go_side(-1)
if self.intersects():
self.go_side(+2)
if self.intersects():
self.figure.rotation = old_rotation
self.resetshadow() |
def generate_normal(p_config: dict, p_old_idx: int, p_test_fmt: str = 'normal{}.dat', p_ans_fmt: str = 'normal{}.dat.ans') -> int:
normal_dict = p_config['normal']
mean = normal_dict['mean']
deviation = normal_dict['deviation']
length = normal_dict['length']
for i in range(normal_dict['number']):
... | The main task of the code is to generate test datasets using normal, uniform, and triangular distributions specified in the configuration. It creates an output directory, sequentially invokes distribution-specific generation functions, and saves results. Each function updates an index for ordered file naming, ensuring ... | def generate_tests(p_config: dict) -> None:
# Create output directory if it doesn't exist.
os.makedirs(p_config['output_path'], exist_ok=True)
idx = generate_normal(p_config, 0)
idx = generate_uniform(p_config, idx)
idx = generate_triangle(p_config, idx) |
def set_dynamic_variables(self):
self.files = os.listdir()
self.files.sort()
if self.hidden:
self.files = [i for i in self.files if i[0] != '.']
terminal_columns, terminal_lines = shutil.get_terminal_size()
self.dynamic_height = max(10, terminal_lines - 20)
se... | The main task of the code is to initialize and update an interface by setting dynamic variables, reading directories, clearing previous content, and displaying a banner, directory listings, and command options in a structured sequence. | def callback(self):
self.set_dynamic_variables()
self.read_directories()
self.clear()
self.display_banner()
self.display_directories()
self.display_cmd() |
def calc_bs_ci(bootstrap_pointests, alpha=0.05):
import numpy as np
percentiles = (alpha * 100. / 2., 100. - alpha * 100. / 2.)
return np.percentile(bootstrap_pointests, percentiles, axis=0)
def bootstrap_accuracy(sim_resp_freq_, stimid_by_outcome=None, nboot=1000, seed=None):
import numpy as np
rng... | (The main task of the code is to compare two emotion understanding models—Emotion Reasoning and Emotion Recognition—using empirical data and simulations. It calculates accuracy and bootstrapped confidence intervals for empirical judgments, simulates outcomes under both models, and estimates Bayes Factors to determine w... | def emotion_understanding_simulations(empiricalOutcomeJudgments=None, empiricalEmotionJudgments=None, nboot=None, seed=None, stim_info=None, stimid_by_outcome=None, plotParam=None):
import numpy as np
import pandas as pd
display_param_ = plotParam['display_param']
paths = {'figsOut': plotParam['figsOut... |
def _fetch_tracked_features(self, before_frame=None, feature_name='embedding'):
"""Get feature data from each tracked frame less than before_frame.
Args:
before_frame (int, optional): The maximum frame to from which to
fetch feature data.
feature_name (str): Name... | The function constructs a cost matrix for cell assignment in tracking by using model predictions on features from previous and current frames. It processes embeddings, adjusts for capped tracks, and returns the cost matrix along with predictions for assignment. | def _get_cost_matrix(self, frame):
"""Use the model predictions to build an assignment matrix to be solved.
Args:
frame (int): The frame with cells to assign.
Returns:
tuple: the assignment matrix and the predictions used to build it.
"""
inputs = {}
... |
def _get_cells_in_frame(self, frame):
"""Find the labels of cells in the given frame.
Args:
frame (int): Frame of interest.
Returns:
list: All cell labels in the frame.
"""
cells = np.unique(self._get_frame(self.y, frame))
cells = np.delete(cells... | The function updates tracks by assigning cells in a frame to existing or new tracks using an assignment matrix. It appends cell data (embeddings, centroids, morphologies) to existing tracks, creates new tracks for unassigned cells, and detects divisions by linking daughter cells to parent tracks. It updates tracking la... | def _update_tracks(self, assignments, frame, predictions):
"""Update the graph based on the assignment matrix for the frame.
Use the assignment matrix to determine if each cell in the frame.
belongs to a track or is a daughter of a track, and updates the graph
accordingly.
Args... |
def reset_steps(self):
self.remaining_steps = self.daily_steps_available
def reset_eggs(self):
self.eggs_laid_during_day = 0
def check_life_stage(self):
dead_or_larvae = False
if self.life_stage == LIFE_STAGE.LARVAE and self.current_life_step < self.larvae_period:
dead_or_lar... | The code advances a simulation step by updating life stages, managing steps/eggs, applying SEIR dynamics, facilitating movement, checking house net interactions, handling biting/egg-laying, and assessing house spraying, with day tracking to trigger resets and state transitions. | def step(self):
if self.prev_day != self.model.day_count:
self.current_life_step += 1
self.reset_steps()
self.reset_eggs()
if self.check_life_stage():
self.prev_day = copy(self.model.day_count)
return
self.check_seir()
self.move... |
def set_exact_objects_order(elastic_objs_ids: list, model: Union[Project, Industry, Technology]) -> list:
"""Returns list of objects in the exact order of returned elastic's sorted projects"""
objs_dict = {x.id: x for x in model.objects.filter(id__in=elastic_objs_ids)}
objects = [objs_dict[i] for i in elast... | This code handles project searches and filters using ElasticSearch, dynamically building queries based on user-selected industries, technologies, and search terms. It processes paginated results, applies sorting, and generates aggregated filters for UI elements, updating context for rendering project lists with appropr... | def projects(request):
context = {}
selected_industries_ids = list(map(int, request.GET.getlist('industries')))
selected_technologies_ids = list(map(int, request.GET.getlist('technologies')))
project_search_text = request.GET.get("search")
public_projects_filter = False
if request.path == rever... |
def destroy_default_buttons(self):
self.next_btn.destroy()
self.prev_btn.destroy()
self.status.destroy()
def setup_buttons(self, urls, num):
new = 0
current_vid = urls[num]
webbrowser.open(current_vid, new=new)
# Need to forget the previous buttons\labels to not m... | The function processes user-selected options to determine how to handle video URLs. It updates the UI, destroys default buttons, and executes actions like opening all videos in a browser, enabling click-based navigation, or playing videos locally via VLC. Labels are updated for user feedback, with error handling if no ... | def get_options(self, select, urls, option, urls2): # Takes users selected options and continues depending on them
choice = select.get()
options = option.get()
if options != 'Options':
url_order = RandomVid.get_url_order(choice, urls, urls2)
self.notice_label.grid_forg... |
def composite(self):
bpy.data.scenes['Scene'].render.alpha_mode = 'SKY'
self.__original(True)
self.__shadeless(False)
render = self.tree.nodes['Render Layers']
composite = self.tree.nodes['Composite']
# self.__unlinkInputNodes(composite, inp=0)
self.__linkNodes(re... | This method switches the rendering mode by calling specific processing functions based on the input 'mode' parameter, such as handling composite, albedo, depth, normals, etc., with optional parameters like 'name' and file type adjustments. It raises an error for unrecognized modes. | def changeMode(self, mode, name='shape'):
if mode == 'composite':
self.composite()
elif mode == 'albedo':
self.albedo()
elif mode == 'depth':
self.depth()
elif mode == 'depth_hires':
self.depth(normalize=False)
self.__filetype('... |
def __daily_calories(self):
"""
daily calories calc
amr (active metabolic rate) = daily calories consumption
Sedentary : your AMR = BMR x 1.2
Lightly active : your AMR = BMR x 1.375
Moderately active: your AMR = BMR x 1.55
Very active : your AMR = BMR x 1.725
... | The main task of the code is to generate a structured recommendation dictionary containing diet, activity, and calorie data. It calculates activity durations (bus, car, still, train, walking), computes ratios for transport, walking, and stillness, derives action recommendations, and compiles these with timestamps, dail... | def __dict_of_recommendation(self,time):
daily_calories = self.__daily_calories()
preds = self.__predict()
l = self.__counts_to_minutes()
print(l)
diet = self.__recommend_diet(500)
b,c,s,t,w = l
#transport duration
transport = b+t+c
tr_ratio = self... |
def load_xray():
# open combined xray catalog
dfx = pd.read_csv(CATALOG_DIR)
xray_skycoord = SkyCoord(ra=dfx.RA, dec=dfx.DEC,
frame="icrs", unit=(u.deg))
return dfx[["xray_name", "RA", "DEC", "err_pos_arcsec"]], xray_skycoord
def check_simbad_and_save(packets_to_simbad, sou... | (The main task of the code is to consume Kafka messages containing astronomical data, process them in batches using Simbad queries, and store results in a SQLite database. It validates input parameters, connects to Kafka, processes packets with X-ray catalog checks, and ensures data is saved while logging progress and ... | def main():
parser = argparse.ArgumentParser()
parser.add_argument("date", type=str, help="UTC date as YYMMDD")
parser.add_argument("program_id", type=int, help="Program ID (1 or 2)")
parser.add_argument("suffix", type=str, help="suffix of db")
args = parser.parse_args()
if len(args.date) != 6... |
def max_length(df, padding_value):
"""
Calculate the maximum lengths of columns in a DataFrame along with an additional padding value.
Parameters
----------
df : pandas.DataFrame
DataFrame containing the data.
padding_value : int
Additional padding value to add to the maximum le... | The function `display_results` formats and prints a table summarizing execution time statistics for a tracked function. It takes a DataFrame with mean and standard deviation of line-level execution times, total iteration times, and function metadata. It calculates and displays overall mean/standard deviation, formats l... | def display_results(df, total_time, no_iter, fn_name):
"""
Display tracked function execution results in a well-formatted table.
Parameters
----------
df : pandas.DataFrame
DataFrame containing the calculated mean and standard deviation of execution times for each line.
total_time : lis... |
def get_sim_rgbd_objects(size: int = -1):
ds = get_sim_rgbd_scenes()
size = size if size > -1 else len(ds)
keep_idces = sample(range(len(ds)), size)
crops, labels = [], []
for i, scene in enumerate(ds):
if i not in keep_idces:
continue
rgb = ds.get_image(i)
crops... | The main task of the code is to load and preprocess simulated and real RGB-D object datasets. It maps labels to standardized categories, filters and tokenizes labels/categories, resizes/crops images, converts data to tensors, normalizes pixel values, and optionally saves the processed datasets. The function returns tup... | def load_datasets(img_resize: Tuple[int, int] = (75, 75),
augment: bool = False,
save: Maybe[str] = None) -> Tuple[Tuple[Tensor, Tensor], ...]:
LABELMAP = {
'bowl_3' : 'bowl_2',
'bowl_4' : 'bowl_2',
'cap_1' : 'cap_white',
'cap_3' ... |
def show_name(lst):
name = ""
for i in lst:
i += " "
name += i
return name
def play(current_ball_handler,action,team_1_players,team_2_players):
stays = True
team_1 = team_1_players
team_2 = team_2_players
while action.lower() == "pass" and stays == True:
#this get... | The main task of the code is to simulate a basketball game between two user-specified teams by reading player data from a file, allowing the user to choose actions for ball handlers, tracking scores, and determining the winner. It processes team and player data, alternates possession, and updates scores based on simula... | def main():
data = open("nba.txt","r")
#Now I want the user to choose which team they want to play as
desired_team_1 = input("What team do you want to play as? ")
desired_team_2 = input("What team do you want to go against? ")
desired_team_1 = desired_team_1.split()
desired_team_2 = desired_t... |
def is_parallel_x(self):
if abs(self.slope() - 0) < 1.0e-6:
return True
return False
def y_intercept(self):
if self.is_parallel_y():
return None
return Point(0, self.p1.y - self.slope() * self.p1.x)
def is_parallel_y(self):
if self.slope() == math.inf:
... | This method generates a string representation of a line. If the line is parallel to the x-axis, it returns "y = [y-intercept]". If parallel to the y-axis, it returns "x = [x-intercept]". Otherwise, it returns the slope-intercept form "y = [slope]x + [y-intercept]". | def __str__(self):
if self.is_parallel_x():
return "y = " + str(self.y_intercept().y)
if self.is_parallel_y():
return "x = " + str(self.x_intercept().x)
return "y = " + str(self.slope()) + "x + " + str(self.y_intercept().y) |
def load_model(model_path):
return pickle.load(open(model_path, 'rb'))
def process_input(input_file):
hsv_tiles = img_to_hsv_tiles(input_file, 100, 5, 0.25)
hsv_tiles = np.array(hsv_tiles)
hsv_tiles = hsv_tiles.reshape(hsv_tiles.shape[0], 75)
return hsv_tiles
def pred_to_dict(pred):
label_counts... | The code's main task is to predict an image's label and confidence using a pre-trained model. It loads the model, processes the input image into HSV tiles, performs prediction, converts results to a dictionary, selects the best prediction, and returns the label and confidence score. | def label_img(model_path, img_path):
dt = load_model(model_path)
hsv_tiles = process_input(img_path)
pred = dt.predict(hsv_tiles)
pred_dict = pred_to_dict(pred)
label, confidence = select_best(pred_dict)
return label, confidence |
def load_model(model_path):
return pickle.load(open(model_path, 'rb'))
def process_input(input_file):
hsv_tiles = img_to_hsv_tiles(input_file, 100, 5, 0.25)
hsv_tiles = np.array(hsv_tiles)
hsv_tiles = hsv_tiles.reshape(hsv_tiles.shape[0], 75)
return hsv_tiles
def pred_to_dict(pred):
label_counts... | The main task of the code is to use a pre-trained model to predict labels and confidence scores for input images. It processes each image's HSV tiles, runs predictions, extracts the best label and confidence, and returns lists of labels, confidence scores, and detailed prediction dictionaries for all images. | def label_imgs(model_path, img_paths):
pred_dicts = []
labels = []
conf_scores = []
dt = load_model(model_path)
for img_path in img_paths:
hsv_tiles = process_input(img_path)
pred = dt.predict(hsv_tiles)
pred_dict = pred_to_dict(pred)
label, confidence = select_best(... |
def display(directory):
'''
Receives a directory as inputs and prints all the files that end with mp4
'''
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(".mp4"):
print(file[:-4])
def convert_to_mp3(input_path,output_path):
'''
... | The main task of the code is to remove ads from a video file by converting it to an audio file, then using a sliding window technique to process the audio. The code deletes existing output directories, prompts user input for the video file, converts the selected video to MP3, and applies the sliding_window function wit... | def main():
os.system("rm -r /home/debanjan/Desktop/Code/ML/CDSAML/Code/src/segments/")
# os.system("rm -r /home/debanjan/Desktop/Code/ML/CDSAML/Code/src/out.mp4")
print("Enter the file you want to be ad freed from the list of files")
display(".")
file_input=input("Enter your choice\n")
convert_... |
def get_waypoint_velocity(self, waypoint):
return waypoint.twist.twist.linear.x
def get_next_waypoint(self):
# if self.next_waypoint is None: # If this is the first time we're computing the next waypoint, we have to iterate over all waypoints.
# closest_waypoint = self.get_closest_waypoint()
#... | The code initializes a ROS node to update vehicle waypoints based on traffic signals and current velocity. It subscribes to pose, waypoints, traffic light, and velocity data, then adjusts the waypoints' velocities to stop or slow down near red lights, restoring reference speeds when the light turns green. It publishes ... | def __init__(self):
rospy.init_node('waypoint_updater')
rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb)
self.sub2 = rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb)
# TODO: Add a subscriber for /traffic_waypoint and /obstacle_waypoint below
rospy.Subsc... |
def draw_butt(drawing, butt, x_offset):
sw_corner = scale_dimensions((x_offset, -butt.y_offset))
draw_rectangle(drawing, sw_corner, scale_dimensions((butt.width, butt.height)))
return
def get_natural_x_to_key(marimba, first_post, key_gap ):
x_to_key = {}
curr_x = first_post
for key in marimba.... | The code draws a marimba's structure by rendering its beams, keys, and adjustments. It calculates optimal beam curves (parabolas) for natural and accidental keys, positions keys based on computed coordinates, and visualizes the midbeam width, left/right butts, and beam dimensions. The function uses mathematical curves ... | def draw_marimba(drawing, marimba):
w = marimba.midbeam_width
draw_butt(drawing, marimba.left_butt, -marimba.left_butt.width)
draw_butt(drawing, marimba.right_butt, w)
## naturals
x_to_key = get_natural_x_to_key(marimba, LEFT_POST_GAP, BAR_GAP)
ideal_adjustment, bottom_parabola, top_parabol... |
def initialize_parameters(layers_dim):
parameters = {}
# for i in range(1,len(layers_dim)):
# ni = layers_dim[i-1]
# ni_next = layers_dim[i]
# parameters["W" + str(i)] = np.random.randn(ni_next,ni)*0.01
# parameters["b" + str(i)] = np.zeros([ni_next,1],dtype=int)
with h5py.File("parametersnew.h5","r")as hf:... | This function trains a multi-layer neural network using gradient descent. It initializes parameters, performs forward propagation with ReLU activations (except the final sigmoid), computes cross-entropy cost, executes backpropagation to calculate gradients, and updates parameters iteratively. It optionally tracks and p... | def L_layer_model(X, Y, layers_dims, learning_rate = 0.07, num_iterations = 3000, print_cost=False):#lr was 0.009
costs = [] # keep track of cost
# Parameters initialization. (≈ 1 line of code)
### START CODE HERE ###
parameters = initialize_parameters(layers_dims)
### ... |
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def start_app():
global creds, user_email
while True:
print("""Welcome to
Select an option to continue
[1] Log in to Voting App
[2] Exit""")
userinput = input("Option: ")
if userinput == "1"... | The main task of the code is to initialize an application by clearing the screen, starting the app, and prompting the user for actions through the `main()` function, which orchestrates setup and interaction流程. | def main ():
clear_screen()
start_app()
prompt_for_action() |
def getbin_lcs(tbin, quad_lc, threshold, filtertype, filterorder,
filterwidth, tclip):
"""Return light curves for the 4 quandrants.
Inputs:
tbin - bin time
quad - Light curve file of quadrant
threshold - Threshold count below which count rate is consid... | The code processes and detrends light curves (LCs) from multiple orbits, handling errors, saving individual FITS files, and combining them. It generates detrended LCs for different time bins and bands, logs errors, and combines results across orbits. Additionally, it creates veto detrended LCs, processes veto data, and... | def make_detrended_lc(orbits,outpaths,args,dirname):
# print(orbits[0])
orbitinfo = pd.DataFrame(columns=['outbase','start_of_orbit','end_of_orbit','error_loc',
'error_flag','veto_start','veto_end','veto_error_loc','veto_error_flag'],index=range(le... |
def parse_args():
parser = argparse.ArgumentParser(
description="Cleans the csv data which was recorded with Muse or Crown."
)
parser.add_argument(
"filename", type=str, help="Input filename including path")
parser.add_argument("device", type=str, help="c(rown) or m(use)", choices=['c', ... | The code processes EEG data by reading a CSV file, cleaning it using device-specific functions (muse or crown), removing invalid rows and columns, and saving the cleaned data to an output path. | def main():
args = parse_args()
file_path = Path(args["filename"])
device = args["device"]
out_path = args["out"]
df_eeg = pd.read_csv(file_path, on_bad_lines='skip')
df_eeg = df_eeg.dropna(subset=['timeStamp'])
df_eeg = df_eeg.drop(columns=['no'])
if device == "m":
df_cleaned ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.