dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_move_AI(self):
print("The computer moved.")
return self.minimax(self.turn, self.turn)['position']
def get_move_human(self):
# gets input for what move to play
try:
result = int(input(f"Enter where you would like to put an {self.turn} (#1-9): ")) - 1
except:
... | The method `play` handles a player's move by selecting a square based on whether the player is human or AI, validates the move, and updates the game state. If invalid, it prompts retry; otherwise, it prints the board and switches turns. | def play(self, player):
# plays
if player == 'c':
square = self.get_move_AI()
if player == 'h':
square = self.get_move_human()
flag = self.play_move(square, self.turn)
# make sure inputs are valid
if flag == False:
print("Inva... |
def get_players(self):
# gets input on whether X and or O are human or computer players
self.x_player = input("The player with X is ('c' for computer, 'h' for human): ")
self.o_player = input("The player with O is ('c' for computer, 'h' for human): ")
# check inputs
if self.x_p... | This code manages a game loop where players take turns making moves until a winner is determined or the game ends in a tie. It initializes players, alternates turns between 'X' and 'O' players, checks for a win condition after each move, and declares a winner or tie when the board is full with no winner. | def game(self):
# get players
self.get_players()
self.print_board_example()
# play game
while self.empty_squares() > 0:
if self.winner == 'X' or self.winner == 'O':
print(f"{self.winner} Wins!")
#print(f"There were {self.count} branch... |
def binary_to_decimal(binary_str):
"""
Converts binary strings to decimal
"""
return int(binary_str, 2)
def get_gamma_binary(filename):
"""
Calculates binary string for gamma ray
"""
binary = ""
with open(filename) as file:
for line in file:
line_len = len(line)
... | The function calculates the power consumption by reading binary data from a file, converting gamma and epsilon rates to decimal, and multiplying them together. | def power_consumption(filename):
"""
Gets both gamma and epsilon rates, and returns them
multiplied together to get power consumption
"""
gamma = binary_to_decimal(get_gamma_binary(filename))
epsilon = binary_to_decimal(get_epsilon_binary(filename))
return gamma * epsilon |
def red_green(self, amount):
if amount >= 0:
return "green"
else:
return "red"
def modify(self, rownumber, sym):
qty = my_crypto_portfolio[sym][0]
paid = my_crypto_portfolio[sym][1]
self.symbolentry = Entry(self, font="Verdana 8")
self.symbolent... | The code generates a cryptocurrency portfolio summary by calculating each asset's current value, profit/loss, and price changes. It creates a GUI table displaying symbols, quantities, prices, and interactive 'Modify/Delete' buttons. It also initializes pie chart data for visualization and supports adding new coins via ... | def create_portfolio(self):
self.portfolio_profits = 0
self.total_current_value = 0
self.pie = []
self.pie_size = []
for item in my_crypto_portfolio:
sym = item
qty = my_crypto_portfolio[sym][0]
paid = my_crypto_portfolio[sym][1]
... |
def get_api_data(self):
listofcrypto = []
for lineitem in my_crypto_portfolio:
listofcrypto.append(lineitem)
listofcrypto_str = ",".join(listofcrypto)
fmt = 'https://min-api.cryptocompare.com/data/pricemultifull?fsyms={}&tsyms={}&api_key=4120b66bee53ddad00260553cac121599740... | The code initializes a GUI application for a cryptocurrency portfolio, setting up a frame with headers, portfolio data display, and a bottom section. It checks if a portfolio exists, fetches API data if so, and creates a menu with "Open" and "Save As" options. The window title dynamically shows the total portfolio valu... | def __init__(self, win):
Frame.__init__(self, win)
self.rows = 1
if my_crypto_portfolio != {}:
self.get_api_data()
self.create_headers()
self.create_portfolio()
self.create_bottom()
self.grid()
menu = Menu(window)
new_item = Menu(me... |
def prepare_input(self, image):
self.img_height, self.img_width = image.shape[:2]
input_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Resize input image
input_img = cv2.resize(input_img, (self.input_width, self.input_height))
# Scale input pixel values to 0 to 1
input... | The code detects objects in an image by preparing input data, performing inference, and processing outputs to return bounding boxes, confidence scores, and class IDs. It uses post-processing if enabled, otherwise processes raw outputs directly. | def detect_objects(self, image):
input_tensor = self.prepare_input(image)
# Perform inference on the image
outputs = self.inference(input_tensor)
if self.has_postprocess:
self.boxes, self.scores, self.class_ids = self.parse_processed_output(outputs)
else:
... |
def poll_new_data(self):
"""Update data"""
self.data['y'].append(self.func() or self.DEFAULT_VALUE)
self.data['x'].append(datetime.now().strftime(self.time_format))
if self.limit_func:
self.data['limit'].append(self.limit_func() or self.DEFAULT_VALUE)
def create_layout(self):... | This code initializes a Dash application for real-time data visualization. It sets up data storage with deques, configures visualization parameters, creates a dynamic color cycle for visual effects, and builds the Dash app layout with callbacks to handle data updates and rendering. The core task is to establish a web-b... | def __init__(self, func, limit_func=None, max_len=50, interval_ms=100):
assert callable(func), 'func argument has to be callable'
assert callable(limit_func) or limit_func==None, 'if specified, limit_func argument has to be callable'
self.func = func
self.limit_func = limit_func
... |
def play(self):
self.render_background()
self.snake.walk()
self.apple.draw()
self.display_score()
if self.is_collision(self.snake.x[0], self.snake.y[0], self.apple.x, self.apple.y):
self.apple_is_eaten()
# snake colliding with itself
for i in... | This code runs a game loop for a snake game, handling keyboard inputs to control snake movement, pause/resume music, and manage game states. It processes events like key presses (ESC to quit, RETURN to unpause, arrow keys for movement) and quits the loop on QUIT events. The game plays continuously unless paused, and ex... | def run(self):
running = True
pause = False
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
if event.key == K_RETURN:
... |
def initializing(self):
pygame.mixer.music.play()
self.score = 0
self.level = 0
self.rows_removed = 0
self.next_tetrimino = False
self.tetrimino = False
self.field = []
for i in range(N_ROWS):
row = []
for j in range(N_COLUMNS):
... | This code manages a game loop using Pygame, handling user inputs for movement, rotation, and pausing/resuming gameplay. It processes events like quitting, key presses, and exceptions during game play, triggering a game over state when errors occur. The loop maintains the game's frame rate, updates the display, and cont... | def run(self):
running = True
pause = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == KEYUP:
if event.key == K_DOWN:
... |
def parse_XML_to_df(xml_file, df_cols) -> pd.DataFrame:
"""Parse the input XML file and store the result in a pandas
DataFrame with the given columns.
The first element of df_cols is supposed to be the identifier
variable, which is an attribute of each node element in the
XML data; other features w... | The code processes clinical trial data from XML files, parsing and cleaning text to generate structured JSON datasets. It reads configurations, extracts relevant trial information, filters data based on inclusion/exclusion criteria, splits into training/test sets, and saves them as JSON files for a classification task,... | def create_JSON(
versions=None,
):
if versions is None:
versions = ["v12"]
for ver in versions:
version = ver
data_list = []
config_file = os.path.join(base_directory, "configs/ct_data.yaml")
with open(config_file, "r") as file:
config = yaml.safe_load(fi... |
def configRead():
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
try:
quiet = config['Config']['quiet']
quiet = quiet.lower() in ("true")
except KeyError:
quiet = False
try:
alg = config['Config']['alg'].lower()
# alg = ... | The main task of the code is to display a menu-driven interface for system management, allowing users to initialize user accounts, test authentication, or exit. It reads configuration parameters, presents options, and routes input to corresponding functions: `login_init` for account setup, `Auth_test` for authenticatio... | def main_menu():
quiet,alg,saltSize,art=configRead()
print("\n--- Main Menu ---")
print("0. Initialize user accounts")
print("1. Test Authentication")
print("2. Exit")
choice = input("Enter your choice: ")
if choice == '0':
login_init('','',True,quiet,saltSize)
elif choice == '1'... |
def read_video(self):
"""
reads video frames and stores each color frame in self.frame_buf_c
and each gray scale frame in self.frame_buf_g as well as calculates
optical flow and stores in self.flow_buf. Also saves some data about
video that is needed later. All frames are downsam... | The code processes a video to identify optimal start/end frames for a loop using color difference and flow analysis, then generates a GIF from the best looping frames. It reads the video, calculates color and motion differences across frames, selects the most consistent loop segment, writes these frames, and creates a ... | def Start(self):
"""starts looper on video to get best start/end frames and write gif"""
try:
self.read_video()
self.get_all_frames_color_diffs()
self.get_all_frames_flow_conts()
# self.get_best_loop_color_flow()
self.get_best_loop_color()
... |
def size_to_string(s):
size = float(s)
unit_counter = 0
while size > 1024:
size = size / 1024.0
unit_counter += 1
return "" + str(round(size, ndigits=2)) + " " + file_sizes[unit_counter]
def get_dir_size(d):
total_size = 0
for entry in os.scandir(d):
if entry.is_file():
... | The function updates the path associated with a given ID if the provided path is a valid directory. It alerts users for invalid paths or access issues, updates the UI with directory size, saves changes, and returns success/failure status. | def change_path(id: str, path: str):
if path == None:
eel.triggerAlert(path + " is not a directory!", "Error", "red")
return False
if id not in paths:
eel.triggerAlert("This entry doesn't exist!", "Error", "red")
return False
elif os.path.isdir(path):
try:
... |
def size_to_string(s):
size = float(s)
unit_counter = 0
while size > 1024:
size = size / 1024.0
unit_counter += 1
return "" + str(round(size, ndigits=2)) + " " + file_sizes[unit_counter]
def get_dir_size(d):
total_size = 0
for entry in os.scandir(d):
if entry.is_file():
... | The code adds a specified directory path to a list, validates the path, calculates its size, generates a unique ID, and updates the UI via Eel. It handles errors by alerting users if the path is invalid or if exceptions occur during processing, ensuring only valid directories are added and data is saved. | def add_path(path: str):
if path == None:
eel.triggerAlert(path + " is not a directory!", "Error", "red")
return
if os.path.isdir(path):
try:
size = size_to_string(get_dir_size(path))
id = get_random_id()
paths[id] = DirectoryListItem(id, paths, path)
... |
def clean_dir(path:str, recursive:bool) -> int:
deleted_size = 0
eel.logText("Processing " + path, "white")
for entry in os.scandir(path):
if entry.is_file():
deleted_size += delete_file(entry.path)
elif recursive and entry.is_dir():
deleted_size += clean_dir(entry.pa... | The main task of the code is to clean specified directories by recursively deleting files, calculate the total size of deleted data, update UI elements with progress/status messages, and log statistics. It disables user input during processing, iterates through predefined paths, cleans each directory, converts deletion... | def _run_cleaner():
eel.disableInput()
eel.logText("Starting cleaning process...", "blue")
total_size = 0
for id, path_obj in paths.items():
size = clean_dir(path_obj.path, path_obj.recursive)
size_str = size_to_string(size)
total_size += size
update_stats(path_obj.path, ... |
def compileExpression(env, x, heap):
return compileTerm(env, x, heap) or compileFormula(env, x, heap)
def freshStr():
return str(random.randint(0,100000)) | The code recursively compiles an abstract syntax tree (AST) into a sequence of instructions, handling statements like Print, Assign, If, Until, Procedure, and Call. It updates the environment and heap during compilation, generating instruction lists for each node type while managing control flow and variable assignment... | def compileProgram(env, s, heap):
if s == 'End':
instsEnd = []
return (env, instsEnd, heap)
elif type(s) == Node:
for label in s:
if label == 'Print':
children = s[label]
f1 = children[0]
f2 = children[1]
(insts1... |
def handle_events(self):
"""
Handle by keypresses
s - start/stop (pause) the game
q - quit
r - randomize grid
:return:
"""
for event in pygame.event.get():
if event.type == pygame.KEYDOWN: # stop and start game
if event.unicode... | The code runs a game loop that continuously handles events, updates the game state, draws the grid, and caps the frame rate until the gameover condition is met. It checks for gameover status, skips updates if paused, and exits when the game ends. | def run(self):
"""
Kick off the game and loop forever until quit state
:return:
"""
while True:
if self.gameover:
return
self.handle_events()
if self.paused:
continue
self.update_generation()
... |
def getLabel(self, index):
return self.trainingData[index][2]
def getTopFeaturesPerLabel(self, label):
if (label not in self.topFeaturesPerLabel):
matrix = self.__getMatrixPerLabel(label)
matrixSum = matrix.sum(axis=0)
sortIndex = np.argsort(matrixSum)
non... | This function extracts the top TF-IDF features for a given data point based on its label. It retrieves the label if not provided, identifies the most significant features for that label, filters the corresponding feature values from the data point, converts them to a numpy array of floats, and returns the result for fu... | def __getTopRowFeaturesAsArray(self, index, label=None):
label = self.getLabel(index) if label is None else label
#get the column index with the top tf-idf
topFeatures = self.getTopFeaturesPerLabel(label)
features = np.array([float(val) for i, val in enumerate(self.getFeatures(i... |
def get_data(self):
"""
Requests data from John Hopkins University database from the most
recent day it can find, and then also from 14 days prior and every day
inbetween (in order to calculate general trajectory)
"""
today_date = date.today()
data = None
... | The main task of the code is to initialize and update key variables (`self.data`, `self.state_cases`, `self.state_hospitals`, `self.state_tests`) by calling specific data-fetching methods (`get_data`, `get_cases_trend`, `get_hospital_capacity`, `get_test_trend`). This method runs nightly at midnight to ensure the class... | def set_data(self):
"""
Sets variables (to be run every night at midnight)
"""
self.data = self.get_data()
self.state_cases = self.get_cases_trend()
self.state_hospitals = self.get_hospital_capacity()
self.state_tests = self.get_test_trend() |
def set_data(self):
"""
Sets variables (to be run every night at midnight)
"""
self.data = self.get_data()
self.state_cases = self.get_cases_trend()
self.state_hospitals = self.get_hospital_capacity()
self.state_tests = self.get_test_trend()
def upload_data_or_ema... | The code initializes a class to automate daily collection and uploading of U.S. COVID-19 data from a GitHub URL. It schedules `set_data()` to fetch data at 00:01 and `upload_data_or_email()` to handle uploads or emails at 00:02, then starts the automated tasks. The main task is to periodically retrieve and transmit COV... | def __init__(self):
self.data_url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports_us/{}.csv"
self.set_data()
print("Script is now running. Waiting to collect and upload data...")
self.upload_data_or_email()
sche... |
def build_cnf(data):
allVarsList = list(data['events'])
allVarsList.sort()
allVars = {el[1]: el[0] for el in enumerate(allVarsList)}
cnf = set()
notCnf = set()
for row in product('01', repeat=len(allVarsList)):
flag = 0
for fact in data['facts']:
if row[allVars[fact]] == '0':
cnf.add(''.join(row))
... | The main task of the code is to analyze logical variables in a CNF structure derived from input data, iteratively resolve undefined variables by assuming they are false, and determine the truth values of queries based on facts and events. It processes variable relationships, updates constraints, and outputs query resul... | def analyze_problem(data):
# print(data)
cnf, notCnf, allVars = build_cnf(data)
result, undefVars = analyzeVars(cnf, allVars, data['events'].difference(data['facts']))
varsInfo = (list(data["left_side"].difference(data["right_side"])) +
list(data["left_side"].intersection(data["right_side"])) +
list(data["right... |
def build_df(vars_list):
df = pd.DataFrame(columns=vars_list)
for num in range(2 ** len(vars_list)):
tmp = str(bin(num))[2:]
row = '0' * (len(vars_list) - len(tmp)) + tmp
df.loc[num] = list(row)
df = df.apply(pd.to_numeric)
return df
def compute_values_for_rule(rule, df, length):
res_col = list()
for i in r... | The function processes a logical rule by extracting relevant variables, constructing a dataframe, computing its CNF representation, and returning either a full CNF structure or a set of binary-encoded integer results based on variable list lengths. | def process_rule(rule, all_vars_list, data):
# print(rule)
vars_list = set(rule)
for operand in operands:
if operand in vars_list:
vars_list.remove(operand)
vars_list = list(vars_list)
# print(vars_list)
df = build_df(vars_list if len(vars_list) < len(all_vars_list) else all_vars_list)
# print(df)
cnf_df =... |
def Gaussian_smooth(self, img = [], k_size = [3, 3], sigma = 3):
if len(img) == 0:
raise Exception('Image input of Gaussian_Smooth cannot be null')
if k_size[0]%2 == 0 or k_size[1]%2 == 0:
print('kernel size is supposed to be odd number')
img_h = len(img)
... | The code performs edge detection on an image by applying Gaussian smoothing, computing image gradients, thresholding, non-maximum suppression, filtering into low/high resolution components, and edge linking to produce final edges. | def Forward(self, img = [], kernel = [3, 3], sigma = 3):
img = self.Gaussian_smooth(img, kernel, sigma)
mag, direct = self.Image_gradient(np.copy(img))
threshold = self.Find_threshold(mag, self.threshold)
NMS_mag = self.Suppress_Nonmaxima(np.copy(mag), direct, self.gmode)
low_res... |
def Buildfreq(self, img = [], S_table = []):
if len(img) == 0:
img = np.copy(self._img)
if len(S_table) == 0:
S_table = self.S_table
for i in range(self.height):
for j in range(self.width):
S_table[img[i][j][0]] += 1
return... | The code processes an input image and frequency table through projection, histogram visualization, optional plane fitting, and lighting correction. It returns the modified image, fitted plane, and lighting-adjusted outputs, with conditional steps based on parameters like 'fit' and 'plane_mode' | def Forward(self, img = [], S_table = [], fit = False, plane_mode = False, process_mode = 3, res_dir = None):
if len(img) == 0:
img = np.copy(self._img)
if len(S_table) == 0:
S_table = self.S_table
plane = []
scaled = []
truncated = []
S_table = s... |
def Sequential(self, img):
for i in range(self.height):
for j in range(self.width):
if img[i][j][0] > 0:
if i == 0 and j == 0 :
self.Label(0, 0, [i, j])
elif i == 0 and j != 0:
self.Label(img[i][j... | The code processes an image through a series of steps: rearranging tables, building and filtering connection tables based on a threshold, and relabeling the image using the filtered tables. The main task is to apply a threshold-based filtering and relabeling operation to an image using predefined tables, returning the ... | def Filter_forward(self, threshold):
img = self.Sequential(self.img)
self.E_table = self.Rearrangeetable(self.E_table)
C_t = self.Buildctable(self.E_table, self.C_table)
C_t2 = self.Size_filter(threshold, self.E_table, self.C_table)
img = self.Relabel(img, self.E_table, C_t2)
... |
def Sequential(self, img):
for i in range(self.height):
for j in range(self.width):
if img[i][j][0] > 0:
if i == 0 and j == 0 :
self.Label(0, 0, [i, j])
elif i == 0 and j != 0:
self.Label(img[i][j... | The main task of the code is to process an input image through a series of transformations: applying a sequential model, rearranging an E_table, building a C_table, relabeling the image based on these tables, and returning the modified image. This likely represents a forward pass in a custom neural network or data proc... | def Forward(self):
img = self.Sequential(self.img)
self.E_table = self.Rearrangeetable(self.E_table)
C_t = self.Buildctable(self.E_table, self.C_table)
img = self.Relabel(img, self.E_table, C_t)
return img |
def draw_morse_code(display_surface: pygame.Surface, letter: str) -> None:
"""Draws the morse code representation of a letter onto a surface
Args:
display_surface (pygame.Surface): main game surface.
letter (str): self-explanatory.
"""
sequence = MORSE_CODE[letter.upper()]
# Offset ... | This function initializes and runs a game loop where players guess letters based on Morse code displays. It tracks score, lives, and handles user input for correct/incorrect guesses, updating the screen accordingly. A cheat button triggers a cheat screen, and game over is triggered when lives reach zero, resetting the ... | def use_game_screen(
display_surface: pygame.Surface,
fps_clock: pygame.time.Clock,
background_color: Color = Color(255, 255, 255),
) -> None:
"""Main game screen, initializes all needed variables and runs the main game loop.
Args:
display_surface (pygame.Surface): main game surface.
... |
def initialize_pygame(
width: int, height: int, caption: str
) -> Tuple[pygame.Surface, pygame.time.Clock]:
"""Initialize pygame and create a pygame display surface and a clock for controlling the FPS
Args:
width (int): width of display surface
height (int): height of display surface
... | The main task of the code is to initialize and run a Morse Code application using Pygame. It sets up a window with specified dimensions and title, then sequentially displays a start screen, instructions screen, and game screen through respective functions. The program structure organizes the application flow, handling ... | def main() -> None:
window_height = 600
window_width = 960
caption = "Morse Code"
display_surface, fps_clock = initialize_pygame(window_width, window_height, caption)
use_start_screen(display_surface, fps_clock)
use_instructions_screen(display_surface, fps_clock)
use_game_screen(display_sur... |
def fernet_encrypt_noninterractive(file_path):
password = sys.argv[4]
password = str.encode(password)
baseSalt = b'\xbf\xe2\xd1\xaf\xbc\xb1\xdd\x82\xe2\xaf\xbc\xdd\x27\xd9\x82\xbf\x61\x62'
userSalt = sys.argv[5]
userSalt = str.encode(userSalt)
finalSalt = userSalt + baseSalt
over_write_or_ne... | The code encrypts a file using AES256, Fernet, or NSA encryption based on command-line arguments or user input. It checks the number of arguments and the third parameter to select the method. If arguments are insufficient or invalid, it prompts the user to choose an encryption type, validates the input, and applies the... | def encrypt(file_path):
if(len(sys.argv) >= 6 and sys.argv[3] == "fernet" ):
fernet_encrypt_noninterractive(file_path)
elif(len(sys.argv) >= 6 and sys.argv[3] == "aes256" ):
aes_encrypt_noninterractive(file_path)
elif(len(sys.argv) >= 6 and sys.argv[3] == "nsa" ):
nsa_enc... |
def fernet_decrypt_noninterractive(file_path):
password = sys.argv[4]
password = str.encode(password)
baseSalt = b'\xbf\xe2\xd1\xaf\xbc\xb1\xdd\x82\xe2\xaf\xbc\xdd\x27\xd9\x82\xbf\x61\x62'
userSalt = sys.argv[5]
userSalt = str.encode(userSalt)
finalSalt = userSalt + baseSalt
kdf = PBKDF2HMA... | The main task of the code is to decrypt a file using specified encryption methods (Fernet, AES256, or NSA) based on command-line arguments or user input. It checks the encryption type via sys.argv or prompts the user to select one, then invokes the corresponding non-interactive or interactive decryption function depend... | def decrypt(file_path):
if(len(sys.argv) >= 6 and sys.argv[3] == "fernet"):
fernet_decrypt_noninterractive(file_path)
elif(len(sys.argv) >= 6 and sys.argv[3] == "aes256"):
aes_decrypt_noninterractive(file_path)
elif(len(sys.argv) >= 6 and sys.argv[3] == "nsa"):
nsa_decrypt_noninterra... |
def encrypt(file_path):
if(len(sys.argv) >= 6 and sys.argv[3] == "fernet" ):
fernet_encrypt_noninterractive(file_path)
elif(len(sys.argv) >= 6 and sys.argv[3] == "aes256" ):
aes_encrypt_noninterractive(file_path)
elif(len(sys.argv) >= 6 and sys.argv[3] == "nsa" ):
nsa_enc... | This function determines the operation to perform based on the input flag and file path, executing tasks such as encryption, decryption, steganography, password change, help display, file destruction, or file movement by calling corresponding functions like encrypt(), decrypt(), stenography_encrypt(), etc. | def arguments(flag, file_path):
if( flag == "-e"):
encrypt(file_path)
if( flag == "-d"):
decrypt(file_path)
if( flag == "-se"):
stenography_encrypt(file_path)
if( flag == "-sd"):
stenography_decrypt(file_path)
if( flag == "-c"):
change_pass(file_path)
if( ... |
def check_params(numb_args):
if numb_args == 3:
return True
elif numb_args < 2 :
print("Incorrect arguments. Correct ussage: py main.py <-flag> <file name or path to file>")
return False
elif numb_args >= 6 :
return True
elif numb_args == 2 and sys.argv[1]== "-h":
... | The main task of the code is to validate command-line parameters, check if specified files exist, and execute a function with the provided file arguments. If parameters are invalid, the program exits with an error code. | def main():
if check_params(len(sys.argv)):
check_if_file_exists(sys.argv[1], sys.argv[2])
arguments(sys.argv[1], sys.argv[2])
else:
exit(1) |
def bubble_sort(a):
"""
Sorts a list using the bubble sort method.
"""
for n_pass in range(len(a)-1, 0, -1):
for i in range(n_pass):
# Swap elements
if (a[i] > a[i+1]):
a[i+1], a[i] = a[i], a[i+1]
def short_bubble_sort(a):
"""
Sorts a list using ... | This function sorts a list or array using a specified algorithm (e.g., bubble, merge, quick) and returns both the sorted data and an index array mapping original positions to sorted positions. It supports ascending/descending order and allows parameter customization for certain algorithms like shell or quick sort. | def sort(data, method='merge', descending=False, param=None):
"""
Sorts a list or array using the specified method. Returns also the index
array.
"""
# Make a copy
a = data.copy()
# Sort (in place) the list
if (method == 'bubble'):
bubble_sort(a)
elif (method == 'short_bubb... |
def create_scenario(self):
candidate_area = copy.deepcopy(self.free_area)
candidate_area_idx = copy.deepcopy(self.free_area_idx)
candi_h, candi_w = self.sample_navigable_position(candidate_area)
candi_idx = candidate_area_idx[candi_h, candi_w]
agent_pose = [candi_h, cand... | The `reset` method initializes the environment by resetting time, agent state, and world state. It loads a scenario (or generates one), updates landmark positions, calculates Euclidean and geographic distances between the agent and landmarks, updates GPS data, and resets reward and collision counters to prepare for a n... | def reset(self, scenario=None):
self.time_t = 0
self.world_state[:,:,1] = 0
if scenario is None:
scenario = self.create_scenario()
self.scenario = {'agent': np.array(scenario['agent']),
'landmark pose': np.array(scenario['landmark pose']),
... |
def getSeriesPathsAndMasterNumb(files_df,files_df_origFolds, currentSeries,masterolds_in_Study):
"""
get list of paths in original data - There may be still duplicates in output !!!
apart from it we will get the master number associated to this series
Also it will give back the proper name of the modali... | The function generates 3D medical image files (MHA/NII) for a single series from a specialist annotator, processing DICOM paths, saving the main MRI volume, and creating annotated label files. It filters anatomical labels, handles lesion annotations per doctor, applies corrections, and returns study details, volume pat... | def mainGenereteFiles(files_df,files_df_origFolds,annot_for_series,files_for_series,currentSeries,current_study_id,mainPaths_studyId,masterolds_in_Study
,jsonFolder,corrections_for_study_id,pureMasterNum):
"""
main functions that gives single series of single annotator specialist
will create files with 3d m... |
def _run_task(self):
if self._task:
c_millis = time.ticks_ms()
if c_millis - self._task_millis >= self._task_period:
self._task_millis += self._task_period
self._task()
def _close(self, emsg=None):
self.conn.close()
self.state = DISCONNECTE... | The code initializes and manages a connection to a Blynk server, handling authentication, message exchange, and state transitions. It establishes TCP/SSL connections, sends login tokens, processes responses, manages hardware pins, and maintains heartbeat intervals. The loop handles data reception, error recovery, watch... | def run(self):
self._start_time = time.ticks_ms()
self._task_millis = self._start_time
self._hw_pins = {}
self._rx_data = b''
self._msg_id = 1
self._pins_configured = False
self._timeout = None
self._tx_count = 0
self._m_time = 0
self.state... |
def pre_process_image(img, skip_dilate=False):
proc = cv2.GaussianBlur(img.copy(), (5, 5), 0)
proc = cv2.adaptiveThreshold(
proc, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2
)
proc = cv2.bitwise_not(proc, proc)
if not skip_dilate:
kernel = np.array([[0.0, 1.0, 0.0]... | The main task of the code is to process a Sudoku image by detecting its grid, warping it for clarity, extracting individual digits, and saving the processed image with identified digits arranged in a puzzle grid. It reads an input image, preprocesses it, identifies the Sudoku grid's corners, crops and warps the grid, s... | def process_image(original_image, save_image, processed_image, puzzle_size):
original = cv2.imread(original_image, cv2.IMREAD_GRAYSCALE)
processed = pre_process_image(original)
corners = find_corners_of_largest_polygon(processed)
cropped = crop_and_warp(original, corners)
save_warped_image(cropped,... |
def search_cell(cell_name):
print("search_cell ",cell_name)
queryset = Hexlandcell.objects.filter(name=cell_name).values('name', 'is_affected','row','col')
# cell_x = Hexlandcell.objects.raw('SELECT row FROM app_hexlandcell where name="'+cell_name+'"')
print("cell_x ", queryset.get())
src_x = queryset.get()['row']... | The main task of the code is to handle HTTP POST requests for searching, inserting, or removing hexagonal grid cells (Hexlandcell) based on user input. It processes form data, validates inputs (e.g., border range), interacts with the database, constructs a grid representation, and renders the updated grid along with st... | def home(request):
# return HttpResponse('Hello, World!')
message=""
if request.method=="POST":
query_type = request.POST['query_type']
name = request.POST['name']
query_set = Hexlandcell.objects.filter(name=name).values('name', 'is_affected','row','col')
if not query_set:
message = ["Incorrect Cell Name"... |
def elevation_tile_path(self) -> str:
elevation_tiles_dir = "tile_data"
path = os.path.join(elevation_tiles_dir, f"elevation_{self.tile_key()}.png")
return path
def download_elevation(self):
# https://docs.mapbox.com/help/troubleshooting/access-elevation-data/
base_url = "https:/... | The code loads or downloads elevation data, generates geographic coordinate grids (x, y) based on the bounding box, and returns the grids along with the elevation values. It ensures the elevation file exists, reads the data, computes spatial coordinates, and logs elevation range for validation. | def elevation(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
if not os.path.isfile(self.elevation_tile_path()):
self.download_elevation()
e = self.elevation_from_file()
nx, ny = e.shape
p0 = self.bl()
p1 = self.ur()
x = np.linspace(start=p0.longitude, sto... |
def static_tile_path(self, style_id: str, tilesize: int):
elevation_tiles_dir = "tile_data"
path = os.path.join(elevation_tiles_dir, f"{style_id}_{self.tile_key()}_{tilesize}.jpeg")
return path
def download_static_tile(self, style_id: str, tilesize: int = 512):
"""
Download and s... | This function retrieves a static tile image for a given style. It checks if the tile file exists, downloads it if missing, loads the image from the file, logs its dimensions, and returns the image. | def static_tile(self, style_id: str, tilesize: int = 512) -> Image:
if not os.path.isfile(self.static_tile_path(style_id, tilesize)):
self.download_static_tile(style_id, tilesize)
im = self.static_tile_from_file(style_id, tilesize)
logging.info(f"static tile {style_id} {im.width}*{im... |
def head(self):
self.view.fill(C64Colors.BACKGROUND.as_tuple())
self._write_capital_b_at((5, 5))
self._write_ascii_at("OUNCE IN THE SPACE", (8, 9))
self._write_ascii_at("WRITTEN BY ATHOS TONIOLO", (5, 20))
# UI
coords = 35, 0
play8.screen64_printall(
... | The code defines a `play` method that enters an infinite loop. It repeatedly calls `self.head()`, checks the result of `self.body()`, and if `self.body()` returns a truthy value, it invokes `self.tail()`. The loop continues indefinitely unless `self.body()` eventually returns a falsy value, which would terminate the lo... | def play(self):
while True:
self.head()
if self.body():
self.tail() |
def _validate_parameters(self):
if not (0.0 <= self.correlation_threshold <= 1.0):
raise ValueError("correlation_threshold must be >= 0.0 and <= 1.0, got {}".format(self.correlation_threshold))
if self.min_cols < 3:
raise ValueError("min_cols must be >= 3, got {}".format(self.mi... | The main task of the code is to compute biclustering by iterating over all row pairs, identifying columns with high correlation between each pair, expanding row sets if additional rows meet criteria, and collecting unique biclusters defined by row and column subsets. The result is a Biclustering object containing all v... | def run(self, data):
"""Compute biclustering.
Parameters
----------
data : numpy.ndarray
"""
data = check_array(data, dtype=np.double, copy=True)
self._validate_parameters()
num_rows, num_cols = data.shape
biclusters = []
for i, j in com... |
def _general_model_(nrows, ncols,
nclusts, nclustrows, nclustcols,
noverlap_rows, noverlap_cols,
colbase, rowshift, rowscale,
background_generator):
"""
Make a dataset, given appropriate parameters.
If rows or columns do not ov... | This function generates synthetic data matrices with biclusters by applying a model, adding noise, and optionally shuffling. It creates a data matrix and expected bicluster structure, incorporating background noise, cluster-specific noise, and overlap parameters. The output includes the noisy data and corresponding exp... | def _make_data_(nrows, ncols, nclusts,
noverlap_rows, noverlap_cols,
colbase, rowshift, rowscale,
noise, nclustrows=None, nclustcols=None, bicluster_noise=None,
background_loc=0, background_scale=1, shuffle=False,
dist=improper_normal):
... |
def _validate_parameters(self):
if not (0.0 <= self.correlation_threshold <= 1.0):
raise ValueError("correlation_threshold must be >= 0.0 and <= 1.0, got {}".format(self.correlation_threshold))
if self.min_cols < 3:
raise ValueError("min_cols must be >= 3, got {}".format(self.mi... | The main task of the code is to perform encrypted biclustering on a dataset using homomorphic encryption (CKKS scheme). It initializes a Pyfhel object, encrypts the input data, and identifies biclusters by comparing row pairs for correlated columns. Valid biclusters are formed by aggregating rows that maintain the corr... | def run(self):
"""Compute biclustering.
Parameters
----------
"""
# Creating empty Pyfhel object
HE = Pyfhel()
ckks_params = {
'scheme': 'CKKS',
'n': 2 ** 15,
'scale': 2 ** 30,
'qi_sizes': [60] + 15 * [30]... |
def _set_defaults_(nrows,
ncols,
nclusts,
nclustrows,
nclustcols,
bicluster_noise):
if nclustrows is None:
nclustrows = divmod(nrows, nclusts)[0]
if nclustrows == nrows:
nclustrows = int(nrows ... | This function generates a synthetic dataset containing constant-value biclusters (submatrices with uniform values) by combining background noise, bicluster signals, and optional overlaps. It creates a 2D numpy array with specified dimensions, cluster configurations, and noise parameters, while returning both the genera... | def make_const_data(nrows=300, ncols=50,
nclusts=5, nclustrows=None, nclustcols=None,
noverlap_rows=0, noverlap_cols=0,
background_loc=0, background_scale=1,
bicluster_signals=None,
noise=0, bicluster_noise=None,
... |
def _set_defaults_(nrows,
ncols,
nclusts,
nclustrows,
nclustcols,
bicluster_noise):
if nclustrows is None:
nclustrows = divmod(nrows, nclusts)[0]
if nclustrows == nrows:
nclustrows = int(nrows ... | The function generates a synthetic dataset with additive biclusters, allowing customizable parameters like cluster count, overlaps, noise, and distributions. It creates a matrix where specified biclusters have shifted values, superimposed on a background, for tasks like bicluster detection testing. | def make_shift_data(nrows=300, ncols=50,
nclusts=5, nclustrows=None, nclustcols=None,
noverlap_rows=0, noverlap_cols=0,
background_loc=0, background_scale=1,
base_loc=0, base_scale=1,
shift_loc=0, shift_scale=1,
... |
def _set_defaults_(nrows,
ncols,
nclusts,
nclustrows,
nclustcols,
bicluster_noise):
if nclustrows is None:
nclustrows = divmod(nrows, nclusts)[0]
if nclustrows == nrows:
nclustrows = int(nrows ... | The function `make_scale_data` generates synthetic datasets with multiplicative biclusters, combining base values, shifts, scales, overlaps, and noise. It creates a matrix with specified rows/columns, clusters, and overlaps, applying distributions for background, base, and scale parameters. Biclusters are formed by mul... | def make_scale_data(nrows=300, ncols=50,
nclusts=5, nclustrows=None, nclustcols=None,
noverlap_rows=0, noverlap_cols=0,
background_loc=0, background_scale=1,
base_loc=0, base_scale=1,
scale_loc=0, scale_scale=1,
... |
def _set_defaults_(nrows,
ncols,
nclusts,
nclustrows,
nclustcols,
bicluster_noise):
if nclustrows is None:
nclustrows = divmod(nrows, nclusts)[0]
if nclustrows == nrows:
nclustrows = int(nrows ... | The function generates a synthetic dataset with shift-scale biclusters, allowing customizable row/column overlaps, noise, and distribution parameters. It creates structured patterns by combining base values, row shifts, column scales, and background noise, returning a matrix with specified bicluster configurations. | def make_shift_scale_data(nrows=300, ncols=50,
nclusts=3, nclustrows=None, nclustcols=None,
noverlap_rows=0, noverlap_cols=0,
background_loc=0, background_scale=1,
base_loc=0, base_scale=1,
... |
def supervised_metric(self):
load_data, random_instances, train_ds = self.get_data_loader()
trainer = pl.Trainer(
max_epochs=self.max_epochs,
enable_progress_bar=False,
enable_model_summary=False,
gpus=1
)
model = pt.models.glvq.GMLVQ(
... | The function determines the index of the active instance by calculating the minimum relative distances from a supervised metric. Depending on whether the instance is near a boundary (`self.close_to_boundary`), it selects the top-p closest instances using either `get_top_p_close` (for boundary proximity) or `get_top_p` ... | def get_active_instance_index(self):
relative_distance_space = self.supervised_metric()[0]
min_relative_distance = [
torch.min(distance) for distance in relative_distance_space
]
if self.close_to_boundary:
return self.get_top_p_close(min_relative_distance)
... |
def get_active_instance_index(self):
relative_distance_space = self.supervised_metric()[0]
min_relative_distance = [
torch.min(distance) for distance in relative_distance_space
]
if self.close_to_boundary:
return self.get_top_p_close(min_relative_distance)
... | This function selects active learning instances iteratively by appending indices from get_active_instance_index() until learned components stabilize. It checks stability using compute_learned_components_stability() after exceeding warm_start iterations, returning selected indices as a numpy array for model training. | def select_active_learned_instances(self):
should_continue = True
selected_instances, learned_components_list, count = [], [], -1
while should_continue:
count += 1
selected_instances.append(self.get_active_instance_index())
learned_components_list.append(self.... |
def get_active_instance_index(self, x):
if self.task == 'binary':
return self.select_minimum_instance_binary(x)
return self.select_minimum_instance(x)
def compute_support_vector_ratio(self, support_vec, support_vec_list):
if self.task == 'binary':
return support_vec_list.... | The function selects instances using active learning by iteratively appending indices from `get_active_instance_index`, evaluates support vector stability, and stops when stability is achieved after a warm-up period, returning the list of selected instance indices. | def select_active_learned_instances(self):
should_continue = True
selected_instances, support_vector_list, count = [], [], -1
while should_continue:
count += 1
selected_instances.append(self.get_active_instance_index(0))
self.compute_support_vector_ratio(self.... |
def get_users():
config = configparser.ConfigParser()
config.read('integrations.ini')
url = config['openproject']['url']
apikey = config['openproject']['apikey']
endpoint = url + 'api/v3/users'
session = requests.Session()
session.auth = ('apikey', apikey)
auth = session.post(endpoint... | The main task of the code is to synchronize user data between a core user list and Openproject. It identifies users that should exist in Openproject (from the core list) and compares them with currently active users in Openproject. The code creates new users in Openproject for emails in the core list not present in Ope... | def integrate_users(core_users):
core_users_data = core_users['users']
openproject_active_users = get_users()
#Obtain all the users that are currently in Openproject
openproject_source_users = []
for user in openproject_active_users:
openproject_source_users.append(user['email'])
... |
def authenticate():
global auth_token
config = configparser.ConfigParser()
config.read('integrations.ini')
url = config['mattermost']['url']
user = config['mattermost']['user']
password = config['mattermost']['password']
endpoint = url + 'api/v4/users/login'
payload = {"login_id"... | This function synchronizes Mattermost users with a core user list by creating new users, removing obsolete ones, and refreshing existing accounts. It excludes default users, compares active Mattermost users against core data, and ensures alignment through creation, deletion, and updates. | def integrate_users(core_users):
with yaspin(text="Processing Mattermost users", color="yellow") as spinner:
authenticate()
result=''
# Default users needed in mattermost to work
mattermost_default_users = [
'appsbot',
'boards',
'channelexport',
... |
def get_users():
config = configparser.ConfigParser()
config.read('integrations.ini')
token = config['wikijs']['apikey']
endpoint = config['wikijs']['url'] + 'graphql/'
headers = {
'Authorization': 'Bearer ' + token
}
transport = AIOHTTPTransport(url=endpoint, headers=headers)
... | The code synchronizes users in a Wiki.js system with a core user list. It identifies users to add (from core_users not in Wiki.js) and removes users no longer needed (in Wiki.js but missing from core_users). It creates new users using their full data and deletes obsolete ones, printing status updates for each action. | def integrate_users(core_users):
wikijs_active_users = get_users()
#Obtain all the users that are currently in wikijs
wikijs_source_users = []
for user in wikijs_active_users:
wikijs_source_users.append(user['email'])
#Obtain all the users that should be in wikijs (in file)
wikijs... |
def authenticate():
global auth_token
config = configparser.ConfigParser()
config.read('integrations.ini')
auth_token = config['netlify']['apikey']
def get_users():
global auth_token
config = configparser.ConfigParser()
config.read('integrations.ini')
url = config['netlify']['url']
... | The code synchronizes Netlify users with a core user list by identifying discrepancies. It creates users in Netlify if they exist in the core list but not in Netlify, removes Netlify users no longer in the core list, and refreshes existing users. This ensures alignment between Netlify's user database and the central us... | def integrate_users(core_users):
authenticate()
netlify_active_users = get_users()
netlify_source_users = []
for user in netlify_active_users:
netlify_source_users.append(user['email'])
#Obtain all the users that should be in netlify (in file)
netlify_local_users = []
for user i... |
def get_users():
jwt = authenticate()
config = configparser.ConfigParser()
config.read('integrations.ini')
url = config['portainer']['url']
endpoint = url + 'api/users'
payload = {}
headers = {
'Authorization': 'Bearer ' + jwt
}
response = requests.request("GET",endpoi... | The main task of the code is to synchronize Portainer user accounts with a provided list of users from an external source. It identifies users to create (present in the external list but missing in Portainer) and users to remove (present in Portainer but absent in the external list), then executes these changes while p... | def integrate_users(core_users):
with yaspin(text="Processing Portainer users", color="yellow") as spinner:
portainer_active_users = get_users()
#Obtain all the users that are currently in Portainer
portainer_source_users = []
for user in portainer_active_users:
po... |
def fetch_instructions(self):
""" Get and save instructions from GUI thread:
config: New config struct for FPGA
config_change: Config struct changed, request to send (could easily optimise out)
record request: First request from GUI, initiates shared memory setup and handsha... | The main task of the code is to handle background operations in a loop, checking for instructions to either update FPGA configurations, initiate recordings, or trigger data capture. It logs debug information to a file, manages state variables (config_change, record_request, trigger), and sends settings to an FPGA devic... | def backgroundThread(self): # retrieve data
"""
"""
#Set up socketlog.log debug log
logging.basicConfig(filename='socketlog.log',
level=logging.DEBUG,
format='%(asctime)s %(message)s',
datefmt='%m... |
def __has(self, t):
"""
Return true if t matches the current token.
"""
ct = self.__lexer.get_tok()
return ct.token == t
def __next(self):
"""
Advance the lexer.
"""
self.__lexer.next()
def __bounds(self):
self.__must_be(Token.INTLIT)
self.__next()
if self... | This method parses a declaration by checking for an opening bracket token (LBRACK). If found, it consumes the token and processes bounds; otherwise, it simply advances to the next token, handling both array and non-array declaration cases. | def __decl(self):
if self.__has(Token.LBRACK):
self.__next()
self.__bounds()
else:
self.__next() |
def skip_space_and_comments(self):
while self.__cur_char.isspace() or self.__cur_char == '#':
if self.__cur_char == '#':
# consume the rest of the line
while self.__cur_char and self.__cur_char != '\n':
self.consume()
# consume all the... | The main task of the code is to tokenize input by skipping whitespace/comments, then attempting to lex single-character, multi-fixed, or other tokens. If no valid token is found, it returns an invalid token after consuming the current character. | def next(self):
self.skip_space_and_comments()
if not self.__cur_char:
self.__tok = self.__create_tok(Token.EOF)
return self.__tok
elif self.__lex_single():
return self.__tok
elif self.__lex_multi_fixed():
return self.__tok
elif se... |
def hasSpecialAA():
return len(aminoAcidTreeColorMap) > 0
def hasTaxa():
return len(taxonColorMap) > 0
def addSupportValues(node):
# If internal node, draws label with smaller font size
if node.name == "":
name_face = TextFace(" ", fsize=10)
else:
color = getSupportOverThresholdColor(node.name)
name_fa... | This function customizes the visual layout of a tree node in a phylogenetic tree. For leaf nodes, it adds annotations like special amino acids, taxon names, node names, and clade labels with specific colors and formatting. For internal nodes, it adds support values and applies a collapsed layout if descendants are not ... | def fullTreeLayout(node):
if node.is_leaf():
columnNum = 0
if hasSpecialAA():
if hasattr(node, 'specialAA'):
aa_face = TextFace(node.specialAA)
aa_face.background.color = aminoAcidTreeColorMap[node.specialAA].color
else:
aa_face = TextFace(" ")
aa_face.background.color = "Black"
aa_face.... |
def collapsedLeafLayout(node, pos):
columnNum = 0
# If terminal node, draws it name
if node.name == "":
name_face = TextFace(" ")
else:
name_face = AttrFace("name", text_prefix=" ", text_suffix=" ")
name_face.margin_top = -2
# Add the name face to the image at the preferred position
node.add_face(name_fac... | This function determines the layout for a tree node, applying collapsed leaf layout if the node is a leaf, or collapsed internal node layout if descendants are not drawn, while adding support values in both cases. It uses "branch-right" positioning and conditionally invokes layout functions based on node type and styli... | def collapsedTreeLayout(node):
# alinged makes some trouble with single branches
pos = "branch-right"
if node.is_leaf():
collapsedLeafLayout(node, pos)
elif not node.img_style["draw_descendants"]:
# Technically this is an internal node
addSupportValues(node)
collapsedNodeLayout(node, 0, -2, pos)
else:
ad... |
def train_val_split(dataset, split=0.20):
# Creating data indices for training and validation splits:
dataset_size = len(dataset)
indices = list(range(dataset_size))
split = int(np.floor(split * dataset_size))
# shuffle
np.random.shuffle(indices)
train_indices, val_indices = indices[split:],... | This function trains a domain adaptation model on the source domain using a feature extractor (netF), bottleneck (netB), and classifier (netC). It incorporates domain embeddings during training, evaluates performance on source validation data, and saves the best model. Finally, it tests the model on the target domain a... | def train_source(args):
# dset_loaders = data_load(args)
dset_loaders = {}
args.class_num, train_source_dataset, train_target_loader = setup_datasets(args, return_dataset=True)
train_source_loader, val_source_loader = train_val_split(train_source_dataset, split=0.15)
dset_loaders["source_tr"] = tr... |
def _return_current_config(self) -> Tuple[str, str]:
key, value = "".join(self._current_key), "".join(self._current_value)
self._reset_state()
return key.rstrip(), value.rstrip()
def _process_initial(self, char):
if self.state != STATE_INITIAL:
return False
if self._... | The main task of the code is to parse configuration key-value pairs from a character stream, handling quotes, comments, escaping, and parsing logic. It iteratively reads characters, processes them through helper methods, and yields parsed tuples of (key, value) when complete, continuing until the stream ends. | def parse_config(self) -> Iterator[Tuple[str, str]]:
key = self._current_key
value = self._current_value
while True:
char = self._stream.read_char()
if not char:
if key or value:
yield self._return_current_config()
brea... |
def add_block(self, block, x=4, y=0):
block.set_pos([x, y])
self.current_block = block
try:
self.update()
except:
self.running = False
def notify_new_block(self):
for view in self.views:
view.draw_next_block()
def generate_bag(self):
ra... | The main task of the code is to process the next block by popping the last element from the bag, adding it as a new block, notifying of the addition, and generating a new bag if the current bag has fewer than 6 items. This ensures a continuous supply of blocks while maintaining the bag's minimum size. | def next_block(self):
self.add_block(self.bag.pop())
self.notify_new_block()
if len(self.bag) < 6:
self.generate_bag() |
def clear_block(self, board, pos, shape):
for i in range(len(shape)):
for j in range(len(shape[0])):
if board[i+pos[1]][j+pos[0]][0] - shape[i][j] < 0:
raise ValueError
if shape[i][j] == 1:
board[i+pos[1]][j+pos[0]] = [0, (15, 1... | This function handles holding a game piece. If holding is allowed, it clears the current block's position, swaps it with the previously held piece (if any), or stores it if no prior hold exists. It then updates the held piece status and disables further holding until the next action.)> | def hold_piece(self):
if not self.able_to_hold:
return
self.clear_block(self.board, self.current_block.pos, self.current_block.shape)
if self.held_piece != 0:
former_held = self.held_piece
self.held_piece = self.current_block
self.add_block(former_... |
def test_update(self, prev_pos=False, prev_shape=False):
test_board = deepcopy(self.board)
if prev_pos or prev_shape:
self.clear_block(test_board, prev_pos, prev_shape)
if self.current_block:
self.place_current_block(test_board)
def update(self, prev_pos=False, prev_sha... | The code's main task is to drop a block as far down as possible in a grid-based game (e.g., Tetris), checking for collisions. It saves the block's initial position and shape, repeatedly attempts to move the block down, and reverts the position if a collision occurs. Once the block can no longer move down, it finalizes ... | def drop(self):
prev_pos = deepcopy(self.current_block.get_pos())
prev_shape = deepcopy(self.current_block.get_shape())
self.current_block.move_down()
while True:
try:
self.test_update(prev_pos, prev_shape)
except:
self.current_bloc... |
def add_widgets_to_tab1(self):
# Widgets for the first tab
# self.label1 = ttk.Label(self.tab1, text='Content for Tab 1')
# self.label1.grid(row=0, column=0, padx=10, pady=10)
self.setup_ui(self.tab1)
def add_widgets_to_tab2(self):
# self.add_player_ui(self.tab2)
# self... | The main task of the code is to create a GUI tabbed interface using ttk.Notebook, initializing five tabs (All info, Add players, Add matches, Player scores, No bitches) and adding corresponding widgets to each via separate methods, then arranging the notebook in a grid layout for the application's main interface. | def create_tabs(self):
self.notebook = ttk.Notebook(self.master)
self.tab1 = ttk.Frame(self.notebook)
self.tab2 = ttk.Frame(self.notebook)
self.tab3 = ttk.Frame(self.notebook)
self.tab4 = ttk.Frame(self.notebook)
self.tab5 = ttk.Frame(self.notebook)
self.notebook.... |
def paymentDone(show_page):
simulate_success_btn.grid_remove()
simulate_error_btn.grid_remove()
done_text.grid()
time.sleep(0.5)
if(getState("current-ticket-Type")=="IF"):
schedule = FerrySchedule(getState("current-port"))
schedule.decrement_seats_by_value(getState("IF-ticket-time"... | The code creates a Tkinter-based payment interface GUI with an image banner, payment details display, simulate payment/error buttons, success/retry controls, and navigation buttons (home/help). It returns the configured frame for integration into a larger application, handling state transitions and UI updates via callb... | def payment_interface(master, show_page):
page = tk.Frame(master)
image = tk.PhotoImage(file=BANNER_IMAGE)
global show
show = show_page
# Create a label to display the image
label = tk.Label(page,image=image)
label.image = image
label.grid(row=0, column=0, columnspan=4)
# label of ... |
def load_acm(use_feat):
path = '../data/others/ACM/ACM_graph.txt'
data = np.loadtxt('../data/others/ACM/ACM.txt')
N = data.shape[0]
idx = np.array([i for i in range(N)], dtype=np.int32)
idx_map = {j: i for i, j in enumerate(idx)}
edges_unordered = np.genfromtxt(path, dtype=np.int32)
edges = ... | This function loads specified datasets (ACM, DBLP, Airports) based on the input name, converts data to sparse format if requested, sets class counts, transfers data to a specified device, and returns processed data with metadata, printing details unless quiet mode is enabled. | def load_other_dataset(
data_name: str, quiet: bool = False,
to_sparse: bool = False,
device='cpu'
):
if data_name == 'ACM':
data = load_acm(use_feat=True)
elif data_name == 'DBLP':
data = load_dblp(use_feat=True)
elif 'Airports' in data_name:
data = load_airp... |
def load_pyg_dataset(
data_name: str, quiet: bool = False,
to_sparse: bool = False,
device='cpu'
):
folder_path = '../data/PyG_data/'
path = folder_path + data_name + '/'
if data_name in ['WikiCS']:
data = WikiCS(path).data
elif data_name in ["Cornell", "Texas", "Wisconsi... | This function loads network/graph datasets based on the input name by selecting appropriate loading functions (PyG, NHB, synthetic, or other) through conditional checks. It handles parameters like `quiet`, `to_sparse`, and `device`, assigns the dataset name, and returns the loaded data object. | def load_nc_data(
data_name: str, quiet: bool = False,
to_sparse: bool = False,
device='cpu'
):
is_pyg_data = is_nhb_data = is_syn_data = is_other_data = False
if ('Twitch' in data_name) or (data_name in ['WikiCS', "Cornell", "Texas", "Wisconsin", 'Actor',
... |
def load_preprocessed_feat(
FEAT_FOLDER, feat_method, num_hops, feat_length, gp_hidden_size
):
FEAT_PATH_RW = f'{FEAT_FOLDER}/rw-{num_hops}-{feat_length[0]}.pt'
FEAT_PATH_SP = f'{FEAT_FOLDER}/sp-{num_hops}-{feat_length[1]}.pt'
FEAT_PATH_GP = f'{FEAT_FOLDER}/gp-{num_hops}-{gp_hidden_size}.pt'
if ... | The code extracts subgraph features for each node in a graph up to a specified number of hops, using methods like random walks, shortest paths, and graph propagation. It processes data sequentially or in parallel, saves/preloads features, and returns a dataset of subgraph representations for each node. | def extract_sub_hop_graph(
data, num_hops, feat_method, feat_length: tuple = (3, 3), parallel: bool = False,
n_worker: int = 8, gp_hidden_size: int = 32,
):
data_name = data.name
# if 'products-' in data.name:
# name = data_name.split('products-')[1]
# FEAT_FOLDER = f'../data/pre... |
def _get_data_format(self, data):
"""Return Data Format"""
if data[7] == 0x7FFF:
return None
return data[7]
def _get_mac(self, data):
return ':'.join('{:02x}'.format(x) for x in data[25:31])
def _get_acceleration(self, data):
"""Return acceleration mG"""
if (... | This function converts Ruuvitag sensor data into a structured JSON format for IoT2Tangle. It validates the data uses 'Data Format 5', extracts temperature, humidity, pressure, acceleration, battery, and metadata, then returns a timestamped JSON payload with sensor readings. Errors trigger a fatal exit for obsolete form... | def json_i2t(self, data):
try:
byte_data = [ x for x in data ] # integer list
if ( self._get_data_format(byte_data) != 5):
print(" ERROR: One of your Ruuvitag uses the obsolete 'Data Format " +
str(self._get_data_format(byte_data)) +
... |
def preProcessHeight(dataHt):
nuDataHt = []
for index in range(len(dataHt)):
if isinstance(dataHt[index], str):
foot = int(dataHt[index][0])
inch = int(dataHt[index][2:len(dataHt[index])])
nuDataHt.append(foot*12.0+inch)
else:
nuDataHt.append(0)
... | The code performs K-means clustering on preprocessed data for varying `k` values (3, 5, 7). It first preprocesses input data by normalizing "Height" and "Weight" columns, filtering irrelevant features, and copying processed data. The `makeDiffFive()` and `designMapperIndexToDiff()` functions likely prepare data for clu... | def kMeans(data):
global DATALEN
global gk
global gi
DATALEN = len(data)
# print(DATALEN)
preProcessedData["Height"] = preProcessHeight(data["Height"]) #26
preProcessedData["Weight"] = preProcessWeight(data["Weight"]) #27
# preProcessAccordingToList(data) ##MAY REQUIRE UNCOMMENTING
a... |
def set_manual_colour(self, state, time):
self.post("stat", {"action": 14, "cswi": {state}, "ctime": {time}})
return self.status()
def post(self, path, data):
if path != "week.html":
try:
response = session.post(
BASE_URL.format(self._host, path), ... | The main task of the code is to convert input color values from millimeters to inches by dividing by 2.54, store them as integers, and send a POST request to update color channels (ch1-ch4) with these values. It also checks if manual color mode is disabled, enabling it with a timestamp, before returning the device stat... | def set(self, white, blue, red, green):
self._white = int(white / 2.54)
self._blue = int(blue / 2.54)
self._green = int(green / 2.54)
self._red = int(red / 2.54)
if self._manual_colour is False:
self.set_manual_colour("true", "01:00")
self.post(
"c... |
def get_word_embedding(self, words)->dict:
"""
This function retrieves the word embedding for the input word.
Args:
----
* words (str or list of str):
The word or list of words for which the embedding is to be retrieved.
Returns:
----
... | The main task of the code is to normalize a raw string by checking if it exists in pre-defined verified or candidate databases via vector search. If not found, it uses an LLM to generate a normalized version, updates the candidate database with the result, and returns the normalized string along with metadata. Threshol... | def normalize(self, raw_string,
threshold_verified_accept=None,
threshold_candidate_accept=None,
flush_db=False):
"""
This function is used to normalize a raw string. It checks if the raw string is already in the verified or candidates collection and if no... |
def build_sam():
checkpoint_url = CFG.SAM_MODELS[CFG.sam_type]
sam = sam_model_registry[CFG.sam_type]()
state_dict = torch.hub.load_state_dict_from_url(checkpoint_url)
sam.load_state_dict(state_dict, strict=True)
sam.to(device = CFG.device)
sam = SamPredictor(sam)
return sam
def build_ground... | This code processes an image by using GroundingDINO and SAM models to segment objects based on a text prompt, then visualizes the original and segmented images side-by-side, saving the result to a specified path. | def process_image(imape_path, output_path, text_prompt):
model_sam = build_sam()
model_groundingdino = build_groundingdino()
models = [model_groundingdino, model_sam]
image_pil = load_image(imape_path)
masks, boxes, phrases, logits = mask_predict(image_pil, text_prompt, models, box_t... |
def build_sam():
checkpoint_url = CFG.SAM_MODELS[CFG.sam_type]
sam = sam_model_registry[CFG.sam_type]()
state_dict = torch.hub.load_state_dict_from_url(checkpoint_url)
sam.load_state_dict(state_dict, strict=True)
sam.to(device = CFG.device)
sam = SamPredictor(sam)
return sam
def build_ground... | The code generates segmentation masks from an image based on a text prompt using GroundingDINO and SAM models. It loads an image, initializes two pre-built models, predicts masks with specified thresholds, and returns the original image along with the generated masks for object segmentation. | def get_segmented(imape_path, text_prompt):
model_sam = build_sam()
model_groundingdino = build_groundingdino()
models = [model_groundingdino, model_sam]
image_pil = load_image(imape_path)
masks, boxes, phrases, logits = mask_predict(image_pil, text_prompt, models, box_threshold=0.3,... |
def get_pk_columns(self, engine: Engine) -> list[str]:
"""Returns list of primary key columns."""
return list(
inspect(engine).get_pk_constraint(self.table_name)["constrained_columns"]
)
def retry_connect(self, engine: Engine) -> Connection:
"""Connects to the database, retry... | The code compares two database tables by checking schema consistency, primary keys, and partitioning. It uses SQLite engines to connect to databases, validates primary key alignment, and yields results via partitioned or full-row comparisons based on configuration and table structure. | def execute(self, task_queue: TaskQueueInterface) -> Iterator[Result]:
"""Analyze tables and their schemas."""
sp = trace.get_current_span()
sp.set_attribute("db_name", self.db_name)
sp.set_attribute("table_name", self.table_name)
if self.partition_key:
sp.set_attribu... |
def fitness(self, angs):
tmp = np.zeros((self.n_sets, 2))
for idx, _angs in enumerate(angs):
tmp[idx] = get_points(_angs, LINKS, self.ang_z)[-1]
return np.array([np.linalg.norm(np.array([i, j]) - self.target) for (i, j) in tmp])
def get_parents(self, fitness):
idx_sort_arr = ... | This code implements an evolutionary optimization algorithm. It iteratively evaluates population fitness, selects parents, applies crossover and mutation to generate offspring, updates the population, tracks the best solution, and validates the final result against target constraints. The loop runs for a specified numb... | def run(self):
history = []
for _ in range(self.iter):
fitness = self.fitness(self.curr_pos)
parents = self.get_parents(fitness)
crossover_offspring = self.crossover_2(parents)
mutation_offspring = self.mutation(crossover_offspring)
# set to ne... |
def __eliminate_outliers_categorically(self, data: DataFrame):
category_col = self.category_col
filtered_df = DataFrame({}, columns = data.columns)
for category in data[category_col].unique():
tmp_df = data[ data[category_col] == category ]
tmp_... | The main task of the code is to filter and clean input data based on predefined criteria specified in `self.filter_by`. It conditionally applies methods like outlier elimination, frequency-based filtering, or value-based restrictions to the data, then returns the processed result. The function prints status updates dur... | def clean_data(self, data):
print("Performing Data Filtering... ")
if "FILTER_OUTLIERS_CATEGORICALLY" in self.filter_by:
filtered_data = self.__eliminate_outliers_categorically(data)
elif "FILTER_OUTLIERS" in self.filter_by:
filtered_data = self... |
def get_audio():
r =sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said=""
try:
said = r.recognize_google(audio)
print("Me: " +said)
except Exception as e:
print("I couldn't hear you " + str(e))
speak(... | The code's main task is to detect a wake word in audio input, trigger a greeting function, and enter a loop for continuous chat interactions. It starts by capturing audio, checks for the wake word, and if detected, calls greetMe() and repeatedly invokes chat() for ongoing dialogue processing. | def main():
print("Start")
text = get_audio().lower()
if text.count(WAKE) > 0:
greetMe()
# remind.read_reminder()
while True:
chat() |
def split_into_codons(rna):
searching = False
codons = []
index = 0
temp = 0
while index < len(rna)-3:
if rna[index:index+3] == 'AUG':
temp = index
index += 3
searching = True
exit = ['UAG','UGA','UAA']
while index < len(rna)-3 and ... | The code identifies all possible codons in an RNA sequence and its reverse complement across three reading frames. It splits the RNA into codons starting at positions 0, 1, and 2, collects them, then repeats the process for the reverse-complemented RNA, aggregating all codons into a list for analysis. | def find(rna):
mrna_1 = split_into_codons(rna)
mrna_2 = split_into_codons(rna[1:])
mrna_3 = split_into_codons(rna[2:])
codon = []
find_codon(mrna_1, codon)
find_codon(mrna_2, codon)
find_codon(mrna_3, codon)
# complements
reverse_rna = reverse_complement(rna)
reverse_mrna = split... |
def init_input(self):
if self.input_type == 'random':
if self.task == 'super-resolution':
self.net_input = torch.rand((self.input_depth, self.noisy.shape[1]*self.factor, self.noisy.shape[2]*self.factor)) * 0.1
else:
self.net_input = torch.rand((self.input_... | The code defines a `train` method that initializes input data, retrieves parameters, and performs optimization. Its main task is to execute the training process of a machine learning model by sequentially setting up inputs, configuring parameters, and optimizing the model's performance through iterative adjustments. | def train(self):
self.init_input()
self.get_params()
self.optimize() |
def get_calories(self):
pass
def get_calories_per_100g(self):
return self.get_calories_per_gram() * 100
def get_calories_per_gram(self):
return self.get_calories() / self.weight if self.weight > 0 else 0 | This code defines the __str__ method to generate a human-readable string representation of an object, displaying its name, weight, measurement unit, total calories, calories per 100g, and calories per gram. It combines the object's attributes with computed values to provide a concise nutritional summary. | def __str__(self):
return f"{self.name} ({self.weight} {self.measurement}): {self.get_calories()} calories total.\n" \
f"{self.get_calories_per_100g()} calories per 100g.\n{self.get_calories_per_gram()} calories per gram\n\n" |
def valid_move(board, move):
if move<0 or move>=COLUMNS:
return False
if board[0, move]!=0:
return False
return True
def make_move(board, move, player):
for i in range(ROWS-1,-1,-1):
if board[i, move]==0:
board[i, move]=player
return
def minimax(board, de... | The code determines the computer's optimal move using the minimax algorithm with alpha-beta pruning. It evaluates all valid column moves on the board, assigns scores via minimax (considering difficulty depth), and handles invalid moves by assigning extreme values. The best move is selected based on the player's turn (m... | def computer_move(board, difficulty, player):
move_vals=[]
# For every valid move, store the score
for move in range(COLUMNS):
if(valid_move(board, move)):
make_move(board, move, player)
move_vals.append(minimax(board,
difficulty,
... |
def prompt(message, validity_test, response_type=None):
response=''
while True:
try:
print(message)
if response_type is None:
response = input()
else:
response = response_type(input())
except ValueError:
print('Pleas... | This code implements a two-player game where a human and computer alternate turns on a board. The human selects their player number, and the computer plays as the opponent. The game alternates between human and computer moves, checking for a win after each turn. If the human wins, the game ends with a "You win!" messag... | def play_game():
os.system("clear")
board = np.zeros((ROWS,COLUMNS), dtype=np.intc)
# Get player order
human_player = prompt("Which player will you be? [1/2]",
lambda x: x==1 or x==2,
int)
computer_player=other_player(human_player)
current_player=1
w... |
def number(letter):
return(ord(letter) - 96)
def search_rotor(pos, rotor):
list_rotor = rotor
for i in range(len(list_rotor)):
if i == pos:
return(rotor[i])
def key_pos(key, pos):
lk = list_key(key)
for i in range(len(lk)):
if pos == lk[i]:
return(i)
def lette... | The code simulates a rotor-based encryption mechanism. It processes an input character (`let`) through three rotors (fast, medium, slow) using positional mappings (`fast_list1`, `medium_list1`, `slow_list1`). Each rotor's position is adjusted based on a `key` (a list of positions). The function applies sequential trans... | def cycle_left(let, key):
rotor1 = number(let) - 1 # i -> 8
cycle1 = search_rotor(rotor1, fast_list1) # 8 -> 13
fastrot = key_pos(key[2], cycle1)
rotor2 = search_rotor(fastrot, medium_list1)
medrot = key_pos(key[1], rotor2)
rotor3 = search_rotor(medrot, slow_list1)
slowrot = key_pos(key... |
def search(pos, key):
key = list_key(key)
return(key[pos])
def slow_rotor(pos):
for i in range(len(slow_list)):
if pos == slow_list[i]:
return(i)
def medium_rotor(pos):
for i in range(len(medium_list)):
if pos == medium_list[i]:
return(i)
def fast_rotor(pos):
... | The code processes an input letter through a series of rotor transformations determined by a key. Each rotor (slow, medium, fast) applies a specific rotation step based on the key elements, encrypting the letter by sequentially passing it through these stages. The final result is a transformed letter after all rotation... | def cycle_right(let, key):
cycle1 = search(let, key[0]) # 25 search(1,x)
rotor1 = slow_rotor(cycle1) # 25
cycle2 = search(rotor1, key[1]) # 22
rotor2 = medium_rotor(cycle2) # 22
cycle3 = search(rotor2, key[2]) # 13
rotor3 = fast_rotor(cycle3) # 13 -> i
return(letter(rotor3+1)) |
def cycle_left(let, key):
rotor1 = number(let) - 1 # i -> 8
cycle1 = search_rotor(rotor1, fast_list1) # 8 -> 13
fastrot = key_pos(key[2], cycle1)
rotor2 = search_rotor(fastrot, medium_list1)
medrot = key_pos(key[1], rotor2)
rotor3 = search_rotor(medrot, slow_list1)
slowrot = key_pos(key... | The code decrypts ciphertext using a key that dynamically updates its characters (key[0], key[1], key[2]) through cyclic increments, similar to a rotor mechanism. Each ciphertext character is processed with a `cycle_left` function based on the current key state. When key components reach 'z', they reset to 'a' and trig... | def decrypt(ciphertext, key):
ciphertext = list(ciphertext)
plaintext = []
for i in range(len(ciphertext)):
plaintext.append(cycle_left(ciphertext[i], key))
if number(key[2]) < 26: # aaa
key[2] = letter((number(key[2]) + 1) % 26)
rotate_forward(fast_list1)
el... |
def cycle_right(let, key):
cycle1 = search(let, key[0]) # 25 search(1,x)
rotor1 = slow_rotor(cycle1) # 25
cycle2 = search(rotor1, key[1]) # 22
rotor2 = medium_rotor(cycle2) # 22
cycle3 = search(rotor2, key[2]) # 13
rotor3 = fast_rotor(cycle3) # 13 -> i
return(letter(rotor3+1))
def n... | The code encrypts plaintext using a key with rotating components. For each character, it applies a right-cycle shift based on the key. The key's third character increments, and if it overflows (e.g., 'z' to 'a'), it triggers rotations on predefined lists. Similar logic applies to the second and first key characters, ca... | def encrypt(plaintext, key):
ciphertext = []
for i in range(len(plaintext)):
ciphertext.append(cycle_right(plaintext[i], key))
if number(key[2]) < 26: # aaa
key[2] = letter((number(key[2]) + 1) % 26)
rotate_forward(fast_list)
elif number(key[2]) == 26 and number(... |
def number_plaintext(plaintext):
num_letter = []
for letter in plaintext:
num_letter.append(number(letter)-1)
return (num_letter)
def filter(plaintext):
remove_punctuation_space = ''.join(i for i in plaintext if i.isalnum())
remove_number = ''.join(
i for i in remove_punctuation_sp... | The code performs encryption and decryption using two keys. It converts plaintext to numbers, sets rotor configurations with key1 for encryption, then applies key2 to decrypt the result. It also groups the encrypted output for further processing, returning encrypted text, grouped encrypted text, and decrypted text. | def Enigma_Process(plaintext, key):
key1 = list(key)
key2 = list(key)
plaintext = number_plaintext(filter(plaintext))
set_list(slow_list, key1[0])
set_list(medium_list, key1[1])
set_list(fast_list, key1[2])
encrypted_text = encrypt(plaintext, key1)
set_list(slow_list1, key2[0])
set... |
def log(self, message, prefix_newline=False):
print(('\n' if prefix_newline else '') +
str(time.time()) + ': ' + str(message))
def process_params(self, params):
if (self.PARAM_IN_WS not in params or
not params[self.PARAM_IN_WS]):
raise ValueError(self.PARAM_IN_W... | The main task of the code is to execute the IDBA assembler on paired-end sequencing libraries, process input parameters, retrieve and validate read data from a workspace, run the assembly, filter contigs by minimum length, and save the resulting contigs and report back to the workspace. It handles input validation, dat... | def run_idba_ud(self, ctx, params):
"""
Run IDBA on paired end libraries
:param params: instance of type "idba_ud_Params" (Input parameters
for running idba_ud. string workspace_name - the name of the
workspace from which to take input and store output.
list<pair... |
def new_window(self):
self.newWindow = tk.Toplevel(self.master)
self.app = UserPage(self.newWindow, path=os.path.join(os.getcwd(), 'FaceRecog', 'images'))
def threadlink(self):
t1 = Thread(target=self.link)
t1.start()
def new_window_1(self):
self.master.destroy()
root = t... | This code initializes a GUI window for a camera testing application, setting up the window's size, title, and background. It creates buttons for user management, verification start, and camera management, with specific commands and states. The Camera button triggers multiple actions including state changes and geometry... | def __init__(self, master):
self.master = master
self.master.geometry("400x400")
self.master.configure(bg=bg)
self.master.title('camera_testing')
self.master.resizable(0,0)
#Reading camera
self.cap = None
#Main frame
self.frame2 = tk.Frame(self... |
def new_window(self):
self.newWindow = tk.Toplevel(self.master)
self.app = UserPage(self.newWindow, path=os.path.join(os.getcwd(), 'FaceRecog', 'images'))
def threadlink(self):
t1 = Thread(target=self.link)
t1.start()
def new_window_1(self):
self.master.destroy()
root = t... | The code initializes a GUI window for a camera testing application, setting up the main frame, buttons for user management, verification start, and camera control. It configures window properties, creates interactive buttons linked to functions like new_window, threadlink, and press, and arranges UI elements with speci... | def __init__(self, master):
self.master = master
self.master.geometry("400x400")
self.master.configure(bg=bg)
self.master.title('camera_testing')
self.master.resizable(0,0)
#Reading camera
self.cap = None
#Main frame
self.frame2 = tk.Frame(self... |
def _register_model_name(self, model: DjangoModel) -> AppModelName:
app_config_name = self._get_meta(model).app_config.name
model_object_name = cast(str, self._get_meta(model).object_name)
model_path = f"{app_config_name}.{model_object_name}"
model_name = self._model_names.get(model_path... | The code creates and registers GraphQL types for a Django model by processing its fields and relations. It filters out hidden fields, enqueues relations, and constructs `__annotations__` for `Types`, `Orders`, and `Filters` classes using `strawberry.auto`. These classes are stored for later use in GraphQL schema genera... | def _create_type(self, model: DjangoModel) -> None:
model_name = self._register_model_name(model)
self._models[model_name] = model
fields_dict: Dict[FieldName, Any] = {}
for field in self._get_meta(model).fields:
if field.hidden:
continue
elif fie... |
def check_ldrb():
if not has_ldrb:
raise ImportError(
(
"Cannot create microstructure using ldrb. "
"Please install ldrb first with 'python -m pip install ldrb'"
),
)
def create_benchmark_ellipsoid_mesh_gmsh(
mesh_name,
r_short_endo=7.0... | This function generates a prolate ellipsoid heart geometry with specified short and long-axis radii for endocardial and epicardial surfaces. It creates a mesh using Gmsh, computes fiber orientations via LDRB, caches the result in an HDF5 file, and returns a HeartGeometry object with microstructure data, ensuring effici... | def prolate_ellipsoid_geometry(
r_short_endo: float = 7.0,
r_short_epi: float = 10.0,
r_long_endo: float = 17.0,
r_long_epi: float = 20.0,
quota_base: float = 0.0,
psize: float = 3.0,
ndiv: float = 1.0,
mesh_size_factor: float = 1.0,
fiber_params: typing.Optional[typing.Dict[str, typ... |
def print_bar():
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print('====================', now_time, '====================')
def train_step(model, inp, targ, optimizer, pad):
targ_inp = targ[:, :-1]
targ_real = targ[:, 1:]
# print(inp.device, targ.device)
enc_padding_mask, ... | The function trains a machine learning model over multiple epochs using a training dataset, validates it on a separate validation dataset, and tracks training/validation loss and accuracy. It uses progress bars, saves model checkpoints, and stores training history in a DataFrame. The model's state and optimizer are sav... | def train_model(model,
optimizer,
epochs,
train_dataloader,
val_dataloader,
print_every,
save_dir,
save_name,
pad,
device,
ngpu=1,):
starttime = ... |
def treeFromList(l):
if type(l) == list:
node = TreeNode()
left, right = treeFromList(l[0]), treeFromList(l[1])
node.left = left
node.right = right
left.parent = node
right.parent = node
return node
else:
node = TreeNode()
node.value = int(... | The code processes each line from "input.txt" as a Snailfish number, sequentially combining them into a single number by parsing, reducing, and merging trees. It returns the magnitude of the final reduced tree. | def partOne():
with open("input.txt", "r") as inputFile:
lines = inputFile.readlines()
result = None
for x in lines:
x = treeFromList(eval(x.strip()))
reduceTree(x)
result = treeFromList([toList(result)] + [toList(x)]) if result else x
reduceTr... |
def treeFromList(l):
if type(l) == list:
node = TreeNode()
left, right = treeFromList(l[0]), treeFromList(l[1])
node.left = left
node.right = right
left.parent = node
right.parent = node
return node
else:
node = TreeNode()
node.value = int(... | The main task of the code is to compute the maximum magnitude of the sum of all possible pairs of numbers from the input file. It reads input lines, generates permutations of pairs, converts each line into a tree structure, reduces the trees, combines them, and tracks the maximum magnitude of the resulting sums. | def partTwo():
with open("input.txt", "r") as inputFile:
lines = inputFile.readlines()
maxRes = 0
for z in permutations(lines, 2):
result = None
for x in z:
x = treeFromList(eval(x.strip()))
reduceTree(x)
result = treeFr... |
def Find_Signal_Params():
for i in range(0,G.No_Actions): # i - changes G.Actions
for j in range(0,len(G.Actions[i])): # j - changes elements in the corresponding Action
G.Action_Indices.append([i,j]) ... | The main task of the code is to generate and process action data from input signals. It initializes action lists, classifies signal types, extracts parameters, identifies signal indices, and prepares data for further analysis. The function structures input data, categorizes actions, and prepares parameters for signal p... | def Generate_Data(InputData): # uncomment this line
G.Actions=[[] for k in range(len(InputData))]
for i in range(0,len(InputData)):
G.Actions[i]=InputData[i]
G.No_Actions= len(G.Actions)
G.Data_Init()
Find_Signal_Params()
Find_ramp_yticks()
Classify_Actions()
Find_Si... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.