dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def deadDelay(obj):
if obj == None:
return 0
delay = getProp(obj.name).dead_delay #bpy.context.scene.objects[obj.name].destruction.dead_delay
return delay
def isGroundConnectivity(obj):
global children
global firstGround
if obj == None:
return False
if obj.name in childr... | This code activates a child object in a physics simulation by setting its dynamics, checking grid integrity, adjusting velocity based on owner properties, and managing activation timing with delays. It identifies the parent, processes grid cells, destroys compromised cells, and either immediately activates the child or... | def activate(child, owner, grid):
print("activated: ", child)
global integrity
global firstShard
global delay
delay = deadDelay(owner)
parent = None
for p in children.keys():
if child.name in children[p]:
parent = p
break
# print("PA... |
def getProp(name):
return dd.DataStore.properties[name]
def findFirstParent(parent):
#TODO: hack -> find first parent, ground connectivity on subparents is unsupported by now.
#what about loose parts parents (they have another name mostly) ?
#maybe store a reference to the firstparent directly.
temp... | The main task of the code is to swap an object with a backup compound in a 3D scene, handling child objects by replacing their meshes, adjusting positions/parents, and updating scene relationships. It processes dynamic properties, connects to ground if needed, and maintains a global children dictionary for tracking obj... | def swapBackup(obj, owner):
global children
global firstparent
print("swap backup", obj)
ret = []
obname = obj.name
parent = getProp(obname).is_backup_for#bpy.context.scene.objects[obname].destruction.is_backup_for
if parent == "":
return ret
if pa... |
def getProp(name):
return dd.DataStore.properties[name]
def isRegistered(destroyable, destructor):
if not isDestroyable(destroyable):
return False
if not isDestructor(destructor):
return False
global isCollapsing
if isCollapsing:
return True
targets = getP... | The function `modSpeed` calculates a modified speed value by combining an object's radius and a modifier, scaled by the input `speed`. It checks conditions to determine whether to use properties from a collided object (`hit`) or the original owner. If conditions are met, it applies `hit`'s radius and modifier; otherwis... | def modSpeed(owner, speed):
#ownerBpy = bpy.data.objects[owner.name]
hit = owner.sensors["Collision"].hitObject
if hit != None and getProp(owner.name).individual_override and \
isRegistered(findParent(hit), owner):
#hitBpy = bpy.data.objects[hit.name]
radius = getProp(hit.name).radius #h... |
def isDestructor(obj):
global children
if obj == None:
return False
# if obj.name.startswith("P_"): #TODO find out compoundparent if not custom_ball!!
# last = children[obj.name][-1]
# destructor = bpy.context.scene.objects[last.name].destruction.destructor
# else:
... | This function calculates the minimum distance between two objects (a and b), considering a's mesh faces if a is a ground/destructor. It iterates through a's mesh polygons, computes distances from b's world position to each triangular face, and returns the smallest distance. If a isn't a ground/destructor, it directly r... | def getFaceDistance(a, b):
# hack
#print(a, b)
if isDestructor(a) and isGround(a):
mindist = sys.maxsize# 10000000000
#obj = bpy.data.objects[a.name]
#for f in obj.data.polygons:
# v1 = obj.data.vertices[f.vertices[0]].co
# v2 = obj.data.vertices[f.vertices[1... |
def loadBGEProps():
#dd.DataStore.properties = json.loads(jsondata.data)
# print("Loaded:", len(dd.DataStore.properties))
d = json.loads(jsondata.data, object_hook = dd.BGEProps.object_hook)
dd.DataStore.properties = d
def getProp(name):
return dd.DataStore.properties[name]
def isGround(obj):
... | The code sets up a scene hierarchy by assigning parent-child relationships to objects based on their 'myParent' properties, manages compound collision groups, and ensures ground connectivity. It initializes global variables, processes object hierarchies, and adjusts parent links for physics interactions, including swap... | def setup():
global firstparent
global firstShard
global ground
global children
# global destructors
global firstGround
print("setup")
loadBGEProps()
#temporarily parent
for o in scene.objects:
if o.name != "Player":
if "myParent" in o.getPropertyNa... |
def isRegistered(destroyable, destructor):
if not isDestroyable(destroyable):
return False
if not isDestructor(destructor):
return False
global isCollapsing
if isCollapsing:
return True
targets = getProp(destructor.name).destructor_targets #bpy.context.scene.o... | The function compares the speed of an object against its distance and glue threshold, returning True if both distance and glue are less than speed, determining if an object should be affected by a speed-based action in a physics simulation. | def compareSpeed(owner, obj):
lastSpeed = 0
if isRegistered(findParent(obj), owner):
maxHierarchyDepth = hierarchyDepth(obj)
else:
maxHierarchyDepth = hierarchyDepth(owner)
dist, speed, depth = distSpeed(owner, obj, maxHierarchyDepth , lastSpeed)
if speed > 0:
lastSpeed = sp... |
def update_config(self):
with urllib.request.urlopen(self.cfg('base_url', str) + '/config') as req:
res = req.read()
self.opt = json.loads(res)
for upscaler in self.opt['upscalers']:
if upscaler not in upscalers:
upscalers.append(upscaler)
se... | The code's main task is to execute a text-to-image generation workflow. It updates configuration settings, adjusts aspect ratios, applies text-to-image processing, and creates a mask layer workaround. The method checks if the process is already running before proceeding, ensuring proper setup and execution of image gen... | def action_txt2img(self):
if self.working:
pass
self.update_config()
self.try_fix_aspect_ratio()
self.apply_txt2img()
self.create_mask_layer_workaround() |
def update_config(self):
with urllib.request.urlopen(self.cfg('base_url', str) + '/config') as req:
res = req.read()
self.opt = json.loads(res)
for upscaler in self.opt['upscalers']:
if upscaler not in upscalers:
upscalers.append(upscaler)
se... | This method processes image-to-image conversion by updating configurations, adjusting aspect ratios, applying the transformation in mode 0, and creating a mask layer workaround. It checks if the system is already working before proceeding, ensuring proper setup for image processing tasks. | def action_img2img(self):
if self.working:
pass
self.update_config()
self.try_fix_aspect_ratio()
self.apply_img2img(mode=0)
self.create_mask_layer_workaround() |
def update_config(self):
with urllib.request.urlopen(self.cfg('base_url', str) + '/config') as req:
res = req.read()
self.opt = json.loads(res)
for upscaler in self.opt['upscalers']:
if upscaler not in upscalers:
upscalers.append(upscaler)
se... | The function `action_sd_upscale` updates configuration settings, applies image-to-image processing in mode 2, and creates a mask layer as a workaround. It checks if `self.working` is active but does nothing if true, likely reserving the method for future implementation or conditional execution. The primary tasks involv... | def action_sd_upscale(self):
if self.working:
pass
self.update_config()
self.apply_img2img(mode=2)
self.create_mask_layer_workaround() |
def update_config(self):
with urllib.request.urlopen(self.cfg('base_url', str) + '/config') as req:
res = req.read()
self.opt = json.loads(res)
for upscaler in self.opt['upscalers']:
if upscaler not in upscalers:
upscalers.append(upscaler)
se... | The main task of the code is to perform image inpainting by updating configurations, adjusting aspect ratios, and applying an img2img process in mode 1, provided the working flag is not active. | def action_inpaint(self):
if self.working:
pass
self.update_config()
self.try_fix_aspect_ratio()
self.apply_img2img(mode=1) |
def create_interface(self):
self.create_txt2img_interface()
self.create_img2img_interface()
self.create_upscale_interface()
self.create_config_interface()
self.tabs = QTabWidget()
self.tabs.addTab(self.txt2img_widget, "Txt2Img")
self.tabs.addTab(self.img2img_widg... | The code initializes a GUI plugin with the title "SD Plugin," creating and connecting multiple interfaces (txt2img, img2img, upscale, config) for image generation and processing. It sets up the main widget, updates configurations, and ensures event handling for each interface component. | def __init__(self):
super().__init__()
self.setWindowTitle("SD Plugin")
self.create_interface()
try:
script.update_config()
except:
pass
self.init_txt2img_interface()
self.init_img2img_interface()
self.init_upscale_interface()
... |
def get_minimum_sensor_values(ps) -> set:
# Get all sensor indexes
ps_indexes = [i for i in range(16)]
sensors = []
# Loop through each sensor index
for i in ps_indexes:
sensors.append(round(ps.get_value(i), 3))
# Get minimum values from sensor pairs
msv = {"fl": min(sensors[1], sen... | The code navigates a robot to avoid walls by analyzing proximity sensors, aligning to axes, turning when obstructed, and moving forward when safe. It manages movement states to prevent loops, adjusts trajectory based on sensor thresholds, and updates navigation goals while ensuring progress toward checkpoints while avo... | def avoid_wall(self, checkpoints, current_coordinates, current_heading, goal_cells, occupancy_grid, probabilities,
prox_sensors, robot_velocity, schedule, schedule_idx, target_time):
current_x, current_y = round(current_coordinates[0]), round(current_coordinates[1])
# Get the sensor ... |
def k_means(
features: npt.NDArray[np.float32],
k: int,
n: int,
M: int,
N: int,
seed: int,
) -> Tuple[npt.NDArray[np.float32], npt.NDArray[np.float32]]:
"""K-Means algorith calculation function
Arguments:
features: Image features array
k: The number of clusters for the k... | The code performs image clustering using K-means on different feature sets (RGB, RGB+spatial coordinates, luminance, luminance+spatial coordinates) based on the input attributes_type. It reads input images, processes features, applies clustering, reconstructs the image, and calculates the RMSE between the generated ima... | def main():
image_filename = str(input().strip())
ref_image_filename = str(input().strip())
attributes_type = int(input().strip())
k = int(input().strip())
n = int(input().strip())
seed = int(input().strip())
image = imageio.imread(image_filename).astype(np.float32)
ref_image = imageio.... |
def load_images(image_names: List[str]) -> npt.NDArray[np.float32]:
"""Helper function for loading images given a path
Arguments:
image_names: list of strings containing the paths of images to be loaded.
Returns: list of ndarrays containing the images loaded in float32 format.
"""
images =... | The code processes images by converting them to grayscale, binarizing with a threshold, and applying morphological operations (opening/closing). It computes texture descriptors using co-occurrence matrices and Haralick features, then retrieves images similar to a query image based on descriptor similarity, outputting o... | def run():
query_index = int(input().strip())
Q = tuple(map(int, input().strip().split(" ")))
F = int(input().strip())
T = int(input().strip())
B = int(input().strip())
image_names = [str(input().strip()) for _ in range(B)]
images = load_images(image_names)
gray_images = convert_gray_lu... |
def apply_gaussian_filter(
image: np.ndarray, k: int, sigma: float
) -> tuple[np.ndarray, np.ndarray]:
"""Changes the image received by applying a Gaussian blur filter to it.
Arguments:
image: The original image in space domain.
k: Size of the side of the square matrix filter.
sigma... | The code performs image restoration using either a Gaussian blur with CLSQ deconvolution or motion blur with Richardson-Lucy deconvolution, based on user input. It reads an input image, applies the selected restoration method, calculates the RMSE between the original and restored images, and prints the result. | def main():
in_image_filename = str(input().rstrip())
method = int(input().strip())
if method == 1:
k = int(input().strip())
sigma = float(input().strip())
gamma = float(input().strip())
base_image = imageio.imread(in_image_filename)
degraded, psf = apply_gaussian_fil... |
def Submit(self,answer):
""" Display the Entry text value. """
self.count_flag = False
if entryWidget.get().strip() == "":
messagebox.showerror("Tkinter Entry Widget", "Please enter a number.")
self.count_flag = True
questionWindow.focus_set()
se... | This code initializes a math quiz GUI application by setting up variables to track quiz state, configuring the window layout, creating input fields and buttons, binding keyboard events for user interaction, and adjusting the window size. It prepares the interface for displaying questions, handling user answers, and man... | def __init__(self) -> None:
answer = 0
questionsAsked = 0
count = 0.0
bindsHelpAsked = 0
self.answer = answer
self.questionsAsked = questionsAsked
self.count = count
self.bindsHelpAsked = bindsHelpAsked
#Configure window
questionWi... |
def N_range(arr,i_measured,r_measured):
get=[]
for N in arr:
result=try_N(N,i_measured, r_measured)
reletive_error=[]
for name, param in result[2].params.items():
reletive_error.append(param.stderr/param.value)
get.append([N,result[2].chisqr,reletive_error])
retur... | The function `get_params` determines the optimal parameters (beta and gamma) for a best-fit model by selecting the most suitable candidate from a range of possible values. It uses the input array and measured values to compute and return the corresponding array element, along with the fitted beta and gamma parameters. | def get_params(arr,i_measured,r_measured):
get=N_range(arr,i_measured,r_measured)
index=compare(get)
result=best_fit(arr,i_measured,r_measured,index)
return arr[index],result[2].params['beta'].value,result[2].params['gamma'].value |
def get_tokens_moves(self) -> list['BoardState']:
"""
Returns all next board state
"""
token_turn_type = self._get_token_turn_type()
token_pos = self._get_token_pos(token_turn_type)
return [
board_state
for pos in token_pos
for board_s... | This function applies a move on a board by updating positions of tokens, validates the move based on the token type (RED/GREEN/BOBAIL), checks if the move is in allowed moves, and raises an IllegalMove exception if invalid. It switches players after moving non-BOBAIL tokens and updates the board state accordingly. | def do_move(self, start_pos: Pos, dest_pos: Pos) -> None:
"""
Apply a move (encoded with 2 positions) to the current board
Also checks the validity of the move
"""
si, sj = start_pos
di, dj = dest_pos
start_token = self.board[si][sj]
if (start_token in (T... |
def have_won( self, tablero ):
return np.array_equal(tablero, self.m_tableroGanador)
def extenderArbol(self,nodoActual, nivel):
movimientos = [ 'a', 'b', 'i', 'd' ]
posicionCasillaVacia = np.where( np.array(nodoActual.tablero) == 0 )
( fila, columna ) = ( posicionCasillaVacia[ 0 ... | This code implements a heuristic search algorithm to solve a board game. It constructs a tree of possible moves, selects the path with the lowest heuristic value at the fourth level, and backtracks to generate the optimal sequence of moves required to reach the winning state. The moves are stored in a stack, reversed t... | def jugar( self, tablero ):
pila_de_movimientos = []
arbol = Nodo(tablero, None, None, None)
while not self.have_won(arbol.tablero):
self.extenderArbol(arbol,2)
nodos4nivel = [ ]
self.buscarHijos4nivel(arbol,nodos4nivel)
min_heurstica = math.inf
... |
def pull_data(address):
with urllib.request.urlopen(address) as url:
data = json.loads(url.read().decode())
return data
def filter_data(data, zip_codes_to_keep):
filtered_data = dict()
for entry in data:
for zip in zip_codes_to_keep:
if "attributes" in entry and "Zip_Numbe... | The code aggregates and analyzes COVID-19 data for specific zip codes by fetching, filtering, and merging statistics from two APIs. It calculates metrics like total cases, population, case rates, test positivity rates, and 7-day/28-day averages, comparing them to historical data. Results are logged, stored in a databas... | def check_safety(request):
zip_codes_to_keep = [94601, 94602, 94606, 94610, 94619]
url1 = "https://services5.arcgis.com/ROBnTHSNjoZ2Wm1P/arcgis/rest/services/COVID_19_Statistics/FeatureServer/0/query?where=1%3D1&outFields=Zip_Number,Population,Cases,CaseRates&returnGeometry=false&outSR=4326&f=json"
url... |
def match_title(self, title=None):
"""
Search movie based on the movie name entered.
:param title: the movie name
:return:
"""
if title is None:
title = self.title
else:
self.__init__(self.file_path, title)
self.__whether_match = F... | The main task of the code is to process a given title by matching it, and if a match is confirmed, generate and output information, a histogram, and a PDF document. It adjusts the title attribute, checks for a match, and triggers subsequent actions like printing details, creating visualizations, and exporting results i... | def main(self, title=None):
if title is None:
title = self.title
else:
self.title = title
self.match_title(title)
if self.__whether_match:
self.print_info()
self.generate_histogram()
self.output_pdf() |
def menue():
msg(bcolors.OKCYAN,
"What would you like to do?\n\n"
"1. Set a new user\n"
"2. Check password\n"
"3. Exit password safe\n\n "
"Please select either 1, 2 or 3: \n")
def write_user(password_file):
username = input(bcolors.OKBLUE + "Please set your username: ").lowe... | The code implements a menu-driven password management system. It maintains a state machine with options to display a menu (state 0), write user data (state 1), check user credentials (state 2), or exit (state 3). The system reads/writes to a password file, handles user input validation, and transitions between states b... | def main():
state = 0
password_file = "password.txt"
pwdtools.check_create_file(password_file)
while True:
match state:
case 0:
menue()
choice = input( )
try:
state = int(choice)
except ValueError:
state = choice
case 1:
print("Wr... |
def get_model_dir(self):
return os.path.join('checkpoints',
f'{self.pde_case}_{self.domain_type}',
f'GFNet_{self.sigma}',
f'{self.z_coarse_num}',
f'{self.x_coarse_num}_{self.x_middle_num}_{self.x_refi... | This code initializes a Physics-Informed Neural Network (PINN) by configuring model parameters, neural network structures, mesh data, and Gauss quadrature rules for boundary/interior points. It loads mesh files, sets up problem-specific settings, and prepares components for solving PDEs using PINN, including neural net... | def __init__(self, args):
self.args = args
self.problem = args.problem
self.layers = args.layers
self.device = args.device
self.cuda_index = args.cuda_index
self.qmesh = args.qmesh
self.qmesh_type = args.qmesh_type
... |
def shift_left(aReg , qReg):
new_bit=qReg[0]
qReg=qReg[1:]
aReg=aReg[1:]
aReg=aReg+[new_bit]
return {
"a":aReg,
"q":qReg
}
def binary_sub(a,m):
converted=two_comp(m)
#print(f'asas {b}')
res=binary_add(a,converted)
m=two_comp(m)
return res
def binary... | This code performs division using a non-restoring algorithm, returning the quotient and remainder. It iteratively shifts and adjusts registers, appending bits based on subtraction results, until the remainder is calculated. | def calc(a_reg , q_reg):
mx=m_reg
count=len(q_reg)+1
global qLast
qLast=0
while(count>1):
# print(f'Before A : {a_reg} , Q : {q_reg}')
shiftL=shift_left(a_reg , q_reg)
a_reg=shiftL['a']
q_reg=shiftL['q']
#print(f'After Shift A : {a_reg} , Q : {q_reg} \n')
... |
def binary_sub(q,m):
converted=two_comp(m)
#print(f'asas {b}')
res=binary_add(q,converted)
m=two_comp(m)
return res
def binary_add(q,m):
result=[]
carry=0
for a_item , b_item in zip(q[::-1],m[::-1]):
addn=0
if a_item+b_item+carry==3:
addn=1
elif a_item+b_item+carry==2:
... | This code implements a binary division algorithm using a modified Booth's method. It iteratively adjusts the accumulator (a_reg) by adding/subtracting the divisor (mx) based on the least significant bit of the quotient (q_reg) and a flag (qLast). The result is constructed through right shifts and stored in steps. The f... | def calc(a_reg , q_reg):
mx=m_reg
count=len(q_reg)+1
global qLast
qLast=0
while(count>1):
#compare Q and Q0:
if q_reg[-1]==1 and qLast==0:
a_reg= binary_sub(a_reg , mx)
elif q_reg[-1]==0 and qLast==1:
# print(f'{a_reg} add {m_reg}'... |
def options_abbrev(options_name):
'''Return an abbreviated version of the option name.'''
prefix = 'OPTIONS_'
assert options_name.startswith(prefix)
return options_name[len(prefix):].lower()
def get_option_description(option_name):
if option_name in build_only_options:
return build_only_opti... | The function builds test configurations for a specified options name by setting up a build directory, cleaning it if requested, and invoking CMake with Ninja to generate build files. It then compiles the tests in parallel using the specified build type. The process includes printing status messages and managing directo... | def build_tests(options_name, build_type, clean):
'''Build all tests for the specified options name.'''
global lvgl_test_dir
print()
print()
label = 'Building: %s: %s' % (options_abbrev(
options_name), get_option_description(options_name))
print('=' * len(label))
print(label)
pr... |
def Swing_Stance(self):
M = []
for i in range(self.num_sets):
M.append(float(self.entries[i][2].get()))
list_ = M.copy()
list_.append(M[0])
code = []
swing = 0
for i in range(len(M)):
if list_[i] != 0 or list_[i + 1] != 0:... | This code plots 3D gait trajectories using input coordinates, applies rotation transformations, and conditionally renders lines/points based on user selections. It handles multiple data sets, adjusts plot axes dynamically, and integrates the visualization into a Tkinter GUI with interactive canvas placement. | def plot_coordinates(self):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x_data = []
y_data = []
z_data = []
for entry in self.entries[:-1]:
x = float(entry[0].get())
y = float(entry[1].get())
z = floa... |
def create_entry(self, num_sets, influenced_axis, component, order):
displacement = (order - 1) * (num_sets * 20 + 50)
tk.Label(self, text = component, font = 15).place(x = 50, y = offset - component_label + displacement)
for i in range(num_sets):
tk.Label(self, text="Set {}:".format... | This code initializes a GUI window for inputting gait parameters, featuring dropdowns for gait modes (Crawl/Trot), entry fields for movement components (Marching, Forward/Backward, Left/Right, Rotation), checkboxes to control 3D plot visibility, a phase diagram canvas with legend, and "Plot"/"Generate" buttons. It sets... | def __init__(self, num_sets, num_legs):
super().__init__()
# Info of the window
self.title("Input Sets Window")
self.geometry("1200x750+-10+0")
# Variables
self.entries = []
self.num_sets = num_sets
self.num_legs = num_legs
# Crea... |
def on_off(self):
if self.tmp == 0:
self.on()
self.tmp = 1
else:
self.off()
self.tmp = 0
def light_up(self, t=1):
if self.pct + t * self.unit > 1:
self.pct = 1
else:
self.pct = self.pct + t * self.unit
self.o... | This code configures button click handlers for a panel, assigning each of the first three buttons to trigger specific actions: the first toggles a state (on/off), the second activates a light, and the third adjusts light intensity downward. The primary task is to link user interface buttons to corresponding functional ... | def _setting(self): #config for actions
self.panel.buttons[0].on_click(lambda x: self.on_off())
self.panel.buttons[1].on_click(lambda x: self.light_up())
self.panel.buttons[2].on_click(lambda x: self.light_down()) |
def rollback(self):
info("Performing rollback")
try:
rollback_path = self.latest_checkpoint_path()
except AssertionError:
info("No checkpoint found - training normally")
else:
warn(f"Resuming from {rollback_path}")
# Discard the lost iterat... | This code implements an iterator for training a model, logging events like initialization, resuming from existing data, progress updates, checkpoints, and epochs. It yields LogEvent enums based on iteration intervals, managing logging state and progressing through training steps while handling directory existence check... | def __iter__(
self,
) -> Iterator[LogEvent]:
with logger.directory(self.path) as exists_already:
info("Starting training")
if exists_already:
self.rollback()
yield LogEvent.RESUME
else:
self.init_logging()
... |
def posterior_to_log_odds(posterior):
"""
Args:
posterior (dict): must have the keys 'right' and 'left'
Returns: log posterior odds if reasonable, otherwise +/- np.inf
"""
try:
log_odds = np.log(posterior['right'] / posterior['left'])
except ZeroDivisionError:
log_odds ... | This function recursively updates beliefs about the source of observations using a probabilistic model, yielding log posterior odds and decisions at each step. It handles two modes (filter_step 0/1): one updates beliefs based on current observations, while the other predicts future states using past data. The algorithm... | def recursive_update():
"""
This is a Python generator
Returns: really yields a tuple (log posterior odds, decision), with decision in SIDES
"""
decision_number = 0
num_observations = len(observations)
if all(self.sources_prior.values(... |
def create_instances(self, nb_instances, batch_name='anonymous', script_filename = os.path.expanduser('~/.tirith/become-gitserver.sh')):
print(f'Create {nb_instances} instances')
with open(script_filename, 'r') as file:
script = file.read()
if os.path.exists(script):
wi... | The code creates EC2 instances, sets up a target group in AWS, and registers instances with the target group for load balancing. It uses parameters like instance count, VPC ID, and instance type. On failure, it deletes resources and re-raises exceptions. | def create(self, nb_instances, batch_name, vpc_id, instanceType = {'type': 't2.micro', 'zone': 'us-east-1a'}):
self.instance_type = instanceType['type']
self.zone = instanceType['zone']
try:
self.create_instances(nb_instances, batch_name)
self.create_target_group_if_need... |
def collect_columns():
signal_cols = [Columns.load(f) for f in glob.glob(DATADIR+'/signal_notruthcone/*.npz')]
signal_cols.sort(key=lambda s: (s.metadata['mz'], s.metadata['rinv']))
bkg_cols = [Columns.load(f) for f in glob.glob(DATADIR+'/bkg/Summer20UL18/*.npz')]
bkg_cols = filter_pt(bkg_cols, 170.)
... | The function `print_cutflow_tables` generates and prints formatted cutflow tables for signal and background processes. It iterates over background types, printing individual tables for each, then combines all background columns into a summary table with metadata. Finally, it prints a separate table for signal columns, ... | def print_cutflow_tables():
signal_cols, bkg_cols, bkg_cols_per_type = collect_columns()
for bkg_type, cols in bkg_cols_per_type.items():
print('-'*80)
print(bkg_type)
print(format_table(make_table(cols)))
print('-'*80)
print('bkg_summary')
combined_bkg_cols = []
for b... |
def collect_columns():
signal_cols = [Columns.load(f) for f in glob.glob(DATADIR+'/signal_notruthcone/*.npz')]
signal_cols.sort(key=lambda s: (s.metadata['mz'], s.metadata['rinv']))
bkg_cols = [Columns.load(f) for f in glob.glob(DATADIR+'/bkg/Summer20UL18/*.npz')]
bkg_cols = filter_pt(bkg_cols, 170.)
... | The function generates and prints a cutflow table for signal samples with 'rinv' metadata value 0.3. It filters signal columns, creates a table with formatting, and outputs the result. | def print_cutflow_tables_rinv0p3_only():
signal_cols, bkg_cols, bkg_cols_per_type = collect_columns()
signal_cols = [s for s in signal_cols if s.metadata['rinv']==0.3]
print('-'*80)
print('signal')
print(format_table(make_table(signal_cols, combined=False))) |
def try_generate_mutation(body):
ans = []
done = False
for line in body:
for m in mutators:
for s in m:
if s in line:
res = try_apply_mutation(m, s, line)
if not done and line != res:
done = True
... | The code processes input lines in different states ("collect", "scan", "skip") to detect mutation points in C++ code. When encountering "break;", it generates and prints mutations conditionally. It captures opcode cases, switches states based on "BEGIN/MUTATE" markers, and outputs original or mutated code blocks while ... | def process_line(s):
global state
global body
global opcode
if state == "collect":
if "break;" in s:
mutation = try_generate_mutation(body)
if mutation is not None:
if raw_mode:
print_body(mutation)
else:
... |
def update_rows():
reset_rows()
global rows, pieces
#TODO if the row has more than 10, we should do something about that
for index in range(0,len(rows)):
for piece in pieces:
if piece.y == index * size:
rows[index] += 1
print("rows are now: ")
print(rows)
def... | This function generates a new game piece by appending blocks to the pieces list, updates row counts, checks for full rows (10 blocks), clears them, resets the current piece's position, and selects a random new piece type. It manages row completion detection and cleanup in a Tetris-like game. | def new_piece():
global pieces,cur_x,cur_y,num, rows
for block in current_piece:
pieces.append(block)
update_rows()
print("making new piece and rows are: " + str(rows))
for i in range(0,len(rows)):
if rows[i] >= 10:
print("found a full row, row number: " + str(i))
... |
def clustering_performance(logits, test_fold, folds, similarity_clusters, similarity_links, min_cluster_size,
individuals_number, output_dir):
test_set = set(folds[test_fold])
val_set = set(folds[(test_fold + 1) % len(folds)])
train_set = set().union(*[set(f) for f in folds]) - te... | The main task of the code is to analyze machine learning model performance across similarity folds by processing clustering metrics, generating UMAP projections, embedding histograms, and loss/temperature plots. It evaluates clustering accuracy (ACC, ARI, NMI) for varying cluster sizes, outputs visualizations, and comp... | def main():
# Parsing command line parameters and necessary configuration
parser = argparse.ArgumentParser()
parser.add_argument("--configuration", help="JSON file configuring the program (layers, size of embeddings, ...)",
required=True, dest="conf_file_path")
parser.add_argumen... |
def get_updates(offset=None):
url = URL + "getUpdates?timeout=100"
if offset:
url += "&offset={}".format(offset)
js = get_json_from_url(url)
return js
def get_last_update_id(updates):
update_ids = []
for update in updates["result"]:
update_ids.append(int(update["update_id"]))
... | The code continuously checks for new messages via an API, updates the last processed message ID, and handles incoming updates. It initializes a database, polls for updates in a loop, processes non-empty results, and sleeps briefly to avoid excessive requests. | def main():
db.setup()
last_update_id = None
while True:
print("getting updates")
updates = get_updates(last_update_id)
#Checks /getUpdates API for new messages
if len(updates["result"]) > 0:
#Have to +1 because position 0 is oldest message
last_update... |
def prompt(message, word):
'''
Write the shell's prompt to stdout
'''
if len(message) == 0:
pre = ""
else:
pre = "|%s| " % message
sys.stdout.write(pre + "> " + word)
sys.stdout.flush()
def getch():
'''
Get a character from stdin
'''
fd = sys.stdin.fileno()
... | This code implements an interactive shell for processing user input with auto-completion, error handling, and reset functionality. It reads characters from stdin, manages word input, checks dictionary validity, handles backspaces, and displays suggestions. The loop updates the prompt state, processes special keys (like... | def shell(eng_dict):
'''
Gather characters from stdin and handle requests for auto
completion, reset, etc.
Type Control-C to get out of this shell.
'''
message = ""
word = ""
misspelled = False
prompt(message, word)
while True:
# Get a character
c = getch()
... |
def prepare_batch(self, batch):
"""
Prepare the batch: from the token_ids and the lengths, compute the attention mask and the labels for CLM.
Input:
------
batch: `Tuple`
token_ids: `torch.tensor(bs, seq_length)` - The token ids for each of the sequence. It is... | This code implements a distributed training loop for a model with a student and teacher architecture. It handles multi-GPU synchronization, gradient accumulation, logging, checkpoint saving, and iterates through epochs using a dataloader. The loop trains the student model while keeping the teacher in evaluation mode, u... | def train(self):
"""
The real training loop.
"""
if self.is_master:
logger.info("Starting training")
self.last_log = time.time()
self.student.train()
self.teacher.eval()
end_train = False
while True:
if self.is_master:
... |
def full_contrastive(self, student, teacher, attention_mask=None, student_dense=None, t_layerid=None, queue=None):
student_reps = student['hidden_states']
teacher_reps = teacher['hidden_states']
teacher_reps = [teacher_rep.detach() for teacher_rep in teacher_reps]
loss = self.token_contr... | This code computes a combined loss for knowledge distillation by aligning student and teacher model outputs through contrastive learning, attention matching, and reconstruction. It calculates original and alignment losses using token queues, then merges them with weighted sums to guide the student model's training. | def forward_generaldistill(self, student, teacher, attention_mask=None, input_ids=None, default_batchsize=None):
# original
ori_loss_contrastive = self.full_contrastive(student[0], teacher, attention_mask,
student_dense=self.student.dense_last,
... |
def read_num(n):
i = 0
A = [0,0]
result = ''
n = int(n)
if(n == 0):
result += 'Khong '
while(n>=1):
A[i] = n%1000
i = i + 1
n = int(n/1000)
for j in range (i-1, -1, -1):
result += num_to_vie_str(A[j])
if(A[j]!=0):
result += hauto[j... | This code generates a Vietnamese audio file announcing the current time by concatenating pre-recorded audio segments for each time component (hours, minutes, day, date, month, year) into a single WAV file, then plays it back. | def time(self):
os.remove("time.wav")
infiles = []
outfile = "time.wav"
data= []
time_string = datetime.datetime.now()
print('Time now: ', time_string)
time_formatted = time_string.strftime('%H %M %w %d %m %Y')
result = 'xtb '
array = time_formatt... |
def play(tile, screen, place = None):
"""
play(tile, screen, place)
this function takes a tile as a "tuple", display
and a place ("left" or "right"). then draws the tile on the screen.
"""
#Initialize the flag that determines the orientation of the tile
orientation = "horizontal"
... | The main task of the code is to handle a human player's turn in a tile-based game by playing the selected tile, updating the game state, checking for win conditions, and triggering the computer's turn if applicable. It manages sound effects, tile removal, display updates, and pass logic to determine game progression or... | def human_play(tile, exact_tile, screen, position, auto_player):
'''
human_play(tile, exact_tile, screen, position, auto_player)
this function is responsible for all the actions that should be
taken when the human clicks on a suitable tile.
'''
global __PASS__
playedtile_sound = pa... |
def human_has_suitable_tile():
"""
human_has_suitable_tile()
this function returns True if there is any suitable
tile to be played, in the HUMAN_TILES list.
"""
#If this is the first tile to be played, then the human
#has some suitable tiles. So, return True.
if len(PLAYED_TILES... | This function checks if a click occurs on the "PASS" button. If so, it verifies if the human player has playable tiles. If they do, it displays a warning message and sound. If not, it toggles the pass flag, disables the button, triggers the computer's turn, and checks for game-ending conditions like the computer having... | def check_if_clicked_on_pass(screen, auto_player, x, y):
'''
check_if_clicked_on_pass(screen, auto_player, x, y)
this function checks if the human clicked on the "PASS"
button, then it takes the necessary actions according to that.
'''
global __PASS__
#Checking whether the user cli... |
def parse_pointer(DIE):
return DIE.attributes["DW_AT_byte_size"].value
def parse_array(DIE):
# find array size through his sibling
# it is possible that an array is multidimensional
arraysize = []
for childrendie in DIE.iter_children():
if "DW_AT_upper_bound" not in childrendie.attributes:
... | The function recursively determines the type of a Debug Information Entry (DIE) by checking its attributes and tags. It returns type information such as "pointer", "array", or "struct" along with parsed details, or "unknown" if the type cannot be resolved. | def die_recursive(DIE):
if "DW_AT_type" in DIE.attributes:
typedie = DIE.dwarfinfo.get_DIE_from_refaddr(DIE.attributes["DW_AT_type"].value+DIE.cu.cu_offset)
else:
return "unknown","unknown"
# print(typedie)
if typedie.tag == "DW_TAG_pointer_type":
return "pointer", parse_pointer(... |
def get_hexrays_vars(ea, stack_size=None):
# print(str(ida_hexrays.decompile(ea)).strip())
hexrays_types[idc.get_func_name(ea)] = {}
try:
decompiled = ida_hexrays.decompile(ea)
except ida_hexrays.DecompilationFailure:
return
if not decompiled:
return
for var in ida_hexray... | This code iterates through functions in a binary, filters user-specified functions in the .text segment with valid stack frames, extracts metadata (stack size, parameters, entry/exit addresses), analyzes local variables, and processes basic blocks via flowcharts for reverse engineering tasks. | def function_iterator(functions):
for ea in idautils.Functions():
if not idc.get_func_name(ea) in functions:
continue
if idc.get_frame_id(ea) == None:
continue
if not idc.get_segm_name(ea) == ".text":
continue
# check if library function
if... |
def storesymbols(function):
try:
res = IFC.decompileFunction(function, 60, monitor)
high_func = res.getHighFunction()
lsm = high_func.getLocalSymbolMap()
symbols = lsm.getSymbols()
HighFunctionDBUtil.commitLocalsToDatabase(high_func, SourceType.ANALYSIS)
except AttributeE... | This function processes each function in the given list by extracting entry/exit points, calculating stack/parameter sizes, updating metadata with function properties, and analyzing local variables/block ownership. It checks RBP usage to adjust stack offsets, applies decompilation if enabled, and structures data for fu... | def function_iterator(fun_blocks, functions):
for function in functions:
if not function in fun_blocks:
continue
# function boundary
fun_entry = function.getEntryPoint()
fun_exit = fun_blocks[function][-1][-1]
# function stack size
# print(function)
... |
def parse_location(location):
if not isinstance(location, list):
return "unknown", "unknown"
if location[0] == 145:
return "local", leb128_decode(location[1:])
# todo: implement decoding algorithm in future
elif location[0] == 3:
return "static", "unknown"
else:
retu... | This function detects local variables and formal parameters in debugging information entries (DIEs) by parsing attributes like names and locations. It filters out ignored variables, adjusts offsets, identifies variable types (pointer/array/struct), and updates a global dictionary with offsets, names, and attributes. Fo... | def detect_locals(function, DIES):
for DIE in DIES:
if DIE.tag == "DW_TAG_variable" or DIE.tag == "DW_TAG_formal_parameter":
# if "DW_AT_location" in DIE.attributes:
# print(describe_attr_value(DIE.attributes["DW_AT_location"], DIE, DIE.cu.cu_offset))
if not "DW_AT_na... |
def get_functions():
# functions = set()
ignore_funs = {"__xstat", "__lxstat", "printf", ".printf", "malloc", "calloc", "realloc", "free", \
"_init" , "puts", "__errno_location", "register_tm_clones", "__libc_csu_init", "_start", \
"_dl_relocate_static_pie", "deregister_tm_clones", "__libc_csu_fini", "_... | The main task of the code is to analyze a binary using IDA's API by retrieving functions, extracting globally defined data symbols, and iterating through functions for processing. It automates tasks like identifying functions, gathering symbol data, and handling user-defined/called functions, likely for reverse enginee... | def main():
# ida automatically "find's" main
# api endpoint is available to get basic blocks
# get functions
# get all user defined/called functions
functions = get_functions()
# get globally defined objects
get_data_symbols(functions)
# iterate through functions
function_iterator(f... |
def get_basicblocks():
# for static blocks
blockiterator = BasicBlockModel(currentProgram).getCodeBlocks(monitor)
fun_blocks = {}
def add_block(function, min_address, max_address):
if function not in fun_blocks:
fun_blocks[function] = []
fun_blocks[function].append([min_add... | The code performs binary analysis by identifying the main function, extracting static basic blocks, retrieving user-defined/called functions, gathering global data symbols, and iterating through functions for further processing. | def main():
# add main function symbol in binary (if not present)
# if not find_main():
# exit()
# find static basic blocks
fun_blocks = get_basicblocks()
# get all user defined/called functions
functions = get_functions()
# get globally defined objects
get_data_symbols(functions... |
def die_recursive(DIE):
if "DW_AT_type" in DIE.attributes:
typedie = DIE.dwarfinfo.get_DIE_from_refaddr(DIE.attributes["DW_AT_type"].value+DIE.cu.cu_offset)
else:
return "unknown","unknown"
# print(typedie)
if typedie.tag == "DW_TAG_pointer_type":
return "pointer", parse_pointer(... | This function parses DWARF debug information to detect global variables, structures, and functions. It categorizes global variables by type (pointers/arrays), records structure definitions with nested elements, and initializes function metadata. Results are stored in dictionaries for further analysis, excluding ignored... | def detect_globals(CU):
# collect all dies for type detection
for DIE in CU.iter_DIEs():
# check if the variable is global
if DIE.tag == "DW_TAG_variable" and "DW_AT_name" in DIE.attributes:
if DIE.get_parent().tag == "DW_TAG_compile_unit":
name = DIE.attributes["DW_A... |
def U1(message, issue):
# log over listener of ?? all images in context (sum) or only specific image
u1 = 0
for i in issue:
u1 += np.log(L1(message, i))
return u1
def U2(message, issue):
# entropy over literal speaker
entropy = - sum([L1(message, i) * np.exp(L1(message, i)) for i in issu... | The code calculates a weighted utility score by combining two utility functions (u1, u2) with coefficients (alpha, beta), then subtracts a cost term (c). The result is an exponential expression representing a decision-making or optimization metric, balancing utility gains against costs. | def S1(message, image, issue):
u1 = U1(message, issue)
u2 = U2(message, issue)
c = cost(image, message)
return np.exp(alpha * ((1 - beta) * u1 + beta * u2)) - c |
def backup(self, current, res):
current.N += 1
current.W += res
current.Q = current.W / current.N
def expand(self, child):
root = self.root
possibleMoves = b.getAllMoves(root.val)
parsedBoard = parseBoard(root.val)
(nprobs, nv) = self.net(parsedBoard)
for ... | This code implements a selection phase in a Monte Carlo Tree Search (MCTS) algorithm. It selects the most promising child node using a heuristic combining exploration (sqrt(current.N)/(1+child.N)) and exploitation (child.Q). It then attempts a move, handles expansion if the node is a leaf, and propagates results upward... | def select(self, current):
X = []
for child in current.children:
X.append(self.cpunct * child.P * np.sqrt(current.N) / (1 + child.N) + child.Q)
index = X.index(max(X))
child = current.children[index]
(pfrom, pto) = child.val
res = self.root.val.move(pfrom... |
def expand(self, child):
root = self.root
possibleMoves = b.getAllMoves(root.val)
parsedBoard = parseBoard(root.val)
(nprobs, nv) = self.net(parsedBoard)
for move in possibleMoves:
subNode = Node(move)
child.addSubNode(subNode)
probs = parseProbsFr... | This function performs Monte Carlo Tree Search (MCTS) to determine the optimal move in a game. It executes 1200 cycles of selecting nodes, expanding with a neural network, and updating values. Afterward, it calculates move probabilities using a temperature parameter (tau) and selects the best move via random sampling f... | def searchNPlay(self, count=1200, tau = 1):
# The MCTS does three steps in a cycle:
# 1: select from the child nodes until a leaf node is got.
# 2: use the neural network for expanding the node,
# 3: update the values for each node on the search route after the expansion.
... |
def is_valid_code(self, code):
"""
:param code: a string stock code
:return: Boolean
"""
if code:
stock_codes = self.get_stock_codes()
if code.upper() in stock_codes.keys():
return True
else:
return False
def bui... | The main task of the code is to retrieve and parse stock quote data from a server using a given stock code. It validates the code, constructs a URL, sends an HTTP request, extracts JSON data from an HTML response, cleans it, and returns the result as a dictionary or None. Exceptions like HTTP/URL errors are raised, and... | def get_quote(self, code, as_json=False):
"""
gets the quote for a given stock code
:param code:
:return: dict or None
:raises: HTTPError, URLError
"""
code = code.upper()
if self.is_valid_code(code):
url = self.build_url_for_quote(code)
... |
def is_valid_index(self, code):
"""
returns: True | Flase , based on whether code is valid
"""
index_list = self.get_index_list()
return True if code.upper() in index_list else False
def clean_server_response(self, resp_dict):
"""cleans the server reponse by replacing:
... | The function fetches index quote data from a server, validates the input code, processes the JSON response, and returns the matching quote as a dictionary or JSON based on the 'as_json' parameter, or None if no match is found. | def get_index_quote(self, code, as_json=False):
"""
params:
code : string index code
as_json: True|False
returns:
a dict | json quote for the given index
"""
url = self.index_url
if self.is_valid_index(code):
req = Request(u... |
def drop(drop_pos, arr):
"""Drop element at drop_pos along axis 1.
Args:
drop_pos (np.array): 1d array of length nobs
arr (np.array): 2d array of shape (nobs, m)
Returns:
res (np.array): 2d array of shape (nobs, m - 1)
"""
length, width = arr.shape
res = np... | This function calculates multinomial probit choice probabilities using the GHK algorithm. It transforms utility values, constructs covariance matrices for each choice, computes Cholesky decompositions, and evaluates the multivariate normal CDF to return probabilities based on observed choices and given covariances. | def mprobit_choice_probabilities(u_prime, cov, choice, num_points=None, seed=1995):
"""Calculate multinomial probit choice probabilities.
The problem is first expressed as an evaluation of a multivariate normal
distribution function. Then this cdf is evaluated using the GHK algorithm.
Args:
... |
def tokenizeLine(line):
words = re.split(punctuationRegex,line) # split on punctuation
result = []
skip = 0
for i in range(0,len(words)):
word = words[i].lower()
word = word.replace("'","")
if skip > 0:
skip -= 1
else:
# handles connecting mr. or... | The main task of the code is to process a text file by tokenizing each line, removing stopwords, applying stemming to each token, and collecting all stemmed words into a list for further analysis or processing. | def parseFile(fileName):
result = []
with open (fileName) as file:
lines = file.readlines()
for line in lines:
# Step 1) Tokenize
tokenizedList = tokenizeLine(line)
# Step 2) Remove Stopwords
removedLine = removeStopwords(tokenizedList)
... |
def make_r_java(project):
# os.remove(os.path.join(get_dir_src_package(project), "R.java"))
subprocess.check_call(
[
get_dir_aapt(project), "package", "-f", "-m",
"-J", get_dir_src(project),
"-M", get_dir_android_manifest(project),
"-S", get_dir_res(project),
"-I", get_dir_android_jar(project)
]
... | The code defines a `build` function that compiles an Android project into a signed APK. It sequentially generates `R.java`, compiles Java code into `.class` files, converts them to Dalvik bytecode (`classes.dex`), packages the APK, aligns it for optimization, and signs it for distribution. The process ensures the proje... | def build(project):
# builds a project (makes final apk)
# make r.java
print("Making R.java...")
make_r_java(project)
# compile .java files into .class files
print("Compiling Java code...")
make_classes(project)
# compile .class files into classes.dex
print("Compiling into Dalvik code...")
make_dex(projec... |
def get_median_mols(starting_smile, target_smile, num_tries, num_random_samples, collect_bidirectional, num_top_iter, apply_filter=False):
smiles_paths_dir1, smiles_paths_dir2 = get_compr_paths(starting_smile, target_smile, num_tries, num_random_samples, collect_bidirectional)
# Find the median molec... | The code generates crossover molecules from two input SMILES strings by iteratively creating and filtering candidate molecules. It applies substructure preservation checks, custom filters, and neural network evaluations to identify valid crossover products that meet criteria, returning those passing all checks for furt... | def crossover(smi_1, smi_2):
num_tries = 3
num_random_samples = 3
collect_bidirectional = True # Doubles the number of paths: source->target & target->source
apply_filter = False
num_top_iter = 1000 # Number of molecules that are selected after each iterat... |
def sanitize_smiles(smi):
'''Return a canonical smile representation of smi
Parameters:
smi (string) : smile string to be canonicalized
Returns:
mol (rdkit.Chem.rdchem.Mol) : RdKit mol object (None if invalid smile string smi)
smi_canon (string) : Can... | The code generates mutated SMILES variants from a given molecule by randomizing SMILES orderings, converting to SELFIES, applying mutations, and filtering invalid or duplicate structures. It validates results via sanitization, external filters, and a neural network (eval_smi), returning only SMILES that pass all checks... | def get_mutated_smi(smi):
num_random_samples = 40 # TODO
num_mutation_ls = [1, 2, 3, 4, 5]
mol, smi_START, did_convert = sanitize_smiles(smi)
if mol == None:
raise Exception('Invalid starting structure encountered')
randomized_smile_orderings = [randomize_smiles(mol) for _ in ... |
def gini(rows):
"""Calculate the Gini Impurity for a list of rows.
"""
counts = class_counts(rows)
impurity = 1
for lbl in counts:
prob_of_lbl = counts[lbl] / float(len(rows))
impurity -= prob_of_lbl**2
return impurity
def split(rows, decision):
true_rows, false_rows = [], []... | The function finds the optimal feature-value split in a dataset to maximize information gain, using Gini impurity to evaluate splits. It iterates through features, partitions data, skips invalid splits, calculates gain, and updates the best split if gain improves. Returns maximum gain and corresponding decision. | def find_best_split(rows, features):
"""Find the best question to ask by iterating over every feature / value
and calculating the information gain."""
best_gain = 0 # keep track of the best information gain
best_decision = None # keep train of the feature / value that produced it
current_uncertain... |
def labels(pred):
flag = False
labels = [-1, 0, 1]
for e in pred:
for label in labels:
if int(e) == int(label):
labels.remove(e)
return labels
def get_weights(f, x, z, x_len, z_len, width):
"""
Gets the weights of the perturbed samples, input is the whole pert... | The main task of this code is to apply the LIME (Local Interpretable Model-agnostic Explanations) algorithm to explain the predictions of a pre-trained classifier model named 'Maria' on a dataset of sentences. It generates perturbed versions of input sentences, trains a logistic regression model on these perturbations ... | def main_pos():
begin = time.time()
model = 'Maria'
# isWSP = False
batch_size = 200 # we have to implement a batch size to get the predictions of the perturbed instances; 200
num_samples = 5000 # has to be divisible by batch size; 5000
# need these to run logit on set of perturbed sentences t... |
def labels(pred):
flag = False
labels = [-1, 0, 1]
for e in pred:
for label in labels:
if int(e) == int(label):
labels.remove(e)
return labels
def get_weights(f, x, z, x_len, z_len, width):
"""
Gets the weights of the perturbed samples, input is the whole pert... | The main task of the code is to apply **LIME (Local Interpretable Model-agnostic Explanations)** for explaining predictions of a sentiment analysis model (Maria) on a balanced dataset. It generates perturbations for each instance, filters them to ensure balanced sentiment classes (negative, neutral, positive), trains a... | def main_pos_balanced():
begin = time.time()
model = 'Maria'
# isWSP = False
batch_size = 200 # we have to implement a batch size to get the predictions of the perturbed instances; 200
num_samples = 5000 # has to be divisible by batch size; 5000; FIRST SET OF NUM SAMPLES
# need these to run lo... |
def find_best_split(rows, features):
"""Find the best question to ask by iterating over every feature / value
and calculating the information gain."""
best_gain = 0 # keep track of the best information gain
best_decision = None # keep train of the feature / value that produced it
current_uncertain... | The function builds a decision tree recursively by partitioning data rows based on information gain from selected features. It stops when no further gain is possible or maximum depth (5) is reached, returning a Leaf node. Otherwise, it splits data into true/false branches, recursively building subtrees, and returns a D... | def build_tree(rows, features, depth):
"""Builds the tree.
Rules of recursion: 1) Believe that it works. 2) Start by checking
for the base case (no further information gain). 3) Prepare for
giant stack traces.
"""
# Try partitioing the dataset on each of the unique attribute,
# calculate th... |
def write_byte(file: BinaryIO, data):
assert len(data) == 1
return write_bytes(file, data)
def write_uint64(file: BinaryIO, value: int):
"""
UINT64 means real UINT64 encoded with the following scheme:
| Size of encoding sequence depends from first byte:
| First_Byte Extra_Bytes Value
... | This code writes structured binary data to a file, including file count, empty stream/file flags, padding for alignment, names, timestamps, and attributes. It handles conditional property writes based on data presence and ensures 4-byte alignment with padding. | def write(self, file: BinaryIO):
assert self.files is not None
write_byte(file, PROPERTY.FILES_INFO)
numfiles = len(self.files)
write_uint64(file, numfiles)
emptystreams = [] # List[bool]
for f in self.files:
emptystreams.append(f["emptystream"])
if s... |
def read_uint64(file: BinaryIO) -> int:
"""read UINT64, definition show in write_uint64()"""
b = ord(file.read(1))
if b == 255:
return read_real_uint64(file)[0]
blen = [
(0b01111111, 0),
(0b10111111, 1),
(0b11011111, 2),
(0b11101111, 3),
(0b11110111, 4),
... | This function reads folder information from a 7z archive by verifying the folder ID, parsing the number of folders, handling external data streams via seeking, and retrieving folder data. It raises an error if the folder ID is invalid, processes folders based on the external flag, and calls _retrieve_coders_info for ad... | def _read(self, file: BinaryIO):
pid = file.read(1)
if pid != PROPERTY.FOLDER:
raise Bad7zFile("folder id expected but %s found" % repr(pid)) # pragma: no-cover
self.numfolders = read_uint64(file)
self.folders = []
external = read_byte(file)
if external == 0x... |
def make_board(self, size):
def pos(x, y):
return (y * size) + x
board = np.zeros(size * size, dtype = int)
for i in range(1, size-1):
board[pos(i, 0 )] = self.B #top
board[pos(i, size-1)] = self.B #bot
board[pos(0 , i)] = self.W #lef... | The code initializes a game board with configurable options, setting default parameters like board size, player turn, and game mode. It populates instance variables for board state, game status (running/won/draw), and precomputes position lists for win checks. The `set_win()` method is called to detect initial win cond... | def __init__(self, options=None):
defaults = {
'size': 8,
'turn': self.B,
'single': False,
'board': self.make_board(8) # np.array
}
options = options or defaults
self.size = options['size']
self.bsize = self.size * self.size
... |
def load_ref_model(model_file=None):
"""Loads the Chemnet model. If called without arguments it will use the
model in the package. In case you want to use a different one provide the path
Args:
model_file: Path to model. (default=None)
"""
if model_file is None:
chemnet_model_filen... | The code computes the Frechet Distance (FCD) between two sets of molecular property predictions generated by a model for given SMILES strings. It calculates mean vectors and covariance matrices of predictions for each SMILES, then applies the FCD formula to quantify distributional similarity, often used to assess model... | def get_fcd(smiles1, smiles2, model=None):
if model is None:
model = load_ref_model()
act1 = get_predictions(model, smiles1)
act2 = get_predictions(model, smiles2)
mu1 = np.mean(act1, axis=0)
sigma1 = np.cov(act1.T)
mu2 = np.mean(act2, axis=0)
sigma2 = np.cov(act2.T)
fcd_scor... |
def _check_submission_folder():
check_files(required_files(sys.argv[1]))
def _check_student_submissions():
task_path = os.path.join("**", "1_task")
students = sorted(
[os.path.dirname(f) for f in glob.glob(task_path, recursive=True)])
for student in students:
file_prefix = os.path.join(... | The main task of the code is to handle command-line arguments for checking student submissions. Depending on the input parameters, it either checks a specific submission folder, processes all students' submissions, or validates a zip file. The code exits with appropriate actions or error messages based on the argument ... | def main():
try:
if len(sys.argv) == 2 and sys.argv[1] != ALL_STUDENTS_FLAG:
_check_submission_folder()
exit(0)
elif len(sys.argv) == 3 and sys.argv[1] == ALL_STUDENTS_FLAG:
_check_student_submissions()
exit(0)
elif len(sys.argv) == 4 and sys.a... |
def upload_page():
st.title("Upload CSV File")
st.session_state['uploaded_file'] = st.file_uploader("Upload your CSV file here", type="csv")
if st.session_state['uploaded_file'] is not None:
print("File uploaded")
process_file()
def table_page():
st.title("Ratings Table")
if st.sessi... | The main task of the code is to handle navigation in a Streamlit app by displaying a sidebar menu with three options (Upload, Table, Flashcard). It stores the selected page in session state and renders the corresponding page function based on user input, enabling dynamic interface switching between different functional... | def main():
st.sidebar.title("Navigation")
page = st.sidebar.radio("Go to", (UPLOAD_PAGE_NAME, TABLE_PAGE_NAME, FLASHCARD_PAGE_NAME))
st.session_state['page'] = page
if st.session_state['page'] == UPLOAD_PAGE_NAME:
upload_page()
elif st.session_state['page'] == TABLE_PAGE_NAME:
table_page()
elif st... |
def prompt(self):
"""Prompt user for name and add score to scores file"""
# Sleep before prompt
time.sleep(self.PAUSE_TIME)
self.user_name = self.input("Enter your name:")
# Record score only if username of at least one char was entered
if (self.user_name and len(self.u... | The code updates the game state by prompting for a username upon game over, checking valid moves, displaying the board, ending the game, updating the score, and managing a money counter that increments and resets when reaching 80, updating a message with "$" symbols accordingly. | def update(self):
"""Updates to make in draw function"""
# Prompt for username when game is over
if self.do_prompt:
self.prompt()
self.do_prompt = False
# Check for valid moves and display the board
self.check_valid_moves()
self.board.display()
... |
def read_input_size(input_data):
lines = input_data.split('\n')
node_count = int(lines[0])
return node_count
def solve_with_2opt(input_data):
# Writes the inputData to a temporay file
tmp_file_name = 'tmp.data'
tmp_file = open(tmp_file_name, 'w')
tmp_file.write(input_data)
tmp_file.close... | The code determines the appropriate solver based on input size: using solve_with_2opt for large inputs (>2000) and solve_with_or_tools for smaller ones, then returns the computed solution. | def solve_it(input_data):
# switch solver based on the input size
solution = 'None'
if read_input_size(input_data) > 2000:
solution = solve_with_2opt(input_data)
else:
solution = solve_with_or_tools(input_data)
return solution |
def _check_events(self):
'''Respond to keypresses and mouse events'''
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event) ... | The main task of the code is to start and maintain the game loop, handling keyboard/mouse events, updating the rocket's position, managing bullets, and continuously rendering the game screen using Pygame. The loop runs indefinitely, ensuring real-time interaction and visualization of game elements. | def run_game(self):
'''Start the main loop for the game'''
while True:
#Watch for the keyboard and mouse events.
self._check_events()
self.rocket.update()
self._update_bullets()
self._update_screen()
pygame.display.flip() |
def generate_report_file(self, oimdict):
"""Generator function that generates the report files to send in email.
This is where we exclude sending emails for those probes we've reported
on in the last week.
:param dict oimdict: Dict of probes registered in OIM
Yields if there ar... | The `run_report` method orchestrates generating probe reports via `generate_report_file`, sends each report using `send_report`, logs exceptions if any, confirms report transmission, and executes cleanup. It centralizes report handling, ensuring error resilience and post-processing. | def run_report(self, oimdict):
"""The higher level method that controls the generation and sending
of the probe report using other methods in this class."""
rep_files = self.generate_report_file(oimdict)
try:
for _ in rep_files:
self.send_report()
exc... |
def log_conversation(self, text):
"""Log the conversation to a text file."""
print(f"Logging conversation: {text}")
with open("./conversations/conversation_log.txt", "a") as f:
f.write(self.name + ": " + text + "\n")
def _speech(self, text, voice_index=0):
"""Generate speech... | This code initializes a conversation between two agents by sending an initial greeting, logging messages, and iteratively generating responses. It attempts up to three times to receive a response from the other agent, logs each exchange, and alternates prompts until a response is generated or attempts exhaust, ensuring... | def initialize_conversation(self, other_agent):
"""Initialize a conversation with another agent."""
initial_prompt = os.getenv(
"INITIAL_PROMPT",
f"Hello {other_agent.name}, my name is {self.name}, how are you? ",
)
print("Initializing conversation...")
# ... |
def detect_tables(self, image):
return self.table_detection.table_detection(image)
def crop_table(self, image, box, padding=50):
box[0] -= padding
box[1] -= padding
box[2] += padding
box[3] += padding
cropped_image = image.crop(box)
return cropped_image
def recog... | This code extracts tables from a PDF by converting pages to images, detecting tables, cropping them, recognizing content, converting to structured data, adjusting coordinates, extracting cell text, and compiling results into DataFrames with optional header recognition. | def extract_tables(self, first_row_header=True):
tables = []
for page_num, image in self.pdf_doc.convert_to_image():
detect_tables = self.detect_tables(image)
for _, table_box in detect_tables.items():
cropped_image = self.crop_table(image, list(table_box))
... |
def CheckBan(step):
reason = "email" if step == "email" else "phone"
if driver.current_url == "https://tinder.com/app/banned" or "Your Account Has Been Banned" in driver.find_element_by_tag_name('body').text:
print(f" > Account got banned because of bad {reason}.")
custom_exit()
def waitForItem(... | The main task of the code is to automate a registration process on Tinder by filling out profile details (email, name, birthdate, gender, photo), handling CAPTCHA challenges using an external solver, and saving the profile. It uses Selenium to interact with web elements, includes error checks for banned accounts, and n... | def completeRegistration(driver):
time.sleep(1)
CheckBan("phone")
driver.save_screenshot("567.png")
emailInput = waitForItem(driver, By.XPATH, "/html/body/div[2]/div/div/div[1]/div[2]/input", timeout=15)
if emailInput:
emailInput.send_keys(globals['AccountInfo'][Columns.TINDER_EMAIL])
el... |
def clickTinderButton(driver):
try:
driver.execute_script("document.querySelector(\"button[aria-label='Log in with phone number']\").click()")
except Exception as e:
print(" > Can't find Log in button.")
print(str(e))
custom_exit()
def getNumber(driver):
phoneNum, actSrc, cou... | The code automates opening Tinder in a browser, switching to a new tab, navigating to the website, waiting for user interaction, and executing registration steps via helper functions. It initializes the process by opening Tinder, handling button clicks, retrieving a phone number, and completing registration, likely for... | def openTinder(driver):
driver.execute_script("window.open('about:blank', 'tinderTab');")
driver.switch_to.window("tinderTab")
driver.get("https://tinder.com?lang=en-GB")
time.sleep(6)
clickTinderButton(driver)
getNumber(driver)
completeRegistration(driver) |
def fixFolders():
cwd = globals['WorkingDir']
folder = cwd + "accounts"
fold_path = os.path.normpath(folder)
if not os.path.exists(fold_path):
os.makedirs(fold_path)
def setAccountId(args):
global globals
try:
accId = int(args[1])
except:
custom_exit()
globals['Acco... | The code automates Tinder interactions by processing Excel data, adjusting coordinates, downloading images, and using a browser driver to open Tinder, refresh the page, capture a screenshot, and exit. It sets up account-specific tasks, handles image downloads, and executes a timed workflow to complete a predefined auto... | def main(args):
global display, driver
fixFolders()
setAccountId(args)
readExcel()
adjustCoords()
downloadMegaImages()
fillImages(globals['AccountId'])
#display = createDisplay()
driver = createDriver()
openTinder(driver)
time.sleep(180)
driver.refresh()
time.sleep(7)... |
def _no_program(self):
return {'no_program': True, 'eobd': False}
def _get_resource_with_id(self, resource_id):
# Param check.
if resource_id == None:
logger.error('_get_resource_with_id(); param error, resource_id is None.')
return None
# First try our r... | This function identifies the next scheduled program after a given date and time. It checks the broadcast schedule, returns "no program" if none are scheduled, or returns the program's details with start/end times and an 'end of broadcast day' flag. It handles missing resources by logging errors and returning None. | def _next_scheduled_program_for_datetime(self, date):
# The 'beginning of broadcast day'.
bobd_date = datetime.datetime.combine(date, self.bobd_time)
# Loop over today's program schedule. The first program scheduled to be broadcast
# after 'date' will be the next one. No... |
def _get_filler_program(self, max_duration, date):
# BOGUS, call self._validate_day_schedule(date)?
if self.list_schedule == None:
return None
filler_program = None
list_ids = list(self._get_list_ids_for_date(date))
while filler_program == None:
... | The main task of the code is to generate a filler program with adjusted start/end times for a specified date and duration. It retrieves a filler program, validates its existence, adjusts timing parameters, sets metadata flags (e.g., 'filler' and 'eobd'), and returns the structured program or None if no valid filler is ... | def filler_to_show(self, date, dead_time):
# Will return either a program (success) or None if error or no filler of specified length.
program = self._get_filler_program(dead_time, date)
if program == None:
return None
if self.is_no_program(program):
program = sel... |
def load_channel_manifest(path):
try:
with open(path, 'r') as manifest_data:
return json.load(manifest_data)
except IOError:
logger.error('load_channel_manifest(); IOError for file: ' + path)
return None
def run_uhf_schedule():
global screen_x
global screen_y
glob... | The main task of the code is to initialize screen settings, load a channel manifest file, set a black background, and execute either a UHF schedule or list based on the manifest's version. It handles debug mode parameters, validates the manifest, and terminates with error logging if the manifest is invalid or unsupport... | def main():
global screen_x
global screen_y
global screen_wide
global screen_tall
global channel_dir
global channel_manifest
logger.info('main(); starting.')
# Screen geometry.
if DEBUG:
screen_x = DEBUG_SCREEN_X
screen_y = DEBUG_SCREEN_Y
screen_wide... |
def _validate_day_schedule(self, date):
success = True
fetch_schedule = False
if self.current_day == None:
self.current_day = date
fetch_schedule = True
elif date.date() != self.current_day.date():
self.current_day = date
fetch_schedule = T... | This function determines the next scheduled program to air on or after a given date. It validates the input date, iterates through schedules (advancing daily if needed), retrieves the next program, and enriches it with series metadata like title and artwork path if available. | def next_scheduled_program_to_show(self, date):
success = self._validate_day_schedule(date)
if success == False:
return None
# Find the *next* program scheduled to be broadcast.
adjustedDate = date
program = None
eobd = False
while (program ==... |
def _validate_day_schedule(self, date):
success = True
fetch_schedule = False
if self.current_day == None:
self.current_day = date
fetch_schedule = True
elif date.date() != self.current_day.date():
self.current_day = date
fetch_schedule = T... | This function determines the current or next scheduled program for a given date, handling edge cases like end-of-broadcast-day (eobd) and filler content. It validates schedules, searches for active/next programs, adjusts dates if necessary, and returns program details with metadata like start/end times, series info, an... | def program_to_show(self, date):
success = self._validate_day_schedule(date)
if success == False:
return None
# First, determine if there is already a program scheduled to be broadcast now.
program = self._scheduled_program_for_datetime(date)
if program == No... |
def angle180_180(a):
"""
Converts an input angle in degrees and returns its representation in
[-180, 180] degrees (from the same origin)
"""
return (a + 180) % 360 - 180
def get_pans_from_coords(coords):
"""
Returns a set of camera pans that face from current point to next,
using [-360, ... | This function generates ESP file data blocks by normalizing coordinates, altitude, and tilt values. It scales longitude, latitude, and pan values to empirical ranges, then creates rotation (X/Y) and position (longitude/latitude/altitude) parameters for animation or rendering. Input coordinates are adjusted to relative ... | def get_esp_file_data(coords, alt_m, tilt_deg):
"""
Generate the esp file data blocks based on filtered coords and camera args
"""
lon_vals = coords[:, 0]
lat_vals = coords[:, 1]
lon_min = lon_vals.min()
lat_min = lat_vals.min()
# scaling found empirically
s_lat = 90 - angle180_180(... |
def coords_from_kml(contents, n=None):
"""
Returns lonlats contained in a standard KML file's <coordinates> tag
"""
marker1 = "<coordinates>"
marker2 = "</coordinates>"
pos1 = contents.index(marker1)
pos2 = contents.index(marker2)
coords_str = contents[pos1 + len(marker1) : pos2]
co... | The code processes a KML file to generate an ESP file by extracting coordinates, filtering stationary points, smoothing data, and formatting it into a template. It reads input KML, applies noise filtering (if enabled), smooths coordinates (if enabled), calculates ESP parameters (position/rotation), populates a JSON tem... | def main(input_kml, out_file, n_steps=None, alt_m=1000, tilt_deg=30, moving_avg=3, noise_dist_m=50):
"""
Uses helper functions to:
* Read input
* Filter coords
* Generate esp file contents
* Write to file
"""
with open(input_kml, 'r') as infile:
contents = infile... |
def loadData():
train = np.loadtxt("train_cancer.csv", delimiter=",")
test = np.loadtxt("test_cancer_pub.csv", delimiter=",")
X_train = train[:, 0:-1]
y_train = train[:, -1]
X_test = test
return X_train, y_train[:, np.newaxis], X_test
def trainLogistic(X,y, max_iters=max_iters, step_size=step_size):
... | The code trains logistic regression models with and without a bias term on the training data, compares their performance via training loss plots, conducts k-fold cross-validation for evaluation, and generates test predictions using the bias-augmented model, saving results to a CSV file. | def main():
# Load the training data
logging.info("Loading data")
X_train, y_train, X_test = loadData()
logging.info("\n---------------------------------------------------------------------------\n")
# Fit a logistic regression model on train and plot its losses
logging.info("Training logistic regression... |
def get_nearest_neighbors(example_set, query, k):
difference = example_set - query # broadcasting
distance = np.linalg.norm(difference, ord=2, axis=1) # calculate the distance
k_nearest = np.argsort(distance) # use argsort to make sure that it runs efficiently
idx_of_nearest = k_nearest[:k]
return i... | The code implements a k-Nearest Neighbors (k-NN) classifier, testing its correctness with sanity checks and accuracy metrics. It performs 4-fold cross-validation to evaluate different k values, identifies the optimal k, and uses it to predict test data for Kaggle submission. The task involves hyperparameter tuning, val... | def main():
#############################################################
# These first bits are just to help you develop your code
# and have expected ouputs given. All asserts should pass.
############################################################
# I made up some random 3-dimensional data and... |
def process_question(
self, topic, question, difficulty_level, current_topic_results
):
"""Process a single question, prompting the user and updating counters."""
choice_info = next(
item for item in topic["choices"] if item["question_id"] == question["id"]
)
prin... | The function processes questions of a specific difficulty level within a topic by filtering, shuffling, and iterating through them. It handles each question, checks thresholds for early termination, and updates the state after processing. | def process_difficulty_level(self, topic, difficulty_level, current_topic_results):
"""Process questions for a specific difficulty level within a topic."""
questions = [
q for q in topic["questions"] if q["difficulty"] == difficulty_level
]
shuffle(questions) # Shuffle quest... |
def load_data():
if "data" not in st.session_state:
load_state()
def render_sidebar():
with st.sidebar:
st.subheader("Progress")
render_topic_tree()
def render_questions():
# Modification: Only display questions if quiz is not complete
if not st.session_state.get("quiz_complete",... | The main task of the code is to manage a Streamlit quiz application with three tabs: "Questions" (displaying quiz content and navigation), "Results" (showing outcomes), and "Debugger" (for troubleshooting). It initializes session state for quiz completion tracking, loads data, renders a sidebar, and conditionally displ... | def main():
if "quiz_complete" not in st.session_state:
st.session_state.quiz_complete = False
load_data()
render_sidebar()
tab_1, tab_2, tab_3 = st.tabs(["Questions", "Results", "Debugger"])
with tab_1:
render_questions()
if not st.session_state.quiz_complete:
r... |
def get_org_raw():
try:
srcdata = client.organizations.get_organizations()
except APIException as e:
print(f'Error {e.response_code} with error message {e.context.response.raw_body}')
return ""
newlist = sorted(srcdata, key=itemgetter('name'))
outdata = [["#", "Organization ID"... | The function `exec_show_parse` processes CLI commands to retrieve and format data based on the current context scope (e.g., root, organization, network, device). It checks the command and scope, calls appropriate data-fetching functions (e.g., `get_org_raw`, `get_net_raw`), formats the output, and returns it alongside ... | def exec_show_parse(data, clitext, contextchain):
# sample data:
# [{'command': 'organizations', 'help': 'show list of organizations'}, '', [], 'exec_show_parse', 'root']
curscope = data["context"]
curcmd = data["command"]["command"]
list_line = clitext.split(" ")[1:]
if curscope == "root" and c... |
def predict(self, image):
self._forward_propagation(image)
return np.argmax(self._output_layer)
def _cost(self, y, y_hat):
return (1/2) * np.sum(pow(y - y_hat, 2))
def _back_propagation(self, label, learning_rate):
self._delta_output_layer = self._cost_derivative(label, self._output_laye... | This code trains a neural network model over multiple epochs by iterating through training data, computing predictions, calculating error and accuracy, and performing backpropagation to update model weights. It tracks average error and accuracy per epoch, printing progress with learning rate applied during weight adjus... | def fit(self, epochs, learning_rate, training_images, training_labels):
for epoch in range(epochs):
error = 0
prediction_count = 0
for training_image, training_label in zip(training_images, training_labels):
y_hat = self.predict(training_image)
... |
def createframes():
global Dark_Hour_Frames
for i in range (TotalFrame+1):
x = i
if i <10:
Dark_Hour_Frames.append(PhotoImage(file = "Pictures/Dark_Hour_Pink/frame_00"+str(x)+"_delay-0.05s.png"))
elif 100>i >=10:
Dark_Hour_Frames.append(PhotoImage(file = "Picture... | This Python code creates a music player GUI with album art and song info display, and controls an LED strip based on time. It toggles between normal and "Dark Hour" modes, updating visuals and background colors, while handling music playback and LED animations using Tkinter, pygame, and Adafruit NeoPixel libraries. | def P3FEMC(NoMusic1, NoLight1, Retro1, LL):
global window, AlbumArt, IsDarkHourGif, MusicLabel, Background_Color, SongPlayer, fps, DHT, Retro
strip = 0
NoMusic = NoMusic1
NoLight = NoLight1
Retro = Retro1
if NoMusic == False:
window= Tk()
createframes()
window.geome... |
def RiseJukeBox(F,G,x):
TrackList = open(F,"r")
ArtList = open(G,"r")
Track = songPick(TrackList,ArtList)
sn= R.randint(0,len(Track)-1)
Song = Track[sn]
playSong(Song.getSong())
TrackList.close()
titileSong = Song.getSong()[x:-4]
titileSong = titileSong.replace("_"," ")
return So... | This function initializes a music player GUI (if enabled) and controls an LED strip (if enabled). It loads song/art data, updates the display, and applies dynamic effects like midnight transitions and weather-based behavior. The core tasks are: 1) GUI setup with album art and song labels, 2) LED strip configuration and... | def P4(NoMusic1, NoLight1, Retro1, LL):
global NoMusic, NoLight, Retro, window, AlbumArt, IsDarkHour, MusicLabel, Background_Color, SongPlayer, fps,MCGIF
NoMusic = NoMusic1
NoLight = NoLight1
Retro = Retro1
strip =0
if NoMusic == False:
window= Tk()
window.geometry('600x660'... |
def get_stream_name_from_arn(stream_arn):
return re.search(r"\/(.+)$", stream_arn).group(1)
def get_region_from_arn(stream_arn):
return re.search(r":(\w+-\w+-\w+):", stream_arn).group(1)
def process_records(records):
processed_records = []
for record in records:
decoded_data = base64.b64decode(... | The code processes incoming Kinesis Firehose records by analyzing and filtering them. It identifies records needing reingestion, sends them back via Firehose, and prepares remaining records for output. The handler logs processing details, handles reingestion attempts, and returns transformed records while maintaining d... | def lambda_handler(event, _context):
print(f"Received {len(event['records'])} records")
stream_arn = event["deliveryStreamArn"]
stream_name = get_stream_name_from_arn(stream_arn)
region = get_region_from_arn(stream_arn)
processed_records = process_records(event["records"])
records_to_reingest,... |
def bringToFront(window):
"""Brings the given frame to the front when selected"""
try:
window.tkraise()
except:
print("ERROR RAISING WINDOW")
def createSearchFrame(searchFrame,mainFrame):
"""Search frame - contains all widgets required to perform a search"""
#labels
title = Label... | The code creates a GUI application for a library management system named "liboro," using Tkinter. It defines a main window with multiple frames (SEARCH, RETURN, CHECKOUT, WEEDING DATA) and buttons to switch between them. Each frame is initialized with error handling, and the main menu starts with the mainFrame, display... | def createMenu():
"""Main menu window - stores and calls all other frames."""
#root window definition and attributes
mainWindow = Tk()
mainWindow.title("liboro")
mainWindow.geometry("800x300")
mainWindow.configure(bg="#E6E6FA")
#Frame definitions
mainFrame = Frame(mainWindow,width=800, h... |
def weight_set():
w0 = np.random.randn(5, 4)
w1 = np.random.randn(5, 5)
w2 = np.random.randn(3, 5)
return w0, w1, w2
def bias_set():
b1 = np.zeros((5,1))
b2 = np.zeros((5,1))
b3 = np.zeros((3,1))
return b1, b2, b3
def all_z_activations(w0, w1, w2, b1, b2, b3, x):
z1 = z(w0, x, b1)
... | The main task of the code is to train a neural network using gradient descent over a 50-second interval, updating weights and biases iteratively to minimize cost on training data, while tracking costs and evaluating average test performance across 30 trials. | def main_train():
costs = [] #keep track of costs
tic = time.time()
weights = weight_set()
biases = bias_set()
z_and_activations = all_z_activations(weights[0], weights[1], weights[2], biases[0], biases[1], biases[2], X_train)
toc = time.time()
while toc-tic <= 50:
z_and_activations ... |
def weight_set():
w0 = np.random.randn(5, 4)
w1 = np.random.randn(5, 5)
w2 = np.random.randn(3, 5)
return w0, w1, w2
def bias_set():
b1 = np.zeros((5,1))
b2 = np.zeros((5,1))
b3 = np.zeros((3,1))
return b1, b2, b3
def all_z_activations(w0, w1, w2, b1, b2, b3, x):
z1 = z(w0, x, b1)
... | The code trains a neural network using gradient descent to minimize a cost function by iteratively updating weights and biases over a time limit. It calculates activations, errors, and derivatives, then adjusts parameters until the cost is minimized or time expires. Finally, it evaluates the model's accuracy on 30 test... | def main():
tic = time.time()
weights = weight_set()
biases = bias_set()
z_and_activations = all_z_activations(weights[0], weights[1], weights[2], biases[0], biases[1], biases[2], X)
toc = time.time()
while cost(Y, z_and_activations[5]) > 0 and toc-tic <= 50:
z_and_activations = all_z_ac... |
def train_add_alpha(train_ngram_is, val_ngram_is, alpha_range, n, report=True):
opt_perp, opt_alpha = float('inf'), float('inf')
opt_probs = []
# get counts of each unique ngram in the training corpus
counts = np.zeros((num_chars,)*n)
ngram_indices, ngram_counts = np.unique(
train_ngram_is,... | The code trains an interpolated n-gram language model by optimizing smoothing parameters (alphas) using the first validation set and interpolation weights (lambdas) using the second validation set. It iteratively combines add-alpha model probabilities with learned lambdas, evaluates perplexity on training and validatio... | def train_interp(train_ngram_configs, val1_ngram_configs, val2_ngram_is, alpha_range, n):
# get the optimal alphas using the first validation set (val1)
opt_alphas, add_alpha_probs = [], []
for i, train_ngram_is, val1_ngram_is in zip(range(n), train_ngram_configs, val1_ngram_configs):
probs, alpha =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.