dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def metaLoad(path):
out = {}
if os.path.exists(path) is False:
print("metaLoad(): File doesn't exist: %s" % (path))
out = None
else:
with open(path, 'rb') as tmpf:
data = tmpf.read()
magicnum = struct.unpack('<I', data[0x0:0x4])[0]
if magicnum!=0x4... | The function `metaDiffPathArray` processes an input dictionary of paths, comparing data from 'Prev' and 'Cur' entries for each ID. It loads these entries, checks for 'Meta' or 'Ini1' keys, computes their differences using `metaDiff` or `metaDiffIni1`, and stores results in an output dictionary. If loading fails or requ... | def metaDiffPathArray(InPaths):
out = {}
for Id, Paths in InPaths.items():
Prev = metaLoad(Paths['Prev'])
Cur = metaLoad(Paths['Cur'])
if Prev is None or Cur is None:
print("metaDiffPathArray(): Skipping diff for %s since loading Prev/Cur failed." % (Id))
else:
... |
def _renew_triton_client(self, triton_client, model_name: str | None = None, model_version: str | None = None):
if not model_name:
model_name = self.flag.model_name
if not model_version:
model_version = self.flag.model_version
triton_client.is_server_live()
trito... | This method handles model inference requests by processing input data (sequences or dictionaries), validating model specifications, and routing to asynchronous or synchronous execution. It defaults to stored model settings, constructs input lists based on required/optional parameters, and delegates to internal methods ... | def __call__(
self,
sequences_or_dict: list[np.ndarray] | dict[str, list[Any]] | np.ndarray,
parameters: dict | None = None,
model_name: str | None = None,
model_version: str | None = None,
):
if model_name is None:
model_name = self.flag.model_name
... |
def read_all_video_names(root_directories: list) -> pd.DataFrame:
"""This function reads all the .mp4 files inside each directory in root_directories."""
list_of_df = list()
for root_dir in root_directories:
dir_df = read_video_names_from_single_dict(root_dir)
list_of_df.append(dir_df)
... | The main task of the code is to split a dataset of video names into train, validation, and test partitions using stratified sampling based on the "target" column. It first reads video data, extracts unique entries, splits them into 60%/20%/20% subsets, then extends each subset with non-unique entries from the full data... | def main(args):
full_df = read_all_video_names(args.root_directories)
full_df.to_csv(f"{args.folder_destination}/full_data_2022.csv")
uniques_dataset = extract_uniques(full_df)
train_df_uniq, validation_df_uniq, test_df_uniq = tri_split(uniques_dataset, (0.6, 0.2, 0.2), stratify_by="target", random_see... |
def isValidNumber(self,cardNumber):
cardDigits = self.getCardDigits(cardNumber)
if len(cardDigits)>16:
return False
else:
validStart = self.isValidStart(cardDigits)
if validStart:
return self.luhnAlgorithm(cardDigits)
else:
... | The main task of the code is to validate a credit card by checking if the card number, expiration date, CVV code, and holder's name are all valid. It aggregates results from four validation methods and returns `True` only if all are valid, otherwise `False` | def validateCard(self):
validNumber = self.isValidNumber(self.cardNumber)
validDate = self.isValidDate(self.date)
validCVV = False
try:
validCVV = self.isValidCVV(int(self.CVV))
except:
return False
validName = self.isValidName(self.holder... |
def user_left_room(self, player_name):
# we get user's current room
user_room = self.get_user_room(player_name)
# if there isn't any we return -1
if not user_room:
return -1
# we set him as not ready
self.execute_raw("UPDATE user_room SET ready=0 WHERE userna... | The code quickly assigns a player to an open game room with available slots. If no such room exists, it creates a new one. It first removes the player from their current room, then searches for rooms with open spots, updates the selected room's user count, and links the player to it. If no room is found, it creates a n... | def quick_join_room(self, player_name):
# we remove the user from his current room
self.user_left_room(player_name)
# we search for rooms which are open to join
# and haven't reached yet max users
self.cursor.execute("SELECT * FROM game_room WHERE (users<=? and open='TRUE') ORDER... |
def logMessage(message, logType, addSeparator=True):
"""
Name
-----
logMesaage
Description
------------
Helper function use to display the message in terminal and in log.
Parameters
-----------
:param message(required str): the log message to... | The main task of the code is to clone a Git repository into a specified directory if the location exists and is a valid folder. It checks for the folder's existence, constructs the repository URL from the config, executes the `git clone` command, and returns `True` on success or `False` if any step fails, including inv... | def cloneRepository(config, repoName, location):
"""
Name
-----
cloneRepository
Description
------------
Helper function to clone the repository in specific location.
Parameters
-----------
:param config(required dict): the dictionary of conf... |
def _m_Y(self, t, tau, X_t):
a2 = X_t * self._M(t, tau) + integrate.quad(
lambda x: self._M(x, tau) *
(
library.models.model_params.lambda_x * library.models.model_params.X_bar + library.models.model_params.sigma_x ** 2 / self.gamma * HFunction... | This method computes an integrand expression involving terms derived from HFunctions and internal methods, combining weighted contributions from A_1/A_2 functions and exponential factors. It returns the product of a base integrand function and a composite term formed by summing two calculated components, likely for use... | def _integrant_d_g_d_X(self, x, t, X_t):
a1 = (HFunctions.A_1(tau=x - t, gamma=self.gamma / 2) * X_t +
HFunctions.A_2(tau=x - t, gamma=self.gamma / 2)) / self.gamma * 2
a2 = 2 * self._m_Y(t=t, tau=x, X_t=X_t) * HFunctions.A_1(
tau=self.T -
x, gamma=self.gamma) /... |
def _start_page(self):
'''
welocome page for input the information of server
'''
ip = input('Please input the IP of chat server : ')
port = input('Please input the PORT of chat server : ')
self.server_ip = ip if ip else self.server_ip
self.server_port = port if po... | The code initializes a client by configuring server settings, establishing a connection, setting user information, and initiating a dialog loop with other clients. It repeatedly attempts to connect to the specified server IP and port, handling connection failures by prompting reconfiguration. Upon successful connection... | def start(self):
'''
start the client
1,set server config
2,connect server
3,set user informaiton
4,start the dialog with other clients
'''
while True:
self._start_page()
try:
self.client_socket.connect((self.server_... |
def findRoutPlans(alpha, n_customer, N, V, Cat, IT, IT_num, nv, Container_vehicle, locationtuples, RP, A, nmaps, dist, historical_routes, historical_routes_tuples):
# Drichlet distribution of routes
multinomial_ed=[]
for alpha_inside in alpha:
drichlet_mean = dirichlet.mean(alpha_inside)
... | The code implements the NSGA-II (Non-dominated Sorting Genetic Algorithm II) for multi-objective optimization. It evolves a population of solutions over `max_gen` generations to optimize two conflicting objectives (F1 and F2), likely representing metrics like route efficiency and cargo distribution. The algorithm uses ... | def NSGA_II_main(pop, max_gen, n_customer, N, V, Cat, IT, IT_num, nv, Container_vehicle, locationtuples, RP, A, nmaps, dist, historical_routes, historical_routes_tuples):
logger.debug("now running function NSGA_II")
max_gen = max_gen
gen_no = 0
pltF1 = []
pltF2 = []
pltF1... |
def initVariables(n_customer, nv, Cat):
# "rnd" is an object that generate random numbers
rnd = np.random
#"seed(0)" is a method that reset (every time), the same random set of numbers
rnd.seed(0)
# Number of collection points
n_customer = n_customer
# The set of nodes without the depot.
... | The function `rout_finding` solves a multi-objective routing problem (SD-VRP) using DTSA and NSGA-II algorithms to optimize vehicle routes for collecting cargo. It initializes variables, generates populations, iteratively refines routes, and handles uncollected items. The process repeats until all cargo is allocated, s... | def rout_finding(request, collection_points, vehicle_number, cargoe_number):
logger.debug("now running function rout_finding")
if request.method == 'GET' or request.method == 'POST':
collection_points = int(collection_points)
vehicle_number = int(vehicle_number)
cargoe_number = int(cargo... |
def _find_clicked_tile(self, mouse_grid_location: Tuple[int, int]) -> Optional[Tile]:
if 0 <= mouse_grid_location[0] < self.columns and 0 <= mouse_grid_location[1] < self.rows:
clicked_tile = self.tiles[mouse_grid_location[0]][mouse_grid_location[1]]
if not clicked_tile.is_empty:
... | This function handles left mouse clicks on a grid or sidebar. If clicking the grid, it selects or builds an item based on 'to_build'. If clicking the sidebar, it unselects and returns building info. | def left_click(self, mouse_grid_location: Tuple[int, int], mouse_sidebar_location: Optional[int], to_build: Optional[str]) -> Optional[str]:
if mouse_sidebar_location is None:
clicked_tile = self._find_clicked_tile(mouse_grid_location)
if to_build is None:
self.handle_sel... |
def _get_msg_path(self):
"""
matrix: parent-children relation in each message passing step
mask: set of nodes doing message passing at each step
"""
msg_mats, msg_masks = [], []
for job_dag in self._job_dags:
msg_mat, msg_mask = self._get_bottom_up_paths(job_... | The main task of the code is to determine if the input job DAGs have changed compared to the stored ones, update internal graph representations (matrices, masks, backward mappings) if changes are detected, and return these updated structures along with a flag indicating whether the DAGs changed. It ensures consistent g... | def get_msg_path(self, job_dags):
if len(self._job_dags) != len(job_dags):
job_dags_changed = True
else:
job_dags_changed = any(i is not j for i, j in zip(self._job_dags, job_dags))
if job_dags_changed:
self._job_dags = OrderedSet(job_dags)
self._... |
def _generate_global_reference(
path_segments: List[Union[str, int]],
) -> Instance:
"""Generate an instance of a global Reference."""
props = collections.OrderedDict() # type: OrderedDict[str, ValueUnion]
props["type"] = aas_core_meta.v3rc2.Reference_types.Global_reference.value
with _extend_in_... | This function generates test cases for the 'Submodel_element_list' class by creating valid and invalid configurations. It produces positive cases (e.g., missing semantic IDs) and constraint violations (e.g., incorrect data types, mismatched semantic IDs). The code uses replication to generate instances with specific pr... | def _generate_additional_cases_for_submodel_element_list(
replication_map: Mapping[Identifier, _Replication],
constraints_by_class: MutableMapping[
intermediate.ClassUnion, infer_for_schema.ConstraintsByProperty
],
symbol_table: intermediate.SymbolTable,
) -> Iterator[CaseUnion]:
# region De... |
def _generate_primitive_value(
primitive_type: intermediate.PrimitiveType,
path_segments: List[Union[str, int]],
len_constraint: Optional[infer_for_schema.LenConstraint],
pattern_constraints: Optional[Sequence[infer_for_schema.PatternConstraint]],
set_of_primitives_constraint: Optional[infer_for_sch... | The function `_generate_property_value` generates a value based on a given type annotation and constraints. It handles primitive types, enumerations, and class instances recursively. For primitives, it applies constraints like length and patterns. For enumerations, it selects literals using a hash of the path. For clas... | def _generate_property_value(
type_annotation: intermediate.TypeAnnotationExceptOptional,
path_segments: List[Union[str, int]],
len_constraint: Optional[infer_for_schema.LenConstraint],
pattern_constraints: Optional[Sequence[infer_for_schema.PatternConstraint]],
set_of_primitives_constraint: Optiona... |
def _extend_in_place(
path_segments: List[Union[str, int]], extension: Iterable[Union[str, int]]
) -> Iterator[Any]:
"""Extend the ``path_segments`` with the ``extension`` and revert it on exit."""
path_segments.extend(extension)
try:
yield
finally:
for _ in extension:
pa... | The main task of the code is to populate all optional properties of a given instance with minimally valid values based on specified constraints. It iterates through the class's properties, generates appropriate values using recursive instance creation, and applies length, pattern, and enumeration constraints to ensure ... | def make_minimal_instance_complete(
instance: Instance,
path_segments: List[Union[int, str]],
cls: intermediate.ConcreteClass,
constraints_by_class: MutableMapping[
intermediate.ClassUnion, infer_for_schema.ConstraintsByProperty
],
symbol_table: intermediate.SymbolTable,
) -> None:
"... |
def _generate_pid(self):
"""
Generate process id.\n
"""
self._pid = f"{random.randrange(1000, 9999)}_{datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')}"
def _get_merged_config(self, config_file: str) -> dict:
"""
Find and merge configs.\n
config.loca... | The code initializes a logger with MongoDB integration, loading configuration from a JSON file. It sets up a process ID, connects to a MongoDB instance using provided credentials, and configures logging to both standard output and MongoDB. The logger duplicates logs based on configuration, handling connection errors gr... | def __init__(self, collection_name='default_logger', pid='', config_file="monolog.json"):
self._pid = pid
if self._pid == '':
self._generate_pid()
self.config = self._get_merged_config(config_file)
self._current_level = self.config["currentLevel"]
self._collection =... |
def get_name(img_src):
org = cv2.imread(img_src)
cropped = crop(org, [700, 300], [300, 45])
cropped = filter_image(cropped)
name = read_img(cropped)
return name
def get_company(img_src):
org = cv2.imread(img_src)
cropped = crop(org, [700, 765], [300, 45])
cropped = filter_image(cropped)... | The function `process_bio_image` extracts and returns structured information from a bio image, including the name, company, and logo match status. It utilizes three helper functions to gather these details and compiles them into a dictionary for output. | def process_bio_image(img_src):
name = get_name(img_src)
company = get_company(img_src)
matches = does_match_logo(img_src)
return {
"name" : name,
"company": company,
"matches": matches,
} |
def runner(ans):
avg = display_average()
while True:
try:
while avg < 200:
try:
runMotor(ans)
avg = display_average()
except KeyboardInterrupt:
motorStop()
sys.exit(0)
motorStop()
avg = display_average()
except KeyboardInterrupt:
... | The code processes user input to control a fan's speed, offering options for fixed levels (1-4), random speeds, or an increasing sequence. It uses the `runner` function for fixed speeds, while "random" and "increasing" modes adjust motor speed dynamically, monitoring an average value. KeyboardInterrupts are handled to ... | def process(rounded):
ans = input("Which fan speed would you like? (1, 2, 3, 4, increasing, or random)\n")
if ans == "1":
runner(25)
elif ans == "2":
runner(50)
elif ans == "3":
runner(75)
elif ans == "4":
runner(100)
elif ans == "random":
avg = display... |
def set_diffs(amp, freq, trans):
""" # Set Difference Values
Args:
amp (list): amplitutes flutuation list.
freq (list): frequencies flutuation list.
trans (list): transition band variation list.
Returns:
tuple: tuple with difference value for each input params.
"""
... | The main task of the code is to design a digital filter by calculating passband, stopband, and transition band parameters, selecting a window type based on stopband attenuation in dB, determining filter magnitude, and generating the filter coefficients. It then outputs the filter and its normalized version. | def main():
""" # Main
This is a backbone of the project. This Fuction runs all the others.
"""
amplitute_variation = [0.99, 1.01]
frequency_variation = [0, 0.06]
transition_band = [(0.15*math.pi), (0.45*math.pi)]
(passband, stopband, transition_band_diff) = set_diffs(
amplitute_vari... |
def parse_settings() -> dict:
# Attempt to load settings.txt file
try:
# Reads the file and converts the json data into a usable dictionary to be returned. Ignores lines
# starting with '#'.
with open("settings.txt", "r") as file:
json_data = '\n'.join(line for line in file i... | The main task of the code is to initialize and run a game by parsing settings, configuring game parameters, adding rooms/anomalies, and executing a loop that generates anomalies, updates the game state, displays information, and handles user input until the game ends. | def main():
# Loads settings using the parse_settings function.
# Jacob Terkuc
args = parse_settings()
"""
The main function is mostly just here to setup the game and keep it running in a loop.
It has a specific order of events that it follows.
There are a lot of comments in here to help yo... |
def quantity_force(self):
"""Forces the user watch a maximum of 3 episodes"""
while self.episode_quantity > 3:
print('\nNo way! You should actually watch a movie then!')
print('Yes, right. I am programmed to not to let you watch more than 3 episodes')
print('So, again... | The main task of the code is to execute the class's core functionality by managing episode selection—either a specified quantity or dynamically determined—through methods like `quantity_force()` and `episode_quantity_decider()`, then processing episodes via `pure_chance()`, `direct_website()`, or `removal_decider()`, u... | def watch(self, quantity: int = 0, full_random: int = 0):
"""Main method to run the class
@param quantity: number of episodes to watch
@param full_random: indicator of choosing from all existing episodes or not.
Implemented for the 'go' command"""
self.duals =... |
def create_obstacle_item():
global obstacle_item
obstacle_item = canvas.create_image(
1600, random.randint(150, 750), image=obstacle_image1)
return obstacle_item
def obstacle_boundary():
car1_edge = canvas.bbox(car1_frame)
car2_edge = canvas.bbox(car2_frame)
obstacle_edge = canvas.bbox(o... | The code defines a game loop that updates and controls a racing game's elements. It moves track frames, obstacles, boost items, and win lines, checks for player inputs to control car movement, enforces boundaries, evaluates win conditions, and sends updated game states. The loop runs until a time limit is reached or a ... | def game_loop():
shared = game_state['shared']
car1_x, car1_y, car2_x, car2_y, obstacle_x, obstacle_y, boost_x, boost_y = list(
shared.values())[0:8]
shared['player_1'] = game_state['me']
shared['player_2'] = game_state['opponent']
while True:
tk_sleep(win, 1/30)
canvas.move(... |
def print_board(board):
for row in board:
print("|".join(row))
print("-----")
print()
def evaluate(board):
# Check rows, columns, and diagonals for a win
for row in board:
if row.count(PLAYER_X) == 3:
return 10
elif row.count(PLAYER_O) == 3:
return... | The code implements a Tic Tac Toe game where a human player (O) competes against an AI (X). It initializes a 3x3 board, alternates turns, validates moves, checks for wins/ties after each move, and uses an AI strategy (via find_best_move) to determine optimal plays. The game ends when a player wins or the board is full,... | def play_game():
board = [[EMPTY]*3 for _ in range(3)]
print("Welcome to Tic Tac Toe!")
print_board(board)
while True:
# Player's move
while True:
row = int(input("Enter row (0, 1, or 2): "))
col = int(input("Enter column (0, 1, or 2): "))
if board[row... |
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def get_best_move(board):
best_eval = -math.inf
best_move = None
for i, j in get_empty_cells(board):
board[i][j] = "X"
eval = minimax(board, 0, False)
board[i][j] = " "
if eval... | The main task of the code is to implement a Tic-Tac-Toe game where a human player ("X") competes against an AI ("O"). The game alternates turns, validates moves, checks for a win or draw, and displays the board. The AI uses `get_best_move` for its strategy, while the human inputs coordinates. The loop continues until a... | def main():
board = [[" "]*3 for _ in range(3)]
current_player = "X"
while True:
print_board(board)
if current_player == "X":
i, j = map(int, input("Enter row and column (0-2) for your move: ").split())
if board[i][j] != " ":
print("Cell already o... |
def print_board(board):
for row in board:
print("|".join(row))
print("-" * (BOARD_SIZE * 2 - 1))
def check_winner(board, player):
# Check rows
for row in board:
if all(cell == player for cell in row):
return True
# Check columns
for col in range(BOARD_SIZE):
... | The main task of the code is to implement a Tic-Tac-Toe game where a player competes against an AI. The game initializes a board, alternates between player and AI moves, validates inputs, updates the board, checks for a win or tie after each move, and declares the result. The AI uses a function to determine its optimal... | def play_game():
board = [[EMPTY] * BOARD_SIZE for _ in range(BOARD_SIZE)]
print("Welcome to Tic-Tac-Toe!")
print_board(board)
while True:
# Player's move
row, col = map(int, input("Enter row and column for your move (e.g., 1 2): ").split())
row -= 1
col -= 1
if b... |
def initialise_grid(self):
"""
Create an empty grid with empty cells, and determine the neighbors and field neighbours of the cell
:return: grid
"""
grid = np.empty((self.n, self.n), dtype=object)
for i in range(self.n):
for j in range(self.n):
... | This code initializes a simulation model for urban land-use dynamics, setting parameters for grid size, decay rates, activity thresholds, and initial conditions. It configures thresholds governing transitions between housing, industry, stores, and streets, initializes a grid, and sets up initial street networks and act... | def __init__(self, n=100, n_radius=1, field_radius=2, street_field_radius=3, n_init=4, n_house_inits=2, init_decay=1/30, mature_decay=1/20, dist_decay=0.9, \
street_thresholds={'activity':0.2}, \
... |
def street_check(self, new_street_nodes):
"""
Loop through list to see which new street nodes can be build
:param new_street_nodes: list with all new street nodes
:return: added nodes
"""
new_nodes = []
for node in new_street_nodes:
new_node_neighborho... | This code generates new street nodes by checking growth candidates for each existing node, verifies if positions are vacant, and lays streets between valid nodes when space is available, ensuring proper street expansion within the environment. | def initiate_streets(self):
"""
Do all checks and make a street
"""
new_nodes = []
for node in self.street_nodes:
new_nodes += [self.street_check(self.get_grow_candidates(node))]
for i in range(len(self.street_nodes)):
init_node = self.street_nodes... |
def determine_activity(self, grow_candidates):
"""
Loop through list with candidates, check what the initial node for activity had, check the neighbours of the
candidate and determine what the new activity is going to be
:param grow_candidates: list with candidates
:return: list ... | The main task of the code is to process all 'init' state activities by identifying potential growth candidates, determining new cell positions and types, and spawning new activities at these positions. It iterates through initial activities, checks their growth candidates, filters unique positions, and adds correspondi... | def initiate_activity(self):
"""
Go through all activities that are in the init state, then check if they can spawn a new cell
"""
init_sites = [act for act in self.all_activities if act.type == 'init']
new_positions = []
new_type = []
for act in init_sites:
... |
def update_types(self):
"""
Updates the types of a given activity
:return: does not return anythhing
"""
for act in self.all_activities:
act.calc_probs()
probsum = cumsum(np.array([act.pi, act.pm, act.pd]))
z = np.random.rand()
if z < ... | The code advances the simulation by one time step, updates activity types, initializes new streets and activities, removes declining elements, and logs counts of housing, industry, and store activities into separate lists for analysis. | def step(self):
"""
Take time step, make new streets and activities, update all the lists
"""
self.t += 1
self.update_types()
self.initiate_streets()
self.initiate_activity()
self.delete_declining()
self.activities[0] += [sum([1 for act in self.all... |
def file_check(self):
file = pathlib.Path(self.nodes_file)
if file.exists():
file_read = open(self.nodes_file, "r")
file_read.seek(0)
data = file_read.read()
file_read.close()
json_file = json.loads(data)
self.nodes.update... | The code initializes a blockchain, checks the network, and creates a new block with a specific address if it's the first node. Otherwise, it replaces the chain. It manages nodes, transactions, and the blockchain's state, ensuring proper setup for a distributed network. | def __init__(self):
self.chain = []
self.transaction = [] #mempools
self.nodes_file = "nodes.json"
self.nodes = {} #empty set
self.url_address = "127.0.0.1:5001"
#print(self.read_node())
network = self.file_check()#read_node()
print(network)
#self.... |
def fill_queues(self):
print('\n----FILL----')
for queue in self.queues:
for flow in queue.flows:
if self.time >= flow.start_time and flow.num_packets > 0 and flow.completion_time is None:
added_packets = flow.send()
dropped = 0
... | The code simulates a time step in a queuing system by updating channel quality indicators (CQI), incrementing the simulation time, filling queues with data, and draining queues based on the selected scheduling algorithm (RR or PF). The CQI is temporarily set to a placeholder value of 1 for all queues. | def simulate_time_step(self):
#self.cqi = [random.randint(1,15) for _ in range(len(self.queues))] # place holder for actual channel condition function
self.cqi = [1 for _ in range(len(self.queues))] # place holder for actual channel condition function
self.time += 1
self.fill_queues()
... |
def new_tetromino(self):
if not self.tetromino.movement:
self.tetromino_count[self.tetromino.tetromino_object.shape] += 1
self.tetromino_to_square_row_group()
self.tetromino = self.next_tetromino
# noinspection PyTypeChecker
self.next_tetromino = Tetro... | This code handles user input for controlling a Tetromino in a game (e.g., Tetris), updates game state (movement, rotation, game over), renders game elements (tetromino, statistics, UI), and returns the speed value. It processes key events for directional control, rotation, cheats, and game mechanics, updating the displ... | def run(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
# print(event.key)
if event.key == pygame.K_DOWN:
# move tetromino Dow... |
def contains(text, pattern):
"""Return a boolean indicating whether pattern occurs in text."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
# TODO: Implement contains here (iteratively and/or recursively... | The code tests string algorithms by checking if a pattern exists in a text, finding its first occurrence index, and listing all occurrence indexes. It uses functions `contains`, `find_index`, and `find_all_indexes` to validate implementations, printing results for verification. | def test_string_algorithms(text, pattern):
found = contains(text, pattern)
print('contains({!r}, {!r}) => {}'.format(text, pattern, found))
# TODO: Uncomment these lines after you implement find_index
index = find_index(text, pattern)
print('find_index({!r}, {!r}) => {}'.format(text, pattern, index)... |
def process_target(df):
df['target'] = df['num'].apply(lambda x: 1 if x > 0 else 0)
df.drop('num', axis=1, inplace=True)
return df
def print_info(df):
pd.set_option('display.max_columns', None)
print('Dataframe shape:', df.shape, '\n')
print('Dataframe sample: \n', df.sample(5), '\n')
print(... | The code's main task is to load a heart disease dataset, handle file not found errors by fetching data if needed, preprocess the target variable, clean data by removing missing values, detect outliers, and generate visualizations. It ensures data availability, performs cleaning, and facilitates exploratory data analysi... | def main():
try:
df = pd.read_csv('heart_disease.csv')
except FileNotFoundError:
fetch_data()
try:
df = pd.read_csv('heart_disease.csv')
except FileNotFoundError:
print('Error fetching data. Please try again.')
exit(1)
df = process_target(... |
def KN_pipeline(X_train, X_test, y_train, y_test):
pipeline = Pipeline([
('imputer', SimpleImputer(strategy='mean')),
('scaler', StandardScaler()),
('clf', KNeighborsClassifier())
])
cv_scores = cross_val_score(pipeline, X_train, y_train, cv=5, scoring='accuracy')
print('\n', '... | The code iteratively evaluates four machine learning models (KNN, Logistic Regression, SVM, XGBoost) on multiple train-test splits of the dataset. For each iteration, it trains and tests the models, records their accuracies, and computes the mean accuracy across all iterations. Finally, it visualizes the performance me... | def evaluate_models_iteratively(X, y, num):
accuracies = {'KNeighbors': [], 'Logistic Regression': [], 'SVM': [], 'XGBoost': []}
for i in range(num):
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
KN_acc = KN_pipeline(X_train, X_test, y_train, y_test)
LR_acc =... |
def KN_pipeline(X_train, X_test, y_train, y_test):
pipeline = Pipeline([
('imputer', SimpleImputer(strategy='mean')),
('scaler', StandardScaler()),
('clf', KNeighborsClassifier())
])
cv_scores = cross_val_score(pipeline, X_train, y_train, cv=5, scoring='accuracy')
print('\n', '... | The function evaluates four machine learning models (KNN, Logistic Regression, SVM, XGBoost) on a given dataset by splitting it into training and test sets. It trains and assesses each model's performance using the same data split, providing a comparative analysis of their accuracy or other metrics in a single executio... | def evaluate_models_once(X, y):
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
KN_pipeline(X_train, X_test, y_train, y_test)
LR_pipeline(X_train, X_test, y_train, y_test)
SVM_pipeline(X_train, X_test, y_train, y_test)
XGBoost_pipeline(X_train, X_test, y_tr... |
def process_target(df):
df['target'] = df['num'].apply(lambda x: 1 if x > 0 else 0)
df.drop('num', axis=1, inplace=True)
return df
def handle_outliers(df):
for col in ['age', 'trestbps', 'chol', 'thalach', 'oldpeak']:
q1 = df[col].quantile(0.25)
q3 = df[col].quantile(0.75)
iqr = ... | The main task of the code is to load and preprocess a heart disease dataset, then evaluate machine learning models on it. It attempts to read a CSV file, fetches data if missing, cleans the dataset by removing missing values and outliers, processes the target variable, and splits features/targets. Finally, it iterative... | def main():
try:
df = pd.read_csv('heart_disease.csv')
except FileNotFoundError:
fetch_data()
try:
df = pd.read_csv('heart_disease.csv')
except FileNotFoundError:
print('Error fetching data. Please try again.')
exit(1)
df = df.dropna().res... |
def _este_check_jucator_curent(self):
for miscari in self.miscari_jucator(not self.index_jucator_curent):
for miscare in miscari:
if type(miscare) == Capturare and type(miscare.piesa_tinta) == Rege:
return True
return False
def miscari_jucator(self, index_... | This function checks if the current player is in checkmate. It first verifies if the player is in check. If not, it returns False. Then, it iterates through all possible moves of the current player. For each move, it checks if there are any legal moves available. If any legal moves exist, it returns False. If no legal ... | def _este_checkmate_jucator_curent(self):
if self._este_check_jucator_curent() == False:
return False
for miscari in self.miscari_jucator(self.index_jucator_curent):
miscari_legale = self.piesa_miscari_legale(miscari)
if len(miscari_legale) > 0:
return... |
def _este_check_jucator_curent(self):
for miscari in self.miscari_jucator(not self.index_jucator_curent):
for miscare in miscari:
if type(miscare) == Capturare and type(miscare.piesa_tinta) == Rege:
return True
return False
def miscari_jucator(self, index_... | This function checks if the current player is in stalemate. It first verifies if the player is in check; if so, it returns False. Then, it iterates through all possible moves for the current player's pieces, checking if any legal moves exist. If any legal moves are found, it returns False. If no legal moves exist and t... | def _este_stalemate_jucator_curent(self):
if self._este_check_jucator_curent():
return False
for miscari in self.miscari_jucator(self.index_jucator_curent):
miscari_legale = self.piesa_miscari_legale(miscari)
if len(miscari_legale) > 0:
return False
... |
def layout_configurare(self):
self.layout.setSpacing(0)
self.layout.setContentsMargins(0, 0, 0, 0)
def creere_background(self):
for i in range(self.randuri):
self.patratele_background.append([])
for j in range(self.coloane):
patratica = Patratica(
... | This code initializes a chessboard GUI by setting up an 8x8 grid, configuring the layout, creating the background squares, and preparing the piece placement structure. It initializes attributes for rows, columns, background squares, piece storage, and graphical elements, then calls methods to configure the grid layout ... | def __init__(self, joc_de_sah):
self.joc_de_sah = joc_de_sah
self.randuri = 8
self.coloane = 8
self.patratele_background = []
self.piese = [[None for c in range(self.coloane)]
for r in range(self.randuri)]
self.piese_grafica_de_sters = set()
... |
def piesa_miscari_legale(self, miscari_piesa):
miscari_legale = []
for miscare in miscari_piesa:
miscare.executa()
if self._este_check_jucator_curent() == False:
miscari_legale.append(miscare)
miscare.anuleaza()
return miscari_legale
def actual... | This function handles mouse click events for a game piece. On left-click, it calculates and updates the piece's legal moves; on right-click, it removes displayed move options. | def piesa_click_event(self, e, piesa):
mouse_butoane = e.buttons()
if mouse_butoane & Qt.LeftButton:
miscari_piesa = piesa.miscari_posibile()
miscari_piesa = self.piesa_miscari_legale(miscari_piesa)
self.actualizare_miscari_posibile(miscari_piesa)
elif mouse_b... |
def _este_stalemate_jucator_curent(self):
if self._este_check_jucator_curent():
return False
for miscari in self.miscari_jucator(self.index_jucator_curent):
miscari_legale = self.piesa_miscari_legale(miscari)
if len(miscari_legale) > 0:
return False
... | The main task of the code is to determine the current game state (check, checkmate, or stalemate) for the active player by evaluating internal game conditions. It updates a UI label with the corresponding status ("Stalemate," "Checkmate," or "Check") if applicable, or hides the label if no critical state is detected. T... | def stare_joc(self):
if len(self.miscari_facute) == 3:
pass
self.este_check_jucator_curent = False
self.este_checkmate_jucator_curent = False
self.este_stalemate_jucator_curent = False
if self._este_stalemate_jucator_curent():
self.este_stalemate_jucator_c... |
def is_random(self, eval=False):
# Use e-greedy for evaluation.
if self.steps < self.start_steps:
return True
if eval:
return np.random.rand() < self.epsilon_eval
if self.noisy_net:
return False
return np.random.rand() < self.epsilon_train.get(... | The `train_episode` method trains a reinforcement learning agent by interacting with an environment. It initializes training parameters, runs episodes until completion or max steps, and selects actions via exploration (random) or exploitation (using Q-values or variant methods). Transitions (state, action, reward, next... | def train_episode(self):
self.online_net.train()
self.target_net.train()
self.episodes += 1
episode_return = 0.
episode_steps = 0
done = False
state = self.env.reset()
gaps = []
while (not done) and episode_steps <= self.max_episode_steps:
... |
def send_alert_water_leakage(self, value):
return self.send_alert_generic(value)
def send_alert_battery(self, value):
did = self.config['domoticz_id_battery']
if int(didb) < 0:
print("Domoticz battery ID not set, bailout.")
return
if value == 'high':
c... | The main task of the code is to process incoming sensor messages by determining the type of alert to send based on the 'code' parameter. It logs the event timestamp, device UID, message code, value, and alert status. The function handles water leakage, battery state, and generic alerts, ensuring appropriate notificatio... | def handle_msg(self, code, value):
t = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
if code == 'watersensor_state':
ret = self.send_alert_water_leakage(value)
elif code == 'battery_state':
ret = self.send_alert_battery(value)
else:
# although this is ... |
def tool_classes() -> Any:
return [{
"id": "workflow",
"name": "Workflow",
"description": "A computational workflow",
}]
def versions(out_dir: Path, meta_vec: Any) -> Any:
versions = [version(out_dir, meta) for meta in meta_vec]
_id = meta_vec[0]["id"]
dump(out_dir, f"tools/{... | The code generates a JSON object describing a tool, extracting metadata like ID, name, organization, and description from `meta_vec`, adding a checker URL, and version info. It saves this object to a file in `out_dir` and returns it. | def tool(out_dir: Path, meta_vec: Any) -> Any:
tool_obj = {
"url": "<FIX ME>",
"id": meta_vec[0]["id"],
"organization": ", ".join([a["name"] for a in meta_vec[0]["authors"]]),
"name": meta_vec[0]["workflow"]["name"],
"toolclass": tool_classes()[0],
"description": meta... |
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("-w", required=True, help="WES location where the test will be run.")
parser.add_argument("metadata_locations", nargs="+", help="Location of the Yevis metadata files (only local file)")
args = parser.parse_arg... | The code's main task is to test workflows using a WES service by parsing command-line arguments, loading metadata from specified files, and executing test cases. It iterates through each metadata entry, submits runs to the WES endpoint, monitors their status in a loop, and prints completion or failure outcomes for each... | def main() -> None:
args = parse_args()
wes_loc = args.w
metadata_locs = args.metadata_locations
meta_vec = []
for metadata_loc in metadata_locs:
with open(metadata_loc, "r") as f:
metadata = yaml.safe_load(f)
meta_vec.append(metadata)
print("Running test")
get_s... |
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("-o", required=True, help="Location of the output directory")
parser.add_argument("metadata_locations", nargs="+", help="Location of the Yevis metadata files (only local file)")
args = parser.parse_args()
... | The code processes command-line arguments, reads metadata files from specified locations, aggregates them, and generates output files ("service-info" and "toolClasses") in a resolved directory. It then calls a `tools` function with the output directory and metadata to further process or organize the data. | def main() -> None:
args = parse_args()
out_dir = Path(args.o).resolve()
metadata_locs = args.metadata_locations
meta_vec = []
for metadata_loc in metadata_locs:
with open(metadata_loc, "r") as f:
metadata = yaml.safe_load(f)
meta_vec.append(metadata)
dump(out_dir, "s... |
def find_first_point(self):
"""Find nodes in front of bot, then find the closest one.
Returns:
Vertex: The closest node to the robot
"""
nodes = []
for node in self.graph:
# p = self.global_to_robot_frame(node.coordinates)
p = self.transform_f... | The main task of the code is to navigate a robot along a precomputed shortest path in a graph-based environment. It starts by identifying the first point and goal node, then iteratively moves the robot from one intersection to the next using calculated headings and directional instructions, logging each step. The robot... | def main(self):
"""Main loop of robot
"""
# self.go_to_goal(self.p)
v = self.graph.get_vertex("J")
first_point = self.find_first_point()
(goal_node, _) = self.nearest_node(v.coordinates)
path = self.find_shortest_path(
first_point.get_id(), goal_node.g... |
def _train_validation_split(
self,
train_x : np.ndarray,
train_y : np.ndarray,
validation_ratio: float,
) -> list:
"""
Splits the training set into a training set and a validation set.
Parameters
----------
train_x: An array of element fea... | This function trains a neural network using gradient descent by iterating over epochs, performing forward and backward propagation on training data, updating weights, and optionally validating performance. It adjusts network architecture if input/output dimensions mismatch, tracks training/validation loss, and plots lo... | def train(
self,
train_x : np.ndarray,
train_y : np.ndarray,
epochs: int = 10,
learning_rate: float = 0.015,
validation_ratio: float = 0,
plot_loss : bool = False,
) -> None:
"""
Trains the neural network on the given dataset (i.e. upda... |
def load_data_frames(
end_points_list: list, data_frames: Dict[str, DataFrame], spark: SparkSession
) -> Dict[str, DataFrame]:
url_link = os.environ.get("URL_LINK")
for end_point in end_points_list:
variable_name = f"{end_point}_df" # Generate a variable name for the df
url = url_link + end... | The main task of the code is to process and transform data from multiple endpoints (e.g., appointment, patient_councillor) using Apache Spark. It initializes a SparkSession, loads data into DataFrames, applies transformations to the combined data, and stores the results in a database. The function orchestrates data int... | def main(data_frame: Dict[str, DataFrame]) -> None:
end_points_list = [
"appointment",
"patient_councillor",
"price_log",
"councillor",
"rating",
]
# Initialize SparkSession
spark = SparkSession.builder.getOrCreate()
data_frames = load_data_frames(end_points_... |
def fFunction(self, round):
T0 = self.gPermutation(self._rVals[0], round, 0)
T1 = self.gPermutation(self._rVals[1], round, 4)
round_keys = self.keySchedule.keys[round]
F0 = (T0 + (2 * T1) + util.concatKeys(round_keys[8], round_keys[9])) % (2**16)
F1 = ((2 * T0) + T1 + util.concat... | The main task of the code is to perform block cipher encryption using a key schedule and rounds of transformation. It applies whitening (key mixing) to the input bytes, iterates through rounds of a Feistel-like structure involving function F and value swapping, and finalizes the encryption with another whitening step. ... | def encrypt(self):
self._rVals = util.whitening(int(self.inputBytes.hex(), 16), self.keySchedule.masterKey)
for round in range(c.ROUNDS):
F0, F1 = self.fFunction(round)
self.swap(F0, F1)
self._rVals = self._rValsNew
self._rValsNew = []
self.finalSw... |
def fFunction(self, round):
T0 = self.gPermutation(self._rVals[0], round, 0)
T1 = self.gPermutation(self._rVals[1], round, 4)
round_keys = self.keySchedule.keys[round]
F0 = (T0 + (2 * T1) + util.concatKeys(round_keys[8], round_keys[9])) % (2**16)
F1 = ((2 * T0) + T1 + util.concat... | This code decrypts input bytes using a block cipher algorithm. It applies key whitening, performs multiple rounds of decryption (involving F-function operations and value swaps), executes a final swap, and converts the result to hex format. The process reverses encryption steps, using the master key for whitening and e... | def decrypt(self):
self._rVals = util.whitening(int(self.inputBytes, 16), self.keySchedule.masterKey)
for round in range(c.ROUNDS):
F0, F1 = self.fFunction((c.ROUNDS-1) - round)
self.swap(F0, F1)
self._rVals = self._rValsNew
self._rValsNew = []
sel... |
def _ast_dict_lookup(dict_object: ast.Dict, lookup_key: str) -> Optional[Any]:
"""Get the value of the lookup key in the ast Dict object."""
key_position = _ast_dict_key_index(dict_object, lookup_key)
if key_position is None:
return None
return _ast_get_constant_value(dict_object.values[key_posi... | The function updates a list (`original_setting`) based on an iterable (`configuration`). It processes each configuration item: if it's a dictionary, it inserts the value at a specified position relative to another item or appends it if not present. If it's a simple value, it appends it only if not already in the list. ... | def _update_list_setting(original_setting: List, configuration: Iterable):
for config_value in configuration:
# configuration items can be either strings (which are appended) or dictionaries which contains information
# about the position of the item
if isinstance(config_value, dict):
... |
def _update_list_setting(original_setting: List, configuration: Iterable):
for config_value in configuration:
# configuration items can be either strings (which are appended) or dictionaries which contains information
# about the position of the item
if isinstance(config_value, dict):
... | The code updates a project's settings file by integrating addon configurations using AST parsing. It modifies existing settings like INSTALLED_APPS or dictionary entries, appending new values or updating keys. If settings are missing, it adds them. The original file is overwritten, losing its structure/comments. AST no... | def update_setting(project_setting: str, config: Dict[str, Any]):
"""
Patch the settings module to include addon settings.
Original file is overwritten. As file is patched using AST, original comments and file structure is lost.
:param str project_setting: project settings file path
:param dict co... |
def load_config():
payload = {
"last_msg": time.time()
}
# check if config.json exists
if not os.path.isfile("config.json"):
sprint("Config file not found. Creating...")
# create config file
save_config()
else:
sprint("Config file found.")
# load con... | This function checks if a cooldown period for a Twitch bot has expired by comparing the elapsed time since the last message with a predefined delay. If the cooldown has expired, it updates the configuration and returns True; otherwise, it returns False. In debug mode, it bypasses the check and always returns True. | def check_if_cooldown_expired():
#skip this is ran in debug
if not config.Bot.debug:
settings = load_config()
last_msg = settings["last_msg"]
calulation = (time.time() - last_msg)
if calulation > config.Twitch.command_delay:
sprint("cooldown expired")
save... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def batch_norm(x):
return tf.keras.layers.BatchNormalization(axis=CHANNEL_AXIS)(x)
def relu6(x):
re... | This code defines a depthwise separable convolution block with residual connection. It processes input tensor x_in through a 1x1 convolution, depthwise convolution, and another 1x1 convolution, applying batch normalization and ReLU6 activations. If stride is 1 and input/output channels match, it adds the original input... | def ds_block(x_in, input_channels, hidden_dim, output_channels, stride):
x = conv(x_in, hidden_dim, 1, 1, 'same')
x = batch_norm(x)
x = relu6(x)
x = depth_conv(x, 3, stride, 'same')
x = batch_norm(x)
x = relu6(x)
x = conv(x, output_channels, 1, 1, 'same')
x = batch_norm(x)
if stri... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def batch_norm(x):
return tf.keras.layers.BatchNormalization(axis=CHANNEL_AXIS)(x)
def relu(x):
ret... | This code generates a lightweight, fast upsampling model using an encoder-decoder architecture. The encoder processes inputs through convolutional blocks with batch normalization and ReLU, followed by max-pooling. The decoder employs reversed feature maps and fast upproj layers for upsampling. A final 3x3 convolution a... | def generate_tiny_fast_upproj_model(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
block_layers = [2, 2, 3]
f1s = [16, 32, 64]
expansion = 2
x = conv(x_input, f1s[0], 7, 2, 'same')
... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def batch_norm(x):
return tf.keras.layers.BatchNormalization(axis=CHANNEL_AXIS)(x)
def relu(x):
ret... | The code defines a neural network model named 's2d' for image reconstruction or segmentation tasks. It creates an encoder-decoder architecture with convolutional blocks, batch normalization, and upsampling. The encoder reduces spatial dimensions while increasing feature depth, followed by a decoder that upsamples featu... | def generate_s2d_model(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
block_layers = [3, 4, 6, 3]
f1s = [128, 256, 512, 1024]
expansion = 4
x = conv(x_input, f1s[0], 7, 2, 'same')
... |
def zero_padding(x, padding):
return tf.keras.layers.ZeroPadding2D(padding, data_format=DATA_FORMAT)(x)
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)... | The code defines a neural network model with an encoder-decoder architecture, creating a smaller version of a CNN for image processing. It processes normalized or non-normalized inputs, applying convolutional blocks, batch normalization, max pooling, deconvolution, and bilinear upsampling. The model outputs a downscale... | def generate_smaller_model(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
block_layers = [3, 3, 3, 3]
f1s = [32, 64, 128, 256]
expansion = 4
x = zero_padding(x_input, 3)
x = co... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def batch_norm(x):
return tf.keras.layers.BatchNormalization(axis=CHANNEL_AXIS)(x)
def relu(x):
ret... | This code defines a neural network model with an encoder-decoder architecture. It creates a smaller model for image processing, using convolutional blocks, batch normalization, and upsampling. The encoder reduces spatial dimensions with progressively larger filters, while the decoder reconstructs the output using decon... | def generate_even_smaller_model(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
block_layers = [2, 3, 3, 2]
f1s = [16, 32, 64, 128]
expansion = 4
x = conv(x_input, f1s[0], 7, 2, 'sam... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def batch_norm(x):
return tf.keras.layers.BatchNormalization(axis=CHANNEL_AXIS)(x)
def relu(x):
ret... | This code defines a compact encoder-decoder CNN model for image processing, creating a "tiny" neural network with configurable input channels (6 or 8). It uses convolutional blocks, batch normalization, max pooling, deconvolution, and bilinear upsampling to generate a lightweight model for tasks like image segmentation... | def generate_tiny_model(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
block_layers = [2, 2, 3]
f1s = [16, 32, 64]
expansion = 2
x = conv(x_input, f1s[0], 7, 2, 'same')
x = batc... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def batch_norm(x):
return tf.keras.layers.BatchNormalization(axis=CHANNEL_AXIS)(x)
def relu(x):
ret... | This code generates a lightweight neural network model with an encoder-decoder structure. The encoder reduces spatial dimensions using convolutional blocks, while the decoder upsamples features via deconvolution. The model adjusts input channels based on normalization, applies batch normalization, and uses residual blo... | def generate_tinier_model(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
block_layers = [3, 3]
f1s = [16, 32]
expansion = 2
x = conv(x_input, f1s[0], 7, 2, 'same')
x = batch_nor... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def batch_norm(x):
return tf.keras.layers.BatchNormalization(axis=CHANNEL_AXIS)(x)
def relu(x):
ret... | The code defines a Keras model for image upscaling using an encoder-decoder architecture. The encoder uses residual blocks with convolutional layers, batch normalization, and max pooling, while the decoder employs transpose convolutions (upproj) for upsampling. The model includes bilinear interpolation for final spatia... | def generate_even_smaller_upproj_model(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
block_layers = [2, 3, 3, 2]
f1s = [16, 32, 64, 128]
expansion = 4
x = conv(x_input, f1s[0], 7, ... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def batch_norm(x):
return tf.keras.layers.BatchNormalization(axis=CHANNEL_AXIS)(x)
def relu(x):
ret... | The code defines a function to generate a compact UNet-like model for image upscaling, using an encoder-decoder structure. It creates a neural network with configurable input channels (6 or 8), convolutional blocks, batch normalization, max pooling, and upsampling layers. The model processes images through encoder bloc... | def generate_tiny_upproj_model(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
block_layers = [2, 2, 3]
f1s = [16, 32, 64]
expansion = 2
x = conv(x_input, f1s[0], 7, 2, 'same')
x... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def ds_conv(x, output_channels, kernel, stride, padding):
x = depth_conv(x, kernel, stride, padding)
... | The code generates a MobileNet model with an encoder-decoder architecture. The encoder uses depthwise separable convolutions to downsample input images, progressively increasing feature maps (64→1024). The decoder upscales features via deconvolution blocks, reversing the encoder's feature sizes. A final 3x3 convolution... | def generate_mobile_net(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
f1s = [64, 128, 256, 512, 1024]
x = conv(x_input, 32, 3, 2, 'same')
x = ds_conv(x, 64, 3, 1, 'same')
x = ds_con... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def inverted_residual_block(x, input_channels, expansion_factor, output_channels, num_blocks, stride):
... | This code defines a MobileNetV2 model for image processing, with an encoder-decoder structure. The encoder uses inverted residual blocks to extract features, while the decoder employs deconvolution layers to upsample feature maps. The model adjusts input channels based on normalization, applies bilinear upsampling, and... | def generate_mobile_net_v2(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
input_channels_list = [32, 16, 24, 32, 64, 96, 160]
expansion_factor_list = [1, 6, 6, 6, 6, 6, 6]
output_channel... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def inverted_residual_block(x, input_channels, expansion_factor, output_channels, num_blocks, stride):
... | The code defines a MobileNetV2-based encoder-decoder model for image processing. It constructs an encoder with inverted residual blocks, followed by a decoder using deconvolution and upsampling. The model adapts input channels based on normalization, applies convolutional layers, and outputs a upscaled image. It return... | def generate_small_mobile_net_v2(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
input_channels_list = [32, 16, 24, 32, 64, 96]
expansion_factor_list = [1, 4, 4, 4, 4, 4]
output_channels_... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def inverted_residual_block(x, input_channels, expansion_factor, output_channels, num_blocks, stride):
... | The code defines a compact MobileNet V2 variant with an encoder-decoder structure. It constructs a model that processes input images through a series of inverted residual blocks (encoder), followed by deconvolution layers (decoder) to upscale features, ending with a bilinear upsampling to restore original resolution. T... | def generate_mini_mobile_net_v2(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
input_channels_list = [32, 16, 24, 32, 64, 96]
expansion_factor_list = [1, 2, 2, 2, 2, 2]
output_channels_l... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def inverted_residual_block(x, input_channels, expansion_factor, output_channels, num_blocks, stride):
... | This code constructs a Micro MobileNet V2 model for image processing, using an encoder-decoder structure. The encoder employs inverted residual blocks with configurable parameters, while the decoder uses deconvolution layers for upsampling. The model adjusts input channels based on normalization, applies depthwise sepa... | def generate_micro_mobile_net_v2(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
input_channels_list = [32, 16, 24, 32, 64]
expansion_factor_list = [1, 2, 2, 2, 2]
output_channels_list = ... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def inverted_residual_block(x, input_channels, expansion_factor, output_channels, num_blocks, stride):
... | This code generates a lightweight CNN model, 'little_mn2', for image processing. It constructs an encoder-decoder architecture: the encoder uses MobileNet V2-style inverted residual blocks to reduce spatial dimensions, while the decoder employs deconvolution and upsampling to reconstruct output. The model handles norma... | def generate_little_mobile_net_v2(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
input_channels_list = [16, 24, 32, 96]
expansion_factor_list = [1, 2, 2, 2]
output_channels_list = [24, 3... |
def conv(x, output_channels, kernel, stride, padding):
return tf.keras.layers.Conv2D(
output_channels,
kernel,
stride,
padding=padding,
data_format=DATA_FORMAT
)(x)
def inverted_residual_block(x, input_channels, expansion_factor, output_channels, num_blocks, stride):
... | This code generates a lightweight neural network model with an encoder-decoder structure, implementing MobileNet V2-inspired inverted residual blocks for feature extraction, followed by fast upsampling projections and spatial restoration. The model adapts input channels based on normalization, uses depthwise separable ... | def generate_little_mobile_net_v2_fast_upproj(normalized):
channels = 6 if normalized else 8
input_shape = (ROWS, COLS, channels) # (H X W x C)
x_input = tf.keras.Input(shape=input_shape)
# Encoder
input_channels_list = [16, 24, 32, 96]
expansion_factor_list = [1, 2, 2, 2]
output_channels_l... |
def arg_parse():
parser = argparse.ArgumentParser()
parser.add_argument('--load_path', type=str, help='Path of the dataset to load.')
parser.add_argument('--crime_code_path', type=str, help='Path of the crime code to load.')
parser.add_argument('--save_path', type=str, help='Path to save the npy files.'... | The code processes crime data by reading and filtering crime types, preprocessing dates, and generating regular/time-series data using embeddings or historic methods. It organizes outputs into directories based on parameters like window size, data type, and embedding usage, saving results for specified years. | def main():
global embedding_dict, crime_types
parser = arg_parse()
crime_types = pd.read_csv(parser.crime_code_path)
crime_types = crime_types[~crime_types[OFFENCE_DESC].isnull()]
df = pd.read_csv(parser.load_path, usecols=LOAD_COLUMNS)
df[DATE_COLUMN] = df[DATE_COLUMN].progress_apply(lamb... |
def read_alpha(message=""):
var = input(message)
if var.isalpha():
return var
print("Incorrect format\nTry again")
return read_alpha(message)
def read_email(message):
var = input(message)
if re.fullmatch(regex, var):
return var
print("Invalid email\nTry again")
return ... | The main task of the code is to collect user registration details—first name, last name, email, password, and mobile number—using specific input functions, then return them as a list of tuples with corresponding keys for structured data storage or processing. | def read_registration_data():
fname = read_alpha("Enter your first name: ")
lname = read_alpha("Enter your last name: ")
email = read_email("Enter your email: ")
password = read_password()
mobile = read_number("Enter your phone number: ")
return ("fname", fname), ("lname", lname), ("email", ema... |
def get_machine_type_from_run_num(run_num):
"""these are the values to be used in config for machine dependent settings"""
id_to_machine = {
'MS001': 'miseq',
'NS001': 'nextseq',
'HS001': 'hiseq 2500 rapid',
'HS002': 'hiseq 2500',
'HS003': 'hiseq 2500',
'HS004': '... | (The main task of the code is to perform quality control (QC) checks on bcl2fastq data using a configuration file. It parses command-line arguments, verifies input directories, runs QC tests, logs results, and sends email alerts if failures are detected. The script checks project directories from the config, executes Q... | def main():
"""main function
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-d', "--bcl2fastq-dir", required=True,
help="bcl2fastq directory (containing a conf.yaml)")
parser.add_argument('--no-mail', action='store_true',
... |
def loadSession(self):
# load the cookie data
self.loadCookie()
# check for existance of the session ID cookie
if 'sessionId' in self.cookie: # if it exists:
sessionId = self.cookie['sessionId'].value
# load the session data for the session ID
self.ses... | The code handles POST requests by loading a session, checking the request path. If the path is "/movies", it processes movie creation; otherwise, it returns a "Not Found" response. | def do_POST(self):
self.loadSession()
if self.path == "/movies":
self.handleCreateMovie()
else:
self.handleNotFound() |
def loadSession(self):
# load the cookie data
self.loadCookie()
# check for existance of the session ID cookie
if 'sessionId' in self.cookie: # if it exists:
sessionId = self.cookie['sessionId'].value
# load the session data for the session ID
self.ses... | The code handles HTTP GET requests by parsing the request path to determine the collection name and member ID. If the collection is "movies", it retrieves either member-specific movies (if a member ID is provided) or the general movie collection. Otherwise, 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
self.loadCookie()
# check for existance of the session ID cookie
if 'sessionId' in self.cookie: # if it exists:
sessionId = self.cookie['sessionId'].value
# load the session data for the session ID
self.ses... | This code handles DELETE requests by checking the URL path to determine the collection and member ID. If the collection is "movies" and a member ID is provided, it deletes the corresponding movie. Otherwise, it returns a "Not Found" response. | 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]
else:
collection_name = path_parts[1]
member_id = None
if collection_name ... |
def get_account_count(database_filename, also_count_invalidated_accounts: bool = True):
count = 0
try:
database_connection = sqlite3.connect(database_filename)
cursor = database_connection.cursor()
if also_count_invalidated_accounts:
sqlstring = SQL_SELECT_COUNT_ALL_FROM_ACCO... | This code searches a SQLite database for accounts matching a given search string. It connects to the database, constructs a query (filtering invalid accounts if specified), fetches results, decrypts each account, checks for matches, and prints formatted results with highlighted search terms. It counts and displays the ... | def search_accounts(self, search_string: str):
results_found = 0
try:
database_connection = sqlite3.connect(self.database_filename)
cursor = database_connection.cursor()
if self.show_invalidated_accounts:
sqlstring = "select uuid, name, url, loginname,... |
def get_account_count_invalid(database_filename):
count = 0
try:
database_connection = sqlite3.connect(database_filename)
cursor = database_connection.cursor()
sqlstring = SQL_SELECT_COUNT_ALL_INVALID_FROM_ACCOUNT
sqlresult = cursor.execute(sqlstring)
result = sqlresult.f... | This function searches invalidated accounts in an SQLite database by querying records where 'invalid = 1', decrypts each account, checks if it matches a search string, and prints matching results with counts. It handles database connections, executes ordered SQL queries, and formats output with colored highlights for s... | def search_invalidated_accounts(self, search_string: str):
results_found = 0
try:
database_connection = sqlite3.connect(self.database_filename)
cursor = database_connection.cursor()
# if self.show_invalidated_accounts:
# sqlstring = "select uuid, name,... |
def get_account_count(database_filename, also_count_invalidated_accounts: bool = True):
count = 0
try:
database_connection = sqlite3.connect(database_filename)
cursor = database_connection.cursor()
if also_count_invalidated_accounts:
sqlstring = SQL_SELECT_COUNT_ALL_FROM_ACCO... | This function searches a SQLite database for accounts matching a specified type string, optionally including invalidated accounts. It executes a query, filters results based on the type, decrypts each account, and prints formatted output with highlighted matches. It handles exceptions, ensures database closure, and rep... | def search_accounts_by_type(self, type_search_string: str):
results_found = 0
try:
database_connection = sqlite3.connect(self.database_filename)
cursor = database_connection.cursor()
if self.show_invalidated_accounts:
sqlstring = "select uuid, name, ur... |
def create_fernet(salt, password, iteration_count: int) -> Fernet:
# _hash = PBKDF2HMAC(algorithm=hashes.SHA256, length=32, salt=salt, iterations=232323)
# _hash = PBKDF2HMAC(algorithm=hashes.SHA256, length=32, salt=salt, iterations=500000)
_hash = PBKDF2HMAC(algorithm=hashes.SHA256, length=32, salt=salt, i... | This code initializes a database handler with encryption, validating the provided database password, setting up encryption parameters, and ensuring the database schema is correctly configured. It raises errors for missing credentials, encrypts the password using Fernet, and verifies the password's validity before proce... | def __init__(self, database_filename, database_password, show_account_details=False,
show_invalidated_accounts=False, shadow_passwords: bool = False,
salt=DEFAULT_SALT, iteration_count: int = DEFAULT_ITERATION_COUNT,
track_account_history: bool = True):
if data... |
def is_valid_database_password(self, _database_filename: str, _database_password: str) -> bool:
try:
value = get_attribute_value_from_configuration_table(_database_filename,
CONFIGURATION_TABLE_ATTRIBUTE_PASSWORD_TEST)
if v... | The main task of the code is to change the database password by re-encrypting all sensitive data stored in multiple tables (accounts, history, aliases, etc.) using the new password. It first validates the old password, updates the configuration table's encryption token, decrypts and re-encrypts all entries with the new... | def change_database_password(self, new_password: str) -> bool:
if not self.is_valid_database_password(self.database_filename, self.database_password):
print("Old database password is wrong.")
return False
try:
database_connection = sqlite3.connect(self.database_filena... |
def decrypt_account(self, account: Account) -> Account:
account.uuid = account.uuid
account.name = self.decrypt_string_if_password_is_present(account.name)
account.url = self.decrypt_string_if_password_is_present(account.url)
account.loginname = self.decrypt_string_if_password_is_present... | This function retrieves historical account records from an SQLite database by UUID, decrypts them, and displays older versions. It also fetches the latest account version separately, counts results, and handles database connections. | def search_account_history(self, uuid_string: str):
results_found = 0
try:
database_connection = sqlite3.connect(self.database_filename)
cursor = database_connection.cursor()
# if self.show_invalidated_accounts:
# sqlstring = "select uuid, name, url, l... |
def get_database_name(database_filename):
value = get_attribute_value_from_configuration_table(database_filename, CONFIGURATION_TABLE_ATTRIBUTE_DATABASE_NAME)
return value
def is_valid_database_password(self, _database_filename: str, _database_password: str) -> bool:
try:
value = get_attribu... | The function merges two SQLite databases by synchronizing account data, handling deleted accounts, resolving discrepancies in UUIDs and update dates, and updating configuration records. It checks passwords, attaches the merge database, executes schema updates, and ensures consistency between local and remote databases ... | def merge_database(self, merge_database_filename: str) -> int:
if not os.path.exists(merge_database_filename):
print("Error: merge database does not exist: '" + merge_database_filename + "'")
return -1
print("Using merge database: " + merge_database_filename + " " + get_database_... |
def get_account_exists(self, account_uuid) -> bool:
account = self.get_account_by_uuid_and_decrypt(account_uuid)
if account is not None:
return True
else:
return False
def set_database_pragmas_to_secure_mode(self, database_connection, cursor):
logging.debug("Setti... | This function securely deletes a user account from a SQLite database by validating the provided UUID, confirming user intent, and logging the deletion in a separate table while maintaining secure database operations. | def delete_account(self, delete_uuid):
if delete_uuid is None or delete_uuid == "":
print("Error deleting account: UUID is empty.")
return
if self.get_account_exists(delete_uuid) is False:
print("Error: Account uuid " + delete_uuid + " does not exist.")
re... |
def get_fund_type():
"""
Prompt the user with available fund types and
obtain valid selection from user
Returns:
str: The selected fund type (1, 2, 3, or 4)
"""
_display_fund_choices()
while True:
print_white("Please enter your choice", '')
print_yellow("1, 2, 3, or 4... | The main task of the code is to gather user inputs for fund type, years, and PFA, compute results using these parameters, display the findings, and save them under the user's name. It orchestrates data collection, computation, and storage for an enquiry process. | def run_enquiry(user: str):
"""
Get the Fund type, years and PFA for the enquiry
and call the function to compute the results and print same
Parameters:
user (string) : the user name of the user
"""
# get the fund type from user
fund_type = get_fund_type()
# get start and end ... |
def build_board():
boxes = []
offset_x = 0
offset_y = 0
for i in range(9):
cols = []
if i == 0 or i == 3 or i == 6:
offset_x += 10
offset_y = 0
for j in range(9):
if j == 0 or j == 3 or j == 6:
offset_y += 10
cols.append... | The code implements a graphical Sudoku puzzle solver with Pygame, allowing users to input numbers, clear cells, solve the puzzle, and view solve time. It handles mouse and keyboard interactions to update the 9x9 grid, visually highlights selected cells, and displays whether the puzzle is solvable along with the time ta... | def run(window):
# box = Box(20, 20)
puzzle = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, ... |
def build_empty_puzzle():
puzzle = []
for i in range(9):
puzzle.append([])
for j in range(9):
puzzle[i].append(0)
return puzzle
def build_board():
boxes = []
offset_x = 0
offset_y = 0
for i in range(9):
cols = []
if i == 0 or i == 3 or i == 6:
... | This code implements an interactive Sudoku game with a graphical interface using Pygame. It allows users to input numbers, solve the puzzle, and visualize changes in real-time. The main task is to create a Sudoku solver where users can edit the grid, attempt automated solving, track solve time, and toggle visibility of... | def run(window):
# Building Empty Default Puzzle
puzzle = build_empty_puzzle()
orig_puzzle = []
# Building Board
boxes = build_board()
# Setting Default Solve Time
solve_time = 0
# Set Current Box Index to unassigned
current_index = (-1, -1)
# Set Show new values
show_new... |
def send(self):
print("\n\t<==== Sending a \'{subject}\' message to the server".format(subject=self.response_subject))
self.response = {"subject": self.response_subject, "content": self.response_content}
# print the message sent if the print option is activated for sent messages
if self.... | The code establishes a client-server connection by prompting the user for their name, shuffling a random secret using specific string manipulation steps, and sending the formatted data. It then enters a loop to continuously receive server messages, handle connection status, and reply accordingly, maintaining communicat... | def run(self):
"""
this function runs the receiving thread to communicate with server
:return:
"""
self.response_subject = "Connect"
client_name = input("\tEnter your name here please: ")
# shuffle the random secret generated at the connect step by applying the ... |
def traject_preprocess(self, setname):
'''
data_dirs : List of directories where raw data resides
data_file : The file into which all the pre-processed data needs to be stored
'''
if setname == 'train':
data_dirs = self.train_dir
data_file = self.train_dat... | The code initializes data processing for a specified dataset (ETH5), splits data directories into training and test sets, preprocesses raw trajectory data into cached batches, and prepares batch pointers for training and testing. It handles dataset-specific configurations, loads preprocessed data, and sets up training/... | def __init__(self, args):
self.args = args
if self.args.dataset == 'eth5':
self.data_dirs = ['./data/eth/univ', './data/eth/hotel',
'./data/ucy/zara/zara01', './data/ucy/zara/zara02',
'./data/ucy/univ/students001', './data/ucy/uni... |
def printValidFlags():
print("---VALID FLAGS---")
printDictionary(langFlags)
printDictionary(helpFlags)
print("-----------------")
def help(flag: str):
if flag == "-h":
printValidFlags()
elif flag == "-r":
os.system("rm -r inputs.in test-suite/ langtests/ *.test")
def test(flag: ... | The main task of the code is to validate command-line arguments for a program, check if flags are valid (help or language-related), enforce correct argument counts, and execute corresponding functions (help or test) based on the provided flags and arguments. | def main():
# check if there is more than one argument
length = len(sys.argv)
if length == 1:
print("suite.py <flag> <process>")
return
# check if flag is valid
flag = sys.argv[1]
if not (flag in helpFlags or flag in langFlags):
print("%s is not a valid flag" % (flag))
... |
def getPath():
'''
Getting the full path to the PDF file to parse
and to the txt file which contains the data of PDF
Return tuple:
:return: pdfDocPath, dataTextPath
'''
# Gets the path to script file
progName = os.path.basename(__file__)
progPath = os.path.abspath(__file__).replace(p... | The main task is to process financial data from a PDF by initializing a regex-based dictionary for categorizing income, expense, and balance entries. The code parses text data using these categories, aggregates sums, and prepares structured output (e.g., tables with dropdowns) for detailed financial analysis. User-defi... | def main():
'''
TODO: User may init the tree of find through categories by create his own categories with corresponding regular expressions
To start, creates a basic dictionary with simple categories like:
Income:
Expense:
Balance:
New subcategories can be added in dicrionary.
End resul... |
def init_embed_(self, data):
if self.initted:
return
embed, cluster_size = kmeans(
data,
self.codebook_size,
self.kmeans_iters,
sample_fn = self.sample_fn,
all_reduce_fn = self.kmeans_all_reduce_fn
)
self.embed.dat... | This code performs vector quantization using a learnable codebook, computing distances between input features and codebook embeddings, then sampling indices via Gumbel-softmax. During training, it updates codebook embeddings based on cluster statistics (cluster size and average embeddings) using exponential moving aver... | def forward(self, x):
needs_codebook_dim = x.ndim < 4
x = x.float()
if needs_codebook_dim:
x = rearrange(x, '... -> 1 ...')
shape, dtype = x.shape, x.dtype
flatten = rearrange(x, 'h ... d -> h (...) d')
self.init_embed_(flatten)
embed = self.embed... |
def l2norm(t):
return F.normalize(t, p = 2, dim = -1)
def init_embed_(self, data):
if self.initted:
return
embed, cluster_size = kmeans(
data,
self.codebook_size,
self.kmeans_iters,
use_cosine_sim = True,
sample_fn = self.sampl... | This code performs vector quantization of input tensors using a learnable codebook. It normalizes inputs, computes distances to codebook embeddings, and uses Gumbel sampling for quantization. During training, it updates codebook embeddings via cluster statistics and all-reduce operations, ensuring distributed consisten... | def forward(self, x):
needs_codebook_dim = x.ndim < 4
x = x.float()
if needs_codebook_dim:
x = rearrange(x, '... -> 1 ...')
shape, dtype = x.shape, x.dtype
flatten = rearrange(x, 'h ... d -> h (...) d')
flatten = l2norm(flatten)
self.init_embed_(f... |
def search_drop(self, name):
# self.driver.save_screenshot('screen.png')
search_field_xpath = '//*[@id="search-input-field"]/input'
search_button_xpath = '//*[@id="search-button"]'
self.find_element_and_send_key(search_field_xpath, name)
self.find_element_and_click(search_button_... | The main task of the code is to extract the listing price of an NFT from a web table. It uses `nft_id` and `to_name` to navigate to the correct data, retrieves the table via XPath, and returns the 'listing_price' value from the first row of the table. | def get_listing_price(self, nft_id, to_name):
self.search_drop(to_name)
self.find_contract_drop(nft_id=nft_id)
table_xpath = '/html/body/div[1]/div[2]/div/div[2]/div[3]/div/div[4]/div/div/div[2]/table'
df = self.get_table(table_xpath)
listing_price = df.loc[0, 'listing_price']
... |
def search_drop(self, name):
# self.driver.save_screenshot('screen.png')
search_field_xpath = '//*[@id="search-input-field"]/input'
search_button_xpath = '//*[@id="search-button"]'
self.find_element_and_send_key(search_field_xpath, name)
self.find_element_and_click(search_button_... | This code scrapes NFT drop information from a webpage using XPath, extracts structured data from a table, and returns it as a dictionary with key-value pairs representing metadata like price, currency, time limits, and claim details. The function searches for a specific NFT drop, waits for page load, parses tabular dat... | def get_info(self, nft_id, to_name):
self.search_drop(to_name)
self.find_contract_drop(nft_id=nft_id)
time.sleep(3)
table_xpath = "/html/body/div[1]/div[2]/div/div[2]/div[3]/div/div[4]/div/div/div[2]/table"
df = self.get_table(table_xpath)
info_dict = {
"drop_... |
def _set_name(self, name):
"""
Sets the name of the Document based on the first key in doc_dict.
"""
self._name = name
def _set_config(self, config):
"""
Sets the config of the Document based on the 'config' value in doc_dict.
"""
self._config = config
d... | The main task of the code is to initialize a Document object by configuring its properties from the provided `doc_dict`, including setting the document name, path, configuration, sections status, and mutations. It then reads the file and initializes sections, preparing the document for further processing or analysis. | def _initialize(self, doc_dict):
"""
Initializes the Document object by setting the name, path, and sections.
"""
#This must be the only key in doc_dict so we can hard-code index 0
document_name = list(doc_dict.keys())[0]
doc_dict = doc_dict.get(document_name)
... |
def red_filter(cropped):
cv_im =np.array(cropped)
img_hsv_r = cv2.cvtColor(cv_im, cv2.COLOR_RGB2HSV)
lower_red = np.array([0,50,50])
upper_red = np.array([10,255,255])
mask0 = cv2.inRange(img_hsv_r, lower_red, upper_red)
# upper mask (170-180)
lower_red = np.array([170,50,50])
upper_red... | The code analyzes image regions defined in a dictionary to count occurrences of specific colors (RED, GREEN, YELLOW). It crops each region, applies color filters, evaluates dominant colors using feature values, and tallies results in a dictionary. | def analyze_color(dictionary, img):
res = dict()
a = []
for i in range(0,len(dictionary[9])):
a.append(dictionary[9][i][0])
for j in range(len(a)):
y1 = int(a[j][1])
y2 = int(a[j][3])
x1 = int(a[j][0])
x2 = int(a[j][2])
# cv2.rectangle(img,(int(x1),int(y... |
def adjust_mods(self):
if self.primary == "lin":
self.apmod = 1
self.bpmod = 10
elif self.primary == "deg2":
self.apmod = 0.1
self.bpmod = 1
self.cpmod = 10
elif self.primary == "deg3":
self.apmod = 0.001
... | The code handles user input for a 3D/2D graph viewer, allowing view switching, parameter adjustments, and rotation. It processes events like mouse clicks (for rotation), keyboard keys (to toggle axes, adjust graph values, and switch views), updates display settings, and renders axes/points based on the current view mod... | def run(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # Left mouse button cl... |
def createNewTournament(self):
print("You are creating a new tournament\n")
name = self.safeStrInput("Name : ")
place = self.safeStrInput("Place : ")
date = self.safeFullDateInput("Date : ")
print("\nSetting up rounds dates :")
date_list = []
for index in range(1... | The code implements a state-driven menu system for managing a tournament. It processes user choices to perform actions like creating/loading tournaments, managing players, updating ELO ratings, progressing rounds, displaying scoreboards, and saving/exit. The behavior depends on the tournament's state: uninitialized (No... | def switchCase(self, choice):
if(self.tournament is None):
if choice == 1:
self.createNewTournament()
elif choice == 2:
self.loadTournamentMenu()
elif choice == 3:
self.dbQueryMenu()
self.view.clearConsole()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.