dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_mol(mol):
"""
generate dictionary containing the atoms and coordinate of a molecule
from RDKit mol object.
:param mol: RDKit mol object
:return: dict_A (dictionary with atoms and coordinate of molecule)
"""
mol_d = {'index': [], 'atom': [], 'coordinates': []}
for i, atom in enum... | The function `getfingerprint` generates empirical features for dispML models by combining molecular charge, hydrogen bond counts between specific atom pairs, and substructure interactions derived from SMARTS patterns, tailored to the specified model type (D3-ML, MBD-ML, etc.). It processes two RDKit molecules, applies ... | def getfingerprint(mol_a, mol_b, model):
"""
Calculates the empirical features used in dispML models
:param mol_a: RDKit mol object for monomer A.
:param mol_b: RDKit mol object for monomer B.
:param model: str: 'D3-ML', 'D3-ML-S', 'D3-ML-X', 'MBD-ML-S' or 'MBD-ML-X'.
:return: lsit: fingerprint ... |
def main_menu():
"""Main menu for the game"""
while True:
cls()
print("Welcome to Battleship!")
print("1. Start game")
print("2. Instructions")
print("3. Quit")
print()
valid = False
while not valid:
try:
choice = int(i... | The main task of the code is to run a two-player turn-based naval battle game. It initializes the game by displaying a menu, setting up ships for both players, placing them on respective boards, and executing a loop where players take turns attacking each other's ships. The game continues until one player's ships are a... | def main():
"""Main function"""
# Main menu
main_menu()
# Game setup
player1_ships, player2_ships = game_setup()
# Place ships
place_ships(p1_board, player1_ships, 1)
place_ships(p2_board, player2_ships, 2)
# Game loop
while True:
cls()
input("Ready for player... |
def setup_board():
"""Setup an empty board."""
board = []
for i in range(BOARD_SIZE): #pylint: disable=unused-variable
board_row = []
for j in range(BOARD_SIZE): #pylint: disable=unused-variable
board_row.append(-1)
board.append(board_row)
return board
def print_bo... | The main task of the code is to initialize a two-player game with board setups, ship placements, and targeting systems. It creates duplicate boards for each player's gameplay and targeting, assigns player identifiers, and executes initial moves. The code is noted as inelegant but functional, handling board creation, sh... | def main():
"""Main function."""
# This entire section of code is absolutely hacky.
# I dislike it, however it works.
player1_board = []
player1_board.append(setup_board())
player1_board.append("Player 1")
player2_board = []
player2_board.append(setup_board())
player2_board.append... |
def clear_all_queries(self):
self.answers.clear()
self.questions.clear()
self.authority.clear()
self.additional.clear()
def parse_header(self, byte_stream):
self.transaction_id = byte_stream.read(2)
byte_stream.read(2) # flags
self.questions_count = unpack('>h', ... | This code parses a DNS response by clearing previous queries, reading the response as binary data, and sequentially parsing the header, questions, answers, authority records, and additional records using specialized methods to extract and organize each section of the DNS response. | def parse_response(self, resp):
self.clear_all_queries()
resp = io.BytesIO(resp)
self.parse_header(resp)
for i in range(self.questions_count):
self.parse_question(resp)
for i in range(self.answer_count):
self.parse_answer(resp, self.answe... |
def get_user_data_from_all_pages():
"""
get_user_data_from_all_pages gets lists of user data from all pages in TUPLE_OF_PAGES_NUMBERS
and join them in the only list
:return : joined list of user data
:example: [{"id":1,"first_name":"George","last_name":"Bluth",
"avatar":"https://s3.amazonaws.com... | The function filters user data based on an ID range specified by a tuple. It retrieves all user data, validates the ID range, and returns a filtered list of users whose IDs fall within the range (inclusive). If the range is invalid, it returns an empty list. | def filter_users_data_by_id(ids_range):
"""
filter_users_data_by_id filters all users by id (id should be in the ids_range including ends of range)
:param ids_range: range specified by user for filtering ids according to requirements: tuple
return filtered list if ids_range is valid and empty list if id... |
def _try_remove_args(self, command: list, infile: Path, message: str, *, extra_args: list = None, **kwargs):
new_command = self._filter_args(command, **kwargs)
print(message, end="", flush=True)
if extra_args:
new_command += extra_args
if new_command == command:
p... | The main task of the code is to simplify a compiler command by systematically removing non-essential flags and preprocessing source files to identify the minimal configuration that still triggers a crash. It reduces compilation arguments, tests for crash persistence, generates preprocessed sources, shrinks them, and el... | def _simplify_frontend_crash_cmd(self, new_command: list, infile: Path):
new_command = self._try_remove_args(
new_command, infile, "Checking whether compiling without warnings crashes:",
noargs_opts_to_remove=["-w"], noargs_opts_to_remove_startswith=["-W"], extra_args=["-w"])
# T... |
def verbose_print(*args, **kwargs):
global options
if options.verbose:
print(*args, **kwargs)
def _simplify_frontend_crash_cmd(self, new_command: list, infile: Path):
new_command = self._try_remove_args(
new_command, infile, "Checking whether compiling without warnings crashes:",
... | This function simplifies crashes in LLVM backend processing by generating IR files from source code, then testing if compiling the IR with llc, opt, or clang reproduces the crash. If a crash is detected, it selects llvm-reduce/bugpoint for faster reduction; otherwise, it defaults to creduce. It modifies command argumen... | def _simplify_backend_crash_cmd(self, infile: Path, clang_cc1_command: list, generate_ir_command: list):
ir_pass_crashing = "-emit-llvm" in clang_cc1_command
assert "-o" in clang_cc1_command
generate_ir_command = generate_ir_command.copy()
irfile = infile.with_name(infile.name.partition(... |
def _try_remove_args(self, command: list, infile: Path, message: str, *, extra_args: list = None, **kwargs):
new_command = self._filter_args(command, **kwargs)
print(message, end="", flush=True)
if extra_args:
new_command += extra_args
if new_command == command:
p... | This function simplifies a Clang crash command by iteratively removing optimization/debug flags and checking if the crash persists. It tests generating LLVM IR with -emit-llvm, adjusting optimization levels (-O0/-O1), and identifies if the crash originates from the frontend or backend. If frontend-related, it removes s... | def _simplify_clang_crash_command(self, new_command: list, infile: Path) -> tuple:
assert new_command[0] == str(self.options.clang_cmd)
assert "-o" in new_command
assert "%s" not in new_command
new_command = self._try_remove_args(
new_command, infile, "Checking whether replac... |
def sample_edge(self, edge, t):
"""The reservoir sampling"""
if t <= self.memory_size:
return True
elif self.flip_biased_coin(self.memory_size / t) == "H":
edge_to_remove = random.sample(self.sample_set, 1)[0]
self.sample_set.remove(edge_to_remove)
... | The code processes a stream of edges, sampling each based on a time-dependent condition, maintaining a sample set, updating counters for tracked elements, and finally generating estimations using the sampled data and current time step. | def run(self):
for edge in self.stream:
self.t += 1
if self.sample_edge(edge, self.t):
self.sample_set.add(edge)
self.update_counters("+", edge)
self.get_estimations(self.t) |
def askopenfile(self):
try:
newfile = filedialog.askopenfilename(initialdir = self.work_dir,title = "Select file",filetypes = (("all files","*.*"),("all files","*.*")))
except:
newfile = filedialog.askopenfilename(initialdir = desktop,title = "Select file",filetypes = (("all file... | This code creates a GUI for a pressure logger using Tkinter, embedding Matplotlib for real-time data visualization. It sets up menus for importing data, settings, and exiting, binds keyboard shortcuts, initializes a plot canvas, and starts a thread for continuous data updates. The GUI displays an introductory message l... | def makeGui(self, root=None):
global first
if root == None:
self.root = Tk()
else:
self.root = root
menu = Menu(self.root)
self.root.config(menu=menu)
self.root.title("Pfeiffer Gauge Pressure Logger")
self.root.geometry("1200x768")
... |
def Create_Bitmap(bitmaps_created):
global MAX_FILE_SIZE
global MAX_BITMAP_SIZE
global SPLIT_RATIO
data = pd.DataFrame(columns=['Input'])
os.path.isdir("./bitmaps/") or os.makedirs("./bitmaps")
os.path.isdir("./splice_seeds/") or os.makedirs("./splice_seeds")
os.path.isdir("./vari_seeds/"... | This function generates gradient information for a neural network model. It creates or loads an LSTM or standard model, trains it if necessary, and prepares mutation parameters based on model type. It also creates bitmaps, tracks training rounds, and measures execution time. | def Gen_Gradient(first, trained, modelType, bitmaps):
global round_cnt
start = time.time()
print("Creating Bitmaps")
Create_Bitmap(bitmaps_created=bitmaps)
print("Bitmaps Created!")
if modelType == "LSTM":
model = Create_LSTM()
else:
model = Create_Model()
if traine... |
def _not_connected_error():
""" Static method for responding to a process request when the robot is not connected"""
message = "Error: MockRobot is not connected. Press 'Open Connection' and then try your request again."
logging.error(message)
return message
def _process_running_error(current_process):
... | The main task of the code is to execute a specified robotic operation (PICK, PLACE, or TRANSFER) initiated by the UI, after validating inputs, ensuring the device is connected and initialized, and handling errors. It processes parameters, checks system state, and delegates to corresponding methods for operation executi... | def ExecuteOperation(self, operation, parameter_names, parameter_values):
"""
UI mapped function. When a user presses the “Execute Operation” button, the UI calls this function and expects
that the Device Driver will perform an operation determined by the parameter operation.
Checks the ... |
def _extract(self):
users_df_list = [
pd.read_csv(
f"{self.INPUT_PATH}/{date.year}/{date.month:02d}/users.csv.gz",
compression="gzip",
)
for date in self.available_data_date_list
]
self.users_df = pd.concat(users_df_list).reset... | The code defines a `run` method that executes three sequential steps: extracting data with `_extract()`, transforming it with `_transform()`, and loading it with `_load()`. The method returns `True` to indicate successful completion of the process. | def run(self):
self._extract()
self._transform()
self._load()
return True |
def cutsize(conn, partition):
cutsize = 0
for key in conn:
for i in range(len(conn[key])): ## see if in same partition
if partition[key] != partition[conn[key][i]]:
cutsize += 0.5 ## gets counted both ways so 0.5 to add up to 1 crossing for cutsize
return cutsize
def numN... | The code implements the K&L algorithm to partition a grid into two balanced subsets, minimizing cut size and net crossings. It initializes partitions evenly, iteratively computes gain values for swapping cells, selects optimal swaps to reduce cut size, and locks cells after swaps to avoid cycles. The process runs up to... | def KL(grid, conn, numcells, c):
## initially assign half half to the two partitions
counts = [0, 0] ## amount in first partition and second partition
partition = {}
gain = {}
## assign half half
for key in conn:
partnum = (counts[0] + counts[1]) % 2
partition[key] = partnum
... |
def create():
"""Creates new contact"""
contact = input_data()
create_contact(**contact)
def update() -> None:
"""Updates contact in contact_book"""
contacts = get_list_by_name()
if not contacts:
return
for contact in contacts:
print_contact(contact)
while True:
... | The function `action_scope` routes actions to corresponding functions based on the `action` variable, executing `create()`, `update()`, `list_all()`, or `remove()` for valid inputs, and printing an error message for invalid inputs. | def action_scope():
"""Scope of functions for actions"""
match action:
case 'create':
create()
case 'update':
update()
case 'list':
list_all()
case 'remove':
remove()
case _:
print("Error: Incorrect inputted data... |
def action_scope():
"""Scope of functions for actions"""
match action:
case 'create':
create()
case 'update':
update()
case 'list':
list_all()
case 'remove':
remove()
case _:
print("Error: Incorrect inputted data... | The main task of the code is to execute database operations based on command-line arguments: seed data (groups/contacts), perform actions, search, or check birthdays, while handling SQLAlchemy errors. It uses conditional checks for input parameters and exits the program afterward. | def main():
"""Main point"""
try:
if seed:
seed_groups()
seed_contacts(num=seed)
elif action:
action_scope()
elif search:
search_scope()
elif birthday:
birth_on_date()
except SQLAlchemyError as err:
print(f'E... |
def get_competition_df(filepath:str='data.xlsx'):
"""Read competition data from an Excel file into a dict of {year (int): DataFrame}.
Args:
filepath (str, optional): The path to the Excel file. Defaults to 'data.xlsx'.
Returns:
dict: Competitions data grouped into years. Keys are the years... | The main task of the code is to collect data from an Excel file and a meeting minutes directory, process it into a JSON-serializable format, and generate JSON files containing competition and meeting minutes data. | def main():
"""Run the program.
-Collects data from an Excel file and the meeting minutes directory\n
-Processes data into a JSON-serializable format\n
-Outputs the data to JSON files
"""
# get the competition and entries data
comp_dfs = get_competition_df()
entry_df = get_entry_df... |
def _soup(url):
soup = BeautifulSoup(_get(url), 'html5lib')
return soup
def __decode(js):
docJs = """
function unbox() {
var evalCode = "";
var document = {
write: function(str) { evalCode = str; }
};
var bdecodeb = function(str, k... | The function `categories(url)` extracts video categories and their decoded URLs from a webpage. It parses HTML to find a script tag containing 'bdecodeb', decodes it to obtain a token, then uses this token to decode URLs from a dropdown menu (`#playURL`). If successful, it returns a list of tuples with titles and decod... | def categories(url):
soup = _soup(url)
token = None
for tag in soup.find_all('script'):
if 'bdecodeb' in tag.getText():
token = __decode(tag.getText())
break
show_list = []
common.error(token)
if hasattr(token, 'token'):
options = soup.select('#pl... |
def getExecutablePath(filename, env):
"""Find an execute in either normal PATH, or Scons detected PATH."""
if os.path.exists(filename):
return filename
# Variable substitution from environment is needed, because this can contain
# "$CC" which should be looked up too.
while filename.startsw... | The main task of this code is to configure the environment to use ClangCL with MSVC by locating the Clang directory, validating its existence, adding it to the PATH, and setting compiler-related environment variables (CC, LINK) to use ClangCL and lld-link. It ensures Visual Studio is present, detects the architecture, ... | def addClangClPathFromMSVC(env):
cl_exe = getExecutablePath("cl", env=env)
if cl_exe is None:
scons_logger.sysexit(
"Error, Visual Studio required for using ClangCL on Windows."
)
clang_dir = os.path.join(cl_exe[: cl_exe.lower().rfind("msvc")], "Llvm")
if (
getComp... |
def isGccName(cc_name):
return (
"gcc" in cc_name
or "g++" in cc_name
or "gnu-cc" in cc_name
or "gnu-gcc" in cc_name
)
def isClangName(cc_name):
return "clang" in cc_name and "-cl" not in cc_name
def getLinkerArch(target_arch, mingw_mode):
# Singleton, pylint: disable=glo... | This function checks if there's a mismatch between the linker and compiler architectures for a given target architecture. It determines the compiler mode (Mingw/MSVC), retrieves the linker and compiler architectures, then returns a tuple indicating whether they differ, along with both architecture values. | def decideArchMismatch(target_arch, the_cc_name, compiler_path):
mingw_mode = isGccName(the_cc_name) or isClangName(the_cc_name)
msvc_mode = not mingw_mode
linker_arch = getLinkerArch(target_arch=target_arch, mingw_mode=mingw_mode)
compiler_arch = getCompilerArch(
mingw_mode=mingw_mode,
... |
def block_touches_field(self):
for line in range(len(self.gameBlock.body)):
for block in range(len(self.gameBlock.body[line])):
if self.gameBlock.body[line][block] == 1:
if self.field[line + self.gameBlock.y][block + self.gameBlock.x] == 1:
... | This code simulates gravity for a game block by incrementing an accumulator. When it reaches 60, the block moves down. If the block hits the grid bottom or collides, it's added to the grid, and a new block is generated. The main task is to handle block movement, collision detection, and spawning in a falling-block game... | def tick(self, _framerate):
self.accumulator = self.accumulator + 2
if self.accumulator == 60:
self.accumulator = 0
self.gameBlock.y = self.gameBlock.y + 1 # gravity
if self.gameBlock.get_lowest_y() == Y_GRID_SIZE or self.block_touches_field():
self.add_figu... |
def tick(self, _framerate):
self.accumulator = self.accumulator + 2
if self.accumulator == 60:
self.accumulator = 0
self.gameBlock.y = self.gameBlock.y + 1 # gravity
if self.gameBlock.get_lowest_y() == Y_GRID_SIZE or self.block_touches_field():
self.add_figu... | This code runs a game loop that maintains a 60 FPS frame rate by processing events, updating game state, rendering graphics, and updating the display until the game stops. It calls self.tick() for frame timing, handles user input events, and cleans up resources with self.destroy() when the loop ends. | def play(self):
while self.isPlaying:
tick = self.clock.tick(60)
self.tick(tick)
for event in pygame.event.get():
self.handle_event(event)
self.render()
pygame.display.update()
self.destroy() |
def update(self, inputs):
self.a1 = np.append(inputs, 1.0)
# hidden activations
self.z2 = np.dot(self.w1, self.a1)
#print("z2:", self.z2)
#self.a2 = np.append(tanh(self.z2), 1.0)
self.a2 = np.append(sigmoid(self.z2), 1.0) #np.vstack(([1.0], sigmoid(self.z2)))
... | This code trains a neural network using backpropagation over a specified number of iterations, updating weights with a regularization parameter Lambda, accumulating error for each pattern, and printing the error every 500 iterations to monitor convergence. | def train(self, patterns, iterations, Lambda):
for i in range(iterations):
error = 0.0
for p in patterns:
inputs = p[0]
targets = p[1]
self.update(inputs)
error += self.backPropagate(targets)
self.weights_update(... |
def handle_non_interactive(self, name, username, **options):
if not username:
raise CommandError(
self.required_error.format(
self.User.USERNAME_FIELD))
if not name:
raise CommandError(
self.required_error.format(
... | This code handles user creation by extracting name and username from options, determining interactive or non-interactive mode, retrieving necessary fields via helper methods, and invoking create_user with the gathered details. | def handle(self, **options):
name = options.pop(self.name_field.name, None)
username = options.pop(self.User.USERNAME_FIELD, None)
password = None
if not options['interactive']:
name, username = (
self.handle_non_interactive(
name,... |
def find_path(self, x, nodes):
"""Find path to location in tree, where node should be inserted"""
if len(nodes) == 0:
return None
nn, dist = self.nearest_neighbour(x, nodes)
if dist < nn.radius: # If x is inside nn
node_path = self.find_path(x, nn.get_children(... | This code inserts a new element into a tree structure. It first checks if the element's key exists in the roots; if not, a new root is added. If the path length is under the maximum depth, a new node is appended to the path. The function manages tree insertion with depth constraints, ensuring nodes are added only when ... | def insert(self, x):
path = self.find_path(x[0], self.roots)
if path is None:
self.add_new_root(x)
elif not len(path) >= self.max_depth:
self.add_new_node(x, path) |
def mem_size(object):
"""Return object size in kb
"""
return sys.getsizeof(object) / 1024
def mem_size_dict(d):
"""Return the size of a dict object in kb (list as dict value)
"""
size = sys.getsizeof(d)
for key in d.keys():
size += sys.getsizeof(d[key])
return size / 1024
def me... | The function calculates the total memory size of an LSHStorage object in kilobytes by summing the sizes of its components: tables, columns, minHashs, and minHashLSH, using specialized helper functions for each part. | def mem_size_lshstorage(storage):
"""Return the size of a LSHStorage obj in kb
"""
size_tables = mem_size(storage.tables)
size_cols = mem_size_dict(storage.cols)
size_minHashs = mem_size_dict_minhash(storage.minHashs)
size_lsh = mem_size_minhashlsh(storage.minHashLSH)
size_storage = size_tab... |
def get_scores(y_hat,y_te,y_dummy):
scores = {}
err = y_hat-y_te
err_dummy = y_dummy - y_te
filter_idx = np.abs(y_te)>1e-2
scores['mape'] = np.mean(np.abs(err[filter_idx])/np.abs(y_te[filter_idx]))
scores['rmse'] = np.mean(err**2)**0.5
dummy_mape = np.mean(np.abs(err_dummy[filter_idx]) / np.... | The code evaluates a model's robustness by iteratively removing control node subsets from training/test data, retraining the model, and assessing performance under noise. It tests different control group sizes (1,2,4,8,12,16), creates partial datasets excluding these nodes, trains the model on combined data, predicts o... | def partial_vsc(x_lingb_tr,y_tr_d,x_tr_d,x_lingb_te, x_te_d,y_te_d,y_mean, model):
n_nodes = int(x_tr_d.shape[1]/2)
scores = {}
for n_control in [1,2,4,8,12,16]:
control_groups = np.vstack([np.random.permutation(n_nodes)[0:n_control] for _ in range(10)])
scores_partial,scores_noise_partial =... |
def cli_get_parser() -> ArgumentParser:
"""Add required fields to parser."""
package_description = \
'Mondo on FHIR'
parser = ArgumentParser(description=package_description)
parser.add_argument(
'-o', '--out-dir',
default=DEFAULTS['out-dir'],
help='The directory where re... | The code defines a CLI function that parses command-line arguments, validates them, and executes a run function with the processed parameters, returning a dictionary of pandas DataFrames. | def cli() -> Dict[str, pd.DataFrame]:
"""Command line interface."""
parser = cli_get_parser()
kwargs = parser.parse_args()
kwargs_dict: Dict = vars(kwargs)
kwargs_dict = cli_validate(kwargs_dict)
return run(**kwargs_dict) |
def best_move(board):
best_eval = -math.inf
best_move = -1
for i in range(9):
if board[i] == ' ':
board[i] = 'O'
eval = minimax(board, 0, False)
board[i] = ' '
if eval > best_eval:
best_eval = eval
best_move = i
retu... | The main task of the code is for the AI to determine its optimal move on a tic-tac-toe board by calling best_move(), update the corresponding button with 'O', disable it, and mark the board. It then checks if the AI has won or if the board is full, updating the result label to indicate a win, draw, or continuing the ga... | def ai_move():
ai_index = best_move(board)
button = buttons[ai_index]
button.config(text='O', state='disabled')
board[ai_index] = 'O'
if check_winner('O'):
result_label.config(text="AI wins!")
elif is_full(board):
result_label.config(text="It's a draw!") |
def check_winner(player):
for combo in winning_combinations:
if all(board[i] == player for i in combo):
return True
return False
def is_full(board):
return ' ' not in board
def ai_move():
ai_index = best_move(board)
button = buttons[ai_index]
button.config(text='O', state='di... | This function handles a player's move in a tic-tac-toe game by updating the board with 'X' at the specified index, disabling the button, checking for a win or draw, and triggering the AI's move if the game continues. | def player_move(button, index):
if board[index] == ' ':
button.config(text='X', state='disabled')
board[index] = 'X'
if check_winner('X'):
result_label.config(text="You win!")
elif is_full(board):
result_label.config(text="It's a draw!")
else:
... |
def train_one_epoch(self, learning_rate):
'''
Train for one epoch
'''
for i in range(len(self.inputs)):
self.setnextinput() # Use next sample of dataset as next input
self.feedforward() # Feed forward...
self.backpropagate(learning_rate)
def print_accu... | The code trains a neural network model for a specified number of epochs using a decaying learning rate. It iteratively calls `train_one_epoch` to update model parameters, adjusts the learning rate by multiplying it with a decay factor each epoch, and optionally prints training progress and accuracy at regular intervals... | def train(self, n_epochs, learning_rate, decay=1.):
'''
Train function (with specified number of epochs, learning rate and decay)
'''
# previous_weights = []
# for l in self.layers[1:]:
# for n in l.neurons:
# previous_weights.append(n.weights)
... |
def train_one_iteration(self, l, eta_t):
'''
Train for one epoch
'''
pass
def print_accuracy(self):
'''
Print accuracy of neural network on current dataset
'''
print("Accuracy:", 100*self.compute_accuracy(), "%")
def compute_accuracy(self):
'''
... | The code trains a model for a specified number of iterations (n_iterations), adjusting the learning rate (eta_t) using a decay factor (l) as 1/((i+1)*l) per iteration. It repeatedly calls `train_one_iteration` with parameters l and eta_t, and optionally prints progress (epoch number and accuracy) if verbose is enabled. | def train(self, n_iterations, l):
'''
Train function (with specified number of epochs, lambda and decay)
'''
if not self.print_step:
self.print_step = max(1, int(n_iterations/50))
# For n_iterations iterations...
for i in range(n_iterations):
# Set... |
def open_position(signal, amount, m_level):
pointer_click(BLANK)
mouse.position = INPUT
time.sleep(0.1)
mouse.click(mouse_button.left, 2)
time.sleep(0.1)
keyboard.type(str(amount))
if m_level==0: print('\n> OPEN TRADE')
else: print('\n> MARTINGALE', m_level)
print(f"{'AMOUNT:':10}... | The function executes a trade based on a signal, opens a position, calculates time delays, applies martingale logic recursively, updates balance and trade results, and returns updated balance, trade outcomes, and martingale levels. It tracks profit/loss, logs trade details, and ensures synchronization with the next min... | def trade(var_static, var_return):
# calculate the time taken to perform these operations
start_time = time.time()
signal, op_list, m_max, m_switching = var_static
balance, trades_list, martingales_list = var_return
print('TRADE NUMBER:', len(trades_list)+1)
print(f'\n------------------------... |
def get_dev_input4() -> list:
"""Build a maze for development purposes."""
form1 = (
"""oooooo+--+oooooo
o+--+o|oo|o+--+o
o|oo+-+oo+-+oo|o
o++oooooooooo++o
oo+-+o+--+o+-+oo
oooo|o|oo|o|oooo
o+--+o+--+o+--+o
++oooooooooooo++
|oooooooooooooo|
+--------------+
oooooooooooooooo
o+-+oo+--+xx+-+o
++o|oo|oo|oo|o++
|oo... | The main task of the code is to count the number of moles in a grid using the `count_moles` function, then output the count. If debugging is enabled, it also prints a debug grid representation. The `get_dev_input4` function retrieves the input grid, and the result is displayed via `print(count)`.)> | def main():
grid = get_dev_input4()
count, debug_grid = count_moles(grid)
if DEBUG:
print_debug_grid(debug_grid)
print(count) |
def delete_bq_table(colors: list[str]) -> None:
print('Emptying existing table...')
creds: GcpCredentials = GcpCredentials.load('de-zoomcamp-gcp-creds')
bq = creds.get_bigquery_client(project='de-zoomcamp-wtfzalgo', location='eu-west-6')
for color in colors:
bq.delete_table(table=f'trips_data_a... | The main task of the code is to process data for specified colors (yellow/green), years (2019/2020), and months (1-12). It optionally deletes an existing BigQuery table if `replace_table` is True, generates local files using `write_all_local`, and uploads them to BigQuery via `upload_all_to_bq`, facilitating data pipel... | def main_flow(
colors: list[Literal['yellow', 'green']] = ['yellow', 'green'],
years: list[Literal[2019, 2020]] = [2019, 2020],
months: Literal[tuple(range(1, 13))] = 12,
replace_table: bool = True
) -> None:
if replace_table:
delete_bq_table(colors)
local_paths = write_all_local(colors... |
def clear_screen(self): #clears screen. requires importing os module
os.system('clear')
def display_menu(self):
# show the menu
print('\t\t\t(Irreverent) Household Inventory\n')
print('\t\t1. New Inventory')
print('\t\t2. Load Inventory')
print('\t\t3. Show Items in House... | The main task of the code is to initialize and run a program by clearing the screen, entering a loop that repeatedly displays a menu and processes user choices until the program stops. It manages the core workflow by handling menu interactions and maintaining the loop based on the `its_working` flag. | def turn_ignition(self):
# starts program, begin with clearing screen.
self.clear_screen()
while self.its_working:
self.display_menu()
self.process_menu_choice() |
def _get_element_text(self, xpath):
element = self._get_element(xpath, limit=1)
if element:
text = element.text
try:
return int(text)
except ValueError:
return text
return None
def get_game_detail_info(self):
# stats inf... | The main task of the code is to monitor a betting game by periodically collecting and updating game details (e.g., teams, odds, stakes, returns) into a dictionary, then outputting this data to a CSV file every 5 minutes. The loop continues until the "bet_count" element disappears, indicating the game has concluded. | def watch_bet_game(self):
data_1 = {
'league_name': self.league_name,
'home_team': self._get_element_text(el.home_team),
'away_team': self._get_element_text(el.away_team),
'how_to_bet': self._get_element_text(el.how_to_bet),
'odds': self._get_element_t... |
def click_game_lavel(self, box):
count = 0
try:
box.click()
return True
except NoSuchElementException:
return False
except ElementClickInterceptedException:
if count > 5:
return False
count += 1
self.... | The function `send_valid_game` validates game data by checking play time and scores, then attempts to bet on valid games. It collects URLs of valid games, opens new browser windows, and sends these URLs to Slack. If no valid games are found, it logs a message indicating no bets were placed. | def send_valid_game(self, data):
can_not_bet = True
urls = []
for i in range(len(data['lavel'])):
try:
# Check number of golas and game time
valid = logic.valid_game(
play_time=int(data['play_time'][i]),
score_1=... |
def __generate_match_lists(self, sentence):
self.key_words_list = []
sentence_words = self.clean_up_sentence(sentence)
for w in sentence_words:
if w not in self.similar_words_list:
self.key_words_list.extend(get_close_matches(w, self.body_parts_muscles_list))
... | The code processes user input to classify and generate appropriate responses. It resets tracking data, checks exercise mode, classifies the sentence into categories like 'exercise' or 'identification', and triggers specific response generation methods based on classification and matching criteria. The core task is dete... | def generate_chat_response(self, sentence):
# Reset info_dict
self.info_dict["tag"] = None
self.info_dict["info"] = []
if self.exercise_response == True:
self.__generate_match_lists(sentence)
response = self.__generate_inner_response()
else:
... |
def init_ui(self):
st.title("Market 📈")
st.write('---')
def init_sidebar(self):
# Refresh button
self.refresh_button = st.sidebar.button('Refresh (Press R)', use_container_width=True)
if self.refresh_button:
st.rerun()
# Table of Content
st.sidebar.... | The code initializes an object by loading system configuration from 'system.json', connecting to a SQLite database using the config's database name, initializing the user interface (UI) components, and refreshing the UI to reflect the current state. | def __init__(self) -> None:
# Load system config
with open('configs/system.json', 'r') as f:
self.system_cfg = json.load(f)
# Connect to the database
self.conn = sqlite3.connect(self.system_cfg['db_name'])
# Init UI
self.init_ui()
self.init_sidebar()... |
def make_purchase():
customer.load_customers()
product.load_products()
# enter customer id
customer_exists = False
product_exists = False
cus_id = input("Enter customer id to purchase: ")
# check if the customer id exists
for cus in customer.CUSTOMERS:
if cus_id == cus.id:
... | The code defines a function `display_purchase_menu()` that presents a menu for purchasing-related actions (make a purchase, list purchases, search purchases, or quit). It uses a loop to repeatedly display the menu, takes user input, and calls corresponding functions (`make_purchase()`, `list_purchases()`, `search_purch... | def display_purchase_menu():
# creating options
while True:
print("""
Purchases Menu
1. Make a purchase
2. List all purchases
3. Search for a purchase
4. Quit
""")
choice4 = int(input("Select Purchase option:"))
# choice ... |
def verifyPosition(playMap,userinput):
# have a check for letter and number
letter_check = False
number_check = False
# if user gives a valid 2 character input
if len(userinput) == 2:
x = userinput[0]
y = userinput[1]
#check if letter given is as according to one of the... | This function inserts a building into a game map based on user input, validating positions and updating the game state. It places the building's name across three cells if the position is valid, handles turn-specific rules (e.g., turn 1 allows placement without extra checks), updates the turn counter, and deducts the b... | def insertBuild(playMap, bPool, userinput, bName, t):
new_row = 0
new_col = 0
#if given input is valid, retrieve row and column index from play map
if verifyPosition(playMap,userinput) == True:
x_y = retrievePos(playMap,userinput[0],userinput[1])
new_row = x_y[0]
new_col = x_y[... |
def get_playlist_id(self, playlist_name):
playlists = self.get_all_playlists()
playlist_id = playlists.get(playlist_name)
return playlist_id
def get_playlist_contents(self, playlist_name):
playlist_id = self.get_playlist_id(playlist_name)
print('start')
r = requests.ge... | This code clears a specified playlist by deleting all its tracks in batches of 15 using HTTP DELETE requests to a media server API, returning status codes for each batch operation. | def clear_playlist(self, playlist_name):
playlist_id = self.get_playlist_id(playlist_name)
tracks = self.get_playlist_contents(playlist_name)
tracklist = [track.get('Id') for track in tracks ]
grouped_ids = list(self.split_list(tracklist, 15))
for group in grouped_ids:
... |
def browse_directory(self, option):
if option == 'pcap':
self.filename = self.pcap_file.replace(".pcap","")
if "/" in self.filename:
self.filename = self.filename.split("/")[-1]
print(self.filename)
print(self.pcap_file)
else:
i... | The code analyzes a pcap file by reading packets in a separate thread, generating a report, and updating UI elements with host information. It checks file permissions, processes packet data, resets tracking variables, and updates menus with IP addresses from memory. If the pcap file is missing, it reports an error. | def pcap_analyse(self):
if not os.access(self.destination_report, os.W_OK):
print("Error","Permission denied to create report! Run with higher privilege.")
return
if os.path.exists(self.pcap_file):
#PcapRead - First of All!
packet_read = threading.Thread(... |
def get_symbol_id(pair, market):
data = search(pair, market)
symbol_name = data["symbol"]
broker = data.get("prefix", data["exchange"])
symbol_id = f"{broker.upper()}:{symbol_name.upper()}"
return symbol_id
def generate_session():
string_length = 12
letters = string.ascii_lowercase
rando... | The main task of the code is to connect to Trading View's WebSocket API, create a session, subscribe to real-time financial data (last price, volume, change, change percentage) for a specified trading pair on a given market, and initiate a socket job to receive and process the streaming data. | def main(pair, market):
symbol_id = get_symbol_id(pair, market)
trading_view_socket = "wss://data.tradingview.com/socket.io/websocket"
headers = json.dumps({"Origin": "https://data.tradingview.com"})
ws = create_connection(trading_view_socket, headers=headers)
session = generate_session()
send... |
def FirstGen(c):
c.execute('''CREATE TABLE projects (project text, exp integer,
replicate integer,
tExp int,tSwitch integer,
nSwitch integer,
nStimuli inte... | The main task of the code is to connect to two SQLite databases, initialize their structures using specific functions (FirstGen, defineStimuli, FirstGenExpBase), commit changes, and securely close connections. It sets up foundational data schemas for "matrixProjects.db" and "matrixExperiments.db", ensuring database int... | def main():
conn = sqlite3.connect('matrixProjects.db')
c = conn.cursor()
FirstGen(c)
defineStimuli(c)
conn.commit()
conn.close()
conn2 = sqlite3.connect('matrixExperiments.db')
c2 = conn2.cursor()
FirstGenExpBase(c2)
conn2.commit()
conn2.close() |
def task1(input_num):
sqRoot = math.pow(input_num, 2)
return sqRoot
def task2(input_num):
return factorial(int(input_num))
def task3(input_num):
if int(input_num) % 2 == 0:
return "Even"
else:
return "Odd" | The code processes input_num concurrently using three threads to execute task1 (float), task2 (int), and task3 (original input), collects their results, and sends the combined output to the client socket as a response. | def handle_client(client_socket, input_num):
thread_results = []
thread1 = threading.Thread(
target=lambda: thread_results.append(str(task1(float(input_num)))))
thread2 = threading.Thread(
target=lambda: thread_results.append(str(task2(int(input_num)))))
thread3 = threading.Thread(
... |
def task1(num1, num2):
return lcm(num1, num2)
def task2(num1, num2):
return gcd(num1, num2)
def task3(num1, num2):
return num1 * num2 | The main task of the code is to handle a client request by concurrently executing three tasks (`task1`, `task2`, `task3`) with two input numbers, collect their string results, and send the aggregated output back to the client via a socket connection. The function uses multithreading to parallelize tasks, waits for all ... | def handle_client(client_socket, input_nums):
num1, num2 = input_nums
thread_results = []
thread1 = threading.Thread(
target=lambda: thread_results.append(str(task1(num1, num2))))
thread2 = threading.Thread(
target=lambda: thread_results.append(str(task2(num1, num2))))
thread3 = thr... |
def _create_cells(self):
for i in range(self._num_cols):
col_cells = []
for j in range(self._num_rows):
col_cells.append(Cell(self._win))
self._cells.append(col_cells)
self._check_random()
def _break_entrance_and_exit(self):
self._cells[0][0].h... | This code initializes a maze generator by setting up grid parameters, creating a cell structure, and configuring randomized pathways. It establishes maze dimensions, positions, and cell sizes, then generates entrance/exit points, breaks walls recursively for path creation, applies randomization based on a seed, and res... | def __init__(
self,
random_index,
x1,
y1,
num_rows,
num_cols,
cell_size_x,
cell_size_y,
win = None,
seed = None
):
self._cells = []
self._x1 = x1
self._y1 = y1
self._num_rows = num_rows
self._num_... |
def parse_hero_ml(code: str) -> List[HeroMLAction]:
actions = []
steps = code.split("->>>>")
for step in steps:
rules = parse_rules(step)
variables = extract_variables(step)
parsed_action = parse_action_string(step)
action = HeroMLAction(
type=ActionType.default... | This function interprets an Abstract Syntax Tree (AST) by evaluating nodes within dynamic and step environments. It processes default actions by evaluating content and handles loops by iterating over referenced lists, updating the dynamic environment with loop variables and step results. It logs progress and returns th... | def interpret(
nodes: Union[List["ASTNode"], str],
dynamic_environment: Environment,
step_environment: Environment = {},
depth: int = 0,
index: int = 0,
) -> Environment:
if isinstance(nodes, str):
parsed_hero_ml_data = parse_hero_ml(nodes)
ast = parse_heroML_to_AST(parsed_hero_m... |
def bind(self, A, B):
"""
Function:Bind: Takes a list of items with its match list and creates a new list where
the items of the list include an a list containing the item in the first index
and the second element is its corresponding matched pair.
Param:A: List of items
... | The main task of the code is to sort list `B` based on the corresponding values in list `A`. It combines the two lists into paired elements, sorts them using QuickSort according to `A`'s values, and returns the reordered `B` list. The function binds the lists, applies sorting, and unbinds to extract the sorted `B` valu... | def sort(self, A, B):
"""
function:sort: Binds two lists Sorts the list according to the values of the A list
And returns a sorted version of the B List.
Param:A: List of values to sort by.
Param:B: List of values to be sorted.
Returns: A sorted version of list B.
... |
def prepare_ddb_table(self):
try:
self.ddbconn.describe_table(TableName=self.ddbTableName)
except Exception:
self.ddbconn.create_table(
TableName=self.ddbTableName,
KeySchema=[{'AttributeName': 'path','KeyType': 'HASH'}],
AttributeD... | The code synchronizes S3 folder metadata with DynamoDB, checking for new incremental files. It lists S3 folders, prepares a DynamoDB table, and inserts/updates records with folder paths, statuses, and last processed files. If active, it identifies new incremental files, processes them, and updates DynamoDB with the lat... | def start(self):
folders = self.s3conn.list_objects(Bucket=self.bucket, Prefix=self.prefix, Delimiter='/').get('CommonPrefixes')
self.prepare_ddb_table()
for f in folders:
full_folder = f['Prefix']
folder = full_folder[len(self.prefix):]
path = self.bucket +... |
def init_camera_pose(self, initial_view):
print("------ start mission ------ \n")
print("------ initialize camera pose ------ \n")
if initial_view is None:
if self.initial_type == "random":
initial_view = utils.uniform_sampling(self.radius, self.phi_min)
... | The main task of the code is to control a sensor or camera to execute a sequence of planned views within a predefined budget. It initializes the camera's starting position, iteratively plans and moves the sensor to the next optimal view, and records the experiment upon completion. The process continues until the planni... | def start(self, initial_view=None):
self.init_camera_pose(initial_view)
while self.step < self.planning_budget:
next_view = self.plan_next_view()
self.move_sensor(next_view)
self.record_experiment()
print("------ complete mission ------\n") |
def check(self, col: Color) -> bool:
"""Checks if given player is endangered in that position
Parameters
----------
col: Color
Player to be checked
Returns
----------
bool
True -- player endangered
False -- player is no... | The function determines if a player can avoid check by either moving their king to a safe position or blocking the attack with another piece. It first checks if the player is already not in check. If so, it returns True. Otherwise, it simulates all possible king moves and checks if any avoid check. If not, it iterates ... | def avoid_check(self, col: Color) -> bool:
"""Checks if given player can avoid check
Parameters
----------
col: Color
Player to be checked
Returns
----------
bool
True -- player can avoid check
False -- player can not a... |
def setup():
global app_paths, assets_path
pymodules = []
for app in frappe.get_all_apps(True):
try:
pymodules.append(frappe.get_module(app))
except ImportError:
pass
app_paths = [os.path.dirname(pymodule.__file__) for pymodule in pymodules]
assets_path = os.path.join(frappe.local.sites_path, "assets")
... | (Bundle function's main task: Concatenate/minify JavaScript files using Node.js package manager (npm/yarn) with configurable build mode, app scope, and asset directory settings. It executes "build" or "production" commands, skips Frappe if specified, and handles asset directory creation and environment setup for fronte... | def bundle(no_compress, app=None, hard_link=False, verbose=False, skip_frappe=False):
"""concat / minify js files"""
setup()
make_asset_dirs(hard_link=hard_link)
pacman = get_node_pacman()
mode = "build" if no_compress else "production"
command = "{pacman} run {mode}".format(pacman=pacman, mode=mode)
if app:
... |
def get_combination(books: list[int]) -> dict[int:int]:
combination = {cnt:0 for cnt in range(1, 6)}
uni_books = set(books)
while len(books) > 0:
combination[len(uni_books)] += 1
for book in uni_books:
books.remove(book)
uni_books = set(books)
return combination... | The main task of the code is to calculate the total price of a list of books after applying combination adjustments. It first generates a combination of books, modifies it by moving elements (e.g., 5 to 3), and then computes the final price based on the adjusted combination. The function returns this computed price as ... | def price(books: list[int]) -> float:
combination = get_combination(books)
move_5_to_3(combination)
return price_of_combination(combination) |
def get_tb_colums(tb_name):
tbs = get_tb_names()
if tb_name not in tbs:
return []
cols = query_db("SELECT name FROM PRAGMA_TABLE_INFO('%s');" % tb_name)
cols = [x['name'] for x in cols]
print(cols)
return cols
def query_db(query, args=(), one=False, db=None):
print(query, args)
... | The main task of the code is to update a database table (`tb_name`) with specified `items` where conditions defined in `filters` apply. It validates that all keys in `items` and `filters` exist in the table's columns, constructs an SQL `UPDATE` query with dynamic fields and conditions, executes the query with combined ... | def update_db(tb_name, items, filters):
keys = items.keys()
filter_keys = filters.keys()
# check
cols = get_tb_colums(tb_name)
for x in list(keys) + list(filter_keys):
if x not in cols:
return False
filters_text = ' WHERE ' + ' AND '.join(['%s=?' % key for key in f... |
def get_tb_colums(tb_name):
tbs = get_tb_names()
if tb_name not in tbs:
return []
cols = query_db("SELECT name FROM PRAGMA_TABLE_INFO('%s');" % tb_name)
cols = [x['name'] for x in cols]
print(cols)
return cols
def query_db(query, args=(), one=False, db=None):
print(query, args)
... | The main task of the code is to insert data into a database table after validating that all keys in the input dictionary correspond to valid columns in the specified table. It checks for invalid columns, constructs an SQL INSERT query with placeholders, executes the insertion, and commits the transaction if successful. | def insert_db(tb_name, d):
cols = get_tb_colums(tb_name)
for x in d.keys():
if x not in cols:
print("ERROR", '`' + x + '`', "invalid colum")
return False
query_db('INSERT INTO %s (%s) VALUES (%s)' % (tb_name, ', '.join(list(d.keys())), ', '.join(['?'] * len(d))), tuple(d.valu... |
def get_tb_colums(tb_name):
tbs = get_tb_names()
if tb_name not in tbs:
return []
cols = query_db("SELECT name FROM PRAGMA_TABLE_INFO('%s');" % tb_name)
cols = [x['name'] for x in cols]
print(cols)
return cols
def query_db(query, args=(), one=False, db=None):
print(query, args)
... | The main task of the code is to safely delete records from a specified database table based on given filters. It validates filter keys against table columns, constructs a parameterized SQL DELETE query, executes it with provided values, and commits the transaction, returning True on success or False if invalid filters ... | def delete_db(tb_name, filters):
filter_keys = filters.keys()
# check
cols = get_tb_colums(tb_name)
for x in list(filter_keys):
if x not in cols:
return False
filters_text = ' WHERE ' + ' AND '.join(['%s=?' % key for key in filter_keys])
sql = 'DELETE FROM %s' % (t... |
def query_db(query, args=(), one=False, db=None):
print(query, args)
if not db:
db = g.db
try:
cur = db.execute(query, args)
rv = [dict((cur.description[idx][0], value)
for idx, value in enumerate(row)) for row in cur.fetchall()]
return (rv[0] if rv else None) ... | This API updates an elder's personal information in the database after validating their existence and person type. It checks if the provided loginID corresponds to an existing elder (personType=3). If valid, it removes the loginID from the input data, updates the PersonalInfo table with the new information, commits the... | def setElderPersonalInfoApi():
Params = request.json
selectResult = query_db("SELECT personType FROM PersonalInfo WHERE loginID=?", (Params["loginID"],))
if len(selectResult) == 0 or selectResult[0]["personType"] != 3:
return make_response(
jsonify(
{
... |
def load_datasets(self):
"""Load the datasets"""
if not all((self.train_loader, self.val_loader, self.test_loader)):
self.train_loader, self.val_loader, self.test_loader = load_data(self.args)
return self.data_loaders
def train_validate_with_scheduling(self, epoch, validate=True, ver... | The code's main task is to execute a training loop over multiple epochs, loading datasets, resetting performance tracking, and iterating through epochs to train and validate the model. It records top-1/top-5 accuracies and loss, finalizes each epoch's results, and returns the historical performance metrics tracked thro... | def begin_train_loop(self):
self.load_datasets()
self.performance_tracker.reset()
for epoch in range(self.start_epoch, self.ending_epoch):
top1, top5, loss = self.train_validate_with_scheduling(epoch)
self._finalize_epoch(epoch, top1, top5)
return self.performanc... |
def load_data(args, fixed_subset=False, sequential=False, load_train=True, load_val=True, load_test=True):
test_only = not load_train and not load_val
train_loader, val_loader, test_loader, _ = apputils.load_data(args.dataset, args.arch,
os.path.expanduser(args.data), args.batch_s... | This code evaluates a quantized model on a test dataset by loading test data, initializing activation statistics collectors, and running the evaluation with the model, loss function, logger, and compression scheduler to assess performance post-quantization. | def quantize_evaluate(self):
test_loader = load_data(self.args, load_train=False, load_val=False, load_test=True)
evaluate_model(test_loader, self.model, self.criterion, self.pylogger,
create_activation_stats_collectors(self.model, *self.args.activation_stats),
self.args,... |
def _matching_api_version(self, operation):
"""Find the latest version of the protocol operation supported by both
this library and the broker.
This resolves to the lesser of either the latest api version this
library supports, or the max version supported by the broker.
:param... | This method creates new Kafka topics by constructing and sending a CreateTopicsRequest, handling API version compatibility, validating parameters like timeout and validation mode, and returning the appropriate response. It supports version-specific features, such as 'validate_only' for pre-validation, and raises errors... | def create_topics(self, new_topics, timeout_ms=None, validate_only=False):
"""Create new topics in the cluster.
:param new_topics: A list of NewTopic objects.
:param timeout_ms: Milliseconds to wait for new topics to be created
before the broker returns.
:param validate_only... |
def _matching_api_version(self, operation):
"""Find the latest version of the protocol operation supported by both
this library and the broker.
This resolves to the lesser of either the latest api version this
library supports, or the max version supported by the broker.
:param... | This method deletes specified Kafka topics from a cluster. It validates the timeout, selects the appropriate API version, constructs a DeleteTopicsRequest for version 1 or lower, sends it to the controller, and returns the response. Higher versions trigger an error as they are not yet supported by KafkaAdminClient. | def delete_topics(self, topics, timeout_ms=None):
"""Delete topics from the cluster.
:param topics: A list of topic name strings.
:param timeout_ms: Milliseconds to wait for topics to be deleted
before the broker returns.
:return: Appropriate version of DeleteTopicsResponse ... |
def _matching_api_version(self, operation):
"""Find the latest version of the protocol operation supported by both
this library and the broker.
This resolves to the lesser of either the latest api version this
library supports, or the max version supported by the broker.
:param... | The code creates additional partitions for existing Kafka topics using the CreatePartitions API. It accepts parameters like topic-partition mappings, timeout, and validation mode. It validates the API version, constructs a request for version 0, and sends it to the controller. If a higher version is used, it raises an ... | def create_partitions(self, topic_partitions, timeout_ms=None, validate_only=False):
"""Create additional partitions for an existing topic.
:param topic_partitions: A map of topic name strings to NewPartition objects.
:param timeout_ms: Milliseconds to wait for new partitions to be
... |
def weight_check():
"""
make sure the weighted values add up to 100% of home cost
"""
if sum(HOMES_ATTRIBUTES_WEIGHTED_VALUES.values()) < 0.9999999999:
print("Miscalculation of weights")
exit(1)
def calculate_and_show_basic_mean():
"""
this is a basic mean of homes based soley on price
"""
print... | The main task of the code is to execute a sequence of data analysis and prediction tasks, including validating weights, calculating averages, processing home data, resolving statistical averages, verifying predictability, and predicting home sale prices. It orchestrates multiple functions to analyze data, ensure consis... | def execute():
"""
This executes main jobs
and can be used to show / print info
"""
weight_check()
calculate_and_show_basic_mean()
loop_homes()
resolve_averages()
verify_predictability()
predict_homes_sale_price() |
def is_baxter_permutation(seq):
is_baxter = True
for subseq in get_subsequence(4, seq):
if subseq_matches_pattern(seq, subseq, [3, 1, 4, 2],
[False, True, False, True]) or \
subseq_matches_pattern(seq, subseq, [2, 4, 1, 3],
[... | The main task of the code is to find the optimal rectangular partitioning (rectangulation) for a given window size by evaluating all valid Baxter permutations of regions. It iterates through permutations, filters valid ones, computes rectangulation equations, minimizes the layout using optimization, and selects the bes... | def get_best_rect_for_window(N, c, k, w, h):
# Check all permutations
f_best = sys.float_info.max
sol_best = np.zeros(0)
B_best = None
seq_best = None
# If the new optimum is only very slightly better, keep the old
# value so solutions are more congruent when the parameters change
# slig... |
def _find_biggest_labels(self):
"""
Sets (self.biggest_labels) and returns a dictionary with the
graphIDs as the keys and the biggest label in the subgraph
as the value.
"""
biggest_labels = dict()
for graphID in self.bridges.sub_graphs_nodes.keys():
... | This code initializes a structure analysis tool by creating voxel representations of an atom group, applying labeling based on neighbor masks or clustering, and identifying structural features like bridges, largest labels, and paths, followed by atom position adjustments. | def __init__(self, atomgroup, resolution=1, hyperres=False,
neighbor_mask=np.ones((3,3,3)), clusters=False):
self.clusters = clusters
if self.clusters is False:
self.voxels = Voxels(atomgroup, resolution, hyperres)
self.voxels.label(neighbor_mask=neighbor_mask)
... |
def __checkNset_labels(self):
"""
Checks if the labels have been generated, if not, generate them using the default
neighbormask of 26 neighbors.
"""
if not hasattr(self, 'labels'):
print('The default 26 neighbormask has been used for labeling.\n'
'R... | The main task of the code is to retrieve an atomgroup containing all atoms located within voxels identified by a specified labelID. It ensures label data exists, identifies the relevant voxels using the labelID, and extracts the corresponding atoms from those voxels to return as an atomgroup. | def get_label(self, labelID):
"""
Returns the atomgroup of all atoms which lie in a voxel with the
specified labelID (int).
"""
# If not self.labels, create them.
self.__checkNset_labels()
# Get the atomgroup.
voxels = self.get_label_voxels(labelI... |
def tab1(self):
self.tab1 = QWidget()
self.tabs.addTab(self.tab1,"Boat Info")
self.tab1.layout = QGridLayout(self)
self.gps_lbl = QLabel()
self.rudder_pos_lbl = QLabel()
self.sail_pos_lbl = QLabel()
self.boat_orient_lbl = QLabel()
self.wind_speed_lbl = QLabel()
self.wind_dir_lbl = QLabel()
#img a... | The code initializes a GUI window with a tabbed interface, setting up four tabs (tab1-tab4), a vertical layout, and a sans-serif font. It prepares variables for animation and adds the tab widget to the layout. | def __init__(self, parent):
super(QWidget, self).__init__(parent) # calls QWidget.init (parent class of tabWidget)
self.layout = QVBoxLayout(self) #lines items up vertically, not relevent as theres only one item (tabWidget)
self.setFont(QtGui.QFont('SansSerif', 13))
# Initialize tab screen
self.tabs = QTabW... |
def get_source_files(root_dir):
source_files = []
for _, _, filenames in os.walk(f'{root_dir}/{Directory.SOLUTIONS}'):
source_files.extend(filenames)
break
return source_files
def load_dict(pkg, file):
return json.loads(resource_string(pkg, file).decode('utf-8'))
def update_with_custom_c... | The function compiles source files using specified compilers, either all files in the project or a specific file based on its extension. It loads compiler configurations, determines files to compile, and executes the compilation process, returning the list of compiled files. Debug mode is supported for detailed output. | def compile_cmd(file, debug=False):
root_dir = find_root_directory(os.getcwd())
source_files = get_source_files(root_dir)
compilers_meta = load_dict('tess.resources.config', 'compilers.json')
update_with_custom_config(compilers_meta)
to_compile = get_files_to_compile(source_files, compilers_meta)
... |
def resolve_runnable_filename(source_filename: str):
name, ext = os.path.splitext(source_filename)
if ext == '.cpp' or ext == '.cc':
return name
elif ext == '.java':
return f'{name}.class'
else:
return source_filename
def concat_cases_absolute_path(tests: list):
root_dir = ca... | The function `run_solution` compiles a source file if needed, determines test cases (either specified or all in a directory), prepares execution arguments, and runs the tests. It handles compilation, test selection, and execution, with debug mode support for detailed output. | def run_solution(file, test, debug=False):
if should_be_compiled(file):
compile_cmd(file, debug)
file = resolve_runnable_filename(file)
if test:
tests = concat_cases_absolute_path([test])
else:
tests = concat_cases_absolute_path(list_files(Directory.CASES))
args = runner_... |
def on_quit(self):
creatures = self.get_creature_group()
averages = self.get_creatures_avg(creatures)
print(averages)
def time_step(self):
for c in self.creatures:
c.run_ai(self.creatures, self.foods)
clamped_distance = self.clamp_movement(c, self.map_width, self.... | This code runs a simulation loop for a game or AI environment, handling events, updating game state, rendering graphics, tracking creature statistics, and resetting daily cycles. It identifies the highest-energy creature, prints its attributes, calculates averages, and manages food resources, ensuring the simulation ru... | def run_sim(self, foods_count):
last_run = 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
self.on_quit()
pygame.quit()
quit()
time.sleep(max(0, self.sim_delay - last_run))
... |
def init_window(self):
pygame.init()
self.render_display = pygame.display.set_mode((self.map_width * self.render_scale, self.map_height * self.render_scale))
window_icon = pygame.image.load("image/evolution.png")
pygame.display.set_icon(window_icon)
pygame.display.set_caption("Ev... | This code initializes a simulation by setting up a window, spawning creatures based on specified percentages of a starting count, positioning them randomly, initializing food items, and starting the simulation. It creates creature instances, assigns their coordinates, and prepares the environment for the simulation to ... | def __init__(self, foods_count, creatures_start):
self.init_window()
for creature_type, percent in self.creatures_spawn:
for i in range(int(math.floor(creatures_start * percent))):
creature_init = creature_type()
creature_init.x = self.generate_x()
... |
def preprocess(raw):
raw = raw.lower()
raw = raw.split()
ps = PorterStemmer()
# all_stopwords = stopwords.words('english')
# print(len(all_stopwords))
# len(all_stopwords)
# all_stopwords.remove('not')
word_lst = [ps.stem(word) for word in raw]
return word_lst
def cosine_similarity_s... | The code predicts a grade based on the similarity between a student's answer and a sample answer. It calculates two similarity scores (cosine_similarity_score and cosine_sim), combines them using an exponential transformation, and returns a percentage grade. The similarity scores are printed for reference. | def predict_grade(student_ans, sample_ans):
stu_lst=preprocess(student_ans)
sam_lst=preprocess(sample_ans)
similarity_score1= cosine_similarity_score(stu_lst, sam_lst)
similarity_score2= cosine_sim(student_ans, sample_ans)
### final grade
grade = 1/(1+math.exp(0-((similarity_score1+similarity_sc... |
def drawBackToMenu():
# Draw in game UI including back to menu button
mouseX, mouseY = pygame.mouse.get_pos() # Get mouse X and Y coords
if mouseOver(5,5,82, 40, mouseX, mouseY):
drawButton("MENU", 5,5, 1)
if mouseWasDown:
global menu, game
menu = 1
game =... | This function handles game state selection by directing to different text-based game modes (0-9) via the 'game' variable, passing corresponding text data to 'inGame()'. If an unimplemented menu item is selected, it displays a warning message or skips back to the menu. | def drawGame():
# Game logic and drawing the selected game
drawBackToMenu()
if game == 0:
inGame(text.topRow[curLine], len(text.topRow))
elif game == 1:
inGame(text.bottomRow[curLine], len(text.bottomRow))
elif game == 2:
inGame(text.bothRows[curLine], len(text.bothRows))
... |
def __is_matching_types(t1, t2) -> bool:
t1 = __type_check(t1)
t2 = __type_check(t2)
if t1 == t2:
return True
return False
def __is_defined_list(type_str: str) -> bool:
return type_str.startswith("typing.List")
def __get_list_inner_type(type_str: str) -> str:
return type_str.replace("typ... | This function maps data from 'src' to 'des' based on type annotations in 'root_class', converting values using reader/writer functions. It handles type mismatches with warnings, processes lists by converting elements, and ensures data conformity with annotated types through dynamic class imports and value transformatio... | def _maprit(src, des, root_class):
rwkey = "d2o" if isinstance(src, dict) else "o2d"
rdr = __rw[rwkey]["r"]
wtr = __rw[rwkey]["w"]
rcv = __rw[rwkey]["rcv"]
annots = root_class.__dict__["__annotations__"]
for k,t in annots.items():
v = rdr(src, k)
tstr = str(t)
if v != ... |
def autoinvert(image):
assert amin(image) >= 0
assert amax(image) <= 1
if sum(image>0.9) > sum(image<0.1):
return 1-image
else:
return image
def random_blotches(image, fgblobs, bgblobs, fgscale=10, bgscale=10):
fg = random_blobs(image.shape, fgblobs, fgscale)
bg = random_blobs(im... | The function generates a printed-like image by combining multiscale noise (ink and paper textures) with a blurred, selectively inverted input image. It applies random blotches, Gaussian blur, and blends the result using ink (dark noise) and paper (light noise) to simulate a textured print effect. | def printlike_multiscale(image, blur=1.0, blotches=5e-5):
selector = autoinvert(image)
selector = random_blotches(selector, 3*blotches, blotches)
paper = make_multiscale_noise_uniform(image.shape, limits=(0.5, 1.0))
ink = make_multiscale_noise_uniform(image.shape, limits=(0.0, 0.5))
blurred = ndi.ga... |
def funcion_evaluadora(self, ficha_, tablero):
resultado = 0
humano_jugador = self.tablero.getfichasMarta(tablero)
humano_marta = self.tablero.getfichasJugador(tablero)
for columna in range(10):
for fila in range(10):
if tablero[fila][columna].ficha_ == 2:
... | This code implements the Minimax algorithm with alpha-beta pruning for a board game. It evaluates possible moves recursively, alternating between maximizing and minimizing players. The function returns the best move and its evaluation value, considering depth limits and time constraints. Alpha-beta pruning optimizes pe... | def minimax(self, profundida, limite, tablero, alpha=float("-inf"), beta=float("inf"), maximizando=True):
nodo = None
if profundida == 0 or time.time() > limite or self.tablero.ganador(tablero):
return self.funcion_evaluadora(2, tablero), None
if maximizando:
nodo_v = flo... |
def _sanatize_update_url(self, url, urls):
_urls = []
# Making sure final output is a list
if isinstance(urls, list):
_urls += urls
elif isinstance(urls, six.string_types):
log.warning('UPDATE_URLS value should only be a list.')
_urls.append(urls)
... | (The main task of the code is to initialize a client with configuration values from an object, handling platform-specific settings, update URLs, public keys, and directories. It processes config parameters like `UPDATE_URL`, `APP_NAME`, and `PUBLIC_KEYS`, ensures proper directory paths for updates, validates inputs, an... | def init_app(self, obj, refresh=False, test=False):
"""Sets up client with config values from obj
Args:
obj (instance): config object
Kwargs:
refresh (bool) Meaning:
True: Refresh update manifest on object initialization
False: Don't refresh ... |
def show_mine(self):
self.cell_btn_obj.configure(bg="red")
ctypes.windll.user32.MessageBoxW(0, "Tocaste una mina", "Game Over", 0)
sys.exit()
def count_mines(self):
number = 0
cells = self.sourronded_cells()
for cell in cells:
if cell.is_mine:
... | This function handles left-click actions in a Minesweeper-like game. It reveals a mine if clicked on one, otherwise checks for empty cells to trigger neighbor reveals, counts surrounding mines, and checks if all non-mine cells are revealed to declare a win, displaying a message and exiting the game. | def left_click_actions(self, event):
if self.is_mine:
self.show_mine()
else:
if self.count_mines() == 0:
# print("Presionar vecinos")
for cell in self.sourronded_cells():
cell.number_mines()
self.number_mines()
... |
def get_dir_files(path, recursive=False):
files = []
for file in os.scandir(path):
files.append(file)
if recursive and file.is_dir():
files.extend(get_dir_files(os.path.join(path, file)))
return files
def filter_non_folders(files):
return [file for file in file... | This code implements a custom file listing utility similar to Unix's `ls` command, allowing users to display directory contents with options for hidden files, recursion, file size, line count, folder-only views, and reverse sorting. It processes command-line arguments, filters files/directories based on flags, and form... | def ls():
args = parse_args()
include_hidden_files = args.a
is_recursive = args.R
display_file_size = args.l
display_file_line_count = args.c
display_only_folders = args.d
display_folder_files_count = args.d
reverse_display_order = args.r
current_path = Path(os.getcwd())
dir_pat... |
def Dprocess(Din,length_unit=u.Mpc):
# this is a hack so we can handle either a single value or a list
if np.isscalar(Din):
oneflag = True
Din2 = [Din]
elif isinstance(Din,list):
oneflag = False
Din2,Dshape = list_flatten(Din)
elif isinstance(Din,np.ndarray):
if l... | This code initializes a gravitational lensing model by grouping lens planes into slabs based on scaled distances, processing reference distances, configuring multi-mode parameters, and setting up grids for critical curves/caustics calculations. It handles observed/intrinsic position transformations, initializes lensing... | def __init__(self,plane_list,xtol=1.0e-5,Ds=1,Dref=None,length_unit=u.arcsec,position_mode='obs',multi_mode=[],Ddecimals=4):
self.xtol = xtol
self.Ds,self.Ds_dim = Dprocess(Ds)
self.length_unit = length_unit
self.position_mode = position_mode
# factor for time delays
sel... |
def points_in_triangle(v,n):
x1 = np.sort(np.random.rand(2,n),axis=0)
x2 = np.column_stack([x1[0],x1[1]-x1[0],1.0-x1[1]])
return x2@v
def lenseqn(self,xarr,stopslab=-1,Dsnew=None,output3d=False):
if stopslab<0: stopslab = len(self.slab_list)
xarr = np.array(xarr)
# need special treat... | The code identifies triangles with sign changes in magnification products, generates new points within these critical triangles, computes their properties, appends them to existing point lists, and re-triangulates to incorporate the new points, enhancing mesh resolution where magnification behavior changes. | def addpoints(self,nnew):
# examine products of magnifications on triangle edges
magprod0 = self.minv[self.tri.simplices[:,0]]*self.minv[self.tri.simplices[:,1]]
magprod1 = self.minv[self.tri.simplices[:,1]]*self.minv[self.tri.simplices[:,2]]
magprod2 = self.minv[self.tri.simplices[:,2]]... |
def calc_tfac(self,Ds):
Ds_proc,Ds_dim = Dprocess(Ds)
if Ds_dim is False:
# we have dimensionless distance(s), so set tfac=1;
# this is a hack to make sure tfac aligns with Ds
tfac = 0*Ds_proc + 1
return tfac
else:
if Ds_proc.unit.is_eq... | This function computes gravitational lensing images for given source positions by optimizing image locations using triangle-based minimization, calculating magnifications, and differential time delays. It handles single or multiple sources, adjusts for distances, and returns image positions, magnifications, and time de... | def findimg(self,u,plane=-1,Dsnew=None):
if self.griddone==False:
print('Error: tiling has not been completed')
return [],[],[]
srcarr = np.array(u)
if srcarr.ndim==1:
oneflag = True
srcarr = np.array([u])
elif srcarr.ndim==2:
... |
def get_attribute(self, command: str) -> str:
"""Get the value of attribute specified in the command.
If the attribute specifies a callable, the function returns that the object is an callable, allowing
the client to send another request with the desired arguments.
Args:
co... | This function executes a JSON-encoded command by either retrieving an attribute or invoking a method on a target class. It processes arguments/kwargs from JSON, converts them to native types, calls the function, and returns the result in JSON format with a "success" status. | def run_command(self, command: str) -> str:
"""Run a command that is encoded in a JSON format.
If the command does not reference a function, the attribute value is returned instead.
Args:
command: JSON representation of the command.
Returns:
Return value of the... |
def check_server_path(self, previous: Path | None, new: Path | None) -> None:
"""Verify that exe and py version do not change over the lifetime of the RunServer instance.
Args:
previous: The current (previous) path.
new: The new path.
"""
if not previous or not n... | This code initializes a server instance by checking provided executable and script paths, ensuring the server is running if not already started, and tracking caller references to manage server termination when all callers release their references. | def __init__(self, caller: object | int, server_exe: Path | None = None, server_py: Path | None = None) -> None:
"""Start up a server if it is not running already.
The calling instance needs to pass a reference to itself as the caller. At the end, the caller needs to call
the release() method w... |
def _get_posts_from_users(self, users: [User]) -> [Post]:
posts = []
for user in users:
for post in user.posts:
posts.append(post)
return posts
def _sort_users_by_posts_count(self, users: [User]) -> [User]:
return sorted(users, key=lambda user: user.posts_coun... | The code's main task is to initiate a user interaction process where users are sorted by their post count, and for each user, it identifies those who have not liked any posts. It then triggers a liking process for the current user, targeting users with zero liked posts, using all retrieved posts. This likely simulates ... | def start(self) -> None:
all_posts = self._get_posts_from_users(self._users)
users_by_posts_count = self._sort_users_by_posts_count(self._users)
for user in users_by_posts_count:
users_with_zero_liked_post = self._get_users_with_zero_liked_post(
self._users)
... |
def _process_json_response(self, r, action_result):
# Try a json parse
# For the valid 201 response, we are getting application/json in the header and empty json response in the body
try:
resp_json = r.json() if r.text else {}
except Exception as e:
msg_string = ... | The function processes an HTTP response by logging debug data, then routing the response based on its Content-Type. It handles JSON, HTML, and empty responses, returning errors for unexpected cases. Debug info includes response text, headers, and status code. If the response is HTML, it parses potential proxy errors. I... | def _process_response(self, r, action_result):
# store the r_text in debug data, it will get dumped in the logs if the action fails
if hasattr(action_result, 'add_debug_data'):
if r is not None:
action_result.add_debug_data({'r_text': r.text})
action_result.a... |
def _run_query(self, param):
""" Action handler for the 'run query' action"""
# This is an action that needs to be represented by the ActionResult object
# So create one and add it to 'self' (i.e. add it to the BaseConnector)
# When the action_result is created this way, the parameter i... | This code queries Elasticsearch using a configured index and query, processes results with a specified parser (or default), and saves parsed data as containers. It validates required config fields, handles parsing errors, and limits results based on container count, returning success or error statuses accordingly. | def _on_poll(self, param):
container_count = param.get('container_count', 0)
config = self.get_config()
if not all(field in config for field in self.REQUIRED_INGESTION_FIELDS):
return self.set_status(phantom.APP_ERROR, ELASTICSEARCH_ON_POLL_ERROR_MESSAGE)
query_params = {
... |
def distance(X1, Y1, X2, Y2):
a = X1 - X2
b = Y1 - Y2
c_2 = squared(a) + squared(b)
return math.sqrt(c_2)
def lawOfCosines(r1, r2, angle):
return round(math.sqrt(squared(r1) + squared(r2) - (2 * r1 * r2) * cos(angle)), 4)
def checkDistance(dCalc, dCos):
if math.isclose(dCalc, dCos, rel_tol=0.01)... | The function `solveCircles` calculates intersection points of two circles defined by radii `r1`, `r2`, angle `angle`, and centers `(X1,Y1)` and `(X2,Y2)`. It verifies if the distance between centers matches the law of cosines result for the given angle. If valid, it computes intersection coordinates using quadratic equ... | def solveCircles(r1, r2, angle, X1, Y1, X2, Y2):
dCalc = distance(X1, Y1, X2, Y2)
dCos = lawOfCosines(r1, r2, angle)
if checkDistance(dCalc, dCos) == True:
# print("Distance: {:.4f} meters".format(dCalc))
if X1 == X2 and abs(Y1) == abs(Y2):
y = solveYSpecial(X1, Y1, X2, Y2, r1... |
def degtorad(degrees):
return math.radians(degrees)
def assignGears(x1_ref, y1_ref, x2_ref, y2_ref, x3_ref, y3_ref, r1, r2, r3, theta12, theta13):
knownD12 = distance(x1_ref, y1_ref, x2_ref, y2_ref) # back landing gears
knownD13 = distance(x1_ref, y1_ref, x3_ref, y3_ref) # front to back landing gears
... | This function calculates the coordinates of points based on gear radii and angular positions, computes circle intersections, rounds the results, and compares points to determine final coordinates (c_x, c_y). | def functionName(r1, r2, r3, x_1, y_1, x_2, y_2, x_3, y_3, angle12, angle13):
theta12 = degtorad(angle12)
theta13 = degtorad(angle13)
x1, y1, x2, y2, x3, y3 = assignGears(x_1, y_1, x_2, y_2, x_3, y_3, r1, r2, r3, theta12, theta13)
x1_, y1_, x2_, y2_ = solveCircles(r1, r2, theta12, x1, y1, x2, y2)
... |
def set_start_and_end(start_point, end_point):
if start_point is not None:
change_point = input("What would you like to change? type 'o' to change the origin, 'd' to change the "
"destination, or 'b' for both: \n")
if change_point == 'b':
start_point = get_s... | The code defines a function `new_route` to find and display the shortest metro route between two points. It uses helper functions to set start/end points and retrieve the route. If a route exists, it formats and prints the path; otherwise, it notifies the user of maintenance issues. After each query, it prompts the use... | def new_route(start_point=None, end_point=None):
start_point, end_point = set_start_and_end(start_point, end_point)
shortest_route = get_route(start_point, end_point)
if shortest_route:
shortest_route_string = ""
for i in range(len(shortest_route)):
shortest_route_string += "{0} ... |
def greet():
print("Hi there and welcome to SkyRoute!")
print("We'll help you find the shortest route between the following Vancouver landmarks:\n" + landmark_string)
def new_route(start_point=None, end_point=None):
start_point, end_point = set_start_and_end(start_point, end_point)
shortest_route = get_... | The code defines a function `skyroute()` that sequentially executes three tasks: greeting the user, creating or processing a new route, and sending a farewell message. It orchestrates these steps in order to manage a route-related workflow, likely for navigation or logistics purposes. | def skyroute():
greet()
new_route()
goodbye() |
def execute_query(self, query, params=()):
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
result = cursor.execute(query, params)
conn.commit()
return result
def clear_entries(self):
self.nim_entry.delete(0, tk.END)
self.nama_entry.d... | The main task of the code is to add new student data to a database after validating inputs. It retrieves NIM, name, address, and major from input fields, checks if NIM is numeric and all fields are filled, verifies NIM uniqueness in the database, inserts valid data into the "Mahasiswa" table, clears input fields, and r... | def add_data(self):
# Ambil data dari input user
nim = self.nim_entry.get()
nama = self.nama_entry.get()
alamat = self.alamat_entry.get()
jurusan = self.jurusan_entry.get()
# Validasi input
if not nim.isdigit():
tkinter.messagebox.showerror("Error", ... |
def execute_query(self, query, params=()):
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
result = cursor.execute(query, params)
conn.commit()
return result
def clear_entries(self):
self.nim_entry.delete(0, tk.END)
self.nama_entry.d... | This code updates selected student data in a database after validating inputs, ensuring NIM uniqueness, and refreshing the display. It retrieves user inputs, checks for selection, validates NIM format and field completeness, prevents duplicate NIM entries, executes the SQL UPDATE query, clears fields, and refreshes the... | def edit_data(self):
if not self.tree.focus():
tkinter.messagebox.showwarning(
title="Warning", message="Please select data to edit"
)
return
# Ambil data dari input user
nim = self.nim_entry.get()
nama = self.nama_entry.get()
... |
def cred_setup(self, cred_path=None):
cred_path = cred_path if cred_path else self.cred_file_path
creds = None
try:
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', self.scopes)
# If there are no (valid) credentials available, let the user log in.
if not ... | This code initializes an object with parameters like document ID, credentials file path, and scopes. It sets up credentials, retrieves a service, and fetches a document, likely for interacting with a document management system or API. The 'template' and 'testing' flags suggest configuration for different modes of opera... | def __init__(self, id, cred_file_path, scopes, template=True, testing=False):
self.doc_id = id
self.scopes = scopes
self.cred_file_path = cred_file_path
self.template = template
self.testing = testing
self.creds = self.cred_setup(cred_file_path)
self.service = self.get_service()
self.document = self.get... |
def animate(self):
center = self.rect.center
if (self.facing_left):
self.image = pg.transform.flip(self.game.img_player, True, False)
else:
self.image = self.game.img_player
self.image.set_colorkey(COLOR_GREEN)
self.rect = self.image.get_rect()
s... | This method updates the player's position and physics in a game, handling gravity, collision checks, platform interactions, and movement. It adjusts velocity with friction, enforces boundaries, manages jumping states, and checks for level-specific boss conditions. It also updates animation, facing direction, and self-d... | def update(self):
mouse_x, mouse_y = pg.mouse.get_pos()
self.animate()
if (self.game.level == 10):
if (not (self.game.boss.current_hp <= 0)):
self.checkCollision()
else:
self.checkCollision()
if self.jumping:
self.acc = vec(0,... |
def move(self):
now = pg.time.get_ticks()
if (self.name == "head"):
if (self.rect.right <= (GAME_TILESIZE + (GAME_TILESIZE / 3))):
self.vel.x = MOB_HEAD_SPEEDX
elif (self.rect.x >= (GAME_WIDTH - self.rect.width - (GAME_TILESIZE / 3))):
self.vel.x ... | This method updates an object's position, checks for collisions, removes lasers when out-of-bounds or destroyed, sets guard facing direction based on player position, and triggers animations. It handles movement, collision detection, entity removal logic, and visual state updates for game objects like lasers and guards... | def update(self):
self.move()
self.checkCollision()
if (self.name == "laser"):
if ((self.rect.bottom <= 0) and (not self.initiated)):
self.killSelf()
if (self.current_hp <= 0):
self.killSelf()
if (self.name == "guard"):
if (... |
def create_matrices() -> list[np.ndarray]:
matrices: list[np.ndarray] = []
rows_i = [x for x in range(7)]
for i in rows_i:
rows_j = rows_i[:]
rows_j.remove(i)
for j in rows_j:
rows_k = rows_j[:]
rows_k.remove(j)
for k in rows_k:
ro... | The function `part_two` processes two input lists of string matrices. It generates a list of matrices, computes transformed versions (`p_matrices`) using the input data and initial matrices, then derives output values based on these transformed matrices and the `input_right` data. Finally, it returns the sum of these o... | def part_two(input_data: list[list[str]], input_right: list[list[str]]) -> int:
matrices: list[np.ndarray] = create_matrices()
p_matrices: list[np.ndarray] = compute_p_matrices(input_data, matrices)
outputs: list[int] = get_outputs(p_matrices, input_right)
return sum(outputs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.