dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def writeToLog(input):
"""
write to logfile
"""
if logfileOn:
f = open(logfileName, "a")
f.write(input)
f.close()
def getBlockHeight():
"""
Get blockchain height at this time
"""
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy... | The main task of the code is to unsilence all nodes by sending a custom "silentmode false" RPC command to each node in parallel using threads. It logs failures and sends alerts if any node fails to unsilence, while ensuring all nodes are processed concurrently. The function handles errors and records outcomes for each ... | def unsilenceAllNodes():
"""
send the slientmode false command to all nodes (NOTE: custom rpc command, not part of standard zcashd, is included in the zcashd of Pranav's observatory nodes)
"""
try:
thread_list = []
results = {} #... |
def stopNode(name):
"""
Send rpc stop command to a node
"""
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(allNodes[int(name)], username=user, key_filename=filepath)
stdin, stdout, stderr = client.exec_comman... | The main task of the code is to stop all nodes and verify their disconnection by repeatedly sending sync commands, ensuring they report "false" (disconnected). It attempts up to three times, logging success or failure. If nodes remain connected after retries, it spam-logs alerts to signal a critical error, risking the ... | def stopAllNodes():
"""
Turn off all nodes and make sure by sending the sync command and ensuring they all report false
"""
try:
tries = 0
while True:
success = True
for n in threadNames:
stopNode(n)
isSynced(n)
for n in... |
def updatePeerListAuto(name):
"""
Update the peerlist without having received the output of a getpeerinfo command - Gets the output of one and then makes the call to parse it
"""
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
clien... | The main task of the code is to identify and remove duplicate peers that exceed a specified maximum occurrence threshold in the network. It disconnects and bans excess duplicates via SSH commands, ensuring nodes only maintain allowed peer connections while logging errors and enforcing network stability constraints. | def removeDuplicates():
"""
Remove any copies of peers that have appeared more than the specified number of times within the networrk. E.g. peer A appears as a peer of 6 nodes but we specified 5 max, so we remove peer A from 1 node
"""
try:
previousPeers = []
for name, info in syncedNode... |
def removeAllPeers(node):
"""
send commands to buffer to remove all node peers - prints & runs only when called by the CLI. Warning - slow and messy
"""
print(f">Pushing commands to remove all peers from node {node}, {len(nodePeers[node])} found")
for ip in nodePeers[node]:
commandBuffer.app... | This function processes node commands by parsing flags (e.g., -t for wait time, -p/-p2 for peer IPs), executing commands via a channel, handling special commands like 'removeallpeerscode' and 'checksync', updating peer lists, logging responses, and error handling. It returns node responses or updates system state based... | def processCommand(chan, cmd, name, addr):
"""
Process command, return response from node
"""
waittime = 1 ### determine if a custom waiting duration was set
if " -t " in cmd:
pieces = cmd.split(" ")
timePos = pieces.inde... |
def startupNode(name):
"""
Send rpc startup command to a node
"""
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(allNodes[int(name)], username=user, key_filename=filepath)
stdin, stdout, stderr = client.exec_... | The main task of the code is to initiate all nodes by broadcasting a startup command three times, iterating through each node in `threadNames` on each attempt. It handles potential errors by logging a warning if the startup fails, then re-raising the exception after a delay, though real-time success confirmation is not... | def startAllNodes():
"""
Turn all nodes on by broadcasting the startup command 3 times, no way to know in real-time if it succeeds since even after startup the sync takes ~5 minutes
"""
try:
tries = 0
while tries < 3:
for n in threadNames:
startupNode(n)
... |
def createConfigCycle():
"""
Add all peers of speedup network to each other in the config file
"""
for n in threadNames:
for i in range(len(allNodes)):
if int(n) != i:
addConfigPeer(n, allNodes[i])
def createCycle():
"""
add all peers of speedup network to eac... | The main task of the code is to ensure all nodes are synchronized, establish peer connections between them, and periodically remove duplicate peers from the network. It continuously checks synchronization status, creates a peer cycle once all nodes are synced, and runs a cleanup process every 30 seconds. The function a... | def managePeers():
"""
Check to see if all nodes are synced then add them to each other as peers. Then, loop through on inverval and remove excess duplicates from the network
"""
createdCycle = False
failCounter = 0
while True:
try:
if createdCycle == False:
a... |
def writeToLog(input):
"""
write to logfile
"""
if logfileOn:
f = open(logfileName, "a")
f.write(input)
f.close()
def startAllNodes():
"""
Turn all nodes on by broadcasting the startup command 3 times, no way to know in real-time if it succeeds since even after startup th... | The main task of the code is to conduct experiments by cycling nodes on/off at intervals defined by the -e flag to measure network propagation times. It monitors blockchain heights, logs timestamps between blocks, and toggles node silence modes to study data transmission dynamics with/without speedup nodes, repeating t... | def manageRun():
"""
Turn on all nodes and let them run for the time specified in the -e flag. Afterwards, turn off nodes for that period of time. Repeat. Used for gathering data about network propagation with/without speedup nodes on
"""
writeToLog(f"Experiment time set to {experimentTime} blocks\n")
... |
def sendALL(input):
"""
send command to all nodes
"""
for n in threadNames:
commandBuffer.append(n + " " + input)
def listNodes():
"""
List all active nodes
"""
print(">All Nodes: ")
for n in threadNames:
print(f"\t Node '{n}' ({allNodes[int(n)]})")
def flushBuffer():... | This function processes user input by normalizing it, checking for exit commands ("q"/"quit") to shut down nodes, executing predefined commands (e.g., listing nodes, flushing buffers), or parsing unknown inputs. It returns False only when exiting; otherwise, it returns True after handling valid commands. | def handleInput(input):
"""
Handle User Input - returns true unless the user wants to exit
"""
input = input.strip()
input = input.lower()
if input == "q" or input == "quit":
print(">User thread closing, shutting down active nodes.")
sendALL("exit")
return False
elif ... |
def isSynced(name):
"""
check if this node is synced yet, and how many peers it has
"""
try:
syncedNodes[name] = (False, 0)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(allNodes[int(name)], username=user, key_fi... | This code manages a remote Zcash node by establishing an SSH connection, monitoring synchronization status, executing commands in a loop, and handling connection cleanup. It runs in a thread, processes commands until "exit" is received, adjusts write frequency, clears banned IPs, and terminates the SSH session. | def work(addr, name):
"""
Main function of a thread - wait for commands and execute after creating channel
"""
client = paramiko.SSHClient() ### Paramiko connection magic
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print(">Node '" + ... |
def check_if_prime(self):
for i in self.key:
for j in range(2, self.key[i] // 2):
if (self.key[i] % j) == 0:
print(f"{i} = {self.key[i]}. It is not a prime number.")
return False
return True
def str_to_int(self):
lst = list()
... | The code implements an RSA encryption function. It converts a message to an integer, verifies prime validity and key generation, then encrypts each integer character using modular exponentiation (i^e mod n) with the public key parameters e and n, returning the encrypted result as a list of integers. | def encrypt(self):
# check if p and q are primes
if not self.check_if_prime():
return
# convert message to int
new_message = self.str_to_int()
# if key is not good
if not self.key_generation():
return "Error."
# init a list to store enc... |
def genTiffName(param='dem', iCode='bi'):
iCode = iCode.lower()
if param == 'dem_250':
param = 'dem'
pCODE = genParamCode(param)
TiffName = PARAM_TIFF_DIR + param + \
'/' + iCode + '_' + pCODE + '_250m.tif'
return TiffName
def get_Coordinates(GeoTiff_name):
# Read raster
... | The function `get_island_grid` generates a DataFrame containing island coordinates (LON, LAT) and parameter data (from `params`) for a given `iCode`. It reshapes 2D arrays into 1D, constructs a pandas DataFrame, retrieves a mask and shape from `getDataArray`, and returns the DataFrame, flattened mask, and shape. | def get_island_grid(iCode, params):
TiffName = genTiffName(iCode=iCode)
LON, LAT = get_Coordinates(TiffName)
LON = LON.reshape(-1)
LAT = LAT.reshape(-1)
myDict = {'LON': LON, 'LAT': LAT}
for param in params:
myDict[param] = getDataArray(iCode=iCode, param=param).reshape(-1)
isla... |
def genTiffName(param='dem', iCode='bi'):
iCode = iCode.lower()
if param == 'dem_250':
param = 'dem'
pCODE = genParamCode(param)
TiffName = PARAM_TIFF_DIR + param + \
'/' + iCode + '_' + pCODE + '_250m.tif'
return TiffName
def get_Coordinates(GeoTiff_name):
# Read raster
... | The main task of the code is to generate a DataFrame containing island coordinates (LON, LAT) and parameter data arrays for a given iCode, along with a mask and shape. It reshapes all data into 1D arrays, constructs a pandas DataFrame from the combined data, and returns the DataFrame, mask, and shape for further analys... | def get_island_grid(iCode, params):
TiffName = genTiffName(iCode=iCode)
LON, LAT = get_Coordinates(TiffName)
LON = LON.reshape(-1)
LAT = LAT.reshape(-1)
myDict = {'LON': LON, 'LAT': LAT}
for param in params:
myDict[param] = getDataArray(iCode=iCode, param=param).reshape(-1)
isla... |
def makeModel(predictand,params,model,threshold=2.5):
"""
Description: Updated version of makeModel.
Development notes:
--Predictand replaces df for clarity. Only available and relevant stations of general predictand should be passed from this variable
--Params replaces parameter list. Param... | The code performs leave-one-out cross-validation for a predictive model, evaluating its performance in predicting a target variable (`varname`) across stations on specified islands (`iCode`). It iteratively trains the model on all but one station, predicts the excluded station's value, and computes metrics (MAE, RMSE, ... | def cross_validation(predictor, response, iCode, varname, MODEL, metadata, threshold=2.5,inversion=2150):
if iCode == 'MN':
isl_list = ['MA','KO','MO','LA']
else:
isl_list = [iCode]
#Only select test values from target island
meta_stn = metadata.set_index('SKN')
targ_skns = []
pr... |
def monthly_mean(temp_data,varname,threshold=15):
#Get monthly mean of temperature for specified island
valid_counts = temp_data.count(axis=1)
stns_threshold = valid_counts[valid_counts>=threshold].index.values
valid_mean = temp_data.loc[stns_threshold].mean(axis=1).rename(varname)
temp_meta_master... | The main task of the code is to generate a monthly mean temperature grid and its standard error for a specified region and month using statistical modeling. It processes station data, extracts predictors, fits a model with thresholds, and outputs geospatial TIFF maps of predicted temperatures and uncertainty, returning... | def minmax_main(varname,iCode,date_str,params=['dem_250'],inversion=2150):
"""
Full monthly mean temperature grid for 1 month of data
"""
threshold = 2.5
station_dir = RAW_DATA_DIR
pred_dir = PRED_DIR
output_dir = MAP_OUTPUT_DIR + varname + '/' + iCode.upper() + '/'
output_se_dir = MAP_O... |
def get_island_grid(iCode, params):
TiffName = genTiffName(iCode=iCode)
LON, LAT = get_Coordinates(TiffName)
LON = LON.reshape(-1)
LAT = LAT.reshape(-1)
myDict = {'LON': LON, 'LAT': LAT}
for param in params:
myDict[param] = getDataArray(iCode=iCode, param=param).reshape(-1)
isla... | The function `generate_county_map` generates geospatial maps (TIFF/PNG) for a specified environmental variable (e.g., temperature) at a given date and region (island). It processes input data, fits a statistical model using predictors, applies quality control (outlier removal), and produces interpolated maps with stand... | def generate_county_map(iCode, varname, params, date_str, output_dir=None):
if output_dir == None:
map_dir = MAP_OUTPUT_DIR + varname + '/' + iCode.upper() + '/'
se_dir = SE_OUTPUT_DIR + varname + '_se/' + iCode.upper() + '/'
png_dir = PNG_OUTPUT_DIR + iCode.upper() + '/'
else:
... |
def check_username(username):
if len(username) < 4 or len(username) > 16:
return False
for char in username:
if not char.isalnum() and char != '_':
return False
return True
def try_again():
print('Would you like to try again?')
retry = input('Retry? (y/n): ').strip().lowe... | The main task of the code is to create a new user account by validating the username (length, allowed characters, uniqueness) and password (length) through a retry loop, prompting the user to input credentials until valid ones are provided, then storing the account and returning the username; if all attempts fail, it r... | def create_account():
retry = True
while retry:
clear()
print('Your username must be between 4 and 16 characters long and can only contain letters, numbers, and underscores.')
username = input('Username: ').strip()
if not check_username(username):
print('Invalid usern... |
def login():
retry = True
while retry:
clear()
username = input('Username: ').strip()
if not username_exists(username):
print("This username doesn't exist")
retry = try_again()
else:
password = getpass('Password: ')
if not match_pas... | The main task of the code is to handle user authentication in a Python RPG application by presenting login or account creation options. It clears the screen, displays a welcome message, and prompts the user to choose between logging in, creating an account, or exiting. If the user selects "Login," it calls the `login()... | def account_main():
clear()
print('Welcome to PYTHON_RPG!')
print('Would you like to login or create an account?')
print('1. Login')
print('2. Create an account')
print('3. Exit')
choice = input('Choice: ').strip()
if choice == '1':
username = login()
if not username:
... |
def calc_point(dist, theta):
rad = np.pi / 180 * theta
return np.sin(rad) * dist, np.cos(rad) * dist
def free(self, pos):
if not self.inbounds(pos):
return False
# make sure not occupied in radius
gpos = convert(self.center, pos, self.nearest)
ngpos, sgpos, egpos, wgp... | This function places objects at calculated positions if the location is free. It iterates through input objects, computes their coordinates using distance and angle, skips occupied spots, and places objects at available positions. | def place_objs(self, objs):
# (dist, angle)
for dist, theta in objs:
pos = calc_point(dist, theta)
# ignore this object
if not self.free(pos):
continue
self.place(pos, obj=True) |
def beam_range(self, endpoint):
delta = endpoint / self.resolution
return np.arange(0, endpoint + 1e-9, delta)
def free(self, pos):
if not self.inbounds(pos):
return False
# make sure not occupied in radius
gpos = convert(self.center, pos, self.nearest)
ngpos,... | The code traces a beam from a given position, placing white pixels until an obstacle is encountered. If no gradient is provided, it traces vertically; otherwise, it traces diagonally based on the gradient value, adjusting the y-coordinate proportionally with x. | def trace(self, pos, grad):
# no gradient
if grad is None:
for y in self.beam_range(pos[1]):
fpos = (0, y)
if not self.free(fpos):
break
self.place(fpos, rgb=(255, 255, 255))
# has gradient
else:
... |
def map_inbounds(self, ppos, local_map):
beam = local_map.beam
# north south east and west edges
npos, spos, epos, wpos = (ppos[0], ppos[1] + beam), (ppos[0], ppos[1] - beam),\
(ppos[0] + beam, ppos[1]), (ppos[0] - beam, ppos[1])
return self.inbounds(npos) and self.inbounds(s... | The main task of the code is to place a local map onto a larger map by rotating and positioning its free and object pixels. It first validates the placement position, then processes free spaces to avoid holes, rotates and translates each pixel's position, places them on the main map, refills gaps, and finally assigns t... | def place_map(self, ppos, local_map, rotation, precision=2):
if not self.map_inbounds(ppos, local_map):
raise ValueError(f"can't place map at {ppos}")
# get pixels, rotate them, then place them
obj_pixels, free_pixels = local_map.pixels()
# place free spaces first
for... |
def calc_point(dist, theta):
rad = np.pi / 180 * theta
return np.sin(rad) * dist, np.cos(rad) * dist
def calc_grad(start, end):
if start[0] == end[0] == 0:
return None
return (end[1] - start[1]) / (end[0] - start[0])
def trace(self, pos, grad):
# no gradient
if grad is None:
... | This code performs ray tracing by casting rays within a field of view (FOV). It iterates over angular steps (dtheta), calculates each ray's endpoint position using `calc_point`, determines the gradient (direction) from the origin to the position, and traces the ray via `self.trace` with the computed position and gradie... | def raytrace(self, dtheta=0.1):
origin = (0, 0) # origin of ray casting
# locate objs in fov
for theta in np.arange(-self.fov // 2, self.fov // 2 + 1e-9, step=dtheta):
pos = calc_point(self.beam, theta)
grad = calc_grad(origin, pos)
self.trace(pos, gr... |
def get_json(name, coerce=identity):
try:
return coerce(request.json[name])
except (ValueError, KeyError):
return err('invalid-json', f"`{name}` is a required parameter")
def req(*args, **kwargs):
try:
return requests.request(*args, **kwargs)
except (ConnectionError, ReadTimeout,... | The function `link_preview` generates a preview for a given URL. It checks if the URL points to an image by examining the `Content-Type` header. If true, it returns an image-only preview with empty title/description. Otherwise, it delegates to `_get_link_preview` to fetch structured metadata, defaulting to an empty dic... | def link_preview():
url = get_json('url')
res = req('head', url)
if (res.headers.get('Content-Type', '') if res else '').startswith('image/'):
return {'title': "", 'description': "", 'image': url, 'url': url}
return _get_link_preview(url) or {} |
def Clear(self):
self.__WriteCommand([CLEAR_WINDOW, 0x00, 0x00, 0x5F, 0x3F])
return
def DrawChar(self, x, y, ch, c):
for i in range(0, 5, 1):
line = ascii[ord(ch) & 0x7F][i]
for j in range(0, 8, 1):
if line & 0x1:
self.DrawPixel(x + i, ... | The main task of the code is to display a grid of ASCII characters (from ASCII 32 to 113) in a 6x16 layout, with each character rendered at specific coordinates and colored using a dynamic palette. The `DrawChar` method places each character at calculated positions, while `Color656` generates varying hues based on loop... | def CharTest(self):
self.Clear()
time.sleep(0.01)
i = 32
for j in range(0, 6, 1):
for k in range(0, 16, 1):
self.DrawChar(k * 6, j * 8 + 4, chr(i), Color656(k * 16, 128, j * 36))
i = i + 1
time.sleep(10)
return |
def Clear(self):
self.__WriteCommand([CLEAR_WINDOW, 0x00, 0x00, 0x5F, 0x3F])
return
def DrawString(self, x, y, str, c):
for i in str:
if x > 0x5F:
break
self.DrawChar(x, y, i, c)
x = x + 6
return
def EnableLockMode(self, enable):
... | This code performs a lock mode test by clearing the display, displaying "Lock Test" text, enabling lock mode, showing a "Lock Test Failed" message in red, waiting 10 seconds, then disabling lock mode. The task verifies lock functionality with visual feedback. | def LockTest(self):
self.Clear()
time.sleep(0.01)
self.DrawString(21, 16, "Lock Test", COLOR_WHITE)
self.EnableLockMode(True)
self.DrawString(0, 16, "Lock Test Failed", COLOR_RED)
time.sleep(10)
self.EnableLockMode(False)
return |
def Clear(self):
self.__WriteCommand([CLEAR_WINDOW, 0x00, 0x00, 0x5F, 0x3F])
return
def DrawStringBg(self, x, y, str, c, bg):
self.DrawLine(x, y, x, y + 9, bg)
x = x + 1
for i in str:
if x > 0x5F:
break
self.DrawCharBg(x, y, i, c, bg)
... | The main task of the code is to demonstrate basic shape drawing functionality by clearing the display, rendering a title text, and drawing a red circle, green triangle, and blue rectangle at specified coordinates, then pausing for 10 seconds to display the result. | def ShapeTest(self):
self.Clear()
time.sleep(0.01)
self.DrawStringBg(18, 4, "Shape Test", COLOR_BLACK, COLOR_WHITE)
self.DrawCircle(16, 32, 10, COLOR_RED)
self.DrawTriangle(38, 42, 58, 42, 48, 22, COLOR_GREEN)
self.DrawRect(70, 22, 90, 42, COLOR_BLUE)
time.sleep(1... |
def check_row(self, row: int):
if {1, 2, 3, 4, 5, 6, 7, 8, 9} != set(self.rows[row]):
raise InvalidRow()
def check_column(self, col: int) -> None:
if {1, 2, 3, 4, 5, 6, 7, 8, 9} != set(self.get_column(col)):
raise InvalidColumn()
def check_quadrent(self, q: int):
if {1, 2... | This function validates a Sudoku board by checking all rows, columns, and 3x3 quadrants for rule violations. It collects error messages and returns a tuple indicating validity status and errors. If invalid and `raise_on_invalid` is True, it raises an exception with the error list. | def check_board(self, raise_on_invalid: bool = True) -> tuple[bool, list[str]]:
errors = []
for row in range(9):
try:
self.check_row(row)
except InvalidRow as e:
errors.append(str(e))
for col in range(9):
try:
se... |
def valid_in_column(self, y: int) -> set[int]:
return nums - set(self._rm_none(self.get_column(y)))
def valid_in_row(self, x: int) -> set[int]:
row_values = set(self._rm_none(self.rows[x]))
return set(nums - row_values)
def which_quadrent(self, x: int, y: int) -> int:
def section(val: in... | The function determines valid numbers for a Sudoku cell by intersecting valid values from its row, column, and quadrant, returning the common set of permissible digits for the cell at position (x, y). | def valid_in_cell(self, x, y) -> set[int]:
c = self.valid_in_column(y)
r = self.valid_in_row(x)
quad = self.which_quadrent(x, y)
q = self.valid_in_quadrent(self.which_quadrent(x, y))
return c.intersection(r.intersection(q)) |
def read_pickles2(pickle_dir, dims, x, y, z, fill_fraction, spacing, expected_labels, num_images, labels_to_change, random_shuffler):
'''
Reads the outputs from "extract_patches.py" and reassembles them as a shuffled list of patches
will also change lables from the original to new value if required
our... | The code trains a deep learning model (e.g., DenseNet121) for medical image classification using 2D/3D patches. It processes training, validation, and test datasets with data augmentation, splits data into training/validation sets, and performs model training with CrossEntropyLoss and Adam optimizer. The model is evalu... | def train( train_directory,
test_directory,
output_dir,
expected_labels,
num_images_train,
fraction_images_val,
num_images_test,
kernel_x,
kernel_y,
kernel_z,
fill_fraction_train,
fill_... |
def read_pickles2(pickle_dir, dims, x, y, z, fill_fraction, spacing, expected_labels, num_images, labels_to_change, random_shuffler):
'''
Reads the outputs from "extract_patches.py" and reassembles them as a shuffled list of patches
will also change lables from the original to new value if required
our... | The function `train_independent_val` trains a deep learning model (e.g., DenseNet) for medical image classification using training, validation, and test datasets. It preprocesses data, applies data augmentations, and trains the model with cross-entropy loss and Adam optimizer. Validation metrics (AUC, accuracy) are eva... | def train_independent_val(
train_directory,
val_directory,
test_directory,
output_dir,
# pickle_prefix_train,
# pickle_prefix_test,
expected_labels,
num_images_train,
num_images_val,
num_images_tes... |
def read_pickles2(pickle_dir, dims, x, y, z, fill_fraction, spacing, expected_labels, num_images, labels_to_change, random_shuffler):
'''
Reads the outputs from "extract_patches.py" and reassembles them as a shuffled list of patches
will also change lables from the original to new value if required
our... | The main task of the code is to perform testing/evaluation of a machine learning model on a given test dataset using specified parameters and configurations. It loads test data, applies transformations, sets up the model architecture, runs inference, computes evaluation metrics (e.g., AUC, accuracy), and saves results.... | def test_only( train_directory,
test_directory,
output_dir,
# pickle_prefix_train,
# pickle_prefix_test,
expected_labels,
num_images_train,
fraction_images_val,
num_images_test,
kernel_x,
kernel_y,... |
def read_pickles2(pickle_dir, dims, x, y, z, fill_fraction, spacing, expected_labels, num_images, labels_to_change, random_shuffler):
'''
Reads the outputs from "extract_patches.py" and reassembles them as a shuffled list of patches
will also change lables from the original to new value if required
our... | The code performs a test phase on a dataset using a pre-trained model, computes evaluation metrics (AUC, accuracy), and saves results. It loads test data, applies transformations, sets up the model, runs inference, and records metrics like AUC and confusion matrices. The training loop is commented out, focusing solely ... | def test_only_with_validate_change(
train_directory,
val_directory,
test_directory,
output_dir,
# pickle_prefix_train,
# pickle_prefix_test,
expected_labels,
num_images_train,
num_images_val,
num_i... |
def checkForDeath(self):
if self.player.lives < 1:
level = self.level
score = self.player.score
self.level = 1
self.player.score = 0
self.player.reset("player", {})
self.map = getGameMap("Level" + str(self.level))
self.player.li... | The main task of the code is to update the player's state in a game by handling movement (left/right), jumping mechanics, gravity, collision detection, and game state checks (death/win). It processes key inputs, updates the player's position, applies physics, and resets the player if they fall off the map, while managi... | def updatePlayer(self):
# Checking if the player is dead
self.checkForDeath()
# Checking if the player has won
self.checkforwin()
# If nothing is pressed set the players direction to idle
self.player.direction = [0, 0, 0, 1]
self.idleAnimation += 1
# Getti... |
def get_valid_moves_now(self) -> list:
"""
Return all valid moves for the current player.
"""
if self.is_white_move:
return list(self.get_valid_moves_white())
else:
return list(self.get_valid_moves_black())
def get_winner(self) -> int:
"""
... | Your returnThe code handles a player's move in a turn-based game (likely Reversi/Othello). It checks if the move is valid for the current player (white or black), updates the game board, flips opponent's pieces, switches turns, and returns captured positions. If invalid, it returns False; if no valid moves or a winner ... | def make_move(self, y: Any, x: Any) -> Any:
"""
Make move for the current color, and return the position of pieces captured
"""
# If the current player has no valid moves AND no one is a winner,
# pass the turn.
if self.get_valid_moves_now() == [] or self.get_winner() != ... |
def user_agent(self):
ua = open('user-agents.txt','r').read().splitlines()
return random.choice(ua)
def agent(self):
agents = {'User-Agent':self.user_agent()}
return agents
def auto_wp_install(self):
try:
st.info('List site harus dengan step 2, jika site sebelumnya udah di install maka akan tertulis succes... | The code defines an initialization method that sets up a user agent, configures an agent, and automates a WordPress installation process. The main task is to initialize an object with these three functionalities, likely for web scraping, system configuration, or CMS deployment. | def __init__(self):
self.user_agent()
self.agent()
self.auto_wp_install() |
def grabber_site(self):
st.info('Date terbaru adalah hari kemarin, jika page nya belum sampai pada input akan error')
tgl_input = st.date_input('Masukan Tanggal : ')
start_page = int(st.number_input('Mulai dari page : ',0))
end_page = int(st.number_input('Sampai page : ',0))
page_start=(start_p... | The code initializes an object by calling three methods: `grabber_site()` to set up a site grabber, `user_agent()` to configure a user agent, and `agent()` to initialize an agent. The main task is to prepare the object for data collection or interaction with a website, likely for scraping or API communication, by confi... | def __init__(self):
self.grabber_site()
self.user_agent()
self.agent() |
def grab_domain_cub(self):
st.info('Date terbaru adalah kemarin, tunggu prosesnya karena banyak domain per pagenya!')
input_tgl = st.date_input('Masukan Tanggal : ')
start_page = int(st.number_input('Mulai Page : ',0))
end_page = int(st.number_input('Sampai Page : ',0))
page=(start_page-1)
pages... | The code's main task is to initialize an object by executing three methods: grabbing domain-related data (grab_domain_cub), setting up a user agent (user_agent), and configuring an agent (agent). This likely prepares the object for tasks like web scraping or data collection by establishing domain context, browser ident... | def __init__(self):
self.grab_domain_cub()
self.user_agent()
self.agent() |
def _generate_sample(self) -> Dict:
_universe = {
'Stock': {
'Korea': ['Ticker_0', 'Ticker_1'],
'US': ['Ticker_2', 'Ticker_3'],
'Europe': ['Ticker_4', 'Ticker_5'],
'Japan': ['Ticker_6', 'Ticker_7'],
'China': ['Ticker_8',... | The main task of the code is to structure a hierarchical representation of the input `universe` data. It calculates the depth of the structure, extracts keys and values by layers, and organizes them into a dictionary (`_hierarchy`) with named layers (e.g., "L0", "L1"). This enables layered access to nested data, separa... | def _update(self, universe: Optional[Dict] = None):
self._universe = universe or self._generate_sample()
self._depth = self._get_depth(self._universe)
self._hierarchy_list = self._get_keys_by_layer(self._universe)
self._last_assets = self._get_bottom_values_by_layer(self._universe)
... |
def get_devices_list(file_name=INVENTORY_FILE):
with open(file_name) as f:
result = yaml.safe_load(f)
return result["devices"]
def configure_device(ip_address):
"""
Login and run list of commands from file on all devices on the site
Args:
ip_address (list): host ip address from lis... | The main task of the code is to configure network devices by iterating through a list of IP addresses, executing configuration commands on each device, saving the output, and measuring the total execution time. It retrieves device IPs, sends configuration commands via `configure_device`, stores results with `save_outpu... | def main():
start_time = time.time()
ip_list = get_devices_list()
for ip in ip_list:
result = configure_device(ip)
save_output(result["device_hostname"], result["commands_output"])
print(result["commands_output"])
print("Please check device logs for any errors")
print(... |
def load_full_codes(train_path, version='mimic3'):
"""
Inputs:
train_path: path to train dataset
version: which (MIMIC) dataset
Outputs:
code lookup, description lookup
"""
# get description lookup
desc_dict = load_code_descriptions(version=version)
... | This code initializes a data processor for medical datasets (e.g., MIMIC-III), loading and preprocessing structured ICD-9 codes, text descriptions, and labels. It constructs mappings between codes and indices, tokenizes descriptions with masking, truncates text, and prepares inputs for models. The core task is to struc... | def __init__(self, version, mode, truncate_length, tokenizer,
label_truncate_length=30, term_count=1):
self.version = version
self.mode = mode
self.tokenizer = tokenizer
if version == 'mimic2':
raise NotImplementedError
if version in ['mimic3', 'mimi... |
def parseth(s):
return "<tr>%s</tr>" % "".join(
["<th>%s</th>" % parsetext(th) for th in s.split("|") if th.strip() != ""]
)
def parserow(s):
if re.match("^(\\||\\s|\\-)*$", s) is not None:
return ""
return "<tr>%s</tr>" % "".join(
["<td>%s</td>" % parsetext(td) for td in s.split... | This code parses a multi-line string into an HTML table structure. It increments a global table counter, processes the header and footer with helper functions, and constructs an HTML figure with a table and caption, including a numbered link. The output combines parsed header, joined rows, and footer into a formatted H... | def parsetable(s):
global tablenum
tablenum += 1
rows = s.split("\n")
table = (
tablenum,
parseth(rows[0]),
"".join([parserow(row) for row in rows[1:-1]]),
tablenum,
tablenum,
parsetext(rows[-1]),
)
return (
'<figure id="table%d"><table>%s%... |
def parsetext(s):
return splitparse(
s.strip(), "`", lambda x: "<code>%s</code>" % html.escape(x), parsetext2
)
def parsepics(s):
global fignum
global metas
lines = [ss[4:].split(None, 1) for ss in s.split("\n")]
out = ""
for ss in lines:
fignum += 1
ss[1] = ss[1].spl... | The code parses markdown-like syntax into HTML, handling headers, blockquotes, images, equations, lists, tables, and buttons. It uses global variables to track header/equation counts and builds a nested table of contents. Each block type is converted with appropriate HTML tags, linking headers to the TOC and equations ... | def parseblock(s):
global hnum
global eqnum
global toc
if len(s.split()) == 0:
return ""
for h in range(6, 0, -1):
# header
if s[:h] == "#" * h:
if hnum[h - 1] == 0:
toc += "<ol>"
hnum[h - 1] += 1
for j in range(h, 6):
... |
def parseth(s):
return "%s\\\\ \\hline\n" % " & ".join(
["\\bf %s" % parsetext(th) for th in s.split("|") if th.strip() != ""]
)
def parserow(s):
if re.match("^(\\||\\s|\\-)*$", s) is not None:
return ""
return "%s\\\\ \\hline\n" % " & ".join(
["%s" % parsecell(td) for td in s.sp... | The code parses a text-based table into a LaTeX `tabu` table. It splits the input string into rows, extracts headers, processes data rows, generates column specifications, and formats the output with a caption and label. The function increments a global table counter and returns the structured LaTeX code for rendering ... | def parsetable(s):
global tablenum
tablenum += 1
rows = s.split("\n")
th = parseth(rows[0])
trows = "".join([parserow(row) for row in rows[1:-1]])
ccc = "c" * (len(rows[0]))
table = (ccc, th, trows, parsetext(rows[-1]), tablenum)
return (
"\\begin{table}[!ht]\n\\centering\n\\begi... |
def parsetext(s):
return splitparse(s.strip(), "`", lambda x: "\\texttt{%s}" % escape(x), parsetext2)
def parsepics(s):
global fignum
lines = [ss[4:].split(None, 1) for ss in s.split("\n")]
out = ""
for ss in lines:
fignum += 1
ss[1] = ss[1].split(": ", 1)
pic = ss[0]
... | The function `parseblock` converts markdown-like input into LaTeX formatting by detecting headers, blockquotes, images, equations, lists, tables, and buttons. It uses global variables to track section numbers and equations, applies appropriate LaTeX environments, and delegates text parsing to helper functions. The outp... | def parseblock(s):
global hnum
global eqnum
global toc
if len(s.split()) == 0:
return ""
for h in range(3, 0, -1):
# header
if s[:h] == "#" * h:
hnum[h - 1] += 1
for j in range(h, 6):
if hnum[j] > 0:
hnum[j] = 0
... |
def get_word(self):
if len(self.words) < 1:
raise ValueError("WORD LIST EMPTY!!!!")
return self.words[randrange(0, len(self.words))]
def get_input(self):
cond = False
while not cond:
guess, pattern = self.prompt()
cond = self.check_input(guess, pattern)
return guess, pattern
def cu... | The code simulates a word-guessing game with up to six attempts. It iteratively selects words, processes user guesses, checks for a correct match ("xxxxx"), and narrows down possible words using `cull_list`. If the word list reduces to one or a correct guess is made, it outputs "FINAL ANSWER" or "congratulations!". If ... | def run(self, print_d=False):
for _ in range(6):
word_choie = self.get_word()
if print_d:
print(f"word space:{len(self.words)}")
print(word_choie)
if len(self.words) == 1 and print_d:
print("FINAL ANSWER")
return
guess, pattern = self.get_input()
if patt... |
def seat_availability(self, station_frm, station_to, train_no, travel_date):
station_frm = self._get_station_code(station_frm)
station_to = self._get_station_code(station_to)
try:
csr = self._connectDB()
csr.execute('select total_coach, days from trains where train_no = {... | The main task of the code is to book a train ticket by checking seat availability, inserting ticket and seat booking records into a database, and returning the booking confirmation (PNR) and seat number. It validates seat availability, retrieves station codes, selects an optimal seat, and records the booking for all st... | def book_ticket(self, psg_name, stn_frm, stn_to, travel_date, train_no):
if self.seat_availability(stn_frm, stn_to, train_no, travel_date) < 0:
raise ValueError('No available seats in the train')
stn_frm = self._get_station_code(stn_frm)
stn_to = self._get_station_code(stn_to)
... |
def _connectDB(self):
self.db = mysql.connector.connect(
host = self.host,
user = self.user,
password = self.password,
database = self.database
)
return self.db.cursor(buffered = True)
def _closeDB(self):
self.db.close()
def _get_station_co... | The main task of the code is to retrieve and organize ticket details (e.g., passenger name, seat, train, travel date) using a PNR from a database. It fetches associated stations, sorts them based on the train's route, identifies the first and last stations, and returns a structured ticket dictionary with journey inform... | def check_pnr(self, pnr):
try:
csr = self._connectDB()
csr.execute("select * from ticket where pnr = {0}".format(pnr))
ticket = dict()
_, ticket['booked_by'], ticket['psg_name'] = csr.fetchone()
csr.execute("select stn_code from seat_booked where pnr =... |
def getlist(self, input_command, sv_dir=SV_PWD):
# Create a new client socket for connections with the server.
try:
cli_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
cli_socket.connect((HOST, PORT))
except socket.error as e:
print("Error: Connecti... | This code performs a one-way synchronization between a local directory (cli_dir) and a server directory (sv_dir), ensuring cli_dir always mirrors sv_dir. It recursively downloads missing files/directories from sv_dir to cli_dir, and updates local files if their server counterparts are newer or have different hashes. Th... | def sync(self, cli_dir=CLI_PWD, sv_dir=SV_PWD, verbose=True):
'''
NOTE: 1. This is one way sync between cli_dir (folder 1) and sv_dir (folder 2). This means clid_dir will always have same files and directories of sv_dir at any instance of time
2. For auto sync, we have to do one-way sync for bo... |
def get_ls_content(self, input_command, sv_dir=SV_PWD):
# Create a new client socket for connections with the server.
try:
cli_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
cli_socket.connect((HOST, PORT))
except socket.error as e:
print("Error: C... | This code runs a client CLI loop that processes user commands (like ls, lls, sync, index, hash, download) with timeout handling. It auto-syncs every 100s if no input is received, handles file operations, and manages command parsing with dynamic path handling. | def run(self):
while True:
os.chdir(CLI_PWD)
print('Client >> ', end=" ", flush=True)
try:
## do auto aync if user dont press "enter" within STDIN_TIMEOUT sec
input_command = func_timeout(STDIN_TIMEOUT, lambda: input())
input_co... |
def parse_cmds(self, raw_cmds):
return (raw_cmd.split(' ') for raw_cmd in raw_cmds.splitlines())
def noop(self):
self.cycle()
def addx(self, x):
self.cycle()
self.cycle()
self.register += x | This code processes a list of commands by iterating through each parsed command and executing corresponding methods. For 'noop' commands, it calls self.noop(). For 'addx' commands, it converts the second argument to an integer and calls self.addx(). The main task is to dispatch and execute command-specific operations b... | def run(self, cmds):
for cmd in self.parse_cmds(cmds):
match cmd[0]:
case 'noop':
self.noop()
case 'addx':
self.addx(int(cmd[1])) |
def load_data():
with open(args.input_data,'rb') as f:
conn_data = pickle.load(f)
conn_matrices = conn_data['FC']
labels = conn_data['labels']
graphs = build_graphs(conn_matrices,conn_matrices)
return graphs, pd.Series(labels)
def create_model(generator):
gc_model = GCNSupervisedGraphCla... | The code trains a Graph Convolutional Network (GCN) model on graph-structured data by splitting the dataset into training, validation, and test sets. It uses stratified sampling to maintain class distribution, trains the model with early stopping and checkpointing, and evaluates performance using metrics like accuracy,... | def run():
graphs, graph_labels = load_data()
# print(graphs[0].info())
# print(graphs[1].info())
# summary = pd.DataFrame(
# [(g.number_of_nodes(), g.number_of_edges()) for g in graphs],
# columns=["nodes", "edges"],
# )
# summary.describe().round(1)
graph_l... |
def define_var_constraints(self, entities):
"""
Define variable constraints, i.e., state the indices of reoccurring entities in a walk.
Parameters:
entities (list): entities in the temporal walk
Returns:
var_constraints (list): list of indices for reoccurring en... | The code creates a rule from a cyclic temporal random walk by processing its entities, relations, and timestamps. It constructs the rule's head relation, inverts and reverses body relations, defines variable constraints, and determines the temporal order of body timestamps. The rule is stored if novel, with confidence ... | def create_rule(self, walk):
"""
Create a rule given a CP temporal random walk.
Parameters:
walk (dict): cyclic temporal random walk
{"entities": list, "relations": list, "timestamps": list}
Returns:
rule (dict): created rule
"""... |
def read_register(self, register, length=1):
buf = [NRF24.R_REGISTER | (NRF24.REGISTER_MASK & register)]
buf += [NRF24.NOP] * max(1, length)
read = self.spidev.xfer2(buf)
if length == 1:
return read[1]
return read[1:]
def write_register(self, register, value):
... | This code configures an NRF24L01+ module to operate in receive mode by setting power-up and primary receiver flags in the CONFIG register, flushing TX/RX buffers, clearing IRQ flags, optionally setting Pipe 0's receive address, and enabling the CE pin to activate reception. | def rx_mode(self):
settings = self.read_register(NRF24.CONFIG)
settings |= NRF24.PWR_UP | NRF24.PRIM_RX
self.write_register(NRF24.CONFIG, settings)
self.flush_tx()
self.flush_rx()
self.clear_irq_flags()
if self.pipe0_reading_address:
self.write_reg... |
def set_CE_level(self, level, period=0):
if self.ce_pin is not None:
GPIO.output(self.ce_pin, level)
if period > 0:
time.sleep(period)
GPIO.output(self.ce_pin, 1 - level)
else:
raise ValueError("CE Pin is not set")
def flush_tx(self):... | This code configures an NRF24L01+ module to enter transmit mode by powering up the device, disabling receive mode (PRIM_RX), and enabling pipe 0 for data transmission. It clears buffers, resets interrupt flags, and updates configuration registers to ensure proper TX operation. | def tx_mode(self):
self.set_CE_level(0)
self.flush_tx()
self.flush_rx()
self.clear_irq_flags()
config = self.read_register(NRF24.CONFIG)
rx_addr = self.read_register(NRF24.EN_RXADDR)
config = (config | NRF24.PWR_UP) & ~NRF24.PRIM_RX # enable TX
rx_add... |
def write_payload(self, buf):
buf = self._convert_to_byte_list(buf)
if self.dynamic_payloads_enabled:
if len(buf) > NRF24.max_payload_size:
raise RuntimeError("Dynamic Payload size exceed Maximum size of Payload")
blank_len = 0
else:
if len(bu... | This code transmits data packets via a radio module, calculating air time and SPI upload durations, handling auto-acknowledgment, retries, and timeouts. It manages TX_DS and MAX_RT status flags, handles errors, and ensures proper CE pin control for transmission. | def write(self, buf, max_rt_handler=True):
length = self.write_payload(buf)
time_on_air = (8 * (1 + self.address_width + length + self.crc_length) + 9) / (self._data_rate_bits() * 1000.)
# ^ Time on-air = (8 bit * [preamble + address + payload + CRC] + 9 bit) / air_data_rate
time_uploa... |
def spi_init(self, spi_bus, spi_device):
# Initialize SPI Connection
self.spidev = spidev.SpiDev()
self.spidev.open(spi_bus, spi_device)
self.spidev.bits_per_word = 8
self.spidev.max_speed_hz = 10000000 # Max supported by NRF24L01+ -> 10 MHz
self.spidev.cshigh = Fal... | This code initializes an NRF24L01+ module by configuring SPI communication, setting up GPIO pins for CE (Chip Enable) and IRQ (Interrupt Request), applying default settings like retry parameters, power amplifier level, data rate, CRC length, disabling dynamic payloads, setting the RF channel, and clearing interrupt fla... | def begin(self, spi_bus, spi_device, ce_pin, irq_pin):
# Setup Configuration
self.spi_init(spi_bus, spi_device)
# Initialize GPIO PINOUT
self.ce_pin = ce_pin
self.irq_pin = irq_pin
if self.ce_pin is not None:
GPIO.setup(self.ce_pin, GPIO.OUT)
if sel... |
def read_register(self, register, length=1):
buf = [NRF24.R_REGISTER | (NRF24.REGISTER_MASK & register)]
buf += [NRF24.NOP] * max(1, length)
read = self.spidev.xfer2(buf)
if length == 1:
return read[1]
return read[1:]
def set_CRC_length(self, length):
settin... | This function enables or disables auto-acknowledgment for a specific data pipe on an NRF24L01+ module. It validates the pipe number (0-5), modifies the EN_AA register to set/clear the auto-ack bit, ensures CRC is enabled if needed, and updates internal state. If the pipe is invalid, it issues a warning. | def set_auto_ACK_pipe(self, pipe, enabled):
if 0 >= pipe or pipe < 6:
settings = self.read_register(NRF24.EN_AA)
if enabled:
if self.crc_length == 0:
self.set_CRC_length(NRF24.CRC_1)
settings |= 1 << pipe
self.auto_ack... |
def get_channel(self):
channel = self.read_register(NRF24.RF_CH)
if channel != self.channel:
warnings.warn("Incorrect channel in settings - overwritten to NRF channel")
self.channel = channel
return channel
def _data_rate_bits(self):
# Interpretation of Data Rat... | The code prints the current configuration and status of an NRF24L01+ module, including RF frequency, data rate, payload size, PA power, register values, addresses, and last error. It formats and displays settings like channel, CRC, and power levels, then iterates through registers and address registers for detailed dia... | def print_details(self):
print("Current Settings:")
print(" RF Channel Frequency: {} MHz".format(2400 + self.get_channel()))
print(" Data Rate: {} kbps".format(self._data_rate_bits()))
print(" Payload Size: {} bytes".format(self.get_payload_size()))
print(" CRC Length: {} bytes"... |
def startup():
# Create cropped and processed folders for images to be saved in
if not (glob.glob(sourceDir + 'Cropped/')): # if a Cropped/ folder exists don't make a new one
os.mkdir(sourceDir + 'Cropped/')
print('Cropped folder did not exist, creating.........')
if not (glob.glob(sourc... | The main task of the code is to process images by reading grayscale JPEGs from a directory, automatically cropping each image, applying Sobel edge detection, saving cropped and processed images, and exporting the mean and standard deviation of pixel values from processed images to a CSV file. | def main():
print('..........running main.......')
print('---------- running startup ---------')
startup() # checking existence of folders and correct naming
# read in each image and convert to grayscale
images = [cv2.imread(file,cv2.IMREAD_GRAYSCALE) for file in glob.glob(sourceDir+'*.jpg')]
... |
def get_current_season():
current_season = pd.read_csv('current_year.csv', header=None).values[0][0]
return(current_season)
def get_historical_rosters(season, week):
site_prefix = get_site_prefix(season)
players = load_player_data()
matchup_response = requests.get(site_prefix + 'matchups/' + st... | The function saves weekly rosters to a CSV file. If `current=True`, it merges historical rosters with current data, updates player statuses (e.g., bench → taxi), and adds season/week metadata. If `current=False`, it retrieves historical rosters directly. The output is filtered to specific columns, formatted with season... | def save_week_rosters(week, current=True, season=None):
if current:
season = get_current_season()
base_rosters = get_historical_rosters(season, week)
current_rosters = get_current_rosters()
rosters = base_rosters
rosters['season'] = season
rosters['week'] = week
... |
def source_magnitude(sample_index, fq, fs):
return np.sin(2 * np.pi * fq * sample_index / fs)
def unit_gain_orientation(covariance_matrix, lead_field_matrix):
A = lead_field_matrix.T @ np.linalg.pinv(covariance_matrix) @ lead_field_matrix
size = lead_field_matrix.shape[1]
B = np.eye(size)
return smallest_gene... | The code simulates EEG data with noise, computes covariance matrices, and reconstructs orientations using three methods (unit gain, array gain, unit noise gain). It compares reconstructed orientations to the true orientation, adjusts for direction, calculates angular differences, and returns results including orientati... | def eeg_reconstruction_experiment(true_orientation, full_lead_field, noise_level, fq, fs, nr_samples, regularization):
# initialize rng
rng = np.random.default_rng()
nr_sensors = full_lead_field.shape[0]
normed_lf = full_lead_field @ true_orientation
lf_norm = np.linalg.norm(normed_lf)
normed_lf /= lf... |
def source_magnitude(sample_index, fq, fs):
return np.sin(2 * np.pi * fq * sample_index / fs)
def unit_gain_orientation(covariance_matrix, lead_field_matrix):
A = lead_field_matrix.T @ np.linalg.pinv(covariance_matrix) @ lead_field_matrix
size = lead_field_matrix.shape[1]
B = np.eye(size)
return smallest_gene... | This function simulates MEG signal reconstruction by generating noisy data from a true orientation, computing covariance matrices with regularization, and reconstructing orientations using three methods (unit gain, array gain, unit noise gain). It evaluates accuracy by comparing reconstructed orientations to the true o... | def meg_reconstruction_experiment(true_orientation, full_lead_field, noise_level, fq, fs, nr_samples, regularization):
# initialize rng
rng = np.random.default_rng()
nr_sensors = full_lead_field.shape[0]
normed_lf = full_lead_field @ true_orientation
lf_norm = np.linalg.norm(normed_lf)
normed_lf /= lf... |
def source_magnitude(sample_index, fq, fs):
return np.sin(2 * np.pi * fq * sample_index / fs)
def unit_gain_orientation(covariance_matrix, lead_field_matrix):
A = lead_field_matrix.T @ np.linalg.pinv(covariance_matrix) @ lead_field_matrix
size = lead_field_matrix.shape[1]
B = np.eye(size)
return smallest_gene... | The code performs orientation reconstruction from EEG, MEG, and combined EMEG data, comparing reconstructed orientations to a true orientation. It generates noisy EEG/MEG data using leadfields, computes covariance matrices with regularization, and applies three reconstruction methods (unit gain, array gain, unit noise ... | def emeg_reconstruction_experiment(true_orientation, full_eeg_leadfield, full_meg_leadfield, eeg_noise_level, meg_noise_level, fq, fs, nr_samples, regularization):
# initialize rng
rng = np.random.default_rng()
nr_eeg_sensors = full_eeg_leadfield.shape[0]
nr_meg_sensors = full_meg_leadfield.shape[0]
... |
def source_magnitude(sample_index, fq, fs):
return np.sin(2 * np.pi * fq * sample_index / fs)
def unit_gain_orientation(covariance_matrix, lead_field_matrix):
A = lead_field_matrix.T @ np.linalg.pinv(covariance_matrix) @ lead_field_matrix
size = lead_field_matrix.shape[1]
B = np.eye(size)
return smallest_gene... | This function evaluates the accuracy of EEG, MEG, and combined EMEG orientation reconstruction methods under bootstrapped noisy data. It simulates data with true orientation, adds noise, performs bootstrap resampling, computes covariance matrices with regularization, reconstructs orientations using unit/array/unit-nois... | def bootstrapped_emeg_reconstruction_experiment(true_orientation, full_eeg_leadfield, full_meg_leadfield, eeg_noise_level, meg_noise_level, fq, fs, nr_samples, regularization, bootstrapping_repetitions):
# initialize rng
rng = np.random.default_rng()
nr_eeg_sensors = full_eeg_leadfield.shape[0]
nr_meg_sen... |
def initialize_weight_matrix(self):
return np.ones(shape = (self.num_classes, self.num_attributes))
def get_ground_truth(self):
ground_truths = []
for i in range(self.num_samples):
truth_value = self.training_labels[i]
ground_truth_i = []
for j in range(self.n... | This code initializes a machine learning model for classification, setting up training data, Bayesian probabilities (prior/likelihood), weight matrices, and optimization parameters (ISTA/FISTA). It computes initial posterior probabilities and prepares for iterative optimization using the selected scheme, with a focus o... | def __init__(self, training_samples, training_labels, scheme, learning_rate, max_iter, convergence_constant, l1_penalty, l2_penalty):
self.scheme = scheme
self.learning_rate = learning_rate
self.convergence_constant = convergence_constant
self.max_iter = max_iter
self.l1_penalty ... |
def testing_sample_likelihood_probabilities(self):
likeihood_probabilities = []
for i in range(self.num_testing_samples):
likeihood_probabilities.append(self.get_testing_sample_likelihood(self.testing_samples.iloc[i]))
return likeihood_probabilities
def fit_posteriors(self):
... | The main task of the code is to predict class labels for testing samples using a probabilistic model. It calculates posterior distributions, selects the most probable class for each sample, and evaluates prediction accuracy by comparing results to actual labels. The process involves computing likelihoods, fitting poste... | def predict(self, testing_samples, testing_labels):
self.testing_samples = testing_samples
self.testing_labels = testing_labels
self.num_testing_samples = len(self.testing_labels)
self.testing_likelihoods = self.testing_sample_likelihood_probabilities()
self.posterior_distributio... |
def get_table_number():
table_number = int(input("Enter your table number: "))
return table_number
def get_table_order(num_diners):
total_before_tax = 0.0
grand_total = 0.0
i = 1
while i <= num_diners:
total_before_tax += get_diner_order()
i += 1
table_total_after_tax = ... | The main task of the code is to calculate and accumulate the total revenue from multiple tables throughout the day. It retrieves table numbers, computes individual table totals based on diner counts, appends these to a daily total list, and recursively continues serving tables until the user decides to stop. Finally, i... | def main():
table_number = get_table_number()
table_total = get_table_order(get_number_of_diners_at_table())
daily_total.append(table_total)
print("For table : " + str(table_number))
while input("Would you like to continue serving a table for today? y/n") == 'y':
main()
else:
... |
def _create_index(self) -> VectorStoreIndex:
# Create client and a new collection
Settings.llm=OpenAI(model="gpt-3.5-turbo", temperature=0)
Settings.embed_model = OpenAIEmbedding(
model="text-embedding-3-small", embed_batch_size=100
)
chroma_client = chromadb... | This code initializes a class to process text files from a source directory, splitting them into configurable token-sized chunks (target_chunk_tokens, max_chunk_tokens) using a specified model (token_model). It creates an index, refreshes nodes, and optionally monitors the directory for changes if 'watch' is enabled. T... | def __init__(
self,
src_dir: str,
target_chunk_tokens: int = 300,
max_chunk_tokens: int = 1000,
enforce_max_chunk_tokens: bool = False,
coalesce: int = 50,
token_model: str = "gpt-3.5-turbo",
watch: bool = False,
):
self.src_dir = src_dir
... |
def _get_address(self, name):
wal_prefix = self._get_prefix()
pair_address = _sha512(name.encode('utf-8'))[0:64]
return wal_prefix + pair_address
def _sha512(data):
return hashlib.sha512(data).hexdigest()
def _create_batch_list(self,transactions):
transaction_signatures = [t.header_signature for t in transacti... | The function constructs and sends a blockchain transaction to a "wal" family network, signing it with the provided public key. It creates a transaction header with inputs/outputs, generates a batch, and optionally waits for the transaction status. If 'wait' is specified, it polls the status periodically before returnin... | def _send_wal_txn(self,name,action,pubkey,wait=None):
payload = ",".join([name,action,pubkey]).encode()
address = self._get_address(name)
sec_address = self._get_address(pubkey)
header = TransactionHeader(
signer_public_key = self._signer.get_public_key().as_hex(),
family_name = "wal",
family_version... |
def compute_occ(site_i, d1, d2, mocoeffs, norbs, ASU = False):
'''
Compute the occupancy of the sites in list site_i
by encoding n_i as an h1e
ASU tells whether we are dealing with molecular orbitals (max occ 2) or spin orbitals (max occ 1)
Generally to compute observable here and below follow... | The function `kernel_plot` computes time-dependent observables (energy, current, occupancy, spin) for quantum system simulations. It iterates over time steps, calculates density matrices, updates the state vector, and evaluates observables like energy, electron current (up/down), and site-specific occupancies/spins. Re... | def kernel_plot(eris, ci, tf, dt, i_dot, t_hyb, RK, spinblind, verbose):
'''
Kernel for getting observables at each time step, for plotting
Outputs 1d arrays of time, energy, dot occupancy, current
Access thru calling kernel (see above) with mode=plot
Returns
timevals, 1d arr of time steps
... |
def read(file_name: str, separator: str = ",") -> Tuple[List[str], Data]:
"""
t3: Load the data into a bidimensional list.
Return the headers as a list, and the data
"""
header = None
data = []
with open(file_name, "r") as fh:
for line in fh:
values = line.strip().split(s... | The main task of the code is to read data from a file, construct a decision tree using the `buildtree` function, and print the resulting tree structure with associated headers. The code handles default file input if none is provided, though most data-processing and evaluation functions are currently commented out. | def main():
try:
filename = sys.argv[1]
except IndexError:
filename = "decision_tree_example.txt"
# header, data = read(filename)
# print_data(header, data)
# print(unique_counts(data))
# print(gini_impurity(data))
# print(gini_impurity([]))
# print(gini_impurity([data... |
def buy(self):
if self.rv:
return str(round(math.ceil((math.ceil(self.pages_bw()/2) * buy_rv + math.ceil(self.pages_col/2) * buy_rv_col + 0.5) * 1.06 * 100)/100, 2))
else:
return str(round(math.ceil((self.pages_bw() * buy_r + self.pages_col * buy_r_col + 0.5) * 1.06 * 100)/100, 2... | This code generates a JSON dictionary containing book-related data, including a fixed key, barcode (constructed with year info), purchase/sell prices, and additional attributes like page counts and format details when `is_same` is False. | def get_json(self):
if self.is_same:
return {
"key": "c9tht3ljfzrsebzywghrskbdyqk36j09",
"is_same": str(self.is_same),
"barcode": "978" + Cursus.get_years_back(1) + cur_year + str(self.barcode),
"purchase... |
def get_json(self):
if self.is_same:
return {
"key": "c9tht3ljfzrsebzywghrskbdyqk36j09",
"is_same": str(self.is_same),
"barcode": "978" + Cursus.get_years_back(1) + cur_year + str(self.barcode),
"purchase... | The code merges PDFs based on the 'is_same' flag. If true, it downloads a front page, combines it with a previous PDF, and saves the result. If false, it processes a directory of PDFs, merges them with formatting rules, checks for issues, and adds a front page before saving. The task involves handling PDF generation an... | def update(self):
if self.is_same:
r = requests.post('https://www.vtk.be/api/cudi/is-same', data=self.get_json())
front_page = r.json()['front_page']
url = 'https://www.vtk.be' + front_page
print(url)
response = requests.get(url)
output = ... |
def find_bbox_number(root):
index = 0
while True:
if get_int('xmin', root, index) == -1:
break
index += 1
return index
def get_int(name, root, index=0):
return int(get_item(name, root, index))
def get_item(name, root, index=0):
count = 0
for item in root.i... | This function parses an XML annotation file, extracts bounding box coordinates, normalizes them to [0,1] relative to image dimensions, and returns a list of BoundingBox objects containing scaled coordinates, image metadata, and labels. It handles parsing errors gracefully by returning None. | def process_xml_annotation(xml_file):
try:
tree = ET.parse(xml_file)
except Exception:
print('Failed to parser: ' + xml_file, file=sys.stderr)
return None
root = tree.getroot()
num_boxes = find_bbox_number(root)
boxes = []
for index in range(num_boxes):
... |
def get_playlist_ids():
"""
Gets playlist ids
No params
Returns dictionary of playlist ids
"""
playlist_info = others_help.file_contents(spotify_dir, 'playlist-info.json')
if playlist_info is None: raise Exception('Error trying to load playlist-info.json.')
for category in play... | The main task of the code is to add tracks to Spotify playlists by processing user-selected categories, retrieving track URIs, authenticating with Spotify's API, and sending PUT requests to update playlists. It validates user input, ensures data integrity, and returns True upon successful execution. | def put_playlists(select=None):
"""
Adds playlist items to generated spotify playlists
Accepts optional array of which categories to place songs into
Returns True if successful else None
"""
playlist_ids = get_playlist_ids()
others_help.print_alert('put_playlists(): Gathering uris for... |
def get_inside_index(anchor, H, W):
index_inside = np.where(
(anchor[:, 0] >= 0) &
(anchor[:, 1] >= 0) &
(anchor[:, 2] <= H) &
(anchor[:, 3] <= W))[0]
return index_inside
def create_label(self, inside_index, anchor, bbox):
label = np.empty((len(inside_index),), dtyp... | The main task of the code is to generate location (loc) and class labels (label) for anchors inside the image. It filters anchors within the image, computes their corresponding bounding box offsets (loc) and class labels (label) based on input bounding boxes, then maps these results back to the original anchor indices,... | def __call__(self, bbox, anchor, img_size):
img_H, img_W = img_size
n_anchor = len(anchor)
inside_index = get_inside_index(anchor, img_H, img_W)
anchor = anchor[inside_index]
argmax_ious, label = self.create_label(inside_index, anchor, bbox)
loc = bbox2loc(anchor, bbox[a... |
def remove_neighbor(self, conn):
self.neighbors_sock.pop(self.neighbors_ip[conn])
self.routes.pop(self.neighbors_ip[conn])
self.neighbors_ip.pop(conn)
def update_routes(self, packet, conn):
self.routes[packet.sender] = self.neighbors_ip[conn]
def handle_packet(self, packet):
if p... | The main task of this code is to receive and process incoming data packets from a socket. It reads data in blocks, checks for disconnections, unpickles the packet, logs its details, updates routing information, and either handles the packet locally, broadcasts it, or forwards it to the next hop based on TTL and receive... | def handle_incomming_data(self, sock):
data = b''
try:
for _ in range(BLOCK_SIZE):
temp = sock.recv(1)
if not temp:
data = b''
break
data += temp
except ConnectionResetError: # Windows doesn't c... |
def sortArray(*xargs):
for i in xargs:
sortChoice(i)
def getLength(xs: list):
return len(xs)
def compareLengthAndBreak(i, j):
return True if i == j else False | This code attempts to merge two sorted lists xs and ys into a single sorted list zs by comparing elements at indices i and j, appending the smaller element to zs, and incrementing the respective index. However, it contains undefined functions (sortArray, getLength, compareLengthAndBreak), improper use of global variabl... | def mergeSortedTwoArray(xs: list, ys: list):
zs = []
sortArray(xs, ys)
xsLength = getLength(xs)
ysLength = getLength(ys)
global i, j
i = 0
j = 0
while i < xsLength or j < ysLength:
xsEle = xs[i]
ysEle = ys[j]
if xsEle < ysEle:
zs.append(xsEle)
i = i + 1
if compareLengt... |
def edit_file(params, cmd_type, ask_edit=True):
if ask_edit:
if not procede("Would you like to edit your params?"):
return params
MARKER = '# Everything below is ignored'
edited = click.edit(str(params)+'\n'+MARKER)
if edited is None:
return params
try:
tag_lines ... | This function removes specified host nodes by processing input arguments, editing configuration parameters, confirming removal settings, and triggering a Jenkins pipeline named 'remove-node-prod' with the configured parameters to execute the node removal process in a production environment. | def remove_cmd(args):
params = RemoveHosts()
if args['<host-id>']:
params.nodes = args['<host-id>']
params = edit_file(params, RemoveHosts, ask_edit=False)
params = confirm_params(params, RemoveHosts, args['--override'])
print(blue('removing nodes...'))
jenkins_build('remove-node-prod',... |
def replace_cmd(args):
# Find Host Information in datadog
params = get_host(args['<host-id>'])
params = confirm_params(params,Provision, args['--override'])
print(blue('execute replacement...'))
jenkins_build('provision-consumer-prod', params)
def replace_many_cmd(args):
# Find Host Information ... | The main task of the code is to execute command-line operations based on user input arguments parsed by `docopt`. It checks for flags like `--replace`, `--replace-many`, `--remove`, or `--config` and invokes corresponding functions. If no valid command is provided, it prints an "Invalid command" error and exits. | def main():
args = docopt.docopt(__doc__, version="1.0")
if args['replace']:
return replace_cmd(args)
elif args['replace-many']:
return replace_many_cmd(args)
elif args['remove']:
return remove_cmd(args)
elif args['config']:
return config_cmd(args)
else:
... |
def is_stuck(self, final, initial):
if final == initial:
return True
return False
def poss_total(self):
total = 0
for i in range(0, len(self.cells)):
total += len(self.cells[i].poss)
return total
def check_all_cells(self):
for i in range(0, len(sel... | The code solves a board by iteratively applying logic until it's stuck, then checks if solved. If not, it creates a duplicate, modifies it, and recursively solves. If the duplicate fails, it backtracks by removing a value and retries. The main task is to solve the board using logical checks and backtracking when necess... | def solve(self):
initial_count = None
final_count = False
# print "before the board reaches stuck tests: ", self.display_board()
while self.is_stuck(final_count, initial_count) == False:
initial_count = self.poss_total()
self.check_all_cells()
final_co... |
def is_solved(self):
for i in range(0, len(self.cells)):
if len(self.cells[i].poss) != 1:
return False
return True
def solve(self):
initial_count = None
final_count = False
# print "before the board reaches stuck tests: ", self.display_board()
... | The method `get_solved_board` repeatedly solves the board using `self.solve()` until `self.is_solved()` returns `True`, then displays the solved board via `self.display_board().` Its main task is to iteratively solve and display a board until it reaches a solved state. | def get_solved_board(self):
while self.is_solved() == False:
self.solve()
self.display_board() |
def get_all_user_details(dbConnection):
""" This function returns all registered users to the application.
:param dbConnection: Connection to the app's database
:return: All registered users to the application
"""
try:
return dbConnection.users.find()
except():
raise Exception("... | The function recommends recipes to users by identifying similar users through KNN, then suggesting recipes completed by similar users that the target user hasn't done, storing recommendations in the database. | def recipe_recommend_user(dbConnection):
""" This function goes through all the users X who are registered for the app and for each one searches for another
user Y so that the details of both are similar, then it looks for a recipe recommendation for X according to the
recipes that Y has done and X has n... |
def get_all_user_details(dbConnection):
""" This function returns all registered users to the application.
:param dbConnection: Connection to the app's database
:return: All registered users to the application
"""
try:
return dbConnection.users.find()
except():
raise Exception("... | The function identifies similar users via KNN based on user details, recommends recipes completed by similar users but not by the target user, and stores these personalized recipe recommendations in the database using the provided connection. | def find_similar_user(dbConnection):
""" This function goes through all the users X who are registered for the app and for each one searches for another
user Y so that the details of both are similar, then it looks for a recipe recommendation for X according to the
recipes that Y has done and X has not y... |
def get_valid_locations(board):
valid_locations = []
for col in range(7):
if isvalid(board, col):
valid_locations.append(col)
return valid_locations
def is_terminal_node(board):
return check_winner(board, 1) or check_winner(board, 2) or moves(board) == 1
def check_winner(board, type)... | The code implements the minimax algorithm for a two-player game, recursively evaluating board states to determine the optimal move. It alternates between maximizing and minimizing players, exploring valid moves, simulating gameplay, and backtracking to select the column with the highest (for maximizing) or lowest (for ... | def minimax(board, depth, maximizingPlayer):
valid_locations = get_valid_locations(board)
is_terminal = is_terminal_node(board)
if depth == 0 or is_terminal:
if is_terminal:
if check_winner(board, 1):
return (None, 100000000000000)
elif check_winner(board, 2):... |
def get_valid_locations(board):
valid_locations = []
for col in range(7):
if isvalid(board, col):
valid_locations.append(col)
return valid_locations
def is_terminal_node(board):
return check_winner(board, 1) or check_winner(board, 2) or moves(board) == 1
def check_winner(board, type)... | This function implements the alpha-beta pruning algorithm to determine the optimal move for a player in a game (likely Connect Four), evaluating board states recursively while pruning non-optimal paths to improve efficiency. It alternates between maximizing and minimizing players, scoring terminal states based on win/l... | def alpha_beta(board, depth, alpha, beta, maximizingPlayer):
valid_locations = get_valid_locations(board)
is_terminal = is_terminal_node(board)
if depth == 0 or is_terminal:
if is_terminal:
if check_winner(board, 1):
return (None, 100000000000000)
elif check_w... |
def buildMenuBar(self):
self.menu = Menu(self.parent)
self.parent.config(menu=self.menu)
self.fileMenu = Menu(self.menu, tearoff=0)
self.menu.add_cascade(label="File", menu=self.fileMenu)
self.fileMenu.add_command(label="New")
self.fileMenu.add_command(label="Open", comm... | This code initializes a GUI application for a number tracking tool. It sets up the main window, configures the title, handles window closure, initializes data storage, and constructs UI components like menus, input fields, action buttons, number display, info text, and layout elements. It also binds the Delete key to a... | def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.parent.title("Numbertrack v%s" % NUMBERTRACK_VERSION)
self.parent.protocol("WM_DELETE_WINDOW", self.quit)
self.numberstore = None
self.buildMenuBar()
self.buildModifyEntry()
... |
def calculateKey(node,start, k_m):
return (min(node.g, node.rhs) + heuristic(node,start) + k_m, min(node.g, node.rhs))
def top_key(q):
if len(q) > 0:
return [q[0][0],q[0][1]]
else:
# print('empty queue!')
return [float('inf'), float('inf')]
def compare_keys(node1,node2):
if node1... | This function computes the shortest path in a graph using a modified Dijkstra-like algorithm with priority queues. It iteratively updates node costs (g and rhs), manages a priority queue for node processing, and propagates changes through parent/child relationships. The algorithm terminates when the start node's estima... | def compute_shortest_path(path,graph, G):
path.start.key=calculateKey(path.start, path.start, path.k_m)
k_old=top_key(path.queue)
while path.start.rhs>path.start.g or compare_keys(k_old,path.start.key):
if len(path.queue)==0:
print("No path found!")
return 0
#prin... |
def compute_c(current,neigh, G):
g=1
if(current.z!=neigh.z):
g=abs(neigh.z-current.z)/current.av_speed_vertical
else:
#g=(abs(neigh.x-current.x)+abs(neigh.y-current.y))*2/(current.speed/current.density+neigh.speed/neigh.density)
#here i need to check if the group is changing (the dro... | The code generates a path route and turn information in a graph traversal. It iteratively finds the next node with minimal cost, appends intermediate coordinates from edge geometries to the route, and updates costs dynamically. It adjusts the path based on changing costs, recalculates shortest paths, and records turns ... | def get_path(path,graph, G):
change=False
edges_geometry=osmnx.graph_to_gdfs(G, nodes=False)["geometry"]
change_list=[]# a list with the nodes between which the cost changed
route=[]
group_numbers=[]
tmp=(path.start.x,path.start.y,path.start.z)
route.append(tmp)
group=path.start.group
... |
def _split_lines(self):
out_line = []
self.temp_array = []
n = 0
# Iterate through the lines and split the edges
idx = 0
for line in self.lines:
for part in _list_to_pairs(line):
out_line.append(
[
pa... | This code initializes a class to process a geospatial edge dataset, splitting edges into line segments, assigning unique IDs, building connectivity tables, and evaluating valid connections based on an angle threshold to model geometric network relationships. | def __init__(self, edge_gdf, angle_threshold=0):
self.edge_gdf = edge_gdf
self.gdf_projection = self.edge_gdf.crs
self.already_merged = False
# get indices of original gdf
self.uv_index = self.edge_gdf.index.tolist()
# get line segments from edge gdf
self.lines ... |
def initialise(path):
path.queue=[]
path.k_m=0
path.goal.rhs=0
path.goal.inQueue=True
path.goal.h=heuristic(path.start,path.goal)
heapq.heappush(path.queue, (path.goal.h,0,path.goal.x,path.goal.y,path.goal.z,path.goal.index, path.goal))
def compute_shortest_path(path,graph, G):
path.start.ke... | The code identifies start and goal nodes in a graph using coordinates, computes the shortest path between them, and returns the route with turns. It uses OSMNX to find nearest nodes, maps these to graph IDs, and employs path computation functions to determine the optimal route. | def plan(self):
start_id=-1
goal_id=-1
#key=G_list[start_id]
start_index=osmnx.distance.nearest_nodes(self.G,self.s_x,self.s_y, return_dist=False)
goal_index=osmnx.distance.nearest_nodes(self.G,self.g_x,self.g_y, return_dist=False)
for i in self... |
def calc_point_squre_dist(point_a, point_b):
"""Calculate distance between two marking points."""
x_a = point_a[1]
y_a = point_a[2]
x_b = point_b[1]
y_b = point_b[2]
distx = x_a - x_b
disty = y_a - y_b
dist = math.sqrt(math.pow(distx,2) + math.pow(disty,2))
return dist
def pair_mark... | The code identifies and categorizes slots (perpendicular/parallel relationships) between pairs of marking points based on distance thresholds and geometric alignment. It filters valid pairs, processes their directional data, and constructs structured outputs (`slots` and `slots2`) containing point relationships, types,... | def inference_slots(marking_points):
"""Inference slots based on marking points."""
num_detected = len(marking_points)
print('numebr of points', num_detected)
perpen_parallel = 0 # perpendicular = 1 , parallel = 2
slot = {}
slots = []
marks_set = set()
marks_list = []
slots_list =... |
def setup_in_user(username):
search = "select user_index from user where user_name = \'" + str(username) + "\';"
cur.execute(search)
index = 0
access_p = 0
for i in cur.fetchall():
index = int(i[0])
if index == 0:
m.halt(301)
return 0
else:
check = "select ac... | This function verifies user credentials against a database. It checks if the username exists, handles empty inputs with specific error codes (100, 101, 200), and validates the password using a helper function. If valid, it sets global variables and returns 1; otherwise, returns 0. | def verify_database(username,password):
if setup_in_user(str(username.get())) == 1:
global username_infor, password_infor
username_infor = str(username.get())
password_infor = get_password()
return 1
if len(str(username.get())) == 0 and len(str(password.get())) == 0:
m.ha... |
def print_fun2_single_1(var):
tb_person = pp.PrettyTable()
list_person = list()
search = "select specialty,name,form_study from specialty_s where name = \'" + var + "\';"
cur.execute(search)
tb_person.field_names = ['Specialty','Name','Form_study']
for i in cur.fetchall():
list_person.ap... | The function `print_fun2` generates and returns a formatted table (`PrettyTable`) based on input parameters. It executes SQL queries to fetch data from a database, dynamically constructs queries using conditions on `var_list`, `var_name`, `var_study`, and `var_string`, and delegates to helper functions (`print_fun2_sin... | def print_fun2(var_list = list(),var_string = '',var_name = '',var_study = ''):
tb = pp.PrettyTable()
lists = list()
print(var_list,var_string,var_name,var_study)
search = "select * from department,discipline,specialty_s where department.title = discipline.title_d and department.specialties = specialty_... |
def refreshTable(self):
self.ui.team1.setRowCount(0)
self.ui.team2.setRowCount(0)
for player_info in self.red_team_players:
self.addRow(self.ui.team1, player_info.name, player_info.id, player_info.score)
for player_info in self.blue_team_players:
self.addRow(sel... | This code updates a countdown timer display, changes its color to red when time is critical, refreshes the UI, ends the game when time runs out, and calculates team scores for high score tracking. | def updateTimer(self, secondsLeft):
timer_text = f"Time Remaining: {countdownTimer.toString(secondsLeft)}"
if secondsLeft <= 10:
self.ui.timeRemaining.setStyleSheet(f"QPlainTextEdit {{color: red;}}")
# self.ui.timeRemaining.setStyleSheet(f"QPlainTextEdit... |
def main(pos="None"):
score = 0
gameCount = 0
if games == "INFINITE":
while True:
try:
if debug:
print(f"=== NEW GAME ===\ngame: {gameCount + 1}")
game_results = game(score, pos, gameCount + 1)
pos = game_results[1]
... | (The main task of the code is to initialize a game menu GUI with configurable position, game count, score, and button visibility. It creates a GraphWin window, sets its background, adjusts positioning, loads assets, and prepares GUI elements like buttons and score display. The code handles infinite game mode logic, foc... | def __init__(self, pos, gameCount=0, score=0, showButtons=True):
if debug:
print(f"==== MENU ====\npos: {pos}, games: {gameCount}, score: {score}, showButtons: {showButtons}")
if not games == "INFINITE" and gameCount == 0:
main()
return
self.win = GraphWin(tr... |
def is_train_test_file_exists(self) -> bool:
"""
It checks if the training and testing files are present in the specified path
:return: The return value is a boolean value.
"""
try:
logging.info(
'Checking if Training And Testing File is Available!!!!?... | The main task of the code is to validate data by checking the existence of train/test files, verifying dataset schema compliance, and detecting data drift. If all checks pass, it returns a DataValidationArtifact with validation results and success status. Errors during validation trigger logging and exception propagati... | def initiate_data_validation(self) -> DataValidationArtifact:
"""
It checks if the train and test files exist, validates the schema of the dataset, and checks if
there is any data drift
:return: DataValidationArtifact
"""
try:
self.is_train_test_file_exists()
... |
def send(message):
print(message)
def get_int_from_user():
try:
user_selection = int(recv())
return user_selection
except:
return 0
def modify_flag_menu():
raise NotImplementedError
def list_flags(flags):
res = "=================================\n"
for i, flag in enumerat... | The main task of the code is to present a menu-driven interface for managing flags in a game or application. It loops, displaying options to list/sell/buy flags, view owned flags, check stats, or exit. User selections trigger corresponding functions, with error handling for invalid inputs. The interface communicates vi... | def main_menu():
while True:
send("What would you like to do?\n")
send("\n".join([
# "0 - MODIFY FLAGS",
"1 - LIST AVAILABLE FLAGS",
"2 - BUY FLAG",
"3 - SELL FLAG",
"4 - LIST MY FLAGS",
"5 - LIST MY STATS",
"6 - EXIT"... |
def __update_window_SEL(self):
self.__window.clear()
for i in range(self.__window_size):
try:
self.__window.append(self.__buffer[self.__buffer_index + i])
except:
self.disconnect()
def __print_window(self):
print("{ ", end="")
for f... | The code implements a selective repeat protocol for data transmission. It initializes a frame buffer, updates the window, and enters a loop to handle sending/receiving data cycles, check for corruption, and manage connection state. The loop continues until the connection completes, then terminates. Key tasks include ma... | def __selective_module(self):
for i in range(self.__sequence_number):
self.__last_sent_frames.append(None)
self.__update_window_SEL()
while self.__connection_flag:
self.__print_window()
self.__send_cycle_SEL()
self.__read_cycle_SEL()
... |
def __go_back_module(self):
while self.__connection_flag:
# self.print_messages()
self.__read_cycle()
self.__time_out_logic()
self.__send_cycle()
print("----------------")
self.check_end_flag()
def __selective_module(self):
while se... | This method determines the connection module type (GOBACK or SELECTIVE), executes the corresponding protocol handling method, outputs buffered data, and then terminates the connection. It uses conditional logic to route to specific module implementations, prints data from the buffer using a static method, and calls a d... | def start(self, connection_module):
if connection_module == "GOBACK":
self.__go_back_module()
elif connection_module == "SELECTIVE":
self.__selective_module()
print(Data.output_stream(self.__buffer))
self.disconnect() |
def start_connection():
con = psycopg2.connect(host="localhost",
user=USER,
password=PASSWORD,
dbname=DBNAME)
return con
def get_user_id(con, discord_id: int, name: str):
cur = con.cursor()
user_query = f"SELECT * FROM User... | This function adds a new show and its episodes to a user's database entry. It connects to the database, retrieves the user's ID, calculates total episodes, adds the show with metadata, and iterates through each episode to insert details like title, filler status, URL, and series ID. Finally, it closes the database conn... | def add_episodes_to_show(episodes: dict, show: str, discord_id: int, name: str, prequel):
con = start_connection()
user_id = get_user_id(con, discord_id, name)
total_episodes = len(list(episodes.keys()))
series_id = add_show_to_user(show, user_id, total_episodes, prequel)
for episode_num in range(1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.