dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def calculate(self):
try:
result = eval(self.result)
if isinstance(result, float) and result.is_integer():
result = int(result)
self.result = str(result)
except ZeroDivisionError:
messagebox.showwarning("Error", "Cannot divide by zero. What... | This function handles button clicks in a GUI calculator. It checks the button's text: if "=", it triggers calculation; if "C", it clears the input; otherwise, it appends the button's text to the result and updates the entry field. | def handle_button_click(self, button):
button_text = button["text"]
if button_text == "=":
self.calculate()
elif button_text == "C":
self.clear()
else:
self.result += button_text
self.update_entry() |
def Transform(v, translate, scale):
return V3(
round((v[0] + translate[0]) * scale[0]),
round((v[1] + translate[1]) * scale[1]),
round((v[2] + translate[2]) * scale[2])
)
def norm(v0):
l = length(v0)
if l == 0:
return V3(0, 0, 0)
return V3(
v0.x / l,... | This function loads a 3D model from an OBJ file, applies translation/scale transformations, calculates face normals, computes lighting intensity using a light vector, and renders each triangular or quadrilateral face as shaded triangles. It uses cross products for normals, dot products for lighting, and adjusts grey-sc... | def load(filename, translate, scale):
model = Obj(filename)
light = V3(0, 0, 0.8)
for face in model.faces:
vcount = len(face)
if vcount == 3:
f1 = face[0][0] - 1
f2 = face[1][0] - 1
f3 = face[2][0] - 1
A = Transf... |
def user_input():
choice = input("")
if choice.capitalize() == "Inventory" or choice.capitalize() == "I":
inventoryfunc()
return choice
else:
return choice
def chest():
print(
".\n.\n.\nYou walk out of the room and wander around the castle carelessly...\nYou found a suspi... | This function presents a game scenario where the player interacts with a priest after awakening, choosing to either ignore or ask for information. Based on the choice, it progresses to 'chest()' and 'kingschallenge()' functions, with the 'Ask' path providing lore about being summoned to defeat a demon lord and completi... | def scenario1():
print(".\n.\n.\nNext to you, you spotted a priest kneeling next to you...")
print("Priest: You finally wake up, sir Hero; you were in a slumber for a whole week!")
print("Priest: We almost thought of dispos- Uhhh... I mean ask for help from the archmage!")
print("What do you want to do?... |
def merchant():
print(".\n.\n.\nOn your way there, a merchant approachs you menacingly..."
"\nMerchant: Hey! Young man, would you like to buy this Roasted Dragon Meat for 100 coins? (Buy/Ignore) ")
print("Hint: Check your inventory!")
choice = user_input()
while choice.capitalize() != "Buy" an... | The main task of the code is to narrate a fantasy adventure scenario where the player journeys to the Archmage Tower, encounters a merchant, battles a slime, and reaches the archmage's tower, using function calls to structure interactive game events and print statements for storytelling. | def scenario2():
print(
"You begin your journey to the archmage tower. According to the priest, Sir Dee Z. Nuts, the archmage, "
"is the strongest mage in the whole continent. ")
merchant()
print("That doesn't stop you as you continue to your adventure courageously.")
slime()
print("... |
def getTileList(self):
return self.tilelist
def getTileListEmpty(self):
return self.tilelistempty
def checkaround8(self, i):
around8list = self.getaround8(i)
for iii in around8list:
(i2,lr) = iii
if i2 >= 0 and i2 < self.totaltiles:
if isinstance(s... | The function `selectTile` checks if a selected tile is valid. If the tile is "X", it returns `False` (indicating a loss). If not, it updates the tile's state: replacing `0` with `_` and triggering a surrounding check, or copying the tile's value. It returns `True` if the move is valid, ensuring game state updates and a... | def selectTile(self, location): # return true if still good, return false if lost
if self.getTileList()[location]=="X":
return False
elif self.getTileList()[location]!="X":
if self.getTileList()[location]==0:
self.getTileListEmpty()[location]="_"
s... |
def update_playing(self):
if self.k_esc:
self.state = self.STATE_PAUSE_MENU
if self.mode == self.MODE_PLAYER_VS_PLAYER:
# player left (HUMAN)
self.update_human(self.PLAYER_LEFT)
# player right (HUMAN)
self.update_human(self.PLAYER_RIGHT)
... | This code updates game states by calling specific methods based on the current state: playing, menus (main, pause, select mode), end game, or wait. It uses conditional checks to determine which update function to execute, ensuring appropriate game behavior transitions. | def update(self):
if self.state == self.STATE_PLAYING:
self.update_playing()
elif self.state == self.STATE_MAIN_MENU or self.state == self.STATE_PAUSE_MENU or self.state == self.STATE_SEL_MODE_MENU:
self.update_menus()
elif self.state == self.STATE_END_GAME:
s... |
def events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.k_up = True
elif event.key == pygame.K_DOWN:
... | This code runs a game loop that maintains a 60 FPS target by updating the game state, processing events, and rendering frames until the loop is exited. It uses Pygame's clock to track time, calculates delta time for smooth animations, and quits the Pygame instance when the loop terminates. | def run(self):
self.running = True
# main loop
while self.running:
self.elapsed = self.clock.tick(60)
self.delta = self.elapsed / 1000.0
self.events()
self.update()
self.render()
pygame.quit() |
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_SPACE:
s... | This method processes user input events in a Pygame game. It checks for quit requests, keyboard presses/releases, and mouse clicks. For each event, it triggers corresponding handlers like _check_keydown_events, _check_keyup_events, or _check_play_button to manage gameplay interactions and exit logic. | def _check_event(self):
"""Checking the player's reaction"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:... |
def _check_fleet_edges(self):
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
if self.stats.ships_left > 0:
self.stats.ships_left -= 1
self.sb.prep_ships()
... | This method updates alien positions, checks for collisions between the player's ship and aliens, and verifies if any aliens have reached the bottom of the screen, triggering responses like ship damage or game state changes. | def _update_aliens(self):
self._check_fleet_edges()
self.aliens.update()
"""Player collision with alien"""
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom() |
def _check_event(self):
"""Checking the player's reaction"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:... | The code runs a game loop that continuously checks for events, updates game elements (ship, bullets, aliens) if the game is active, and renders the screen. It maintains gameplay by handling user input, updating object positions, and displaying visuals until the game ends. | def run_game(self):
while True:
self._check_event()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen() |
def initialize_with_zeros(dim):
### START CODE HERE ### (≈ 1 line of code)
w = np.zeros((dim,1))
b = 0
### END CODE HERE ###
assert(w.shape == (dim, 1))
assert(isinstance(b, float) or isinstance(b, int))
return w, b
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = ... | The code trains a logistic regression model using gradient descent on training data, evaluates it on test data, and returns metrics. It initializes parameters, optimizes them via gradient descent, predicts class labels, calculates train/test accuracy, and stores results in a dictionary. The main task is to perform bina... | def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.005, print_cost = True):
### START CODE HERE ###
# initialize parameters with zeros (≈ 1 line of code)
w, b = initialize_with_zeros(X_train.shape[0])
# Gradient descent (≈ 1 line of code)
parameters, gr... |
def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
s... | The code defines a game loop that continuously checks for events, updates the player's ship, manages bullets, updates the screen, and maintains a 60 FPS frame rate to keep the game running smoothly. | def run_game(self):
while True:
self._check_events()
self.ship.update()
self._update_bullets()
self._update_screen()
self.clock.tick(60) |
def _check_events(self):
# Check for keypresses
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
... | The code defines a game loop that continuously processes events, updates game elements (ship, bullets, aliens), creates new aliens, and redraws the screen to maintain real-time gameplay interaction and visual updates. | def run_game(self):
while True:
self._check_events()
self._create_alien()
self.ship.update()
self._update_bullets()
self.aliens.update()
self._update_screen() |
def determine_index_of_covid(data: list[tuple[tuple[int, int], int]]) -> int:
"""Helper Function
Determine index of March 2020 in list
Preconditions:
- all(len(data) != 0
- all(1 <= data[i][0][1] <= 12 for i in range(len(data))
# Months are between 1 and 12
- all(data[i][1] >... | The code processes economic data by calculating actual GDP values, predicted values (via linear regression on pre-COVID data), and deviations for each sector. It returns a dictionary mapping sectors to tuples containing lists of (date, actual), (date, predicted), and (date, deviation) pairs, all rounded to integers. Th... | def run_computations(data: dict[str, list[tuple[tuple[int, int], int]]]) \
-> dict[str, tuple[list[tuple[tuple[int, int], int]], list[tuple[tuple[int, int], int]],
list[tuple[tuple[int, int], int]]]]:
""" Given data, return a dictionary of sector mapped to a list of dates and actu... |
def aggregate_4_sectors(combined_dict: dict) -> dict[str, list[tuple[tuple[int, int], int]]]:
"""
Helper Function 5:
Return a dictionary mapping the name of each economic sector
(Primary/Secondary/Tertiary/Quaternary) to the aggregated
sum of GDP values per industry in the respective sector.
In... | The function `open_convert_and_aggregate` processes a dataset file by opening it, converting its contents into a dictionary mapping industry names to tuples of year-month and GDP values. It then categorizes industries into four economic sectors (Primary/Secondary/Tertiary/Quaternary) and aggregates their GDP values per... | def open_convert_and_aggregate(filename: str) -> dict[str, list[tuple[tuple[int, int], int]]]:
"""
Opens and converts the dataset file into a dictionary mapping each industry name to
year-month tuples and their respective GDP value, then sorts each industry into an
economic sector (Primary/Secondary/Ter... |
def gauss (a, b, n,precision):
string_solution = ""
for k in range(n):
max = k
for i in range(k+1, n):
if abs(a[i][k]) > a[max][k]:
max = i
temp = a[k]
a[k] = a[max]
a[max] = temp
t = b[k]
b[k] = b[max]
b[max] = t
... | The function `solve` executes numerical methods to solve systems of linear equations, selecting between direct methods (Gauss Elimination, LU decompositions) or iterative methods (Gauss-Seidel, Jacobi). It accepts parameters like the matrix `a`, vector `b`, size `n`, precision, and optional inputs for iterative methods... | def solve(method, a, b, n, precision, x=None, iterations=None, rel_error=None):
time_i = time.perf_counter_ns()
result = ""
if (method == "Gauss Elimination"):
result = gauss(a, b, n, precision)
elif(method == "Gauss-Jordan"):
result = GaussJordan(a, b, n, precision)
elif(method =... |
def draw_field_matrix(mat_holder):
global fields_mat
global textvars_mat
global size
old_size= len(fields_mat)
new_size = size.get()
if (new_size == old_size): return
elif (new_size > old_size):
for i in range(old_size, new_size):
add_new_column(fields_mat, textvars_mat,... | The code defines a function `draw_system` that visualizes a system by drawing a matrix field using `draw_field_matrix`, rendering vectors with `draw_vec`, and initializing or handling an interaction via `on_choice`. It processes inputs like matrix holders, vector data, and text variables to generate a graphical represe... | def draw_system(mat_holder, b_vec, vec_holder, b_textvars):
draw_field_matrix(mat_holder)
draw_vec(b_vec, vec_holder, b_textvars)
on_choice("") |
def run_adaboost(X_train, y_train, T):
"""
Returns:
hypotheses :
A list of T tuples describing the hypotheses chosen by the algorithm.
Each tuple has 3 elements (h_pred, h_index, h_theta), where h_pred is
the returned value (+1 or -1) if the count at index h_inde... | The code implements AdaBoost with $ T = 80 $ iterations on a dataset, splitting it into training and test sets. It trains hypotheses and computes their weights ($ \alpha $-values), then evaluates cumulative training and test errors, as well as exponential loss, across iterations. Finally, it visualizes how these metric... | def main():
data = parse_data()
if not data:
return
(X_train, y_train, X_test, y_test, vocab) = data
T = 80
hypotheses, alpha_vals = run_adaboost(X_train, y_train, T)
#print("hypotheses: ", hypotheses)
#print("alpha_vals: ", alpha_vals)
"""
hypotheses = [(1, 26, 0.5), (-1, 31... |
def helper_ce():
mnist = fetch_openml('mnist_784')
data = mnist['data']
labels = mnist['target']
train_idx = numpy.random.RandomState(0).permutation(np.where((labels[:8000] != 'a'))[0])
test_idx = numpy.random.RandomState(0).permutation(np.where((labels[8000:10000] != 'a'))[0])
train_data_unsc... | The code performs a grid search over learning rates (eta) to find the optimal value for a classifier using stochastic gradient descent (SGD). It evaluates average validation accuracy across 10 runs for each eta, plots accuracy vs. eta on a log scale, and highlights the best-performing eta. The goal is to identify the l... | def q_2a():
train_data, train_labels, validation_data, validation_labels, _, _ = helper_ce()
#print("got data")
T = 1000
eta_vector = np.array([10.0 ** p for p in np.arange(-9, 5.5, 0.5)])
accur_vector = []
best_eta = -1
best_accur = -1
for eta in eta_vector:
print("eta is", eta... |
def helper_ce():
mnist = fetch_openml('mnist_784')
data = mnist['data']
labels = mnist['target']
train_idx = numpy.random.RandomState(0).permutation(np.where((labels[:8000] != 'a'))[0])
test_idx = numpy.random.RandomState(0).permutation(np.where((labels[8000:10000] != 'a'))[0])
train_data_unsc... | The code trains a model using Stochastic Gradient Descent (SGD) with a specified learning rate and iterations on training data, evaluates its accuracy on test data, and visualizes the learned weight matrices as 28x28 images. The main tasks are: loading data, model training, accuracy computation, and weight visualizatio... | def q2_bc():
train_data, train_labels, _, _, test_data, test_labels = helper_ce()
eta_0 = 3.162277660168379e-07
T = 20000
W = SGD_ce(train_data, train_labels, eta_0, T)
accur = find_accur_multi_class(test_data, test_labels, W)
print("accuracy is ", accur)
fig = plt.figure()
for index, w... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('path', help='path to data file')
parser.add_argument('-errors', help='show plot', action='store_true')
parser.add_argument('-plot', help='show plot', action='store_true')
parser.add_argument('-r2', help='show R2 metric', actio... | The main task of the code is to train a linear regression model using provided data, validate input parameters (learning rate, epochs), and optionally visualize results (plot, R² metric) or save model parameters. It reads data, checks for valid arguments, trains the model, and handles output based on flags like plot, r... | def main():
args = parse_args()
km_list, prices = Reader.read_data_file(args.path)
if (args.lr > 1) | (args.lr < 0):
Printer.print_error_exit('invalid parameter value: -lr: learning rate must be in range (0;1)')
if args.epochs <= 0:
Printer.print_error_exit('invalid parameter value: -epo... |
def import_construction_category(node: _Element, mod: Mod):
guid_node = node.xpath("Standard/GUID/text()")
guid = int(guid_node[0])
name = node.xpath("Standard/Name/text()")[0]
text = (node.xpath("Text/LocaText/English/Text/text()") or [""])[0]
icon_path = (node.xpath("Standard/IconFilename/text()")... | This function imports construction categories and their contents from XML data into a menu state. It processes 'ConstructionCategory' nodes, maps them to GUIDs in a dictionary, handles extensions, and ensures category contents are imported. The result is a populated dictionary of construction categories logged for veri... | def import_extracted_construction_categories(root: _Element, menu_state: MenuState, base_game: Mod):
construction_categories = menu_state.construction_categories
for node in root.xpath("ConstructionCategory/Asset/Values"):
construction_category = import_construction_category(node, base_game)
con... |
def import_extracted_buildings(root: _Element, base_game: Mod):
buildings = dict()
for building_node in root.xpath("Building/Asset/Values"):
building = import_building(building_node, base_game)
buildings[building.guid] = building
logging.info("Loaded %d Buildings from xml", len(buildings.ke... | The function parses an XML file containing extracted game assets, initializes a base game mod, imports buildings, production chains, and extensions, constructs a partial menu state, processes construction categories, logs parent category counts, imports the construction menu, and returns a fully populated MenuState obj... | def read_extracted_assets() -> MenuState:
assets = etree.parse(resource_path("assets-extracted.xml"))
root = assets.getroot()
base_game = Mod(Path("."), True)
buildings = import_extracted_buildings(root, base_game)
production_chains = import_extracted_production_chains(root, base_game)
import_... |
def getNonBlank():
while nextChar.isspace():
getChar()
def addChar():
global lexeme
if len(lexeme) <= 98:
lexeme += nextChar
else:
printf("Error - lexeme is too long \n")
def getChar():
global nextChar, charClass
nextChar = getc(in_fp)
if nextChar != EOFCHR:
i... | The code defines a lexical analyzer function `lex()` that tokenizes input characters into identifiers, integers, or other tokens. It processes characters based on their class (letter, digit, unknown, EOF), builds lexemes, and assigns the appropriate token type (`IDENT`, `INT_LIT`, etc.). It handles EOF by setting the t... | def lex():
global lexeme, nextToken
lexeme = ""
getNonBlank()
if charClass == LETTER:
addChar()
getChar()
while charClass == LETTER or charClass == DIGIT:
addChar()
getChar()
nextToken = IDENT
elif charClass == DIGIT:
addChar()
... |
def get_agent_id(doc, root_id):
root = doc[root_id]
agent_id = None
for tok in root.children:
if tok.dep_ == "agent":
agent_id = list(doc).index(tok)
# if agent_id == None:
# for tok in root.children:
# for childtok in tok.children:
# print(childto... | The code converts a passive-voice sentence to active voice using spaCy for NLP analysis. It identifies grammatical components (root, agent, objects), rearranges them, and reconstructs the sentence. If conversion fails (e.g., already active voice), it raises an error. Your return | def passive_to_active(sentence):
nlp = spacy.load("en_core_web_sm")
doc = nlp(sentence)
#for k in doc:
# print(k.text, k.dep_)
first_root_id = get_first_root_id(doc)
agent_id = get_agent_id(doc, first_root_id)
print('agentid', agent_id)
nsubjpass_id = get_nsubjpass_id(doc, first_root_... |
def P(self,i,k,t):
P_ = self.points;
w_ = self.weights;
num=0;
den=0;
if k==0:
return P_[i]
for j in range(0,k+1):
num+= self.B(j,k,t)*w_[i+j]*P_[i+j]
den+= self.B(j,k,t)*w_[i+j]
return num/den
def P_prime(self,i,t):
n =self.n
P_ = np.array(self.points)
w_ = np.array(self.weights)
P_pri... | This code computes points and their first and second derivatives along a Bézier curve by evaluating the curve function `P()`, its first derivative `P_prime()`, and second derivative `P_two_prime()` at evenly spaced time intervals between 0 and 1. It returns three NumPy arrays containing these values for curve generatio... | def get_bazier_curve(self):
dt = 1/self.number
n = self.n
ret_P=[]
ret_P_prime=[]
ret_P_two_prime=[]
for j in range(self.number):
t= j/self.number;
ret_P.append(self.P(0,n,t))
ret_P_prime.append(self.P_prime(0,t))
ret_P_two_prime.append(self.P_two_prime(0,n,t))
return np.array(ret_P),np.arra... |
def P(self,i,k,t):
P_ = self.points;
w_ = self.weights;
num=0;
den=0;
if k==0:
return P_[i]
for j in range(0,k+1):
num+= self.B(j,k,t)*w_[i+j]*P_[i+j]
den+= self.B(j,k,t)*w_[i+j]
return num/den
def P_prime(self,i,t):
n =self.n
P_ = np.array(self.points)
w_ = np.array(self.weights)
P_pri... | The code computes the Bezier curve and its first/second derivatives at parameter `s` using control points, returning them as NumPy arrays for position, velocity, and acceleration. | def get_bazier_curve_s(self,s):
dt = 1/self.number
n = self.n
ret_P=[]
ret_P_prime=[]
ret_P_two_prime=[]
t= s;
ret_P.append(self.P(0,n,t))
ret_P_prime.append(self.P_prime(0,t))
ret_P_two_prime.append(self.P_two_prime(0,n,t))
return np.array(ret_P),np.array(ret_P_prime),np.array(ret_P_two_prime) |
def del_from_list(
self,
args,
media_type,
arr_data,
trakt_ids,
idtag,
trakt_imdb_ids,
arr_ids,
arr_imdb,
all_trakt_ids,
):
"""
super complicated logic to find and identify unneeded ids
and remove them from the t... | The function compares ARR and Trakt media lists, identifies items to add/remove, constructs a JSON payload for Trakt API requests, sends add-to-list commands, and logs results including added items, total listed items, and IDs that failed to match. It handles media type-specific data, uses fallback IDs if IMDb is missi... | def add_to_list(
self,
args,
media_type,
arr_data,
trakt_ids,
idtag,
trakt_imdb_ids,
arr_ids,
arr_imdb,
all_trakt_ids,
):
"""
parse out and compares arr lists with trakt, then runs
del_from_list and updates/adds ... |
def generate_random_node(self, goal_sample_rate):
delta = self.utils.delta
if np.random.random() > goal_sample_rate:
return Node((np.random.uniform(self.x_range[0] + delta, self.x_range[1] - delta),
np.random.uniform(self.y_range[0] + delta, self.y_range[1] - delta)... | The code implements the RRT* (Rapidly-exploring Random Tree star) path planning algorithm. It iteratively generates random nodes, finds nearest neighbors, creates new states, checks for collisions, and updates the tree by adding valid nodes, rewiring connections, and optimizing paths. After reaching the iteration limit... | def planning(self):
self.start_time = time.time()
for k in range(self.iter_max):
node_rand = self.generate_random_node(self.goal_sample_rate)
node_near = self.nearest_neighbor(self.vertex, node_rand)
node_new = self.new_state(node_near, node_rand)
if k % ... |
def train_epoch(self):
"""
Trains the model for one epoch using the training dataloader and returns the mean loss.
"""
self._model.train()
with t.enable_grad():
loss_accum, n_batches = 0, 0
for x, y in self._train_dl:
# Transfer data to G... | This code trains a model for a specified number of epochs, adjusting hyperparameters like gamma and prior weight based on predefined schedules. It tracks training/validation losses, manages learning rate scheduling, implements early stopping, and saves checkpoints. The function returns lists of training and validation ... | def fit(self, epochs=1):
"""
Trains the model for 'epochs' epochs. Returns list of training and validation losses.
"""
best_model_epoch = 0
for epoch in range(epochs):
if self.gs is not None:
if epoch < self.gs["steps_const"]:
... |
def read_input():
with open('input.txt', 'r') as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
return lines
def init_grid(lines, padding):
grid = {}
num_rows = len(lines)
num_columns = len(lines[0])
ACTIVE = '#'
INACTIVE = '.'
for row in range(-pa... | The code simulates a grid-based process over multiple cycles. It initializes a grid with padding, applies a series of transformations (run_cycle) for a fixed number of cycles, and finally counts and prints the number of "active" elements in the grid. The main task is to model and compute the state of a dynamic grid sys... | def main():
NUM_CYCLES = 6
lines = read_input()
grid = init_grid(lines, padding=NUM_CYCLES)
# print_grid(grid)
for i in range(NUM_CYCLES):
grid = run_cycle(grid)
# print("Cycle {}".format(i + 1))
# print_grid(grid)
print(count_active(grid.values())) |
def setup_args():
parser = argparse.ArgumentParser(description="HD Wallet Key Tool")
parser.add_argument("--version", "-v", dest="version",
default=False, action="store_true",
help="show version")
parser.add_argument("--non-interactive", "-N", dest="interactive",
... | (The main function processes command-line arguments, checks for a version flag to print and exit, executes a main loop, handles interruptions in interactive mode by displaying errors, and exits with a "Quitting" message if interactive. It manages user input, error handling, and program flow based on flags and exception... | def main():
args = setup_args()
if args.version:
print(__version__)
raise SystemExit
try:
main_loop(args)
except (KeyboardInterrupt, EOFError):
if args.interactive:
pstderr()
if args.interactive:
pstderr("Quitting") |
def define_resolutions(settings):
latitudes = np.linspace(-90, 90, settings["n_latitudes"] + 1) # 180*16
longitudes = np.linspace(
-180, 180, np.round(settings["n_longitudes"]).astype(int) + 1
) # np.round(360*16/5.75).astype(int)
# base_resolution = 111
base_resolution = settings["base_... | The main task of the code is to process geographical data by loading configurations, checking for pre-existing refinement and mesh files, generating resolutions or triangulating meshes if necessary, and applying land-cutting operations. It reads YAML settings, utilizes pickle for data persistence, and employs Jigsaw tr... | def main():
with open("./configure.yaml") as file:
settings = yaml.load(file, Loader=yaml.FullLoader)
print(settings["levels"])
if (settings["use_existed_refinements"]) & (Path("_result_temp.pkl").exists()):
with open("_result_temp.pkl", "rb") as file:
regions, result, latitude... |
def evalInterval(self, measure, lowerindex, upperindex):
"""
=======================================================================
% Evaluate the valid interval width of a measure, then sort in descending order.
%
% INPUT
% measure - measure to be evaluated after upd... | The function samples a new measure element via small or large-scale mutation based on a probability threshold (eta). It updates either one element (small-scale) or all elements (large-scale) of the measure, sorts intervals by width, and computes the new measure's fitness using softmax evaluation. The output includes th... | def sample_population(self, Bags, Labels, childMeasure, lowerindex, upperindex, nPntsBags, oneV, bag_row_ids, diffM, Parameters):
"""
===========================================================================
% Sample new measure elements using either small or large-scale mutation
%
... |
def compute_bounds(self):
"""
===============================================================================
%
% This function returns the lower and upper bounds on each measure element
%
% INPUT
%
% OUTPUT
% lowerindex - list that stores all t... | The main task of the code is to learn a fuzzy measure for Multiple Instance Choquet Integral (MICI) using an evolutionary algorithm and generalized-mean objective function. It initializes a population of measures, iteratively evolves them through selection, mutation, and replacement strategies, and returns the optimize... | def produce_lattice_softmax(self, Bags, Labels, Parameters, trueInitMeasure=None):
"""
===============================================================================
%% produce_lattice_softmax()
% This function learns a fuzzy measure for Multiple Instance Choquet Integral (MIC... |
def welcome_animation():
player_y = int((SCREEN_HEIGHT - PLAYER_H) / 2)
player_generation = cycle([0, 1, 2, 1])
return {
'player_y': player_y,
'base_x': 0,
'player_generation': player_generation
}
def main_game(info):
score = player_id = loops = 0
player_generation = info... | The code's main task is to load pre-defined hit masks from a file, then enter an infinite loop where it displays a welcome animation, runs the main game logic, and shows the game-over screen repeatedly. The loop ensures continuous game sessions, restarting after each game-over. | def main():
global HIT_MASKS
with open('data/hit_masks.pkl', 'rb') as hit_masks:
HIT_MASKS = pickle.load(hit_masks)
hit_masks.close()
while True:
start_game = welcome_animation()
game_info = main_game(start_game)
show_game_over_screen(game_info) |
def get_hitmask(image_alpha):
"""Returns a hitmask using an image's alpha."""
mask = []
for x in range(image_alpha.get_width()):
mask.append([])
for y in range(image_alpha.get_height()):
mask[x].append(bool(image_alpha.get_at((x, y))[3]))
return mask
def welcome_animation():
... | The main task of the code is to initialize and configure a Flappy Bird game using Pygame. It loads game assets (images, sounds), sets up the display, generates random game elements (background, player, pipes), creates collision detection hitmasks, and prepares to run the game loop with welcome, main game, and game-over... | def main():
global SCREEN, FPS_CLOCK, FPS, MODE
pygame.init()
FPS_CLOCK = pygame.time.Clock()
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Flappy Bird')
IMAGES['numbers'] = (
pygame.image.load('flappy-bird-assets/sprites/0.png').convert_al... |
def is_subtree(node):
if node.get('cat')is not None:
return True
else:
return False
def open_wrap(node):
bracket = '{'
name = node.get('cat')
if name.startswith('mwu'):
name = 'mwu'
return str(bracket + name)
def is_leaf(node):
... | This function recursively traverses a tree structure, processing nodes to build a list of descendants. It handles subtree and leaf nodes by wrapping elements, appending them to the list, and managing closing tags based on span comparisons. The recursion processes children, ensuring proper nesting and closure of element... | def _recursive_navigation(node, _descendants=None):
if _descendants is None:
_descendants = []
else:
if is_subtree(node):
level = open_wrap(node)
_descendants.append(level)
to_close.append('')
if is_leaf(node):
... |
def create_view(self, model):
"""create_view
:param model:
"""
renderer = Gtk.CellRendererCombo()
def editingstarted(cell, widget, path):
widget.set_wrap_width(1)
chs = Gtk.TreeStore(TYPE_STRING, TYPE_STRING)
renderer.props.model = self.create_choic... | This code initializes a GTK-based UI component for managing actions, setting up a scrollable list view, sensitivity conditions for UI elements, and associated controls like toolbars and context menus. It configures data models, action callbacks, and dynamic UI state management through conditional switches. | def __init__(self, proptable=None):
# self.widget = Gtk.VBox()
self.widget = Gtk.ScrolledWindow()
self.actions = None
self.proptable = proptable
self._actions_choices = ACTIONS_CHOICES
# actions callback, called when action added or deleted
# for chroot possibili... |
def initialization(dim):
w = np.zeros((dim,1))
b = 0
assert(w.shape == (dim,1))
assert(isinstance(b, float) or isinstance(b, int))
return w, b
def optimize(X, Y, w, b, num_steps, alpha) :
for i in range(num_steps) :
cost, grads = calculation(X, Y, w, b)
dw = grads["dw"]
... | This code trains a linear model using gradient descent on given training data, optimizes parameters (weights and bias), evaluates model accuracy on both training and test sets, and returns predictions along with optimized parameters. It calculates accuracy as 100 minus the mean absolute error scaled by 100, then output... | def model(train_set_x, train_set_y, test_set_x, test_set_y, num_steps, alpha) :
dim = train_set_x.shape[0]
w, b = initialization(dim)
params, grads = optimize(train_set_x, train_set_y, w, b, num_steps, alpha)
w = params["w"]
b = params["b"]
y_prediction_test = predict(test_set_x, w, b)
y_pre... |
def avail_steps_score(self):
num_steps_available = len(self.get_legal_moves())
if num_steps_available == 0:
return -1
else:
return 4 - num_steps_available
def dist_from_rival(self):
man_dist = abs(self.rival_pos[0] - self.player_pos[0]) + abs(self.rival_pos[1] - s... | This function calculates a weighted heuristic score by combining multiple game-related factors: available steps, distance from the rival, Manhattan distance to the closest fruit, score difference, and fruits collected. Each factor is multiplied by a corresponding weight from the input list, then summed to produce an ov... | def heuristic_weights(self, weights):
return weights[0]*self.avail_steps_score() \
+ weights[1] * self.dist_from_rival() \
+ weights[2]*self.man_dist_to_closest_fruit() \
+ weights[3]*(self.player_score - self.rival_score) \
+ weights[4]*self.fruits_ta... |
def print_header(header, expected_cksum=None):
"""
Report the contents of the given bitcoin message header
:param header: bitcoin message header (bytes or bytearray)
:param expected_cksum: the expected checksum for this version message, if known
:return: message type
"""
magic, command_hex, ... | The function `print_message` processes and reports the contents of a Bitcoin message, identifying its type (e.g., 'version', 'inv', 'block') and printing relevant details. It extracts the message header, calculates a checksum, and delegates payload processing to specialized functions. The output includes the message le... | def print_message(msg, text=None, iteration=0):
"""
Report the contents of the given bitcoin message
:param msg: bitcoin message including header
:return: message type
"""
print('\n{}MESSAGE'.format('' if text is None else (text + ' ')))
print('({}) {}'.format(len(msg),
... |
def print_message(msg, text=None, iteration=0):
"""
Report the contents of the given bitcoin message
:param msg: bitcoin message including header
:return: message type
"""
print('\n{}MESSAGE'.format('' if text is None else (text + ' ')))
print('({}) {}'.format(len(msg),
... | This function processes a message by sending it, receiving a response, and validating checksums. It handles fragmented data by continuously receiving and reassembling messages until a valid checksum matches the header. If the command is "getblocks" and validation fails, it recursively processes the message. The functio... | def processMessage(self, message, command ='', count=0):
print_message(message, 'Sending')
self.listener.send(message)
received = self.listener.recv(buffer_size)
processedMessages = self.splitMessage(received)
check, msg, top, found = '','','',False
for msg in processedM... |
def getblocks_payload(self, genesis, top=''):
version = int32_t(70015)
count = compactsize_t(1)
if genesis:
blockhead_hash = struct.pack("32s", b'\x00')
else:
blockhead_hash = bytearray.fromhex(hex_littletobig(top))
hash_end = struct.pack("32s",b... | The function `findBlock` repeatedly sends `getblocks` messages to retrieve blockchain data, updating `top_inv` and checking for a found block. It loops until the block is found, incrementing a counter each attempt, then returns the final `top_inv` value. | def findBlock(self, top_inv, found):
count = 1
while not found:
getblocks_payload = self.getblocks_payload(False, top_inv)
getblocks_header = self.create_Header(getblocks_payload, 'getblocks')
getblocks_message = getblocks_header + getblocks_payload
top_in... |
def _weight_all(self):
"""Loop though all the pages and questions
in order to compute weights and changes that improve the score.
:return:
"""
w = {}
for page_id, questions in self.answers.iteritems():
for q_id, ans in questions.iteritems():
... | The code identifies optimal changes (pages with scores) to meet a points requirement by iterating through sorted weights, adjusting points based on scores, and recursively checking lower weights for combinations. It collects valid changes, selects the best from all possibilities, and returns it. | def _get_changes(self, points_needed):
all_possible_changes = []
w_q = self._weight_all()
sorted_weights = {}
for w, details in w_q.iteritems():
sorted_weights[w] = sorted(details.itervalues(), key=attrgetter('score'), reverse=self.higher_is_better)
for w, details in... |
def get_zillow_data():
'''
This function reads in the zillow data from Codeup database, writes data to
a csv file if a local file does not exist, and returns a df.
'''
if os.path.isfile('zillow_df.csv'):
# If csv file exists, read in data from csv file.
df = pd.read_csv('zil... | The main task of the code is to load, clean, encode, split, and scale the Zillow dataset for modeling. It prepares data by cleaning and preprocessing, encoding categorical variables, splitting into train/validate/test sets, and scaling features. The function returns all processed datasets for machine learning tasks. | def wrangle_zillow():
'''
This function accesses (or creates) the zillow_df.csv file and wrangles it (clean, prep, split, scale)
'''
df = get_zillow_data()
df = clean_and_prep_data(df)
df = encode_zillow(df)
train, validate, test, X_train, y_train, X_validate, y_validate, X_test, y_te... |
def changeAlbumArt():
GetDomColor = ColorThief('album.png')
W = 414
H = 896
backGround = gradientBackground(GetDomColor)
album = Image.open("album.png")
albumArt = album.resize((int(album.size[0] * 0.573), int(album.size[1] * 0.573)))
# gradient = Image.open('gradient.png')
w, h = albumA... | The code's main task is to create a UI texture for a music player by initializing background elements, buttons (play, shuffle, repeat), time display, and updating artist/song names. It orchestrates visual setup and data binding for an audio interface, ensuring all components are configured and displayed properly. | def createTexture(self):
print("Creating texture...")
print("Creating Background...")
changeAlbumArt()
print("Creating Buttons...")
Button(self.playButton)
Shuffle(self.shuffle)
repeat(self.repeatButton)
print("Getting Time...")
Time(self.time)
... |
def u(self):
d = [{"color": "g", "nums": [0, 0, 1]}, {"color": "o", "nums": [0, 0, 1]}, {"color": "b", "nums": [0, 0, 1]}, {"color": "r", "nums": [0, 0, 1]}, ]
self.turn_side("w", d)
def f(self):
d = [{"color": "w", "nums": [3, 2, 2]}, {"color": "r", "nums": [0, 3, 3]}, {"color": "y", "nums": [1, 0, 0]}, {"col... | This function executes Rubik's cube face rotations based on input notation. It maps move strings like "u", "u'", "u2" to corresponding face rotation methods, calling the base method once, thrice, or twice respectively. Similar logic applies to other faces (f, r, l, d, b). The code translates standard cube notation into... | def move(self, move:str):
#This function calls the function of the corresponden face, ih a variable that gets passed, iths the recomended function to acces
if move == "u":
self.u()
if move == "u'":
self.u()
self.u()
self.u()
if move == "u2":
self.u()
self.u()
if move == "f":
self.f(... |
def logwrite(self, option, event):
'''
Function that write to file for Logging
event : Logging Sentence
option : LOGGING(1) - Write to File
CMDLINE(2) - Write to Command Line
BOTH(3) - Wrte to File and Command Line
'''
#if option == CM... | The main task of the code is to initialize a PDU (Power Distribution Unit) by sending specific commands, checking connection status, logging operations, and handling errors. It verifies connectivity, transmits initialization commands, records logs, and re-establishes connections if failures occur, ensuring proper PDU s... | def initPDU(self):
if not self.comStatus[PDU]:
print(f' you have to connect first, please {PDU} ')
return
try:
cmd = "@@@@\r"
#self.comSocket[PDU].send(cmd.encode())
log = "send: %s >>> %s" % (self.comList[PDU], cmd)
self.... |
def connect_to_component(self, nCom):
print(f" Simulating connection to hardware ")
time.sleep(1)
self.comStatus[nCom] = True
print(f' Connected to simulator hardware ')
def connectRabbitMq(self):
self.producter.connectServer()
def initPDU(self):
if no... | The main task of the code is to initialize system components (COM_CNT), establish RabbitMQ connections, and periodically collect sensor data (TMC, TM, VM, power status) from hardware. It continuously sends this data to a message broker using predefined routing keys, with a 1-second interval per component and a longer p... | def main(self):
for i in range(COM_CNT):
self.connect_to_component(i)
self.connectRabbitMq()
self.initPDU()
while (True):
for i in range(COM_CNT):
msg = f"tmc,{self.get_value_fromTMC(i,'A')}"
self.producter.sendMessage([self._routingKe... |
def get_ds(config):
ds_raw = load_dataset('opus_books',
f'{config["lang_src"]}-{config["lang_tgt"]}',
split='train', cache_dir=path_git + '/' + 'DataFolder')
# Build tokenizer
tokenizer_src = get_or_build_tokenizer(config, ds_raw, config['lang_src'])... | This code trains a sequence-to-sequence transformer model using a specified configuration. It loads datasets, initializes the model, and performs training with backpropagation, logging losses via TensorBoard, validating periodically, and saving model checkpoints after each epoch. The model is preloaded if specified, an... | def train_model(config):
# Define the device
print('device: ', device)
Path(config['model_folder']).mkdir(parents=True, exist_ok=True)
# Load dataset
train_dataloader, val_dataloader, tokenizer_src, tokenizer_tgt = get_ds(config)
model = get_model(config, tokenizer_src.get_vocab_size(), tokeni... |
def load_yaml_file(filename, is_template=False):
"""Loads a given YAML file name into a dictionary.
If is_template is True, then the file's contents are passed through the \
template function first.
"""
fo = open(os.path.join(config.root, filename))
data = fo.read()
if is_template:
data = re.compile(r"^%(YAML|T... | This code loads a YAML configuration file into an object's attributes, updates the working directory if the config's root path differs from the current one, and disables debugging. | def load(self, fname=_default_config_file):
self._dict = load_yaml_file(abspath(fname))
setattrs(self._dict, self)
if self.root != self._root:
self._root = self.root
os.chdir(self.root)
debug(False) |
def fvalue(self, state):
return state.g + self.epsilon * state.h
def checkGoal(self, state):
goal_x = self.goal[0]
goal_y = self.goal[1]
goal_theta = self.goal[2]
return (state.x == goal_x) and (state.y == goal_y) and (almostEqual(goal_theta, state.theta))
def getSuccessors(self,... | This function improves a pathfinding algorithm by iteratively selecting the lowest-cost state from the open set, checking if it's the goal, and expanding it. If not optimal, it updates closed states and processes successors, adding them to the open set if they offer a better path. The loop terminates when the goal is f... | def improvePath(self):
self.expansions_count = 0
while (not self.open.empty()):
min_state = self.open.get()[1]
if (min_state in self.closed): continue # state could be a dummy node
if (self.fvalue(self.goal_state) < self.fvalue(min_state)):
break
... |
def heuristicFunc(self, state):
goal_x = self.goal[0]
goal_y = self.goal[1]
#return self.heuristic_maps[self.resolution][state.y][state.x]
return math.sqrt((state.x - goal_x)**2 + (state.y - goal_y)**2)
def fvalue(self, state):
return state.g + self.epsilon * state.h
def improveP... | This function searches for a path in a state space using a resolution-based approach, iterating through 'low' and 'high' resolutions. It initializes search structures (priority queue, closed set), adjusts epsilon values to refine solutions, and improves paths until a goal is reached or time limits are exceeded. It prin... | def findPath(self):
start_time = time.time()
for resolution in ['low', 'high']:
self.resolution = resolution
start_state = State(self.start[0], self.start[1], self.start[2], g=0)
start_state.h = self.heuristicFunc(start_state)
self.goal_state = State(sel... |
def heuristicFunc(self, state):
goal_x = self.goal[0]
goal_y = self.goal[1]
#return self.heuristic_maps[self.resolution][state.y][state.x]
return math.sqrt((state.x - goal_x)**2 + (state.y - goal_y)**2)
def fvalue(self, state):
return state.g + self.epsilon * state.h
def improveP... | The code implements an algorithm to find a path in a state space using a priority queue (open set) and heuristic functions. It initializes start/goal states, iteratively improves the path by adjusting epsilon (a parameter controlling exploration), and switches to higher resolution if no solution is found. The function ... | def findPathNoReset(self, resolution='low'):
start_time = time.time()
self.resolution = resolution
start_state = State(self.start[0], self.start[1], self.start[2], g=0)
start_state.h = self.heuristicFunc(start_state)
self.goal_state = State(self.goal[0], self.goal[1], self.goal... |
def get_url(self, year):
url = self.url.replace("{year}", str(year))
return url
def get_file(self, year, extension=".json"):
filename = self.get_filname(year, extension)
file = Path(self.path)/filename
return file
def write_json(self, dictData, file=None):
if file == None... | The code's main task is to download data for each year in `self.years`. For each year, it checks if the corresponding file already exists. If not, it fetches the data from a dynamically generated URL, parses the JSON response, and saves it to a file. The process avoids redundant downloads by skipping existing files and... | def download(self):
for year in self.years:
url = self.get_url(year)
file = self.get_file(year)
if os.path.exists(file):
print("year " + str(year) + " skip download, file already exists")
else:
print("year " + str(year) + " download... |
def get_table(database_name: str, table_id: NonNegativeInt) -> Table:
database = get_database(database_name)
try:
return database.tables[table_id]
except KeyError:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail=f"Database '{database_name}' doesn... | This function deletes a specified table from a database by first verifying its existence and then removing it from the database's table collection. | def delete_table(database_name: str, table_id: NonNegativeInt):
get_table(database_name, table_id)
get_database(database_name).remove_table(table_id) |
def get_row(database_name: str, table_id: NonNegativeInt, row_id: NonNegativeInt) -> Row:
try:
return get_table(database_name, table_id)._rows[row_id]
except KeyError:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail=f"Table #{table_id} in database '{... | The main task of the code is to delete a specific row from a database table by first retrieving the row using `get_row` and then calling the `remove_row` method on the table object with the provided row ID. The function requires a database name, table ID, and row ID as parameters to identify and remove the target row f... | def delete_row(database_name: str, table_id: NonNegativeInt, row_id: NonNegativeInt):
get_row(database_name, table_id, row_id)
get_table(database_name, table_id).remove_row(row_id) |
def get_table(database_name: str, table_id: NonNegativeInt) -> Table:
database = get_database(database_name)
try:
return database.tables[table_id]
except KeyError:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail=f"Database '{database_name}' doesn... | The main task of the code is to update a specific cell in a database table by validating the column index and the provided value. It retrieves the target table and row, checks if the column exists, verifies the value's compatibility with the column's type, updates the cell if valid, and returns the modified row. Errors... | def update_cell_value(
database_name: str,
table_id: NonNegativeInt,
row_id: NonNegativeInt,
column_id: NonNegativeInt,
value: Value) -> Row:
table = get_table(database_name, table_id, )
row = get_row(database_name, table_id, row_id)
if column_id >= len(table.columns)... |
def setupButtons(self): # setup handlers for all buttons in UI
# self.dataRecvdAction = QAction('Action Triggered On Response From Client', self)
# self.dataRecvdAction.triggered.connect(lambda : self.dispClientResponse(self.client.response))
self.client.response = ''
runBtn = self.ui.btn... | The main task of the code is to initialize a GUI application by setting up the user interface, configuring application and command flags, creating a client instance, connecting UI elements to actions, and starting UI animation threads. It serves as the constructor for a window class, preparing the application's state a... | def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.APP_RUNNING = True
self.CMD_RUNNING = False
self.client = Client()
self.setupButtons()
self.setupAppActions()
self.startUIAnimThreads() |
def search_smallest_neighbor(self, vector, bmu, best):
if self.topology == "Hex":
neighbors = self.return_all_neighbors_hex(bmu)
else:
neighbors = self.return_all_neighbors(bmu)
for i in neighbors:
value = quadratic_distance(self.neurons[i[0], i[1]], vector)
... | This code identifies the Best Matching Unit (BMU) for a given input vector in a self-organizing map (SOM) by iteratively searching neighboring neurons. Starting from an initial BMU, it expands the search radius if no closer match is found locally, ensuring the optimal BMU is selected through a neighborhood traversal pr... | def particle(self, vector, start):
cont = True
bmu = start
best = quadratic_distance(self.neurons[bmu], vector)
self.dist_memory[bmu] = best
while cont:
new_bmu, new_best = self.search_smallest_neighbor(vector, bmu, best)
if new_bmu == bmu: # There is no ... |
def generate_random_list(self):
self.vector_list = list(range(len(self.data)))
np.random.shuffle(self.vector_list)
def unique_random_vector(self):
self.current_vector_index = self.vector_list.pop(0)
return self.current_vector_index
def fast_winner(self, vector, vector_id=None):
s... | This function performs one iteration of a neural network training process, checking for max iterations, handling epoch boundaries by updating parameters and normalizing distance vectors, selecting a random vector, identifying the best matching unit (BMU), updating weights based on the BMU, and returning the BMU indices... | def run_iteration(self):
if self.iteration >= self.max_iterations:
return False
# Start of an epoch
if self.iteration % self.data.shape[0] == 0:
self.generate_random_list()
self.alpha.execute()
self.sigma.execute()
for i in range(len(s... |
def get_all_winners(self):
winners_list = np.zeros(self.data.shape[0], dtype=tuple) # list of BMU for each corresponding training vector
for i in np.ndindex(winners_list.shape):
winners_list[i] = self.winner(self.data[i])
return winners_list
def get_all_fast_winners(self):
w... | The code computes quantization and mismatch metrics by comparing real and fast winners. It calculates Mean Square Distance to Neighbors (MSDtN), Mean Square Quantization Errors (MSQE_S/MSQE_F) for both winner sets, and Mismatch rate (proportion of differing winners). Results are stored in a metrics dictionary and retur... | def compute_metrics(self):
real_winners = np.array(self.get_all_winners())
fast_winners = self.get_all_fast_winners()
self.metrics["MSDtN"] = self.mean_square_distance_to_neighbour()
self.metrics["MSQE_S"] = self.mean_square_quantization_error(real_winners)
self.metrics["MSQE_F"... |
def apply_for_each(path, function, base_path=''):
if os.path.exists(path):
with open(path,'r') as f:
lines = f.readlines()
entries = [l.split(' ') for l in lines]
entries = flatten(entries)
for e in entries:
e = e.split('#')[0]
... | The main task of the code is to generate a YAML configuration file for VHDL libraries. It processes library files from specified paths, adds entries for the "work" library and IEEE-compliant `.vhd` files, then writes the structured data into `vhdltool-config.yaml` for tool usage. | def main():
relpath = os.path.dirname(args.libs_file)
apply_for_each(args.libs_file, parse_lib, relpath)
parse_lib(relpath+'/grlib')
output_file["Libraries"].append(create_libentry("work", work))
if args.ieee:
files = [os.path.join(args.ieee, f) for f in os.listdir(args.ieee)
... |
def center(self):
qr = self.frameGeometry()
cp = PyQt5.QtWidgets.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
return
def createToolbar(self):
mainAct = PyQt5.QtWidgets.QAction(PyQt5.QtGui.QIcon('media/icecream.png'),'Main',self)
mainAct.triggered.connect(self.mai... | The main task of the code is to initialize the user interface by setting the window size, centering it on the screen, assigning a title, creating a toolbar, configuring the main screen, and displaying the window. The method prepares the GUI for interaction by organizing essential components and ensuring proper window s... | def init_UI(self):
self.resize(400,150)
self.center()
self.setWindowTitle('Ice cream for everyone!')
self.createToolbar()
self.mainScreen()
self.show()
return |
def read_data(self):
n = int(input())
self._data = [int(s) for s in input().split()]
self.size = len(self._data)
assert n == self.size
def generate_swaps(self):
# The following naive implementation just sorts
# the given sequence using selection sort algorithm
# a... | The code's main task is to process data by reading input, generating swap operations, and writing the resulting output. The `solve` method orchestrates these steps: `read_data` loads input, `generate_swaps` computes necessary swaps, and `write_response` outputs the solution. This structure is typical for problems requi... | def solve(self):
self.read_data()
self.generate_swaps()
self.write_response() |
def get_total_faith(self):
self.create_day_of_worship()
c = self.conn.cursor()
c.execute("SELECT SUM(faith) FROM faith")
return c.fetchone()[0]
def get_faith(self, date):
self.create_day_of_worship()
c = self.conn.cursor()
c.execute("SELECT faith FROM faith WHERE ... | The code calculates a user's "blessing" level based on their accumulated faith, daily faith, and virtue score. It determines a blessing tier (top, mid-high, mid-low, low) by combining faith ratios and virtue modifiers, returning corresponding image URLs. Lower faith or virtue reduces the blessing tier, while higher vir... | def calculate_blessing(self, username):
total_faith = self.get_total_faith()
todays_faith = self.get_faith(self.get_date())
days = self.get_days_of_prayer()
if days < 2:
average_faith = todays_faith
else:
average_faith = total_faith/days
virtue = s... |
def todays_faith_message(self):
faith = self.get_faith(self.get_date())
if faith < 0:
return "Oh, this is awful...what should we do? It seems no one has faith..."
elif faith < 50:
return "Ah...we've gathered some, but..."
elif faith < 100:
return "Our ... | This code processes user commands in a chat system, routing each command to the appropriate response. It checks if the user's message starts with predefined commands like !services, !checkfaith, etc., and sends corresponding information via `send_msg` to the channel. The function handles shrine-related tasks, such as d... | def run_command(self, user_message, username, channel):
commands = ["!services", "!checkfaith", "!totalfaith", "!checkvirtue",
"!blessing"]
command = user_message[1:]
if command.startswith("services"):
self.send_msg("@{} Here are the services offered at this shrine: {}".
... |
def update_domain(self, document, path):
yaml = ruamel.yaml.YAML()
document = document['domain']
intent = document['intent']
utter = document['response']['utterResponse']
response = document['response']['text'][0]
print("Response updated for {}: {}".format(intent, respo... | The main task of the code is to approve selected records by updating their status to 'Approved' and then synchronize these changes with a MongoDB database. It updates Rasa AI model components (domain, stories, NLU) by querying database documents matching approved records and applying corresponding updates to files in a... | def approve_selected_records(self, request, queryset):
# Update the status of selected records to 'Approved'
rows_updated = queryset.update(status='Approved')
self.message_user(
request,
f'{rows_updated} record(s) have been approved.',
)
... |
def sort(folder, train, test):
n_images = os.listdir(folder)
if len(n_images) < 10:
img = cv2.imread(folder+str(n_images[0]), 1)
n = 10-(10-len(n_images))+1
for i in range(n, 13):
cv2.imwrite(folder+str(i)+'.jpg', img)
elif len(n_images) > 10:
pass
_ = os.list... | The code registers a new employee by creating directories for their facial data, processing images, updating datasets, generating face vectors, and retraining a classifier. It ensures all steps succeed for a "Registration Successful" status, reverting temporary changes and handling errors. | def register(org_id, employee_name):
# Define absolute path
path = "/var/www/djangomac/facerecognation/media/documents/"+str(org_id)
# Check for parallel processing
try:
from .dummy import dummy
# Change the dummy function
os.rename('/var/www/djangomac/facerecognation/main/dummy.... |
def chackactions(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self.checkkeyinput(event)
elif event.type == pygame.KEYUP:
self.checkreleaseinput(event)
def bu... | The main task of the code is to run an infinite game loop that continuously checks for actions, updates the ship's state, manages bullets, and refreshes the screen to create real-time game dynamics. | def startgameprog(self):
while True:
self.chackactions()
self.ship.shipupd()
self.bulletupd()
self.screenupd() |
def _get_auth_service(self):
try:
creds = self._get_credentials()
except RefreshError as e:
logger.error(f"Error during authentication: {e}")
logger.info("Deleting credentials and reauthenticating.")
os.remove(PATH_TO_TOKENS)
return self._get_a... | The code initializes a class by authenticating a drive service, retrieving the root folder ID, and setting up the folder structure. It first obtains an authenticated drive service, identifies the root folder, and then initializes the folder hierarchy for organized data management. | def __init__(self):
self.drive_service = self._get_auth_service()
self.folder_ids = {"root": self._get_root_folder_id()}
self.initialize_folder_structure() |
def parse_single_resource(self, resource_name: str) -> DefinitionFile:
"""Parse a resource in the package into a DefinitionFile.
Imported files will appear as ImportDefinition objects and
will not be followed.
This method will try to load it first as a regular file
(with a path... | This function parses a file or resource into a collection of DefinitionFiles, recursively resolving and parsing imported files. It uses disk caching if enabled, determines file paths based on resource status, and aggregates all parsed definitions into a DefinitionFiles object. | def parse(self, file, is_resource: bool = False) -> DefinitionFiles:
"""Parse a file or resource into a collection of DefinitionFile that will
include all other files imported.
Parameters
----------
file
definitions or file containing definition.
is_resource
... |
def set_memory_buffer(self, keyframes):
self.input_processor.set_memory_buffer(keyframes)
def get_memory_size(self):
return self.input_processor.get_memory_size()
def add_double_sided_edge(self, first, second):
self.graph.add_edge(first, second)
self.graph.add_edge(second, first)
def com... | The code constructs a graph from keyframes and their coordinates. It initializes nodes based on memory size, connects consecutive nodes bidirectionally, computes shortcuts between non-consecutive nodes, and adds these shortcuts as edges. The graph visualizes transitions between keyframes, likely for animation or pathfi... | def build_graph(self, keyframes, keyframe_coordinates):
if len(keyframes) > 0 and len(keyframe_coordinates) > 0:
self.keyframes=keyframes
self.keyframe_coordinates=keyframe_coordinates
self.set_memory_buffer(keyframes)
memory_size = self.get_memory_size()
... |
def read_images():
for subdir in images.keys():
im_dir = os.scandir("images/" + subdir)
for im in im_dir:
if im.name == "README":
continue
images[subdir].append(im.path)
random.shuffle(images[subdir])
def next_image(image_idx, img_select):
if image... | The main task of the code is to run a Pygame-based GUI application that visualizes real-time power data (Grid, Solar, House) with image overlays. It processes data from a queue, updates displayed images and text metrics, handles termination signals, and renders dynamic visualizations with transitions and text overlays ... | def main(terminate_event, pvdata_queue):
pygame.init()
sans_font = None
if pygame.font.get_init():
sans_font = pygame.font.SysFont("Calibri", 70)
else:
print("pygame.font.init() failed. This module is optional and requires SDL_ttf as a dependency. Not text can be shown")
screen = pyg... |
def predict(s=NUM_TRAINING_SENTENCES, num=NUM_DEV_SENTENCES, display=True, plot=False, p_filt=0, r_filt=0):
print("English predictions, s={0:d}, num={1:d}:".format(s, num))
metrics = {"cp":[], "tp":[], "t":[]}
filter_count = 0
with open(text_fname["fr"], "rb") as fr_file, open(text_fname["en"], "rb")... | The code trains a sequence-to-sequence model for machine translation using a bilingual corpus, performing multiple epochs of training with backpropagation. It logs training loss, evaluates model performance on a dev set (precision, recall, F1, perplexity), saves the best model based on perplexity, and outputs metrics. ... | def train_loop(text_fname, num_training, num_epochs, log_mode="a"):
# Set up log file for loss
log_train_fil = open(log_train_fil_name, mode=log_mode)
log_train_csv = csv.writer(log_train_fil, lineterminator="\n")
log_dev_fil = open(log_dev_fil_name, mode=log_mode)
log_dev_csv = csv.writer(log_dev_... |
def compute_dev_pplx():
loss = 0
num_words = 0
with open(text_fname["fr"], "rb") as fr_file, open(text_fname["en"], "rb") as en_file:
with tqdm(total=NUM_DEV_SENTENCES) as pbar:
sys.stderr.flush()
out_str = "loss={0:.6f}".format(0)
pbar.set_description(out_str)
... | The main task of this code is to train a neural network model using bucketed data in batches, logging training loss and validation perplexity/BLEU scores, and saving model checkpoints periodically. It processes data from multiple buckets, performs backpropagation with an optimizer, evaluates model performance on a deve... | def batch_train_loop(bucket_fname, num_epochs,
batch_size=10, num_buckets=NUM_BUCKETS,
num_training=2,
bucket_width=BUCKET_WIDTH, log_mode="a", last_epoch_id=0):
# Set up log file for loss
log_train_fil = open(log_train_fil_name, mode=log_mode)
... |
def reset_state(self):
# reset the state of LSTM layers
for lstm_name in self.lstm_enc + self.lstm_rev_enc + self.lstm_dec:
self[lstm_name].reset_state()
self.loss = 0
def encode_list(self, in_word_list, train=True):
xp = cuda.cupy if self.gpuid >= 0 else np
# convert... | This function trains an encoder-decoder model with attention by encoding input sequences, initializing the decoder with the encoder's final state, and iteratively decoding output sequences. It adds GO/EOS tokens, computes predicted outputs, calculates cross-entropy loss for each step, and accumulates the total loss for... | def encode_decode_train(self, in_word_list, out_word_list, train=True):
xp = cuda.cupy if self.gpuid >= 0 else np
self.reset_state()
# Add GO_ID, EOS_ID to decoder input
decoder_word_list = [GO_ID] + out_word_list + [EOS_ID]
# encode list of words/tokens
self.encode_list(... |
def reset_state(self):
# reset the state of LSTM layers
for lstm_name in self.lstm_enc + self.lstm_rev_enc + self.lstm_dec:
self[lstm_name].reset_state()
self.loss = 0
def encode_list(self, in_word_list, train=True):
xp = cuda.cupy if self.gpuid >= 0 else np
# convert... | This function performs sequence-to-sequence prediction by encoding an input word list, initializing the decoder with the final encoder state, and generating a predicted output sequence starting from the GO_ID token. It returns the predicted sentence, attention weights, and intermediate states. The process involves remo... | def encode_decode_predict(self, in_word_list, max_predict_len=20):
xp = cuda.cupy if self.gpuid >= 0 else np
self.reset_state()
# encode list of words/tokens
in_word_list_no_padding = [w for w in in_word_list if w != PAD_ID]
# enc_states = self.encode_list(in_word_list, train=Fal... |
def reset_state(self):
# reset the state of LSTM layers
for lstm_name in self.lstm_enc + self.lstm_rev_enc + self.lstm_dec:
self[lstm_name].reset_state()
self.loss = 0
def pad_list(self, data, lim, at_start=True):
xp = cuda.cupy if self.gpuid >= 0 else np
if at_start:... | This function processes a batch of input-output pairs for training a sequence-to-sequence model. It pads and stacks source sequences (forward and reversed) and target sequences (with GO/EOS tokens) into batches. It encodes the source, initializes the decoder with encoder states, decodes the target, and computes the los... | def encode_decode_train_batch(self, batch_data, src_lim, tar_lim, train=True):
xp = cuda.cupy if self.gpuid >= 0 else np
self.reset_state()
fwd_encoder_batch = xp.empty((0, src_lim), dtype=xp.int32)
rev_encoder_batch = xp.empty((0, src_lim), dtype=xp.int32)
decoder_batch = xp.em... |
def create_buckets():
buck_width = BUCKET_WIDTH
buckets = [[] for i in range(NUM_BUCKETS)]
print("Splitting data into {0:d} buckets, each of width={1:d}".format(NUM_BUCKETS, buck_width))
with open(text_fname["fr"], "rb") as fr_file, open(text_fname["en"], "rb") as en_file:
for i, (line_fr, line_... | The main task of the code is to train a model by checking if a model file exists, creating buckets if requested, determining the latest saved epoch, loading an existing model if allowed, and executing a training loop with specified parameters. It also computes a BLEU score for evaluation. | def main():
print("here", os.path.exists(model_fil))
if create_buckets_flag:
create_buckets()
else:
print("not creating buckets as requested. will crash if buckets not present")
max_epoch_id = 0
if os.path.exists(model_fil):
# check last saved epoch model:
for fname ... |
def _resolve_groups(self):
self._find_groups()
if len(self.resolving_groups) > 0:
self.num_chains += 1
for (x, y) in self.resolving_groups:
self.remove_puyo((x, y))
self.resolving_groups.clear()
self.current_pair_locations = STARTING_POINTS... | The code's main task is to resolve matched puyos by checking for falling puyos, clearing resolved groups, detaching unconnected hanging puyos, and updating their positions to maintain game state consistency. It ensures proper removal of matched pairs and repositions remaining puyos for the next game phase. | def resolve(self):
if len(self.falling_puyos) == 0:
self._resolve_groups()
self._detach_hanging_puyos()
self._update_falling_puyo_locations() |
def getdata(durationValue,spec):
#get data here from spectrometer i guess
print( "also wait for " + durationValue );
start=time.time()
c=0;
x=[1,2,3,4,5]
devices=[]
global spectrometerFlag
if(spectrometerFlag==1):
x=spec.intensities()
while((time.time()-start... | The code's main task is to execute a manual calibration process for a spectrometer. It checks the spectrometer flag, initiates calibration with nitrogen and a second gas (if enabled), waits for user input to trigger measurements, collects data, calculates an alpha value, and finally performs an air measurement. The fun... | def manual():
global spec
print("spectrometer flag is");
print(spectrometerFlag)
durationValue=duration.get()
print("manual mode is started")
calibrateValue=calibration.get()
var=tk.IntVar()
var2=tk.IntVar()
frame2=Frame(root,width=450,height=50);
frame2.grid(row=0);
if(spec... |
def getdata(durationValue,spec):
#get data here from spectrometer i guess
print( "also wait for " + durationValue );
start=time.time()
c=0;
x=[1,2,3,4,5]
devices=[]
global spectrometerFlag
if(spectrometerFlag==1):
x=spec.intensities()
while((time.time()-start... | This code automates a calibration process by controlling gas valves (nitrogen, CO2, air), collecting spectrometer data during specified durations, and calculating an alpha value from nitrogen and CO2 measurements. It updates a GUI with status messages, handles device settings, and performs time-based operations for acc... | def automatic():
global spec
print("automatic mode here we go")
print("spectrometer flag is");
print(spectrometerFlag)
durationValue=duration.get()
calibrateValue=calibration.get()
fillValue=int(fillWait.get())
devices=sb.list_devices()
frame2=Frame(root,width=450,height=50);
... |
def pretrain_infomax(self, batch):
"""
words: (batch_size, word_length)
entity_labels: (batch_size, n_entity)
"""
words, entity_labels = batch
loss_mask = torch.sum(entity_labels)
if loss_mask.item() == 0:
return None
entity_graph_representat... | This function executes different forward passes based on the 'stage' parameter. If multiple GPUs are available, it transfers essential tensors to the current GPU. For 'pretrain' stage, it computes info-max loss; for 'rec' and 'conv' stages, it handles recommendation and conversation tasks respectively, returning corres... | def forward(self, batch, stage, mode):
if len(self.gpu) >= 2:
# forward function operates on different gpus, the weight of graph network need to be copied to other gpu
self.entity_edge_idx = self.entity_edge_idx.cuda(torch.cuda.current_device())
self.entity_edge_type = self.... |
def pretrain(self):
self.init_optim(self.pretrain_optim_opt, self.model.parameters())
for epoch in range(self.pretrain_epoch):
self.evaluator.reset_metrics()
logger.info(f'[Pretrain epoch {str(epoch)}]')
for batch in self.train_dataloader.get_pretrain_data(self.pretr... | The code's main task is to train a model through three phases: pretraining to establish foundational knowledge, training a recommender system for content/item recommendations, and training a conversation model for dialogue understanding/generation. This structured approach builds general capabilities first, then narrow... | def fit(self):
self.pretrain()
self.train_recommender()
self.train_conversation() |
def hide_window(self):
self.root.withdraw()
def resetImage(self):
image_url = getAssetPath("resources/image/shishi-odoshi.gif")
innerWidth = int(self.windowWidth * 0.8)
image = Image.open(image_url).resize((innerWidth, int(innerWidth*(9/16))))
image = self.round_corners(image, 10... | This method initializes the GUI for the Shishi Odoshi application, setting up the window properties, UI elements (image display, status text, start/stop button, monitor selection dropdown, interval spinner), and event bindings. It configures the interface for monitoring screen motion and triggering alerts, while enabli... | def setup_gui(self):
self.root.title("Shishi Odoshi")
pygame.mixer.init()
self.windowWidth = 450
self.windowHeight = 380
self.root.geometry(f'{self.windowWidth}x{self.windowHeight}')
self.root.resizable(False, False)
self.root.configure(bg='#FFFFFF')
self... |
def init():
global flag, ctr, go, e, n, pt, ct
with open("flag.txt", "r") as f:
flag = f.read()[:54]
pt = flag + "".join(choice(ascii_uppercase + ascii_lowercase + digits) for _ in range(16))
ctr = 0; e = 5; go = True
mod(); enc()
def enc():
global flag, ctr, go, e, n, pt, ct
ct = po... | The code implements a menu-driven program for interacting with cryptographic operations. It allows users to generate new ciphertexts, modulus values, restart the program, or exit. The main loop displays the current modulus and ciphertext, processes user input, and handles exceptions. Global variables track state, while... | def main():
global flag, ctr, go, e, n, pt, ct
init()
while go:
print("=======================")
print("""Welcome to Gacha Universe
Your modulus: {}
Your ciphertext: {}\n""".format(n, ct))
print("""Menu:
1. Get new ciphertext
2. Get new modulus
3. Restart program
4. Exit
Select menu:... |
def prep_input(
self,
X: pd.DataFrame
):
# Store column names in list based on their datatype
cat_columns, num_columns, text_columns = self.get_dtype(X)
self.best_approach_dict["text_columns"] = text_columns
# Preprocess categorical columns
if cat_columns:
... | The code's main task is to evaluate and select the best machine learning approach (chained, independent, or powerset models) by preprocessing input data, combining features and targets, splitting into train/test sets, and comparing model accuracies. It iterates through specified estimators, trains each approach, tracks... | def fit(
self,
X: pd.DataFrame,
y: pd.DataFrame,
):
"""Calculates and returns the best approach among the methods provided.
"""
# Preprocess input columns
df_cat, df_text, df_num = self.prep_input(X)
# Combine the preprocessed input dataframes and
... |
def load_transfer_info(filename):
ransac_mats = []
with open(filename) as f:
lines = f.readlines()
idx = 0
while idx < len(lines):
ransac_mat = []
for i in range(1, 5):
line = lines[idx+i]
nums = [float(n) for n in line.rstrip().split(" ")]
ransac_mat.append(nums)
ransac_mats.append(n... | The code processes RGB-D image sequences to generate and align 3D point clouds using ICP registration. It creates directories for outputs, loads camera poses, iterates through frames, converts RGB-D images to point clouds, applies transformations, projects aligned points onto images, and saves visualized results showin... | def main():
img_dir = "lobby/image/"
depth_dir = "lobby/depth/"
n_frames = 20000
depth_path_regex = depth_dir + '%06d.png'
img_path_regex = img_dir + '%06d.jpg'
pcloud_saved_dir = 'pcloud/'
if not os.path.exists(pcloud_saved_dir):
os.makedirs(pcloud_saved_dir)
ply_saved_dir = 'registered_ply/'
if not ... |
def get_unique_poss(self, mgrid: np.ndarray, row: int, col: int):
y_coords, x_coords = mgrid
# Get the coordinates of all cells
# except the current cell
cells = np.array([
cell for cell
in np.vstack([y_coords.ravel(), x_coords.ravel()]).T
if not (cel... | This function checks if a value is uniquely possible in a specific cell of a Sudoku grid by examining its row, column, and 3x3 square. It returns the unique possible value if found in any of these regions, aiding in solving the puzzle by identifying cells with only one valid candidate. | def get_unique_possible_value(self, row: int, col: int):
'''
Check if any value is only possible for one cell
'''
return (self.get_unique_poss(get_row(row), row, col)
or self.get_unique_poss(get_col(col), row, col)
or self.get_unique_poss(get_square(row, ... |
def sending_proceed(self):
for name, p in self.client_pos.items():
if p[0]!=0:
self.client_sockets.get(name).send(("$proceed "+str(p[0])+" "+str(p[1])).encode())
self.client_pos[name]=(0,None)
def findBySocet(self, so):
for k, v in self.client_sockets.items():... | The main task of the code is to handle client communication by receiving and processing messages, managing client connections, broadcasting messages to all clients, adding/removing clients, listing online users, handling file downloads, and initiating threaded data transfers. It processes commands like "set_msg_all," "... | def clientListen(self, cl, cAddr):
while True:
self.sending_proceed()
try:
msg = cl.recv(1024).decode()
print(msg)
source = self.findBySocet(cl)
first_word = msg.split()[0]
msg = msg.replace(first_word+"... |
def geting_info(self):
global name
while True:
info = input().strip()
try:
if info.split()[0] =="connect" and info.split()[1] is not None:
name = info.split()[1]
break
except Exception as e:
pr... | The code connects to a server using predefined IP and port, spawns a daemon thread to listen for client messages continuously, and initiates data retrieval/sending. The main tasks are: 1) Establishing server connection, 2) Starting a background thread for message listening, 3) Handling data exchange via get_and_send(). | def join_to_server(self):
self.geting_info()
host = server_IP
port = server_PORT
self.connect_to_server(host, port)
# creating new thread for each client messages
th1 = threading.Thread(target=self.messagesListener, )
# make the thread run until the main threa... |
def get_args():
parser = argparse.ArgumentParser(description='get some COVID-19 stats')
parser.add_argument('-c',
'--country',
help='get results for the specified country')
parser.add_argument('-s',
'--state',
he... | The code processes COVID-19 data from CSV files, either listing countries, states, or administrative regions based on command-line flags, or printing/graphing aggregated statistics. It reads daily reports, extracts relevant data, and outputs structured information or visualizations depending on user-specified parameter... | def main():
args = get_args()
kw = {'country': args.country, 'state': args.state, 'admin': args.admin}
data_dir = "COVID-19/csse_covid_19_data/csse_covid_19_daily_reports"
all_files = sorted(fn for fn in os.listdir(data_dir) if fn.endswith("csv"))
data = [process_file(os.path.join(data_dir, p)) for ... |
def checkForIndirect(gramA, a, ai):
if ai not in gramA:
return False
if a == ai:
return True
for i in gramA[ai]:
if i[0] == ai:
return False
if i[0] in gramA:
return checkForIndirect(gramA, a, i[0])
return False
def rep(gramA, A):
temp = gramA[A]
newTemp = []
for i in temp:
if checkForIndirect(g... | The code removes left recursion (direct and indirect) from a context-free grammar. It maps original symbols to temporary symbols, transforms productions to eliminate recursion, and maps back to original symbols. The process involves detecting and resolving indirect left recursion, then removing direct left recursion, f... | def rem(gram):
c = 1
conv = {}
gramA = {}
revconv = {}
for j in gram:
conv[j] = "A"+str(c)
gramA["A"+str(c)] = []
c+=1
for i in gram:
for j in gram[i]:
temp = []
for k in j:
if k in conv:
temp.append(conv[k])
else:
temp.append(k)
gramA[conv[i]].append(temp)
#print(gramA)... |
def _get_beam_from_hdu(self): #two
"""
Look up the beam information in the header of the SourceFinder's image
"""
try:
with fits.open(self.image_name) as hdu:
beam_maj = hdu[0].header["BMAJ"]
beam_min = hdu[0].header["BMIN"]
bea... | The code executes a source finding algorithm using PyBDSF on an astronomical image. It processes the image with configurable parameters (e.g., SNR thresholds, beam info, output options), automatically retrieves missing beam/RMS box data from the image header, manages working directories, handles exceptions, and returns... | def run( # one
self,
adaptive_rms_box=False,
advanced_opts=True,
atrous_do=False,
psf_vary_do=False,
psf_snrcut=5.0,
psf_snrcutstack=10.0,
output_opts=True,
output_all=True,
opdir_overwrite="overwrite",
beam=(),
blank_limit=... |
def _access_token_is_expired(self):
"""
Private method that tells you if your access token doesn't exist,
or is expired.
"""
if self.access_token is None:
return True
my_jwt = jwt.decode(self.access_token, verify=False)
if my_jwt['exp'] < int(round(... | The code's main task is to make API requests with automatic access token refresh when necessary. It handles authentication, sends HTTP requests with specified parameters, and retries requests with a refreshed token if a 401 Unauthorized error occurs due to an invalid access token, ensuring seamless SDK interactions wit... | def request(self, method, url, json=None, headers=None, form=None,
params=None, force_token_refresh=False, app='API'):
"""
Makes a request against API service. Refreshes your access token if
necessary. Use this for all requests in the SDK!
Arguments:
method (str)... |
def setup_signal_handler(self):
signal.signal(signal.SIGINT, self.signal_handler) # Handle Ctrl-C
if hasattr(signal, "SIGBREAK"):
# Handle Ctrl-Break e.g. under Windows
signal.signal(signal.SIGBREAK, self.signal_handler)
def do(self):
"""
Send one ICMP ECHO_REQUEST and... | The main task of the code is to repeatedly send and receive pings in a loop, controlled by either a specified number of pings (`count`) or a time deadline (`deadline`). It increments a sequence counter after each ping, terminating the loop when the count limit is reached or the elapsed time exceeds the deadline. If the... | def run(self, count=None, deadline=None):
"""
send and receive pings in a loop. Stop if count or until deadline.
"""
if not self.quiet_output:
self.setup_signal_handler()
while True:
delay = self.do()
self.seq_number += 1
if count and self.se... |
def get_train_transform():
train_transform = transforms.Compose([
transforms.Resize(256),
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
])
return MultiDataTransform(train_transform)
def get_class_datasets(benchmark, data_file, ... | The function `get_dataset_2` prepares domain adaptation datasets by loading and organizing data from multiple sources based on the specified benchmark (e.g., OfficeHome, DomainNet). It applies training transforms, constructs class-specific `ConcatDataset` objects, and optionally includes pseudo-labeled data if provided... | def get_dataset_2(P, train=True, target_known_mask=None, target_known_pseudo_labels=None):
if train:
transform = get_train_transform()
benchmark = P.dataset
domain_datasets = {}
if benchmark == "OfficeHome":
domains = ["Art", "Clipart", "Product", "RealWorld"]
... |
def awslogs_handler(event):
# Get logs
with gzip.GzipFile(
fileobj=BytesIO(base64.b64decode(event["awslogs"]["data"]))
) as decompress_stream:
# Reading line by line avoid a bug where gzip would take a very long
# time (>5min) for file around 60MB gzipped
data = b"".join(BufferedReader(decompress_... | This Lambda function handler processes AWS CloudWatch Logs events by validating the input, parsing log data, generating metadata, normalizing log entries, and forwarding them to an S3 logger. It logs progress and errors for debugging, ensuring only valid "awslogs" events are processed and stored in S3. | def handler(event, context):
logger.info(f"log forwarder starting ...")
if "awslogs" not in event:
logger.error(f"Not an awslog event")
return
parsed = awslogs_handler(event)
metadata = generate_metadata(parsed)
logger.debug(f"metadata: {metadata}")
normalised = normalise_events(parsed["logEve... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.