dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def load_moves(file_name):
with open(file_name, 'r') as seq_file:
raw_seq = seq_file.readlines()
clean_seq = list()
for move in raw_seq:
clean_seq.append(move.rstrip())
return clean_seq
def crossover(parent1_moves, parent2_moves):
offspring_moves = parent1_moves.copy(... | The code generates a new generation of candidates by performing crossover on the top three parent candidates and mutating selected offspring, then appending these evolved individuals to form the next generation for further optimization in an evolutionary algorithm. | def evolve_fixed_length_kormoran(candidates, generation):
best_parent1 = candidates[0]
best_parent1_moves = load_moves(best_parent1["seq_file"])
best_parent2 = candidates[1]
best_parent2_moves = load_moves(best_parent2["seq_file"])
best_parent3 = candidates[2]
best_parent3_moves = load_moves(b... |
def check_file_name():
"""
Checks if this file has a valid name for *submission*
leave this function and as and don't use it. it's just
to notify you if you're submitting a file with a correct
name.
"""
script_name = os.path.basename(__file__)
import re
matches = re.findall(r"(\d{4}_... | The main task of the code is to launch a proxy server on a specified port (default 18888) by invoking the `entry_point` function. It logs command-line arguments, validates the file name via `check_file_name()`, and retrieves the port number using `get_arg()`. The commented-out line suggests potential HTTP request handl... | def main():
"""
Please leave the code in this function as is.
To add code that uses sockets, feel free to add functions
above main and outside the classes.
"""
print("\n\n")
print("*" * 50)
print(f"[LOG] Printing command line arguments [{', '.join(sys.argv)}]")
check_file_name()
... |
def calculate_tree(current_state, depth):
"""
belal
calculate depth number of future steps, and also calculating current score
:param current_state: {
"player": 0,
"score": 2,
"mancala_state": [4, 4, 4, 4, 4, 4, 0,
4, 4, 4, 4, 4, 4, 0],
"steps": ... | The function `AI_play` generates a game tree from the current state, applies the Min-Max algorithm to determine the optimal move, and executes the selected step. It returns a new game state with updated player, score, Mancala board, and steps taken. The process involves evaluating possible moves at a given depth, selec... | def AI_play(current_state, depth=7):
"""
Esraa
1. calculate tree
2. apply min max algorithm
3. do_step
:param current_state:
:return: new_state {
"player": 0,
"score": 2,
"mancala_state":[4, 4, 0, 4, 4, 0],
"steps": []
}
"""
tree = calculate_tree(c... |
def winner(current_state):
"""
Esraa
check if the game is finished by looking at each user six pockets (if all is empty then the game is finished)
:param current_state:
:return: 0 for player0, 1 for player1, None if the game is still running
"""
for i in range(len(current_state['mancala_stat... | The code initializes a Mancala game, alternating between human and AI turns. It takes user inputs for starting the game, stealing mode, and move selection, updates the game state using `do_step` or `AI_play`, and continues until a winner is determined by the `winner` function. The main task is to run a turn-based Manca... | def main():
game_state = {
"player": int(input('enter 1 if you want to start: ')),
"score": 0,
"is_stealing": int(input('enter 1 for stealing mode: ')),
"mancala_state": [4, 4, 4, 4, 4, 4, 0,
4, 4, 4, 4, 4, 4, 0],
"steps": []
}
while winner(... |
def justify_epoch_string(epoch: int, epochs: int) -> str:
"""Justify the epoch string for logging.
:param epoch: current epoch
:param epochs: total number of epochs
:return: epoch string
"""
n = len(str(epochs))
return str(epoch).ljust(n, ' ')
def split_into_ba... | This function trains a machine learning model using provided training data over specified epochs, processing data in batches. It tracks training loss and accuracy, and optionally validation loss and accuracy if validation data is provided. The results are logged and returned as a dictionary containing metric histories ... | def fit(
self,
x_train: np.ndarray,
y_train: np.ndarray,
epochs: int,
batch_size: int = 1,
verbose: bool = True,
validation_data: Optional[Tuple[np.ndarray, np.ndarray]] = None,
) -> Dict[str, List[float]]:
"""Fit.
... |
def spaced_points(lengths: tuple, number_of_sites: int, n_optimisation_steps: int, optimisation_rate: float):
"""
creates a set of points randomly and then uses the spacing algorithm to arrange them nicely so they're all roughly spaced from one another
Args:
lengths (tuple): system size
num... | The code generates an amorphous lattice with periodic boundaries, creating either Voronoi cells or their dual (nearest-neighbor connections). It optimizes point spacing, duplicates points for periodicity, computes Voronoi diagrams, and filters edges to identify internal and boundary connections. Edges crossing boundari... | def create_amorphous_lattice(self, lattice_type: str, n_optimisation_steps=20, optimisation_rate=0.1):
"""This creates an amorphous lattice - lattice is always created with periodic boundaries - but we keep a list
of all the edges that cross the boundaries so they can be removed to create open boundarie... |
def apply_IP(plaintext):
""" Apply the Initial Permutation (IP) """
ip_permutation_table = [
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 2... | This code decrypts a 64-bit ciphertext using 16 rounds of a Feistel network. It applies an initial permutation, splits the data into left/right halves, iteratively applies function F with round keys, XORs results, swaps halves, and finally applies a reverse permutation to produce decrypted plaintext. | def decrypt_round_keys(ciphertext, round_keys):
# Initial Permutation (IP)
initial_permutation_result = apply_IP(ciphertext)
# Split the 64-bit ciphertext into left and right halves
left64, right64 = split_in_half(initial_permutation_result)
# Perform 16 rounds of decryption
for round_number i... |
def ensure_deck(self, threshold=78):
"""Reshuffle the deck if it has fewer than the threshold number of cards."""
if len(self.deck) < threshold:
self.deck = create_deck()
shuffle_deck(self.deck)
def update_display(self):
# Clear the current displayed cards
for lab... | This code handles a player's "Hit" action in a Blackjack game by drawing a card, updating the display, checking for a bust (hand >21), and recording game data to a database if the player busts. If the hand reaches 21, it triggers an automatic "Stand." It also provides strategy advice and updates UI elements to reflect ... | def hit(self):
# Ensure there are enough cards in the deck
self.ensure_deck()
self.player_hand.append(self.deck.pop())
# Update the display before checking for bust
self.update_display()
self.update_deck_table()
if hand_value(self.player_hand) > ... |
def _init_file(self):
"Initialise file to record training progress."
cols = ["loss", "month", "month_n", "epoch"]
cols = cols + self.var_list + ["linear_comb", "val_loss", "restart"]
header = pd.DataFrame(columns=cols)
if not os.path.exists(self.save_fp):
header.to_c... | The main task of the code is to train a model to optimize target values for selected variables by iteratively computing candidate values, calculating loss, and applying gradient updates. It initializes variables, tracks training progress, and saves results to a CSV file, aiming to refine target values through gradient ... | def train_cc(self, n_epochs):
"Train to seek appropriate target values for selected variables."
# Init tracking file
self._init_file()
linear_comb = tf.Variable(
tf.ones((1,len(self.var_list))),
dtype="float32", name="line... |
def get_db_connection(config,logger):
"""
established a database connection
"""
try:
# Connect to the database
connection= pymysql.connect(
host=config.get("mysql", "host"),
port=int(config.get("mysql", "port")),
user=config.get("mysql", "user"),
... | The main task of the code is to process database records in batches according to configuration parameters, logging progress and updating state. It reads settings from a config file, retrieves data via a database connection, processes records using a loop with limits, and manages state persistence. The function handles ... | def main(id: Optional[int] = 0,commit: bool = False,):
'''
This is the main fucntion that extracts the required data from the config file
'''
config = configparser.ConfigParser(interpolation=None)
config.read(os.path.join(os.path.dirname(__file__), "config.ini"))
log_file_name=config.get('metada... |
def re_meshing(path,
path_e,
path_e_grad,
a,
atomic_symbols,
calc_type,
ml_model_path,
re_meshing_type=1,
change_factor=0.1):
"""
Refine the path of geometries by adding a new point at the max... | The code implements gradient descent to optimize and find the critical path between start and end points, adjusting intermediate points iteratively based on energy gradients and constraints. It uses re-meshing, convergence checks, and saves the optimized path coordinates and energies. The main task is to compute the cr... | def find_critical_path(calc_type,
atomic_symbols=None,
initial_points=None,
start=None,
end=None,
num_steps=None,
step_factor=None,
action_type=1,
... |
def load_settings(filename):
with open(filename,'r') as f:
lines = f.readlines()
line0 = lines[0]
l = line0.split("=")
dim = l[-1]
line1 = lines[1].strip()
l = line1.split("=")
apple_count = l[-1]
return int(dim),int(apple_count)
def initialize_board(d... | The main task of the code is to run a snake game by loading settings from a file, initializing the game board with a snake and apples, displaying the board, and executing the gameplay loop until the game ends, then printing "Game over.") | def main():
dim,apple_count = load_settings('settings.txt')
snake_head, snake_body = initialize_board(dim,apple_count)
view_board(dim)
play(dim,snake_head,snake_body)
print("Game over.") |
def start_with_list(self,lisst):
for item in lisst:
it = item[2].strftime("%d %b %Y")
act = [item[0], item[1], it, str(item[3]), item[4]]
self.add_activity(act)
self.act_id.append(item[0])
self.write_text_file1('act1.txt')
self.write_pickle_file('a... | The code initializes an activity list based on the specified repository type (inmemory, textfiles, or binaryfiles). It sets up activity data, links activities to persons, and manages file operations (pickle/text) for data persistence. The method clears previous operations and objects in the associated pserv instance. | def __init__(self, pserv,properties):
'''
initialize the activity list
'''
self.properties_dict = properties
self.activities = []
self.pserv = pserv
self.act_id = []
lisst = [["001", ["8h8td", '54ydf4'], datetime.datetime(2020, 11, 13), 9, "hangout"],
... |
def check_connected(AC):
seen, queue = {0}, collections.deque([0])
while queue:
vertex = queue.popleft()
for node in np.argwhere(AC[vertex] > 0).flatten():
if node not in seen:
seen.add(node)
queue.append(node)
# if the seen nodes do not include al... | The code generates the best bond order (BO) matrix from an adjacency matrix (AC) based on atomic valences and unsaturation constraints. It checks connectivity, validates possible valences for each atom, iterates over valence combinations, calculates unsaturated atoms (UA) and degree of unsaturation (DU), and evaluates ... | def AC2BO(AC, atoms, use_graph=True):
"""
implemenation of algorithm shown in Figure 2
UA: unsaturated atoms
DU: degree of unsaturation (u matrix in Figure)
best_BO: Bcurr in Figure
"""
if not check_connected(AC):
return AC, 0
global atomic_valence
# make a list of val... |
def xyz2AC_vdW(atoms, xyz):
# Get mol template
mol = get_proto_mol(atoms)
# Set coordinates
conf = Chem.Conformer(mol.GetNumAtoms())
for i in range(mol.GetNumAtoms()):
conf.SetAtomPosition(i, (float(xyz[i][0]), float(xyz[i][1]), float(xyz[i][2])))
mol.AddConformer(conf)
AC = get_AC(m... | The function `xyz2mol` converts atomic coordinates and types into a molecular structure with bond information. It generates an atom connectivity matrix (AC) from coordinates, derives a bond order matrix (BO) from AC, and updates a molecule object (`mol`) with connectivity and charge data. The output includes the bond o... | def xyz2mol(atoms, coordinates, use_graph=True):
# Get atom connectivity (AC) matrix, list of atomic numbers, molecular charge,
# and mol object with no connectivity information
AC, mol = xyz2AC_vdW(atoms, coordinates)
# Convert AC to bond order matrix and add connectivity and charge info to
# mol ... |
def fwdFeed(w1, w2, w3, w4, b1, b2, b3, b4, x):
global a1, h1, a2, h2, a3, h3, a4, y
a1 = (np.dot(w1, x) + b1).diagonal()
h1 = sigmoid(a1)
a2 = (np.dot(w2, h1) + b2).diagonal()
h2 = sigmoid(a2)
a3 = (np.dot(w3, h2) + b3).diagonal()
h3 = sigmoid(a3)
a4 = (np.dot(w4, h3) + b4).diagonal(... | The code trains a 4-layer neural network on the MNIST dataset using backpropagation. It initializes weights with He scaling, reads training/test data from CSV files, performs forward and backward propagation for each image over 15 epochs, tracks training accuracy, and evaluates test accuracy. The results are visualized... | def train():
global w1, w2, w3, w4, b1, b2, b3, b4
w1 = np.random.randn(256, 784)*np.sqrt(1./256)
w2 = np.random.randn(128, 256)*np.sqrt(1./128)
w3 = np.random.randn(64, 128)*np.sqrt(1./64)
w4 = np.random.randn(10, 64)*np.sqrt(1./10)
b1 = np.random.randn(256, 1)*np.sqrt(1./256)
b2 = np... |
def get_piece(self, loc) :
return next((piece for piece in self.pieces if piece.pos == loc), None)
def save_state(self, save = SAVE_LOCATION) :
f = open(save, 'w')
state = {}
for piece in self.pieces :
state[str(piece.pos)] = piece.to_json()
json.dump(state, f)
... | This function handles a chess piece's move from start_coord to end_coord, validating legality, executing captures (including en passant), managing special moves (castling, promotion), checking for king endangerment, updating game state, and switching turns. It returns True on valid moves, False otherwise. | def move(self, start_coord, end_coord) :
old = tuple(start_coord)
curr = self.get_piece(start_coord)
self.save_state()
if not curr :
self.prev = (-1, -1)
self.selected = (-1, -1)
return False
elif end_coord in curr.moves() :
... |
def king_pos(self, team) :
k = list(filter(lambda piece : piece.p_type == 'king', self.team_peices(team)))
if len(k) > 0 :
return k[0].pos
else :
print('no king? huh?')
return (-1, -1)
def save_state(self, save = SAVE_LOCATION) :
f = open(save, 'w')
... | The main task of the code is to determine if a chess game has reached checkmate for a specified team. It checks if the king is under attack, verifies if any of the team's pieces can move to escape check, and returns 'checkmate' if no valid moves exist. If the game is in stalemate (only two pieces left) or the king is n... | def is_checkmate(self, team = None) :
if self.message :
return 'neither'
self.message = True
if len(self.pieces) == 2 :
return 'stalemate'
if not team :
team = self.game.turn
king_pos = self.king_pos(team)
enemy_sight = (self.black_sig... |
def advance(self):
try:
self.current_char = next(self.input)
except StopIteration:
self.current_char = None
def generate_number(self):
with_dot = "." + DIGITS
number_str = self.current_char
dot_number = 0
self.advance()
while self.current_c... | The main task of the code is to tokenize input by identifying and categorizing characters into tokens such as numbers, variables, operators, and symbols, while skipping comments and whitespace, ultimately returning a list of tokens for further processing. | def generate_tokens(self):
while self.current_char != None:
if self.current_char == "#": # comment
while self.current_char != "\n":
self.advance()
if self.current_char in WHITESPACE:
self.advance()
if self.cur... |
def _get_top_market_cap_coins():
coin_ids = [c['id'] for c in cg.get_coins_markets(vs_currency='USD', order='market_cap_desc', per_page=250)]
return _get_coins_metadata(coin_ids)
def _get_coins_metadata(coin_ids):
coins_metadata = {}
for coin_id in coin_ids:
coin_metadata = retry(cg.get_coin_by... | The function retrieves market data for specified cryptocurrency IDs or the top market cap coins, fetching their daily historical market cap data sorted by date. It handles rate limiting with a delay between requests and returns a dictionary containing each coin's metadata along with its historical market cap values. | def get_market_data(coin_ids=None):
if coin_ids is None:
coins = _get_top_market_cap_coins()
else:
coins = _get_coins_metadata(coin_ids)
for coin_id in coins:
coins[coin_id]['market_caps'] = _get_coin_market_cap_daily_history_sorted_from_latest_to_earliest(coin_id)
sleep(COIN... |
def get_challenge(self):
params = self.__params()
req = self.client.get(url=(
"https://" + self.host + "/captcha/get?" + params), headers=self.__headers())
return req.json()
def find_parameters(self, parsed_json, parameters):
found_parameters = {}
def search_in_json(... | The main task of the code is to solve a CAPTCHA by retrieving a challenge, extracting specific parameters (e.g., URLs, IDs), and using an API solver. It includes retry logic (up to `max_retries`) to handle failures in fetching the challenge. If parameters are successfully extracted, it returns the API's solution; other... | def solve_captcha(self, max_retries=3):
retries = 2
while retries < max_retries:
try:
captcha_challenge = self.get_challenge()
break
except Exception as e:
retries += 1
if retries >= max_retries:
... |
def isLocFromSystemLibrary(loc):
if "file" in loc and isSystemLibrary(loc["file"]):
return True
if "includedFrom" in loc and isSystemLibrary(loc["includedFrom"]["file"]):
return True
if "expansionLoc" in loc:
return isLocFromSystemLibrary(loc["expansionLoc"])
return False
def isRangeFromSystemLibrary(r... | This function parses declarations by filtering out system library and built-in declarations, then dispatching to specific parsers based on the declaration type (e.g., struct, enum, function) to process non-system, user-defined declarations. | def parseDecl(decl):
if isLocFromSystemLibrary(decl["loc"]):
return None
elif "range" in decl and isRangeFromSystemLibrary(decl["range"]):
return None
if "previousDecl" in decl:
prev2 = nodes_by_id[decl["previousDecl"]]
if isLocFromSystemLibrary(prev2["loc"]):
return None
elif "range" in prev2... |
def init(self):
#print("initialized")
self.grid = newGrid()
self.played = 0
self.next = tetrominoes[self.pop.data[self.played]]
self.newPiece()
self.level = 1
self.score = 0
self.lines = 0
self.gameover = False
pygame.time.set_timer(pygame.... | The code simulates a Tetris-like game where each individual in a population (self.pop) is evaluated for fitness using neural network controls. It runs a game loop, updates the game state, renders visuals, handles input, and tracks metrics like score and time. Upon game over, it initializes a new game, updates the indiv... | def play(self):
self.gameover = False
#dont_burn_my_cpu = pygame.time.Clock()
while 1:
for i in range(self.pop.size):
count = 0
while 1:
if self.gameover:
print(i, "Fitness:", self.pop.pop[i].fitness)
... |
def analyze_categorical(self, as_str: bool = False) -> pd.DataFrame:
out = self.counts(self.cat, as_str=as_str).reset_index(drop=True)
return out
def analyze_numeric(self, as_str: bool = False) -> pd.DataFrame:
out = pd.concat([
self.mean_and_sd(self.num, as_str=as_str),
... | The main task of the code is to concatenate results from three analysis methods—categorical, numeric, and boolean—into a unified DataFrame. It combines outputs using pandas' concat function, resets the index for continuity, and returns the merged DataFrame. The `as_str` parameter determines if results are formatted as ... | def analyze(self, as_str: bool = False) -> pd.DataFrame:
out = pd.concat([
self.analyze_categorical(as_str=as_str),
self.analyze_numeric(as_str=as_str),
self.analyze_boolean(as_str=as_str)
]).reset_index(drop=True)
return out |
def gameSetup():
# Read in File dictionary
# Read in Turn Text Files
global turntext
global dictionary
print("Welcome to Wheel of Fortune! To begin enter the names of the three players below.")
readDictionaryFile()
readTurnTxtFile()
readWheelTxtFile()
getPlayerInfo()
rea... | The main task of the code is to initialize a game with `gameSetup()` and execute rounds. For the first two rounds, it runs `wofRound()` for regular gameplay, then switches to `wofFinalRound()` for subsequent rounds, likely implementing a structured progression from standard rounds to a final round format. | def main():
gameSetup()
for i in range(0,maxrounds):
if i in [0,1]:
wofRound()
else:
wofFinalRound() |
def process_yaml(config_yml, key_name=None):
"""
Import yaml file. If key_name is provided, return value associated with key_name
otherwise, return the whole file content.
"""
try :
with open(config_yml, 'r') as config:
dict_config = yaml.safe_load(config)
if key_name:
... | (The code initializes a Relacs object by processing configuration YAML files, determining base directories from provided or default configurations, extending the main config with additional parameters, and verifying the existence of required files and paths through the `check_paths()` method.) | def __init__(self, config_yml, experiment_name="GenericRelacsObject", snakePipes_config=None):
""" initializer of relacs object """
# 2. check that bam files exist and are indexed
self.experiment_name = experiment_name
self.config_yml = process_yaml(config_yml,"chip_dict")
self.s... |
def restore_failed(db):
res = db[RAW_DATA].update({'status' : FAILED}, {'$set' : {'status' : READY}})
print(f"...restored {res}")
def get_ready_data(db, limit):
res = db[RAW_DATA].find({'status' : {'$in' : [None, READY]}}).limit(limit)
print(f"...found messages to enrich limit={limit}")
return res
... | The main task of the code is to connect to a database, restore failed records, retrieve up to 100,000 messages, check if any messages exist, and enrich them if found. The function exits early if no messages are retrieved, otherwise processes the data for further use. | def main():
db = sync_db_connect()
restore_failed(db)
messages = get_ready_data(db, 100000)
if not messages:
print("...Didn't find any messages")
exit(0)
enrich_messages(db, messages) |
def _get(self, url, params=None, check_auth=False):
headers = self._get_headers()
if params is not None:
url = url + '?' + urlencode(params, True)
full_url = self._get_full_url(url)
response = requests.get(full_url, headers=headers, timeout=self.timeout, allow_redirects=False... | This function performs paginated user searches by sending requests to "/app/search" with CSRF token authentication, yielding results one by one up to the specified limit, with a timeout between requests. It uses an offset parameter to handle pagination, incrementing it after each response until no more users are found ... | def search(self, options, limit=1000, timeout=0.0):
response = self._get("/app/search", check_auth=True)
csrf_token = find_csrf_token(response.text)
offset = 0
params = self._prepare_search_params(options)
params['csrf_token'] = csrf_token
while True:
params[... |
def initialize_player_team_data():
teams = {
'Argentina': 'Ah, the most in-form team in the world! They are strong favourites to win for sure. Coming into the World Cup off the back of a 36-match unbeaten streak isn\'t too shabby. They will be looking to add to their recent Copa America victory.',
'... | The main task of the code is to initialize and train machine learning models (logistic regression, SVM, MLP) using word2vec embeddings from a dataset, while loading player/team data and questions. It returns trained models, embeddings, and data structures for further processing or analysis. | def initialize():
teams, players, questions = initialize_player_team_data()
documents, labels = load_as_list("dataset.csv")
word2vec = load_w2v(EMBEDDING_FILE)
logistic, svm, mlp = instantiate_models()
logistic = train_model(logistic, word2vec, documents, labels)
svm = train_model(svm, word2vec,... |
def initialize_player_team_data():
teams = {
'Argentina': 'Ah, the most in-form team in the world! They are strong favourites to win for sure. Coming into the World Cup off the back of a 36-match unbeaten streak isn\'t too shabby. They will be looking to add to their recent Copa America victory.',
'... | The main task of the code is to run a FIFA World Cup-themed chatbot that interacts with users by collecting their preferences (favorite team, player, confidence level), analyzing sentiment of responses using SVM/Word2Vec, and performing stylistic analysis. It maintains a loop to ask follow-up questions, handle dynamic ... | def run_chatbot():
# [YOUR CODE HERE]
teams, players, questions = initialize_player_team_data()
welcome_state()
name = get_name_state()
excited = input("Are you excited for the upcoming FIFA World Cup?\nYou: ")
sentiment_analysis_state(excited, svm, word2vec, 0)
fav_team = input(f"Tell me {n... |
def extract_user_info(user_input):
name = re.search("((^|\s)([A-Z][A-Za-z.'&\-]*)\s+([A-Z][A-Za-z.'&\-]*\s+){0,2}([A-Z][A-Za-z.'&\-]*)(\s+|$))", user_input)
if name:
return name.group().strip()
return ""
def sentiment_analysis_state(user_input, model, word2vec, first_time=0):
# Check the user's ... | The code processes user prompts in a chatbot context, appending messages to a list and returning tailored responses. It checks for specific questions about the FIFA World Cup, performing sentiment analysis, stylistic analysis, or extracting user info. Conditional logic directs outputs like greetings, team/player prefer... | def reply(prompt, msg, model, answers):
answers.append(msg)
print("Answer stored in list:", answers)
if " no " in prompt.lower():
return ""
if prompt[:7] == "Welcome":
name = extract_user_info(msg)
return f"Hi {name}!"
elif prompt == "Are you excited for the upcoming FIF... |
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
def train_without_vol(opt, device):
if opt.dataset == 'mnist':
train_set, val_set, test_set, model, T = experiment_mnist(opt)
... | The main task of the code is to set up a device (CPU/GPU) based on availability and configuration, then execute either `train_without_vol` or `train` functions depending on the `opt.without_vol` flag, which determines whether to train with or without volume-related processing. The code initializes random seeds for repr... | def main(opt):
setup_seed(opt.seed)
device = torch.device("cuda:"+str(opt.device) if torch.cuda.is_available() else "cpu")
if opt.without_vol:
train_without_vol(opt, device)
else:
train(opt, device) |
def add_code_texts_key(self) -> None:
"""Add code text to the dictionary.
Adds an entry to the self.code_texts dictionary with self.first_letter as the key
and self.code_text as the value. If the key already exists, it does nothing.
"""
if self.first_letter not in self.code_texts... | The code generates function definitions for Maya commands by processing HTML files in the document root. It extracts return data, arguments, and descriptions from each HTML, creates function text, organizes it in `code_texts`, and prepares for PYI export. It iterates through files, skips ignored names, and structures d... | def create_code_text(self) -> None:
"""
Generates the complete code text for each Maya command.
This method iterates through all the HTML files in the document root directory, extracts the necessary
information (including return data, arguments, and descriptions), and creates the functi... |
def versionCompatible(self) -> None:
"""
Handles version-specific compatibility adjustments for the documentation.
This method checks the specified version of the Maya documentation and performs necessary adjustments
to ensure compatibility. For example, it handles specific file copying... | The main task of the code is to execute the complete process of generating PYI files for Maya commands by ensuring version compatibility, creating function texts for all commands, and handling the export of generated PYI files along with the creation of '__init__.py' files. | def run(self) -> None:
"""
Executes the complete process of generating PYI files for Maya commands.
This method is the main entry point for the PYI file generation process. It ensures version compatibility,
creates the function texts for all commands, and handles the export of the gener... |
def raise_error(message):
if message.find('E: ')==-1:
message = "\nE: " + message
raise Exception(change_font_color("bright red", message))
def read_path_list(file_paths: Union[str, list, tuple], extension=''):
extension = extension.strip('*.')
extension_str = f'/*.{extension}' if extension != '... | This function checks if all file paths in the provided list, after removing their respective base paths, are identical. It raises an error if fewer than two paths are provided, processes the paths with an optional extension, and returns `True` if all relative paths match, otherwise `False`.) | def compare_path_list(file_paths: Union[list, tuple], extension=''):
if len(file_paths) < 2:
raise_error("Check number of file_paths in compare_path_list()")
path_list = read_path_list(file_paths, extension)
compare_list = []
for i, file_path in enumerate(path_list):
compare_list.append... |
def sign(x):
if x > 0:
return 1
elif x < 0:
return -1
return 0
def side(team):
if team:
return 1
return -1
def new_play(self, packet):
# Check for the round being active - otherwise we might start a play during the goal reset time
if packet.game_info.is_round_... | The code processes game packets to update player and boost states, manages game phases (countdown, live play, scoring), checks for boost collection by attackers, tracks scores, and renders game status text. It handles ball physics, game state transitions, and triggers new plays or halftime logic based on elapsed time a... | def run(self):
while True:
packet = self.wait_game_tick_packet()
# Pre-process the packet
if len(self.players) != packet.num_cars:
self.players = [Car(i, packet) for i in range(packet.num_cars)]
else:
for player in self.players:
... |
def greatest_database_seq_num(filename):
"""Return the greatest match sequence number stored in the local database."""
with open(filename) as data:
database = json.load(data)
matches = database['matches']
match_seq_nums = [m['match_seq_num'] for m in matches]
return max(match_seq_nums)
def s... | The function fetches Dota 2 match data based on specified game mode, lobby type, and human player count, filtering out matches with leavers. It retrieves matches within a sequence number range defined by start/end match IDs, avoids duplicates, and writes valid matches to a JSON file. The process handles error checking,... | def fetch_matches(filename, game_mode, lobby_type, human_players=10, start_match_id=None, end_match_id=None):
"""Fetch matches and write data to file if specified conditions are met."""
max_match_length = 18000 # seconds
# Setup start sequence number.
if start_match_id == 'latest':
try:
... |
def sort_images_by_scene(
self,
path_imges: List[Path], is_person: bool = False
) -> Tuple[List[Path], List[float]]:
"""
get matching features from a sequence of images (features are computed two /two)
:param ref_path:
:param img_path:
:return:
... | The code processes images by detecting people using a model, segments them based on a threshold, analyzes mask data, and reconstructs a video. It divides images into batches, saves detection results, sorts scenes, plots values, and generates a final video from segmented images with person data. | def run(self, threshold: float):
list_path_img = []
for img_path in list((Path(__file__).parent / "raw").glob("*.png")):
list_path_img.append(img_path)
# division des image avec/sans personne
self.model.detect(list_path_img[0:20], saveas=Path(__file__).parent / 'person.csv')
... |
def unzip(zip_file_path):
"""
Unzips a zip file and extracts its contents to the current directory.
Parameters:
zip_file_path (str): The path to the zip file to be extracted.
"""
# open the zip file in read-only mode
with zipfile.ZipFile(zip_file_path, 'r') as zip_file:
# extrac... | (The main task is to extract .bib files from a provided .zip archive, preprocess each .bib file using a script, and upload the processed data to a Solr instance. The function first unzips the input file, retrieves all .bib files in the directory, and iterates through them to execute preprocessing and subsequent Solr da... | def main():
"""
Extracts .bib files from a .zip file, calls the preprocess script for each .bib file, and uploads the resulting data to a Solr instance.
The function extracts .bib files from a .zip file,
calls the preprocess script for each .bib file,
and sends the resulting data to a Solr instance... |
def doAuth(self, key_id, secret, req_path, req_body, method="POST", content_type="application/json", datestring=False):
''' Calculate an authorization header value to accompany the request
Solis' API docs describe the method as:
Authorization = "API " + KeyId + ":" + Sign
... | The function fetches detailed information about a specific inverter from an API by sending a POST request with the inverter ID, handling authentication, and returning the response data or False if the request fails. | def fetchInverterDetail(self, inverter_id):
''' Fetch detail on a specific inverter
'''
# Construct the request body
req_body_d = {
"id": inverter_id
}
req_body = json.dumps(req_body_d)
req_path = "/v1/api/inverterDet... |
def doAuth(self, key_id, secret, req_path, req_body, method="POST", content_type="application/json", datestring=False):
''' Calculate an authorization header value to accompany the request
Solis' API docs describe the method as:
Authorization = "API " + KeyId + ":" + Sign
... | The main task of the code is to fetch a list of inverters from an API endpoint by constructing a request with pagination parameters, station ID (if provided), and authentication headers. It sends a POST request, processes the JSON response, and returns the result if successful, otherwise False. The function is part of ... | def fetchInverterList(self, station_id=False):
''' Fetch the list of inverters.
TODO: may want to implement iterating through pages at some
point
'''
# Construct the request body
req_body_d = {
"pageNo": 1,
"p... |
def doAuth(self, key_id, secret, req_path, req_body, method="POST", content_type="application/json", datestring=False):
''' Calculate an authorization header value to accompany the request
Solis' API docs describe the method as:
Authorization = "API " + KeyId + ":" + Sign
... | The main task of the code is to fetch a list of stations (referred to as "plants" in the UI) from an API by constructing a POST request with pagination parameters, handling authentication, and returning the response data if successful. The function retrieves up to 100 stations per page and includes a TODO for future pa... | def fetchStationList(self):
''' Fetch the list of stations.
In the Solicloud UI these are referred to as plants
Basically, the site at which devices are deployed.
So, if you had multiple inverters in one location this
would return the total values
... |
def aggregate(self, params):
if self.rule == 'trimmed':
return self.trimmed(params, self.compromised)
if self.rule == 'median':
return self.trimmed(params, (len(params) - 1) // 2)
return params[0]
def krum(self, compromised_states, n=None):
"""
select ... | The code updates a model's parameters using aggregation rules ('trimmed', 'median', or 'krum') to defend against attacks. For 'krum', it dynamically adjusts parameters like lambda to handle compromised states, iteratively refining aggregated weights. It loads the updated parameters into the model and logs the state. Th... | def update(self):
if self.rule == 'trimmed' or self.rule == 'median':
d = {}
i = 0
for k, v in self.model.state_dict().items():
t = torch.zeros_like(self.states[i][0])
for j in range(t.shape[0]):
t[j] = self.aggregate(self.s... |
def select_clients(self, n=2):
return random_selection(self.clients, n)
def _remote_method_async(method, rref, *args, **kwargs):
args = [method, rref] + list(args)
return rpc.rpc_async(rref.owner(), _call_method, args=args, kwargs=kwargs)
def step(self, client_weights, new_weights=None):
self.st... | This function executes federated learning epochs across selected clients, aggregates training results, logs metrics, and optionally improves the model using compromised clients' data. It runs client training asynchronously, collects weights, and updates the global model through aggregation. Conditional 'improve' logic ... | def remote_run_epoch(self, epochs):
responses = []
client_weights = []
selected_clients = self.select_clients(self.config.clients_per_round)
self.epoch_counter += epochs
for client in selected_clients: # de facto sequential execution for CPU acceleration
responses.ap... |
def get_items(
self,
):
"""
Retrieve a dict of *all* items.
```
{'module 1': {
'url': ***,
'branch': ***,
},
...
}
```
This is implemented in a separate function as many functions from this router
... | The main task of the code is to filter a list of modules based on optional tag parameters, applying OpenStack-style tag logic with wildcard support. It processes tags, tags_any, not_tags, and not_tags_any to retrieve modules whose metadata keywords match the specified criteria, handling wildcards for partial matches an... | def get_filtered_list(
self,
tags: Union[Tuple, None] = Query(default=None),
tags_any: Union[Tuple, None] = Query(default=None),
not_tags: Union[Tuple, None] = Query(default=None),
not_tags_any: Union[Tuple, None] = Query(default=None),
):
"""
Retrieve a l... |
def draw_tiles(self, matrix, offsets=(0, 0), outline_only=False):
for y, row in enumerate(matrix):
for x, val in enumerate(row):
if val == 0:
continue
coord_x = (offsets[0] + x) * self.grid_size
coord_y = (offsets[1] + y) * self.gri... | This code renders a game screen by drawing a grid, tiles, and UI elements. It fills the background, alternates grid line colors, displays the game board and predicted tiles, renders dynamic text (score, high score, controls), and updates the display. It handles game states like "Game Over" or "Paused" and adjusts visua... | def draw(self):
self.screen.fill(TUtils.get_color_tuple(COLORS.get("BACKGROUND_BLACK")))
for a in range(GRID_COL_COUNT):
color = TUtils.get_color_tuple(COLORS.get("BACKGROUND_DARK" if a % 2 == 0 else "BACKGROUND_LIGHT"))
pygame.draw.rect(self.screen, color,
... |
def add_tile_to_board(self):
for cy, row in enumerate(self.tile_shape):
for cx, val in enumerate(row):
if val == 0:
continue
self.board[cy + self.tile_y - 1][min(cx + self.tile_x, 9)] = val
def calculate_scores(self):
score_count = 0
... | This function handles the downward movement of a game tile, updating the score based on the distance dropped. If 'instant' is True, it calculates the maximum drop distance and updates the score accordingly; otherwise, it moves the tile one step. After checking for collisions, it adds the tile to the board, calculates f... | def drop(self, instant=False):
if not self.active or self.paused:
return
if instant:
destination = TUtils.get_effective_height(self.board, self.tile_shape, (self.tile_x, self.tile_y))
self.score += PER_STEP_SCORE_GAIN * (destination - self.tile_y)
self.til... |
def log(self, message, level):
if MIN_DEBUG_LEVEL > level:
return
current_time = datetime.now().strftime("%H:%M:%S:%f")[:-3]
print(f"[{level}] {current_time} >> {message}")
def reset_board(self):
self.board = [[0] * GRID_COL_COUNT for _ in range(GRID_ROW_COUNT)]
def move_tile... | The main task of the code is to initialize a Tetris game by setting up the game board, configuring keyboard controls for tile movement and rotation, generating the tile bank, spawning the initial tile, and initializing score, line count, and fitness metrics to zero. | def init_game(self):
self.log("Initializing game...", 2)
self.active = True
self.reset_board()
self.grid_size = int(SCREEN_HEIGHT / GRID_ROW_COUNT)
self.log("Tetris grid size calculated to: " + str(self.grid_size), 2)
self.key_actions = {
"ESCAPE": self.tog... |
def move_tile(self, delta):
if not self.active or self.paused:
return
new_x = self.tile_x + delta
new_x = max(0, min(new_x, GRID_COL_COUNT - len(self.tile_shape[0])))
if TUtils.check_collision(self.board, self.tile_shape, (new_x, self.tile_y)):
return
self... | This function processes a game action (move, rotate, swap, drop), updates the game state, calculates the reward based on score or fitness, and returns the updated board, reward, game status, and next tile for the agent's environment interaction. | def step(self, action=0, use_fitness=False):
if HAS_DISPLAY:
pygame.event.get()
previous_fitness = self.fitness
previous_score = self.score
if action in [1, 2, 3, 4]:
self.move_tile((-1 if action in [1, 3] else 1) * (1 if action in [1, 2] else 2))
elif... |
def move_tile(self, delta: int):
assert delta in [-2, -1, 1, 2], "Invalid move distance"
new_x = self.tile_x + delta
new_x = max(0, min(new_x, GRID_COL_COUNT - len(self.tile_shape[0]))) # clamping
if TUtils.check_collision(self.board, self.tile_shape, (new_x, self.tile_y)):
... | This code processes a game action by updating the game state based on the input action. It validates the action (0-8), executes corresponding operations like moving, rotating, swapping, or dropping tiles, and ensures the game continues if not over. | def step(self, action: int):
assert action in list(range(8 + 1)), "Invalid action, use 0-8 for actions"
if self.game_over:
return
if action in [1, 2, 3, 4]:
self.move_tile((-1 if action in [1, 3] else 1) * (1 if action in [1, 2] else 2))
elif action == 5:
... |
def log(self, message, level):
if MIN_DEBUG_LEVEL > level:
return
current_time = datetime.now().strftime("%H:%M:%S:%f")[:-3]
print(f"[{level}] {current_time} >> {message}")
def init_game(self):
self.log("Initializing game...", 2)
self.active = True
self.reset... | This code initializes a game system by setting up game state variables (score, grid, etc.), initializing a pygame display for rendering, and starting the game. It handles both internal game logic and graphical interface setup, including event handling and logging, to prepare the game for execution. | def __init__(self):
self.tile_shape = None
self.tile = None
self.key_actions = None
self.paused = False
self.grid_size = None
self.active = None
self.score = 0.0
self.lines = 0
self.high_score = 0.0
self.high_score_lines = 0
self.fi... |
def prepare_data(config):
# prepare the train/test data for the model
print('Loading data......')
with open(config['load_file'], 'r', encoding='utf8') as f:
data = f.read().splitlines()
if config['mode'] == 'train':
with open(config['risk_file'], 'r') as f:
__risks = [float(x... | This code trains a token classification model (with optional CRF) using BERT, loading pre-trained weights and updating from checkpoints. It prepares training/validation data, implements multi-task learning with MRT loss and regularization, and evaluates performance using external scoring scripts. The model is saved per... | def train(config):
print('-' * 50)
print('Loading pre-trained transfer model......')
if config['CRF']:
model = BertForTokenClassificationWithCRF.from_pretrained(config['model_name'],num_labels=config['tagset_size']+1)
else:
model = BertForTokenClassification.from_pretrained(config['... |
def prepare_data(config):
# prepare the train/test data for the model
print('Loading data......')
with open(config['load_file'], 'r', encoding='utf8') as f:
data = f.read().splitlines()
if config['mode'] == 'train':
with open(config['risk_file'], 'r') as f:
__risks = [float(x... | The main task of the code is to perform token classification inference using a pre-trained BERT model (with optional CRF) on test data. It loads the model from a checkpoint, prepares test data, runs predictions, and saves results to a file. The process includes checking model existence, configuring device placement, an... | def test(config):
print('-' * 50)
print('Loading core model......')
load_model_name = config['test_model']
if os.path.exists(config['test_model']):
pass
else:
print('the test model ' + config['test_model'] + ' is not exist pls check it in the config.txt')
print('Core model name i... |
def load_config(config_data):
new_config = dict()
multi_line_flag = 0
multi_key = ''
multi_value = ''
for token in config_data:
config_list = token.split('=')
if re.sub('\W', '', token) == '':
continue
if token[0] == '#':
#it is a note
cont... | The main task of the code is to initialize and configure a machine learning model based on a provided configuration file. It sets up token mappings, loads configuration parameters, handles device (CPU/GPU) initialization, and executes either training or testing mode depending on the config. The code prepares the model ... | def main(config_file):
print('initialize the configuration')
token_mapping_rule = {'<pku>': '[unused4]', '/<pku>': '[unused5]',
'<zx>': '[unused6]', '/<zx>': '[unused7]',
'<msr>': '[unused8]', '/<msr>': '[unused9]',
'<ctb>': '[unused1... |
def start_session(self) -> None:
"""
Turn on the driver for automation.
:return: None
"""
logger.info("Session preparing...")
self.driver = webdriver.Chrome(DRIVER_PATH)
def load_cookie(self, path: str) -> None:
"""
Load cookies if exists.
:param p... | The main task of the code is to scrape job links from LinkedIn by either loading existing cookies or logging in, then compiling the data into a pandas DataFrame for return. | def run(self) -> pd.DataFrame:
"""
Run the scraping from
:return:
"""
self.start_session()
if os.path.exists("data/cookies.txt"):
self.driver.get("https://www.linkedin.com/")
self.load_cookie("data/cookies.txt")
self.driver.get("https:/... |
def _conv_block(x,
num_filters,
kernel_size=(9, 9),
strides=(1, 1),
activation="mish",
kernel_regularizer=regularizers.l2(0.0005)):
if isinstance(strides, int):
strides = (strides, strides)
if strides[0] == 2:
x = la... | The function constructs the CSPDarknet53 neural network backbone, processing input through convolutional and CSPResnet blocks with specified filters and activations. It splits the network into three feature maps (path1, path2, path3) at different scales, applies spatial pyramid pooling, and returns these paths for mult... | def _CSPDarknet53(x, activation1="mish", activation2="leaky", kernel_regularizer=None):
x = _conv_block(x, num_filters=32, kernel_size=3, activation=activation1, kernel_regularizer=kernel_regularizer)
x = _CSPResnet(x,
num_iter=1,
num_filters1=64,
num_fil... |
def get_digit(img_path):
cropped=crop_grid(img_path)
cells_coor=extract_cells_coordinates(cropped)
total_dig=np.zeros((81, 45, 45, 1), dtype=float)#raw images
for i in range(0, np.shape(cells_coor)[0]):
digit=extract_clean_digit_area(cropped, cells_coor[i, :])
total_dig[i, :, :, :]=... | The code solves a Sudoku grid from an input image by replacing each cell with the corresponding solved digit's image, then generating a visual grid with lines. It returns the final solved grid as a numpy array of uint8 type. | def get_solved_grid_img(grid_img_path):
original_grid=get_digit(grid_img_path)
original_grid2=original_grid.copy()
print(original_grid2)
solution=grid_solver(original_grid)
print(original_grid2)
side=50
backgr=np.ones((9*side+1, 9*side+1, 3))*255
print('------------')
print... |
def _run_query_cos(self, query, top_n=-1, show_detail=True):
"""
Match score(altered) algorithm for ranking query search
"""
tokens = self._qtokenizer.tokenize(query)
if REMOVE_STOP_WORDS:
tokens = [i for i in tokens if i not in self._stop_words]
tokens = ... | The code processes a query by tokenizing, normalizing (stemming/lemmatizing), and searching for tokens in a dataset. If ranking is enabled, it uses specified algorithms (cos/match). It handles missing tokens by attempting substitutions, aggregates results, maps them to original documents, fetches CSV data, and returns ... | def run_query(self, query, ranking=False, top_n=-1, ranking_algo=None, show_detail=True):
"""
Calls algo based query search anf ranking if specified or
returns normal query search
"""
if ranking:
if ranking_algo == 'cos':
return self._run_query... |
def explode_first(tree, cursor=[]):
ourcursor = cursor.copy()
# print("explode? considering",tree,"cursor",cursor, "cursor length",len(cursor))
if len(cursor)==0:
thing = tree
else:
thing = get_pos(tree, cursor)
# print("looking at", thing)
if type(thing) != int:
... | The code processes a list of snailfish numbers by sequentially combining them, then repeatedly applying explosion (for nested pairs at depth >4) and splitting (for values >9) until no further reductions are needed. It finally computes and returns the magnitude of the reduced snailfish number. Your return | def process_snailfish(snailfish_additions):
snailfish = None
while len(snailfish_additions):
# print("snailfish before", snailfish)
if not snailfish:
snailfish = snailfish_additions.pop(0)
else:
snailfish = [ snailfish, snailfish_additions.pop(0) ]
# p... |
def get_image(self):
print("Loading...")
cam = cv2.VideoCapture(self.source)
img_counter = 0
frame_num = 0
detector = MTCNN()
start = time.time()
red_flag = 10
img_size = 180
scale_w = 30
scale_h = 0
percent_progress = 0
try... | The code processes image data by validating input, creating temporary directories, fetching images, applying data augmentation if enabled, splitting data into training and test sets, and cleaning up temporary files, while handling errors and measuring execution time. | def run(self):
if self.num_of_img < 1:
return print("Please input number of image!")
start = time.time()
try:
shutil.rmtree(self.temp_dir, ignore_errors=True)
os.mkdir(self.temp_dir)
except FileExistsError:
pass
status = self.get_im... |
def process_forecasts_and_observations(df):
"""Pandas dataframe with columns:
City, forecast_date, Platform, forecast_temperature,
observed_date, observed_temperature
make sure they are the correct type and create an error column.
error = observed - forecast"""
df = df.copy()
df = df.drop... | The main task of the code is to calculate and return odds for weather predictions based on input forecasts and thresholds. It processes forecast data, iterates through city-specific operators and thresholds, computes odds using helper functions, and stores results in a dictionary with generated keys. The function handl... | def odds(forecast_list, handles):
"""Wrapper function that takes a forecast for the next day
and the thresholds for prediction and then calculates the odds"""
odds_dict = dict()
df = db.forecasts_and_observations()
df = process_forecasts_and_observations(df)
df_f = list_to_dataframe(foreca... |
def delete():
setUnwatched()
index = listboxOne.curselection() #find index of selected cell
if len(index) != 0: #if if listbox 1
name = listboxOne.get(index[0]) #get name of movie to delete
movieList.pop(getIndex(name)) #delete from global list
listboxOne.delete(index[0]) #delete fro... | This function handles keyboard events to manage movie watchlist actions: Delete removes a movie, Ctrl+W marks it as watched, Ctrl+U unmarks it, Ctrl+S saves the list, and Ctrl+I opens movie info. Error handling is included for certain operations. | def key_pressed(event):
if event.keysym == "Delete":
delete()
#ctrl + w sets movie to watch
if event.keysym == 'w':
try:
setWatched()
except:
pass
#ctrl + u sest movie to unwatched
if event.keysym == 'u':
try:
setUnwatched()
... |
def ask_self_response_questions(q_num, num_correct):
"""The purpose of this function is to ask the user the 16 short response
questions, store their answers, and call the self_grade_answers function
which grades the answers and keeping a running score.
q_num - the question number that the user is on
... | The main task of the code is to serve as a program's table of contents, orchestrating a study guide by introducing the user, initializing tracking variables, and sequentially calling functions for two question types: 16 short-response questions and 7 math questions, concluding with closing remarks. | def main():
"""The purpose of this function is to act as a table of contents for the
program which includes calling the other functions."""
# Welcome statement and introduction
print("Welcome to your all inclusive certification study guide!")
name = input("Your name: ")
print("Hello,", name, ", ... |
def create_rpc_part(file_we, data):
if not has_rpc(data):
return ""
return """\
#include "{0}_ClientTransport.h"
namespace capnzero::{0}
{{
{1}
inline void registerMetatTypes()
{{
{2}
}}
class QClientRpc : public QObject, public {0}ClientRpcTransport
{{
Q_OBJECT
public:
QClientRpc(zmq::contex... | The main task of the code is to generate a C++ header file for a QObject-based Cap'n Proto RPC client. It creates a template with placeholders for RPC methods, signals, and Qt client code, formatted using snake-case naming. The output includes necessary includes, macro guards, and dynamically inserted components to def... | def create_capnzero_qobject_client_file_h_content_str(data, file_we):
return """\
#ifndef {0}_QOBJECT_CLIENT_H
#define {0}_QOBJECT_CLIENT_H
#include <QObject>
#include <QString>
{1}
{2}
{3}
#endif
""".format(to_snake_case(file_we).upper(), create_rpc_part(file_we, data), create_signal_part(file_we, data), create... |
def adjust_learning_rate(optimizer, epoch, gammas, schedule):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr
assert len(gammas) == len(schedule), "length of gammas and schedule should be equal"
for (gamma, step) in zip(gammas, schedule):
if (epoch >= st... | The code trains a neural network model using stochastic gradient descent (SGD) with learning rate adjustment, validates after each epoch, tracks training/validation metrics, saves the best model checkpoint, and plots performance curves. It initializes the optimizer, manages GPU usage, updates learning rates, computes t... | def train(model, train_loader, test_loader, criterion, log):
optimizer = torch.optim.SGD(model.parameters(), args.lr, momentum=args.momentum,
weight_decay=args.decay, nesterov=True)
if args.use_cuda:
torch.cuda.empty_cache()
model.cuda()
recorder = RecorderMeter(args.total_epo... |
def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 every args.decay_epoch_step epochs"""
lr = args.lr * (0.1 ** (epoch // args.decay_epoch_step))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
def train_epoch(train_l... | The code trains a neural network model over multiple epochs using a specified optimizer and loss function. It adjusts the learning rate, trains on the provided dataset, validates performance on a test set, logs accuracy and loss metrics, saves the best-performing model checkpoints, and plots training curves to track pr... | def train(model, train_loader, test_loader, criterion, start_epoch, total_epoches, log):
optimizer = torch.optim.SGD(model.parameters(), args.lr, momentum=args.momentum,
weight_decay=args.decay, nesterov=True)
if args.use_cuda:
torch.cuda.empty_cache()
model.cuda()
recorder = ... |
def get_train_subset_in_memory(train_loader_subset):
sub_inputs = []
sub_targets = []
for _, (input, target) in enumerate(train_loader_subset):
if args.use_cuda:
target = target.cuda(non_blocking=True)
input = input.cuda(non_blocking=True)
sub_targets.append(target)
... | The code performs iterative pruning of a neural network's convolutional layers to reduce computational cost (FLOPs) while maintaining performance. It selects layers for pruning based on loss evaluation of subsets, alternates between normalization and Euclidean methods, and periodically retrains the model to recover acc... | def prune(model, train_loader, train_loader_subset, test_loader, criterion, log):
sub_inputs, sub_targets = get_train_subset_in_memory(train_loader_subset)
with torch.no_grad():
val_acc_1, val_loss = validate(test_loader, model, criterion)
print_log("Before Prune - Val [Acc|Loss]: %.3f %% | %0... |
def get_train_subset_in_memory(train_loader_subset):
sub_inputs = []
sub_targets = []
for _, (input, target) in enumerate(train_loader_subset):
if args.use_cuda:
target = target.cuda(non_blocking=True)
input = input.cuda(non_blocking=True)
sub_targets.append(target)
... | The code performs iterative pruning on a neural network to reduce computational cost (FLOPs) while maintaining performance. It evaluates the model's accuracy and FLOPs baseline, then repeatedly prunes convolutional layers by selecting the layer with the smallest validation loss increase. Pruning alternates between 'nor... | def prune(model, train_loader, loader_subset, test_loader, criterion, log):
sub_inputs, sub_targets = get_train_subset_in_memory(loader_subset)
with torch.no_grad():
val_acc_top1, val_acc_top5, val_loss = validate(test_loader, model, criterion)
print_log("Before Prune, Val Acc@1: %0.3lf, Acc@5... |
def print_log(print_string, log, display=True):
if display:
print("{}".format(print_string))
log.write('{}\n'.format(print_string))
log.flush()
def prune(model, train_loader, train_loader_subset, test_loader, criterion, log):
sub_inputs, sub_targets = get_train_subset_in_memory(train_loader_sub... | The main task of the code is to handle pruning, training, and evaluation of a neural network (likely VGG) on CIFAR datasets. It initializes logging, datasets, and models, then executes tasks based on the specified mode: pruning a pre-trained model, training from scratch, or evaluating model performance (accuracy, FLOPs... | def main():
# Init logger
if not os.path.isdir(args.save_path):
os.makedirs(args.save_path)
log = open(os.path.join(args.save_path, 'log_seed_{}.txt'.format(args.manualSeed)), 'w')
state = {k: v for k, v in args._get_kwargs()}
print_log(state, log)
print_log("Random Seed: {}".format(a... |
def print_log(print_string, log, display=True):
if display:
print("{}".format(print_string))
log.write('{}\n'.format(print_string))
log.flush()
def prune(model, train_loader, loader_subset, test_loader, criterion, log):
sub_inputs, sub_targets = get_train_subset_in_memory(loader_subset)
wi... | The main task of the code is to handle model pruning, training, and evaluation for a neural network, with logging of parameters, FLOPs, and performance metrics. It creates data loaders, initializes models, applies pruning methods, trains models, and evaluates accuracy and computational efficiency (FLOPs) across differe... | def main():
# Init logger
if not os.path.isdir(args.save_path):
os.makedirs(args.save_path)
log = open(os.path.join(args.save_path, 'log_seed_{}.txt'.format(args.manualSeed)), 'w')
print_log('save path : {}'.format(args.save_path), log)
state = {k: v for k, v in args._get_kwargs()}
pr... |
def get_engage_lanes(data,config):
lanes = data['road_info']['lane']
orig = data['orig']
theta= data['theta']
engage_lanes = dict()
if 'manhattan' in config and config['manhattan']:
x_min, x_max, y_min, y_max = config['pred_range']
radius = max(abs(x_min), abs(x_max)) + max(abs(y_m... | The code generates a downsampled graph representation from input data by aggregating lane node information, features, and directional relationships (predecessor, successor, left, right) into a structured dictionary. It processes lane pairs, concatenates node attributes, converts data to numpy arrays, and applies dilati... | def get_dsmp_graph(self, data: dict) -> dict:
"""
get downsampled graph information.
"""
engage_lanes = get_engage_lanes(data,self.config)
ctrs, feats,node_idcs,num_nodes = get_nodes(engage_lanes,config)
pre_pairs,suc_pairs, left_pairs, right_pairs = get_lane_pa... |
def get_obj_states(self, index: int) -> dict:
"""Get the states of objects in a scenario corresponding to the given index.
Args:
index: index of scenario
Returns:
data: a dict with dict_keys(['index',
'objects_of_interest... | The main task of the code is to retrieve and process scenario data at a given index, constructing a dictionary with 9 keys. It combines object states and features using `get_obj_states()` and `get_obj_feats()`, then adds road information via `get_road_info()` and graph data via `get_dsmp_graph()`, returning the aggrega... | def __getitem__(self, index: int) -> dict:
"""
Args:
index
Notes:
A scenario is a dict of 9 keys:
'currentTimeIndex',
'dynamicMapStates'
'mapFeatures',
'objectsOfInterest',
'scenarioId',
'... |
def load_current_data(self):
with open('CurrentBars.csv', encoding='utf-8') as f:
data = f.read().strip()
x = self.parse_input_data(data)
return self.parse_input_data(data)
def gauss_normalize_my_input_data(self, input_data, train_means, train_stds):
input_data["ES"] ... | The code's main task is to predict the current value of a time series (ES) using pre-trained models. It loads model weights, normalizes input data with statistics from a CSV file, generates predictions, adjusts them using statistical parameters, and saves results with model performance metrics (R-squared) to a CSV file... | def calculate_current_prediction(self):
obj_name = "ES"
train_means = {}
train_stds = {}
with open('CurrentStats.csv', encoding='utf-8') as fStats:
data = fStats.read().strip()
for rec in str.split(data, '\n', maxsplit=-1):
srec = str.split(rec, '... |
def initialize_new_model(self, model_place):
# define model
#self._logger.debug('Re-creating new models')
model = Sequential()
model.add(LSTM(self.NUM_TS_LAGS, activation='tanh', input_shape=(self.NUM_TS_LAGS, self.NUM_FEATURES))) #"ARI")
model.add(Dropout(0.25)) ... | The main task of the code is to load and manage multiple pre-trained models (e.g., "ES_model_0", "ES_model_1"), initialize new models if files are missing, process incoming data by normalizing inputs/outputs, and generate new model generations using updated statistics. It continuously loads data, prepares objectives, d... | def main_loop(self):
obj_name = "ES"
for model_place in range(self.MODEL_POOL_SIZE):
modelfile = Path('.\{}_model_{}'.format(obj_name, model_place))
if modelfile.is_file():
mtime = modelfile.stat().st_mtime
model = keras.models.load_model('.\{}_mo... |
def get_backup_files(backup_path):
return list(
backup_path.glob(get_filename_with_counter(AVAILABLE_ACS_FILE, "*"))
) + list(backup_path.glob(get_filename_with_counter(ASSIGNED_ACS_FILE, "*")))
def get_backup_file_counters(files):
available_stem = get_filename_without_txt(AVAILABLE_ACS_FILE)
as... | The main task of the code is to back up specific files (AVAILABLE_ACS_FILE and ASSIGNED_ACS_FILE) from a working directory to a designated backup directory, using incremental counters to generate unique filenames. It verifies the backup directory exists, retrieves existing counters, calculates the next counter value, c... | def backup_files(working_path):
backup_path = working_path / BACKUP_DIR
if not backup_path.exists():
raise FileNotFoundError(backup_path)
files = get_backup_files(backup_path)
counters = get_backup_file_counters(files)
next_counter = counters[-1] + 1 if counters else 1
counters.append(ne... |
def get_ids_from_flat_file(flatfile):
if not os.path.exists(flatfile):
raise FileNotFoundError("flatfile")
ids = []
with open(flatfile, "r", encoding="utf-8") as f:
for line in f:
if line.startswith("ID "):
ids.append(line.split()[1])
return ids
def backup_fi... | The function `ac_assign` assigns specific accessions (ACs) from a file to a designated list based on entries in a flatfile. It verifies the working directory exists, backs up files, partitions available ACs into assigned and remaining groups, writes newly assigned ACs to a file with metadata (date, user, comment), and ... | def ac_assign(flatfile, comment, working_dir, today, user):
flatfile_entry_ids = get_ids_from_flat_file(flatfile)
working_path = Path(working_dir)
if not working_path.exists():
raise FileNotFoundError("working path")
backup_files(working_path)
available_acs_file = working_path / AVAILABLE_AC... |
def is_nested_dataframe(obj, return_metadata=False, var_name="obj"):
"""Check whether the input is a nested DataFrame.
To allow for a mixture of nested and primitive columns types the
the considers whether any column is a nested np.ndarray or pd.Series.
Column is consider nested if any cells in column h... | This function converts a nested pandas DataFrame (with time series as Series in cells) into a 3D NumPy array of shape (n_instances, n_columns, n_timepoints). It handles two cases: if all columns are nested, it directly stacks converted Series; if some columns are primitive, it first converts to a multi-indexed DataFram... | def from_nested_to_3d_numpy(X):
"""Convert nested Panel to 3D numpy Panel.
Convert nested pandas DataFrame (with time series as pandas Series
in cells) into NumPy ndarray with shape
(n_instances, n_columns, n_timepoints).
Parameters
----------
X : pd.DataFrame
Nested pandas DataFrame... |
def _enforce_min_instances(x, min_instances=1):
n_instances = x.shape[0]
if n_instances < min_instances:
raise ValueError(
f"Found array with: {n_instances} instance(s) "
f"but a minimum of: {min_instances} is required."
)
def is_nested_dataframe(obj, return_metadata=Fals... | The function `check_X` validates and standardizes input data (`X`) by ensuring it meets specified criteria: correct type (DataFrame/array), dimensionality (2D/3D), minimum columns/instances, and univariate constraints. It reshapes arrays, enforces structural rules, checks nested DataFrames, and converts to 3D numpy arr... | def check_X(
X,
enforce_univariate=False,
enforce_min_instances=1,
enforce_min_columns=1,
coerce_to_numpy=False,
):
"""Validate input data.
Parameters
----------
X : pd.DataFrame or np.array
Input data
enforce_univariate : bool, optional (default=False)
Enforce th... |
def __folder_path(folder):
assert folder.startswith('/'), folder
if not folder.endswith('/'):
folder = folder + '/'
return folder
def db_cursor(host=None, device_id=None):
conn = db_get_conn(host=host, device_id=device_id)
cursor = conn.cursor()
return cursor
def db_cursor_select_fetchon... | This function checks if a file exists in a database by querying with parameters like filename, folder, host, and device_id, returning True if a match is found, otherwise False. | def db_any_file_path(filename, folder=None, host=None, device_id=None, **kwargs):
'''Find any matching file by path and return bool.'''
assert host
fields = ('size',)
where = dict(
host=host,
filename=filename,
**kwargs,
)
if folder:
where.update(dict(
... |
def __folder_path(folder):
assert folder.startswith('/'), folder
if not folder.endswith('/'):
folder = folder + '/'
return folder
def db_cursor(host=None, device_id=None):
conn = db_get_conn(host=host, device_id=device_id)
cursor = conn.cursor()
return cursor
def db_cursor_select_fetchon... | The function retrieves the size of a specified folder from a database by querying records that match the given host, folder path, and optional device ID, returning the result as a database record. | def db_get_folder_size(folder, host=None, device_id=None):
'''Find a matching folder and return size.'''
assert host
fields = ('size',)
where = dict(
host=host,
folder=__folder_path(folder),
filename="",
)
if device_id:
where.update(dict(
device_id=dev... |
def db_cursor(host=None, device_id=None):
conn = db_get_conn(host=host, device_id=device_id)
cursor = conn.cursor()
return cursor
def __folder_path(folder):
assert folder.startswith('/'), folder
if not folder.endswith('/'):
folder = folder + '/'
return folder
def db_cursor_update_file(cu... | This function updates a file's status in a database by modifying the 'code' field, using parameters like folder, filename, host, and optional device_id to target the specific record. It constructs SQL update conditions and executes the change, committing the transaction to persist the update. | def db_update_file_status(folder, filename, status, host=None, device_id=None):
'''Update file status.'''
assert host
cursor = db_cursor(host=host, device_id=device_id)
data = dict(
code=status, # field is named code, status may involve other field changes
)
where = dict(
host=ho... |
def _create_slots(self, var_list):
# Create the beta1 and beta2 accumulators on the same device as the first
# variable.
if (self._beta1_power is None or
self._beta1_power.graph is not var_list[0].graph):
with ops.colocate_with(var_list[0]):
self._beta1_power = variables.Variable(self.... | This function applies gradients to model variables using accumulated gradients, with gradient clipping. It iterates over variable-gradient pairs, clips each gradient by norm, and applies the update via _apply_dense. The operations are grouped and returned as a TensorFlow operation for execution. | def apply_gradients(self, var_list, accum_grad_list, name=None):
update_ops = []
with tf.control_dependencies(None):
self._create_slots(var_list)
with tf.name_scope(name, self._name, []) as name:
self._prepare()
for var, accum_grad in zip(var_list, accum_grad_list):
with... |
def horizontal_movement(self, dt):
self.acceleration.x = 0
if self.LEFT_KEY:
self.acceleration.x -= horizontal_acceleration
elif self.RIGHT_KEY:
self.acceleration.x += horizontal_acceleration
self.acceleration.x += self.velocity.x * self.friction
self.velo... | This code updates an object's position by handling horizontal and vertical movement over time (dt), then checks for collisions with tiles and killer entities in both x and y axes to manage interactions or obstacles during movement. | def update(self, dt, tiles, killers, chains):
self.horizontal_movement(dt)
self.checkCollisionsx(tiles, killers)
self.vertical_movement(dt)
self.checkCollisionsy(tiles, killers) |
def __check_collision(self):
return self.player.rect.collidelistall(self.layers)
def __check_end_level(self):
end=self.current_level["end"]
point=end["location"]
if self.player.rect.collidepoint(point["x"],point["y"]):
self.__change_level()
def __restart_level(self):
if self.player.rect.y>610:... | The code updates the game state by checking collisions, updating the player based on collision presence, checking if the level should end, and restarting the level. It processes input, handles game logic, and triggers level transitions or resets. | def update(self, delta_time, time):
hits = self.__check_collision()
self.player.update(len(hits) > 0)
self.__check_end_level()
self.__restart_level() |
def _read_data(*input_paths):
all_jsons = []
path_not_found_fmt = "Warning! Path {0} not found."
for path in input_paths:
if not os.path.exists(path):
print(path_not_found_fmt.format(path))
elif os.path.isfile(path):
all_jsons.append(_read_json(path))
else:
... | The main task of the code is to read data from specified paths, filter it using a thesaurus, and convert the filtered dataset into a table format for structured output. | def _read_table(thesaurus, *paths):
data = _read_data(*paths)
data, _ = _filter_data(data, thesaurus)
return _dataset_to_table(data) |
def _read_data(*input_paths):
all_jsons = []
path_not_found_fmt = "Path {0} not found."
for path in input_paths:
if not os.path.exists(path):
_print_warning(path_not_found_fmt.format(path))
elif os.path.isfile(path):
all_jsons.append(_read_json(path))
else:
... | The function `_read_table` processes data by reading files from specified paths, filters the data using a provided thesaurus, and converts the resulting dataset into a structured table format for further use. | def _read_table(thesaurus, *paths):
data = _read_data(*paths)
data, _ = _filter_data(data, thesaurus)
return _dataset_to_table(data) |
def _read_data(*input_paths):
all_jsons = []
path_not_found_fmt = "Path {0} not found."
for path in input_paths:
if not os.path.exists(path):
_print_warning(path_not_found_fmt.format(path))
elif os.path.isfile(path):
all_jsons.append(_read_json(path))
else:
... | The main task of the code is to read data from specified paths, filter it using a thesaurus, and convert the filtered dataset into a table format. The function first loads data via `_read_data`, applies filtering with `_filter_data` using the thesaurus, and finally transforms the result into a table using `_dataset_to_... | def _read_table(thesaurus, *paths):
data = _read_data(*paths)
data, _ = _filter_data(data, thesaurus)
return _dataset_to_table(data) |
def _create_statements_table(code_marks, thesaurus):
table = None
for code, text in thesaurus.items():
marks = code_marks.get(code)
if marks is None:
continue
stats = _marks_to_stats(marks)
if table is None:
table = pandas.DataFrame(columns=stats.keys())
... | The function generates a report table from code marks and a thesaurus. It creates either a statements table (if no unions) or groups table (with unions), then adds a "TOTAL" row summarizing all marks. The table is returned with aggregated statistics. | def _create_report_table(code_marks, thesaurus, unions=None, strict=False):
if unions is None:
table = _create_statements_table(code_marks, thesaurus.items)
else:
table = _create_groups_table(
code_marks, thesaurus.data, unions, strict)
table.loc["TOTAL"] = _marks_to_stats(
... |
def _read_data(input_paths):
all_jsons = []
path_not_found_fmt = "Warning! Path {0} not found."
for path in input_paths:
if not os.path.exists(path):
print(path_not_found_fmt.format(path))
elif os.path.isfile(path):
all_jsons.append(_read_json(path))
else:
... | The main task of the code is to read data from specified paths, filter it using a thesaurus, and convert the filtered dataset into a table format for further processing or analysis. | def _read_table(paths, thesaurus):
data = _read_data(paths)
data, _ = _filter_data(data, thesaurus)
return _dataset_to_table(data) |
def _read_table(thesaurus, *paths):
data = _read_data(*paths)
data, _ = _filter_data(data, thesaurus)
return _dataset_to_table(data)
def _calculate_match_table(ref_data, test_data, thesaurus, group_unions=None):
excess_items = set()
match_table = {}
for db in ref_data:
if db not in test_... | The function compares reference and test datasets using a thesaurus, calculating matches, excess items, and statistics. It validates input data, checks required groups, and returns a structured result containing match details, statistical analysis, and compliance flags. | def _compare(input_data):
thesaurus_label = input_data.thesaurus.label
ref_data = _read_table(thesaurus_label, input_data.ref_path)
test_data = _read_table(thesaurus_label, *input_data.test_paths)
if not ref_data or not test_data:
raise Error("Input files not found")
match_marks, excess_item... |
def _parse_thesaurus(filename):
data = _read_json(filename, ordered=True)
items = OrderedDict()
ann_groups = OrderedDict()
for group in data[Text.GROUPS]:
for ann in group[Text.REPORTS]:
ann_id = ann[Text.ID]
items[ann_id] = ann[Text.NAME]
ann_groups[ann_id] =... | The main task of the code is to read and validate input data for a processing task. It parses a thesaurus, reads reference and test datasets, checks their existence, and compiles them with additional parameters into an `InputData` object. If required data is missing, it raises an error. The function ensures all input c... | def _read_input_data(input_data):
error_message = "Input files not found"
thesaurus = _parse_thesaurus(input_data.thesaurus)
thesaurus_label = thesaurus.label
ref_data = _read_table(thesaurus_label, input_data.ref_anns)
test_data = _read_test_table(thesaurus_label, *input_data.test_anns)
if not ... |
def _parse_args():
parser = argparse.ArgumentParser(
description="Select records by dianoses group")
parser.add_argument("paths", nargs="+", help="Paths to annotation folders")
parser.add_argument("-g", "--groups", nargs="*")
parser.add_argument("-t", "--thesaurus", required=True)
args = par... | The main task of the code is to parse command-line arguments, read data from specified paths into a table using a thesaurus label, generate a structured report by grouping data with thesaurus terms, and save the final report as a JSON file named "result.json". | def main():
args = _parse_args()
datatable = _read_table(args.paths, args.thesaurus.label)
report = _create_report(datatable, args.groups, args.thesaurus.data)
_write_report(report, "result.json") |
def _parse_args(args):
parser = argparse.ArgumentParser(description="Annotations comparing")
parser.add_argument(
"ref_path", help="Path to file or folder with reference annotaions")
parser.add_argument(
"test_paths", nargs="+",
help="Path to file or folder with test annotations"
... | The main task of the code is to parse input arguments, set a language, compare data, generate a report, and handle errors. It processes input data via `_parse_args`, configures language with `_set_language`, executes comparison via `_compare`, and outputs results with `_print_report`. Error handling captures specific `... | def main():
try:
input_data = _parse_args(os.sys.argv)
_set_language(input_data.lang)
result = _compare(input_data)
_print_report(result, input_data)
except Error as exc:
print("Error: {0}\n".format(exc))
except Exception as exc:
if _is_debug():
ra... |
def _parse_args(args):
parser = argparse.ArgumentParser(description="Annotations comparing")
parser.add_argument(
"ref_path", help="Path to file or folder with reference annotaions")
parser.add_argument(
"test_paths", nargs="+",
help="Path to file or folder with test annotations"
... | The main task of the code is to parse command-line arguments, compare data using `_compare`, generate a structured report table with `_create_report_table`, and output the report via `_write_report`, while handling errors by logging exceptions to a file or raising them in debug mode. | def main():
try:
input_data = _parse_args(os.sys.argv)
code_marks = _compare(input_data)
table = _create_report_table(
code_marks, input_data.thesaurus, input_data.unions,
input_data.strict)
_write_report(table)
except Error as exc:
print("Error: {... |
def _parse_args(args):
parser = argparse.ArgumentParser(description="Annotations comparing")
parser.add_argument(
"ref_anns", help="Path to file or folder with reference annotaions")
parser.add_argument(
"test_anns", nargs="+",
help="Path to file or folder with test annotations"
... | The main task of the code is to parse input arguments, compare data using `_compare`, generate a report with `_write_report`, and handle errors by logging fatal exceptions to a file or re-raising them in debug mode. | def main():
try:
input_data = _parse_args(os.sys.argv)
result = _compare(input_data)
_write_report(result, input_data)
except Error as exc:
print("Error: {0}\n".format(exc))
except Exception as exc:
if _is_debug():
raise
log_filename = "errors-log.... |
def bounding_box(z_where, x_size):
z_where = np.reshape(z_where, (2, 3))
# TODO: support non-quadratic patch-sizes
corners = np.array([[0.0, 0.0], [0.0, x_size], [x_size, x_size], [x_size, 0.0]])
corners = np.concatenate((corners, np.ones((4, 1), dtype=np.float32)), axis=1)
transformed_corners = np... | The function draws rectangles on an image based on parameters z_where (positions) and z_pres (presence indicators), overlays optional text, and returns the modified image as an array. It converts the input array to an image, generates bounding boxes for active elements (z_pres > 0.3), draws them with overlap, and adds ... | def draw_image(img_arr, z_where, z_pres, window_size, text=None):
mode = 'L' if len(img_arr.shape) == 2 else 'RGB'
img = Image.fromarray((img_arr * 255).astype(np.uint8), mode=mode)
img = img.convert('RGB')
draw = ImageDraw.Draw(img)
rectangles = np.zeros((z_where.shape[0], 4, 2))
for i in rang... |
def h_delete(root, value, path):
"""
attempts to delete the node with a specified value in the tree
parameters:
root (Node): the tree to delete from
value (int): the value of the node to search for and delete
path [(string, int)]: the path and operations taken to perform the
... | The function `delete` attempts to remove a node with a specified value from a binary tree. It returns the modified tree (or original if not found), a list of operations performed, the tree's height post-operation, and the level of the deleted node. If the node isn't found, it returns the original tree and a `NOT_FOUND`... | def delete(root, value):
"""
attempts to delete the node with a specified value in the tree
parameters:
root (Node): the tree to delete from
value (int): the value of the node to search for and delete
returns (Node, [(string, int)], int, int):
1st value is the new tree (possibl... |
def h_insert(root, value, path):
"""
helper function to insert a node into a binary search tree.
parameters:
root (Node): the tree to insert into
value (int): the value to try and insert into the tree
path [(string, int)]: the path and operations taken to perform the
inserti... | The function `insert` inserts a node into a binary search tree (BST) while enforcing a maximum height constraint. If insertion would cause the tree's height to exceed `max_height`, it reverses the insertion by deleting the node. It returns the updated tree, a list of operations (e.g., insertions/deletions), the tree's ... | def insert(root, value, max_height):
"""
function to insert a node into a binary search tree.
parameters:
root (Node): the tree to insert into.
value (int): the value to try and insert into the tree.
max_height (int): the maximum tree height allowed by the view
returns (Node, [... |
def generate_real_samples(dataset, n_samples):
# random index
idx = np.random.randint(0, dataset.shape[0], n_samples)
X = dataset[idx]
# labels = 1
y = np.ones((n_samples, 1))
y = smooth_labels(y)
return X, y
def generate_fake_samples(g_model, latent_dim, n_samples):
x_input = generate_l... | This function trains a GAN by alternating between updating the discriminator with real/fake samples and training the generator via the GAN model. It iterates through epochs/batches, generates real/fake data, trains discriminator twice per batch, trains generator with latent vectors, prints loss metrics, and evaluates p... | def train(g_model, d_model, gan_model, dataset, latent_dim, n_epochs=100,
n_batch=128):
batch_per_epoch = int(dataset.shape[0] / n_batch)
half_batch = int(n_batch / 2)
# enumerate epochs
for i in range(n_epochs):
for j in range(batch_per_epoch):
# get random real samples
... |
def read_input():
with open('../input/03.txt') as f:
return f.read().split()
def consumption(input):
transposed = [list(row) for row in zip(*input)]
gamma = ''.join(['1' if row.count('1') > row.count('0') else '0' for row in transposed])
epsilon = ''.join(['1' if row.count('1') < row.count('0') ... | The main task of the code is to read input data, compute two values using the `consumption` and `life_support` functions, and print the results. It processes input to determine consumption and life support metrics, then outputs them sequentially. | def main():
input = read_input()
print(consumption(input))
print(life_support(input)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.