dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def format_next_str(s):
return "(" + format_str(s).replace("next","").replace("(","").replace(")","") + "')"
def format_str(s):
return ((s.replace(".", "_")).replace("!","~")).replace("&","/\\").replace("|","\/")
def format_post(post):
post_lst = post.split()
for i in range(len(post_lst)):
if("next" in post_lst[i... | The main task of the code is to process an input string `tr` by checking if it contains a colon (`:`). If present, it splits the string into two parts, formats them separately using `format_str` and `format_post`, then passes them to the `trans` function. If no colon exists, it uses `format_next_str`. The function retu... | def format_trans(tr):
if (tr is ''):
return ""
if (":" not in tr):
return format_next_str(tr)
tr = tr.split(":")
pre = format_str(tr[0])
post = format_post(tr[1])
return trans(pre, post) |
def isBoolean(key):
return ((key == 'TRUE') or (key == 'FALSE'))
def assignBool(key, dict):
var_name = remove_dot(key)
if (dict[key] == 'TRUE'):
return var_name
else:
return NOT+var_name
def isNumber(key):
return key.isdigit()
def assignBin(key, dict, bitblasting_dict):
bits = []
var_name = remove_dot(key)
... | This code parses an SMV model to generate initial states (I) and transition relations (R) as boolean expressions. It uses pynusmv to load the model, extract state variables, build a bit-blasting dictionary for variable widths, and construct I/R by iterating over reachable states. The results are written to files, handl... | def main_parse(smv_file_name, bitblasting_dict, parsed_madel_file_I_name, parsed_madel_file_R_name):
#########################
# Model Initialization #
#########################
# pynusmv.init.init_nusmv()
pynusmv.glob.load_from_file(smv_file_name)
pynusmv.glob.compute_model()
fsm = pynusmv.glob.prop_database()... |
def isBoolean(key):
return ((key == 'TRUE') or (key == 'FALSE'))
def assignBool(key, dict):
var_name = remove_dot(key)
if (dict[key] == 'TRUE'):
return var_name
else:
return NOT+var_name
def isNumber(key):
return key.isdigit()
def assignBin(key, dict, bitblasting_dict):
bits = []
var_name = remove_dot(key)
... | This code parses a SMV model using PyNuSMV, extracting state variables, reachable states, and constructing bit-blasting dictionaries for variable widths. It generates initial condition (I) and transition relation (R) files in Boolean logic format, handling data types like unsigned words. The output files represent the ... | def main_model_parse(smv_file_name, bitblasting_dict, parsed_madel_file_I_name, parsed_madel_file_R_name, PARSE_INDEX):
# pynusmv.init.init_nusmv()
pynusmv.glob.load_from_file(smv_file_name)
pynusmv.glob.compute_model()
fsm = pynusmv.glob.prop_database().master.bddFsm
enc = fsm.bddEnc
# ### DEBUG
# print("======... |
def setup(self):
seed_index_everything(self.cfg.train)
self.fast_dev_run: bool = self.cfg.train.trainer.fast_dev_run
if self.fast_dev_run:
pylogger.info(
f"Debug mode <{self.cfg.train.trainer.fast_dev_run=}>. Forcing debugger friendly configuration!"
)
... | The main task of the code is to execute a machine learning pipeline by initializing configurations, loading a dataset via a datamodule, determining the number of classes, selecting a neural network architecture, instantiating a model, and training it using the provided data and model. The result of the training process... | def run(self) -> str:
self.setup()
datamodule = self.get_datamodule(cfg=self.cfg)
num_classes = len(datamodule.metadata.class_vocab)
arch = self.get_arch(cfg=self.cfg, num_classes=num_classes)
model = self.get_model(cfg=self.cfg, arch=arch, metadata=datamodule.metadata)
r... |
def build_callbacks(self) -> None:
self.template_core: NNTemplateCore = NNTemplateCore(
restore_cfg=self.cfg.train.get("restore", None),
)
self.callbacks: List[Callback] = build_callbacks(self.cfg.train.callbacks, self.template_core)
self.storage_dir: str = self.cfg.core.stor... | The code initializes a class with configuration settings, setting up callbacks, logger, and trainer components. It configures instance attributes using the provided DictConfig, builds essential modules like callbacks, logger, and trainer, preparing the object for tasks like training or logging. | def __init__(self, cfg: DictConfig):
self.cfg = cfg
self.template_core = None
self.callbacks = None
self.storage_dir = None
self.logger = None
self.trainer = None
self.fast_dev_run = None
self.build_callbacks()
self.build_logger()
self.buil... |
def game_over(self):
if ' ' not in self.board or self.check_win('X') or self.check_win('O'):
return True
return False
def display_board(self):
for i in range(0, 9, 3):
print(' | '.join(self.board[i:i + 3]))
if i < 6:
print('---------')
def available_moves(se... | The code implements a Tic-Tac-Toe game where a player (O) interacts with an AI opponent (X). The loop continues until the game ends, displaying the board, validating user moves, and applying the AI's optimal move. After the game concludes, it displays the final board and declares the winner or a tie based on the outcom... | def play(self):
while not self.game_over():
self.display_board()
user_input = int(input("Your move (0-8): "))
if user_input in self.available_moves():
self.board[user_input] = 'O'
else:
print("Invalid move. Try again.")
continue
... |
def filter_found_paths(paths):
return [i for i in paths if evaluate_path(i)]
def find_paths(G, node, length):
'''
Taken from: https://stackoverflow.com/questions/28095646/finding-all-paths-walks-of-given-length-in-a-networkx-graph/28103735#28103735
'''
if length == 0:
return [[node]]
pa... | The code solves a puzzle by either loading precomputed paths from a file (if the grid shape is 5) or generating paths from all top-row start points. It filters valid paths and scores them against the puzzle's targets to determine the solution. | def solve(puzzle):
if puzzle.grid_shape == 5:
try:
fp = Path(f'solver/data/{puzzle.buffer_size}.dill')
with open(fp, 'rb') as fp:
all_paths = dill.load(fp)
except FileNotFoundError:
fp = Path(f'data/{puzzle.buffer_size}.dill')
with ... |
def saveVideoFile(body):
print("Saving video file to directory in python")
#with open('/src/VideoAnalysis/Video.mp4', 'wb') as file:
with open("/src/VideoAnalysis/Video.mp4", 'wb')as file:
#print(body)
file.write(body)
file.close()
def run_script(filename):
#left_wrist_keypoints... | The code defines a callback function that processes incoming video data by saving it, analyzing it using a script, and sending the analysis result to a C# Web API. The function handles message consumption, triggers video analysis, and transmits results back to an external system. | def callback(ch, method, properties, body):
#print(" [x] %r:%r" % (method.routing_key, body))
saveVideoFile(body)
analysisResult = run_script("/src/VideoAnalysis/Video.mp4")
print("Analysis result: " + analysisResult)
print("Sending result back to the C# Web API")
sendResult(analysisResult) |
def _get_obj_data(o: JsonT) -> ObjData:
if isinstance(o, str):
if o.startswith('@Tcl_Obj:'):
return _get_tcl_obj_data(o)
return ObjData('@Py_str', o)
if isinstance(o, int):
return ObjData('@Py_int', str(o))
if o is None:
return ObjData('@Py_None', 'None')
if i... | The function `_merge_loose_eq_values` merges values that are loosely equal by first extracting their data, checking if all values are loosely equivalent. If not, it returns `None`. If they are, it removes duplicates, then constructs a structured result containing a type difference marker, the common value, and sorted u... | def _merge_loose_eq_values(values: tuple[T, ...]) -> JsonT | None:
"""Sorts all options for consistent output,
only return None if not loose eq"""
data = [_get_obj_data(d) for d in values]
all_val_eq, val = _get_all_loose_eq(data)
if not all_val_eq:
return None
data_no_dup = _remove_dup_... |
def _get_all_strict_equal(values: tuple[T, ...]) -> tuple[bool, T | None]:
assert values
first, *rest = _remove_dup(values)
if not rest:
return True, first
return False, None
def _merge_loose_eq_values(values: tuple[T, ...]) -> JsonT | None:
"""Sorts all options for consistent output,
on... | The function merges multiple input values into a single value by first checking if all are strictly equal, then attempting a loose equality merge, and finally combining distinct values if necessary. | def merge_attr(*values: T) -> JsonT:
all_eq, val = _get_all_strict_equal(values)
if all_eq:
return val
if (ret_loose_eq := _merge_loose_eq_values(values)) is not None:
return ret_loose_eq
return _merge_different_vals(values) |
def collectCourses(data, cupsToConsider):
courses = []
cupsData = data["tour"]["Cups"]
cupNumber = -1
for cup in cupsData:
cupNumber += 1
if cupsToConsider and (not cupNumber in cupsToConsider):
continue
cupDriverIds = []
for driver in cup["Drivers"]:
... | The code reads a JSON file, extracts course data using `collectCourses`, gathers related items with `readItems`, populates course names via `fillCourseNames`, and returns processed course details along with collected items. | def readJson(file, cups):
f = open(file, encoding="utf-8")
data = json.load(f)
courses = collectCourses(data, cups)
allItems = readItems(courses, FIRST_WEEK_SPOTLIGHTS, SECOND_WEEK_SPOTLIGHTS, data)
fillCourseNames(courses,data)
return courses, allItems |
def createOriginalInventoryIdToItem(inventory):
originalInventoryIdToItem = dict()
for d in inventory.drivers:
originalInventoryIdToItem[d.gameItem.id] = d
for k in inventory.karts:
originalInventoryIdToItem[k.gameItem.id] = k
for g in inventory.gliders:
originalInventoryIdToItem... | The function generates optimal loadout combinations for each course by evaluating different upgrade scenarios (drivers, karts, gliders) using heuristic methods. It calculates total scores at each upgrade stage, updates inventory accordingly, and constructs detailed course loadouts with performance metrics. The result i... | def createSolutionCombinations(inventory, courses, tickets, playerLevel):
DO_HEURISTIC = True
currentInventory = copy.deepcopy(inventory)
if DO_HEURISTIC:
currentTickets = copy.deepcopy(tickets)
currentTickets.setKartsToZero()
currentTickets.setGlidersToZero()
originalInven... |
def calculateBonusPointsBoostPerAction(course, driver, kart, glider):
oColumn = bonusPointsBoostMultiplier(course, driver)
oColumn += bonusPointsBoostMultiplier(course, kart)
oColumn += bonusPointsBoostMultiplier(course, glider)
oColumn *= 150.0 / 30000
return oColumn
def calculatePositionPoints(lev... | The function calculates a "Well-Fought Points" score for a racing game scenario. It returns 0 if the driver's skill is "Coin Box"; otherwise, it combines position points (based on race level) and bonus points from actions (calculated per course, driver, kart, and glider). The final score is derived by multiplying bonus... | def calculateWellFoughtPoints(level, course, driver, kart, glider):
if driver.skill == "Coin Box":
return 0
bpbpa = calculateBonusPointsBoostPerAction(course, driver, kart, glider)
positionPoints = calculatePositionPoints(level)
actions = totalActions(course, driver)
return math.ceil(0.5 * (... |
def lapDependent(course):
result = 30
if course.englishName in {"3DS Rainbow Road","3DS Rainbow Road R","3DS Rainbow Road T","3DS Rainbow Road R/T","GCN Baby Park T"}:
result += 400
elif course.englishName in {"GCN Baby Park","GCN Baby Park R"}:
result += 800
else:
result += 200
... | This function calculates a composite score for a driver's performance in a course by aggregating points from various in-game actions (e.g., mini-turbo, jump boosts, coins) multiplied by factors, adjusting for course type, and applying track/skill multipliers. It adds bonus points for remaining unaccounted actions and B... | def action(level, course, driver, kart, glider):
result = lapDependent(course)
result += course.courseActions.miniTurbos * 5
result += course.courseActions.jumpBoosts * 10
result += course.courseActions.dashPanels * 10
result += course.courseActions.glideTime * 10
result += course.courseActions.... |
def action(level, course, driver, kart, glider):
result = lapDependent(course)
result += course.courseActions.miniTurbos * 5
result += course.courseActions.jumpBoosts * 10
result += course.courseActions.dashPanels * 10
result += course.courseActions.glideTime * 10
result += course.courseActions.... | The main task of the code is to calculate and return the total bonus points by summing four components: action, kart skill, glider skill, and combo, derived from the input parameters level, course, driver, kart, and glider. The function aggregates these values and returns their total, with commented-out debug logic for... | def calculateBonusPoints(level, course, driver, kart, glider):
sum = action(level, course, driver, kart, glider) + kartSkill(course, kart) + gliderSkill(course, driver, glider) + combo(course, driver, glider)
# if abs(action(level, course, driver, kart, glider) - 9628) < 1:
# action(level, course, drive... |
def calculatePositionPoints(level):
constantPoints = 3000 # No idea why 3000
if level <= 150:
return constantPoints + level * 20
elif level <= 200:
return constantPoints + 150*20 + (level - 150)*10
else:
return constantPoints + 150*20 + 50*10 + (level - 200)*5
def calculateBonusP... | The function calculates a total score by summing base points from driver, kart, and glider components, position points based on player level, and bonus points derived from course and component interactions. It combines these values into a final score, with optional debug checks commented out. | def calculateScore(driver, kart, glider, playerLevel, course):
basePoints = driver.basePoints + kart.basePoints + glider.basePoints
posPoints = calculatePositionPoints(playerLevel)
bonusPoints = calculateBonusPoints(playerLevel, course, driver, kart, glider)
bonusPointsBoost = calculateBonusPointsBoost(... |
def is_white(piece_id):
if piece_id % 4 == 0 or piece_id % 4 == 3:
return True
return False
def black_pawn_movement(selected_piece_pos, pieces):
available_pos = []
# Is pawn on starting row?
if selected_piece_pos[1]==1:
for i in range(2):
if (selected_piece_pos[0],selecte... | The function checks if the white king is in check by iterating through all pieces. For each non-white piece, it determines if the piece's movement (based on type) can reach a position with value 83 (white king). If any such path exists, it returns True; otherwise, returns False. | def white_in_check(pieces):
for position in pieces.keys():
if is_white(pieces[position]):
continue
# Check pawn movement
if pieces[position] % 2 == 0:
if 83 in [pieces[key] for key in black_pawn_movement(position, pieces) if key in pieces]:
return True... |
def is_white(piece_id):
if piece_id % 4 == 0 or piece_id % 4 == 3:
return True
return False
def white_pawn_movement(selected_piece_pos, pieces):
available_pos = []
# Is pawn on starting row?
if selected_piece_pos[1]==6:
for i in range(2):
if (selected_piece_pos[0],selecte... | The code checks if the black king (represented by 81) is in check by iterating through all white pieces, generating their possible moves, and verifying if any of these moves can capture the black king. It returns True if the black king is under attack, otherwise False. | def black_in_check(pieces):
for position in pieces.keys():
if not is_white(pieces[position]):
continue
# Check pawn movement
if pieces[position] % 2 == 0:
if 81 in [pieces[key] for key in white_pawn_movement(position, pieces) if key in pieces]:
return ... |
def is_white(piece_id):
if piece_id % 4 == 0 or piece_id % 4 == 3:
return True
return False
def black_pawn_movement(selected_piece_pos, pieces):
available_pos = []
# Is pawn on starting row?
if selected_piece_pos[1]==1:
for i in range(2):
if (selected_piece_pos[0],selecte... | This function handles chess piece movement validation and execution on a board. It checks if a selected piece's move is legal based on its type, updates the board state, verifies if the move puts the player in check, and toggles turns. It also manages piece selection, capture, and visual updates on the canvas. | def move_piece(event):
nonlocal selected_piece_id, selected_piece_pos, whites_turn, pieces
cell_x = event.x // cell_size
cell_y = event.y // cell_size
if selected_piece_id:
current_board = pieces.copy()
if (is_white(selected_piece_id) ^ whites_turn):
... |
def create_sample_input_files(template_filename,
database_filename,
config_filename):
"""Create sample template email and database."""
print("Creating sample template email {}".format(template_filename))
if os.path.exists(template_filename):
... | This code performs a mail merge by generating and sending emails based on a template and CSV database. It reads a Jinja2 template, processes CSV records, renders each as an email, handles attachments, and sends messages with options for dry runs, limits, and sample data creation. | def main(sample=False,
dry_run=True,
limit=1,
no_limit=False,
database_filename=DATABASE_FILENAME_DEFAULT,
template_filename=TEMPLATE_FILENAME_DEFAULT,
config_filename=CONFIG_FILENAME_DEFAULT):
"""Python API for mailmerge.
mailmerge 0.1 by Andrew DeOrio <ll... |
def detect_symbol_state(symbol):
"""Detect if the symbol has an open or closed position"""
connection = sqlite3.connect(db_file)
cursor = connection.cursor()
sql = "SELECT state FROM algo_record where symbol = '{}'".format(symbol)
cursor.execute(sql)
state = cursor.fetchall()
if len(state) =... | This function processes financial data for each symbol, checking its state (open/closed). For open symbols, it updates or creates database tables, executes trades based on date comparison (today vs last trade date), and handles 'hold' logic. Closed symbols trigger table creation and trade execution without 'hold' param... | def add_data(data):
today = str(datetime.date.today())
for symbol in data.keys():
state = detect_symbol_state(symbol)
create_symbol_table(symbol)
if state == 'open':
last_date = get_date(symbol)
if last_date is None:
create_symbol_table(symbol)
... |
def get_domain_name(path):
"""
Function that extracts the domain name from a file path.
Input:
- path: a string representing the file path from which to extract the domain name.
Output:
- A string representing the domain name.
Behavior:
- The function splits the file path by the OS... | The function generates markdown documentation for a specified database relation by creating a header with placeholders and dynamically appending documented column blocks from related models in the same domain, excluding specified columns. It fetches column metadata, filters out dry columns, and constructs markdown usin... | def create_relation_md(relation_name, relation_path, selected_models, selected_paths, dry_arr, doc_blocks_in_relation):
"""
Function: create_relation_md(relation_name, relation_path, selected_models, selected_paths, dry_arr, doc_blocks_in_relation)
Description:
This function generates markdown for a sp... |
def _get_intervals(self):
# Get number of complete episodes of length episode_length
if self.max_episode_steps < self.episode_length:
raise Exception(f'Episode length {self.max_episode_steps} '
f'cannot be less than the total data lenghth {self.episode_le... | The `reset` method initializes a new episode in a reinforcement learning environment, resetting the battery to standby mode, tracking episode progress, and preparing initial states. It initializes counters, resets rewards, sets up episode intervals, creates a new battery instance, and prepares benchmark metrics if enab... | def reset(self, seed=None, options=None) -> Tuple[Any, Dict]:
"""
Resets the episode and performs the first action, which is always
putting the battery in standby mode. Assumed to always run before
.step()
"""
# We need the following line to seed self.np_random
s... |
def removeDbIfExists():
dbFile = 'gewdMusic.db'
if os.path.isfile(dbFile):
os.remove(dbFile)
def getGroupmeData(params, ids):
response = httputil.get(urls['groupmeUrl'], params)
parsed = json.loads(response)
messages = parsed['response']['messages']
data = []
for message in messages:... | The main task of the code is to generate a database by first removing any existing database, fetching GroupMe data with a token and limit, processing it with Spotify data, reversing the order, and creating a new database with the processed music records. The function ensures a fresh database is created with updated mus... | def generateDb():
removeDbIfExists()
limit = 100
params = {'token': groupmeToken, 'limit': limit}
spotifyIds = set()
data = getGroupmeData(params, spotifyIds)
data.reverse()
musicRecords = appendSpotifyData(data)
db.createDB()
db.createMusicRecord(musicRecords)
return 'the db was... |
def Ai(self):
#inputs
netlineR = self.NetlineScan()
velR = (self.vel/self.maxspeed) * 2 - 1
#left
leftinputs = [netlineR[3], netlineR[4]]
#right
rightinputs = [netlineR[0], netlineR[1]]
#speedcontrol
speedcontrolinputs = [netlineR[1], netlineR[2]... | This code updates an object's position and rotation in a game or simulation. It increments laptime, handles tire effects, adjusts visibility, calculates movement using trigonometry, rotates the image based on direction, updates coordinates, manages an outline for highlighting, and triggers elimination if velocity is ze... | def Calc(self):
#AI
self.Ai()
#laptime
self.laptime += 1
#tiremarks
self.TireDelayNote()
#hidden
if self.hide:
self.image = self.hidden
#displace
pythag = [0,0]
radians = math.radians(self.deg)
pythag[0] = se... |
def get_input():
"""Get password from user.
Args:
None
Returns:
Password to be tested or nothing to exit the program.
"""
print("Please enter a password or press <Enter> to quit:")
password = str(input())
print("You entered: " + str(password))
return passwor... | The code evaluates password strength, checks for spaces, and verifies if the password exists in common dictionary files or user-specific lists. It warns users about weak or reused passwords, appends new entries to a user file, and handles errors during file operations. The program terminates after processing inputs. | def main():
"""Runs main program logic."""
while True:
password = get_input()
if password == "":
break
if check_string_has_one_of(" ", password) == "Pass":
print("Password should not have spaces.")
continue
strength = password_strength(password... |
def process_input(self, input_path: str):
moves = []
directions = {'U': IntVector2(0, 1), 'D': IntVector2(0, -1), 'L': IntVector2(-1, 0), 'R': IntVector2(1, 0)}
for line in self.read_input(input_path):
direction, step = line.split()
moves.append([directions.get(directi... | The code simulates the movement of a rope's knots based on input commands, tracking the unique positions visited by the tail. It reads movement data, initializes the rope's knots, processes each move to update their positions, and outputs the count of distinct positions the tail has occupied at least once during the si... | def solve(self) -> None:
""" The main function to solve the task. """
moves = self.process_input(r'day9/input.txt')
self.initialize_knots()
self.process_moves(moves)
print(f'Number of positions the tail visited at least once: {len(self.visited_positions)}') |
def pick_hue(self, color_input):
if hue_range := self.get_hue_range(color_input):
hue = self.random.randint(*hue_range)
# Instead of storing red as two separate ranges,
# we group them, using negative numbers
if hue < 0:
hue += 360
re... | The main task of the code is to generate an HSV/HSB color by determining hue, saturation, and brightness values based on input parameters. It validates the luminosity, selects a hue, computes saturation using the hue and luminosity, determines brightness from hue/saturation/luminosity, and returns an HSVColor object wi... | def generate(self, hue=None, luminosity=None):
if luminosity is not None:
try:
luminosity = Luminosity[luminosity]
except KeyError as exc:
values = [str(enum_) for enum_ in Luminosity]
raise ValueError(
f"Invalid luminos... |
def get_balance(self):
print(self.balance)
pass
def send_jewels(self, amount):
"""Send request to server containing jewels and recipient address."""
recipient_addr = self.get_recipient_addr()#get the address
print(recipient_addr)
#send query containing address and jewel/s... | The code handles user commands for a jewel management system, allowing actions like viewing balance, sending/receiving jewels, and exiting. It validates input for sending jewels, ensuring correct quantities and handling errors. The 'send' command processes user input to determine how many jewels to send, using differen... | def get_user_input(self):
commands = ["help", "balance", "send", "receive", "exit"]
while True:
choice = input("Type 'help' for a list of commands or enter the command now: ")
if choice == "help":
#display list of commands
for i in commands:
... |
def add(root1, root2):
root = Node()
root.left = root1
root.right = root2
return root
def explode(root):
n_explosions = 0
while True:
nodes = []
get_nodes(root, nodes)
node_to_explode = get_node_to_explode(root, 0)
if node_to_explode is None:
return n... | The code performs a full addition operation on two data structures (root1 and root2). It first combines them using an 'add' function, then repeatedly applies 'explode' and 'split' operations until no more changes occur, ensuring the result is fully reduced. The final root is returned after stabilization. | def full_addition(root1, root2):
root = add(root1, root2)
while True:
n_explosions = explode(root)
n_splits = split(root)
if n_explosions == 0 and n_splits == 0:
break
return root |
def read_number(line):
root = Node()
node = root
for c in line:
if c == '[':
new_node = Node()
node.left = new_node
new_node.parent = node
node = new_node
elif c == ']':
node = node.parent
elif c == ',':
new_nod... | The main task of the code is to compute the magnitude of the sum of all numbers parsed from the input lines. It initializes the sum with the first number, sequentially adds each subsequent number using a `full_addition` function, and finally prints the magnitude of the resulting value. | def part_1(lines):
numbers = [read_number(line) for line in lines]
root = numbers[0]
for root2 in numbers[1:]:
root = full_addition(root, root2)
print(magnitude(root)) |
def read_number(line):
root = Node()
node = root
for c in line:
if c == '[':
new_node = Node()
node.left = new_node
new_node.parent = node
node = new_node
elif c == ']':
node = node.parent
elif c == ',':
new_nod... | The code computes the maximum magnitude of all possible pairwise additions of numbers derived from input lines. It generates permutations of line indices, performs full addition on copied number trees, resets trees after each operation, and finally determines the maximum magnitude from all results. | def part_2(lines):
og_numbers = [read_number(line) for line in lines]
numbers = [copy_tree(r) for r in og_numbers]
import itertools
combinations = itertools.permutations(range(len(lines)), 2)
results = []
for (i,j) in combinations:
results.append(full_addition(numbers[i], numbers[j]))
... |
def normalized_path(path):
"""Replaces \ in paths on Windows with /"""
return path.replace('\\', '/')
def includes_from_file(header):
includes = []
with open(header, 'r', encoding = 'utf-8') as file:
for line in file:
if not line.startswith('#include'):
continue
... | The function verifies a convenience header file in a specified folder by checking: 1) its existence, 2) sorted includes, 3) no duplicate includes, 4) presence of all required includes, and 5) absence of unnecessary includes. It logs errors globally if any issues are found, ensuring headers adhere to strict formatting a... | def verify_convenience_header(folder):
"""
Performs the actual checking of convenience header for specific folder.
Checks that
1) The header even exists
2) That all includes in the header are sorted
3) That there are no duplicated includes
4) That all includes that should be in the header ar... |
def verify_convenience_header(folder):
"""
Performs the actual checking of convenience header for specific folder.
Checks that
1) The header even exists
2) That all includes in the header are sorted
3) That there are no duplicated includes
4) That all includes that should be in the header ar... | This function recursively processes non-internal directories by verifying convenience headers and traversing subfolders, excluding predefined internal directories from further processing. | def walk_source_folders(current):
verify_convenience_header(current)
for folder in folders_in_folder(current.path):
fname = folder.name
if fname not in internal_dirs:
walk_source_folders(folder) |
def I(n): return np.identity(n, dtype=int)
def quad(a_b, c_d):
return np.vstack((np.hstack(a_b), np.hstack(c_d)))
def diag(a, b=None):
if b is None:
return a * I(len(a))
if isinstance(a, int) or isinstance(a, float):
a = np.array([[a]])
if isinstance(b, int) or isinstance(b, float):
... | The function `add_m` constructs specific matrix operators based on parameters `n`, `b`, and `modified`. When `modified` is False, it returns identity matrices or combines matrices using `sqrt1_2`, `quad`, `diag`, and `dot` for `b=0` or `b=1`. When `modified` is True, it generates modified operators involving `diag`, `q... | def add_m(n, b, modified):
n1 = n // 2
if not modified:
if b == 0:
return I(n)
elif b == 1:
m = sqrt1_2 * quad((I(n1-1), I(n1-1)), (I(n1-1), -I(n1-1)))
op1 = diag(diag(1, m), -1)
op2 = diag(I(n1), D(n1).dot(J(n1)))
return op1.dot(op2)
... |
def dotx(y, matrix, x, code):
calc = legacy_dot(sp.Matrix(matrix), sp.Matrix(x))
if not (isinstance(calc, list) or isinstance(calc, sp.Matrix)):
calc = [calc]
for ij in zip(y, calc):
code.append(ij)
return y
def next_syms(x):
n = len(x)
global call_num
prefix = 'x%x_' % call_... | The function performs a recursive transformation on input data using matrix operations and scaling factors. It processes input arrays through recursive calls, splitting data into segments, applying transformations with twiddle factors, and combining results via matrix multiplication. The task involves signal processing... | def tfm_run(name, y, x, code, scale_factor=None):
neq2_mat, n_delay, b, v1_tfm, v2_tfm, hvec_size_add, modified_matrix = tfm_props[
name]
n_orig = len(x)
n = n_orig + n_delay
n1 = n // 2
if scale_factor is None:
scale_factor = 1./sqrt(n >> modified_matrix)
if n == 2:
retu... |
def Round_constant_XOR(eng, k, rc, bit):
for i in range(bit):
if (rc >> i & 1):
X | k[i]
def copy(eng, a, b, length):
for i in range(length):
CNOT | (a[i], b[i])
def Squaring(eng, vector, n):
P = [1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
0, 1, 0, 0, 0, 0,... | This code implements the Itoh-Tsujii algorithm for computing multiplicative inverses in finite fields using quantum operations. It performs repeated squaring, recursive Karatsuba multiplication, and polynomial reduction to calculate a^(-1) mod irreducible polynomial, with conditional resource checks and verification st... | def Inverison_Itoh_Tsujii_based(eng) :
n = 8
a = eng.allocate_qureg(n)
a1 = eng.allocate_qureg(n)
check = eng.allocate_qureg(n)
if (resource_check != 1):
Round_constant_XOR(eng, a, 0xab, n)
Round_constant_XOR(eng, check, 0xab, n)
ancilla = eng.allocate_qureg(38)
count = 0... |
def tally_tag(dict_ref, values):
values = values.replace('##NBSP##', '')
values = values.replace('xx', ' ')
values = values[1:]
values = values.split(' ')
for value in values:
if value == '':
continue
tally(dict_ref, value)
def tally_dice(dict_ref, dice_text):
... | The code processes mission card data from a CSV file, aggregating and printing statistics on threats, skills, defense, and offense across regions (EMPIRE, REDBANK, SETTLED). It tallies counts of threats/skills by region and total, and sums defense/offense dice values, then outputs the results. | def populate_dicts():
total_threats = {}
threats_by_region = {"EMPIRE": {}, "REDBANK": {}, "SETTLED": {}}
total_skills = {}
skills_by_region = {"EMPIRE": {}, "REDBANK": {}, "SETTLED": {}}
total_defense = {}
total_offense = {}
mission_file_name = os.path.join("..", "..", "... |
def _do_install_or_upgrade(self):
"""Runs the install or upgrade of the minio and nginx packages."""
# apt upate before starting the package install/upgrades
apt_update()
# minio install/upgrade
try:
for p in [self.config.get("package", ""),
self... | This method handles configuration changes for a MinIO service, including upgrading packages, setting up users/groups, managing disks, validating certificates, ensuring cluster readiness, generating environment files, and restarting services. It checks for upgrade needs, verifies cluster state, manages SSL certificates,... | def _on_config_changed(self, event):
"""CONFIG CHANGE
1) Treat the case we are dealing with an upgrade
1.1) Address user/group setup and disks
2) Check if we can do a config change or are we waiting for sth:
2.1) Check certificates
2.2) Ensure cluster relation has the cor... |
def get_finger_position(self, image, finger_index):
positions, _ = self.find_position(image)
return positions[finger_index][1], positions[finger_index][2]
def index_up_and_middle_finger_down(self, image):
return self.compute_distance_between_two_fingers(image, 8, 7) > 0.05 > self.compute_distanc... | The code determines hand gestures by analyzing index and middle finger positions. If the index is up and middle down, it activates drawing (blue circle). If both fingers are up, it activates selection (black circle). Otherwise, no action. The function updates flags to control drawing/selecting actions based on detected... | def choice_state(self, image):
index_positions = self.get_finger_position(image, 8)
middle_positions = self.get_finger_position(image, 12)
if self.index_up_and_middle_finger_down(image):
self.draw_activated = True
self.select_activated = False
cv2.circle(image... |
def make_grid(width, height):
"""
Creates a grid that will hold all of the tiles
for a boggle game
"""
return {(row, col): choice(ascii_uppercase)
for row in range(height)
for col in range(width)}
def get_dictionary(dictionary_file):
"""
Load dictionary file
"""
... | The main task of the code is to generate a 4x4 grid, load a dictionary of words from a file, search for valid words in the grid using the dictionary, and print each found word along with the total count of discovered words. | def main():
"""
This is the function that will run the whole project
"""
grid = make_grid(4, 4)
dictionary = get_dictionary('words.txt')
words = search(grid, dictionary)
for word in words:
print(word)
print("Found %s words" % len(words)) |
def create_board():
new_board = [[0 for i in range(w)] for j in range(l)]
new_board[l//2][w//2] = head_val
snek = Snake(new_board)
make_apple(new_board)
return new_board, snek
def draw_board(b):
window.fill(BLACK)
# print_board(b)
for r, row in enumerate(b):
for c, spot in enumer... | The main task of the code is to simulate a snake game using a neural network (net) to determine actions. It creates a game board, tracks the snake's movements, detects loops by checking repeated head/body positions, updates the board based on actions, and terminates the loop if the snake collides with itself or the gam... | def play_net(net):
board, snek = create_board()
played_situations = []
run = True
while run:
pygame.time.delay(delay)
if drawing and board is not None:
draw_board(board)
pygame.display.update()
for event in pygame.event.get():
if event ... |
def create_board():
new_board = [[0 for i in range(w)] for j in range(l)]
new_board[l//2][w//2] = head_val
snek = Snake(new_board)
make_apple(new_board)
return new_board, snek
def cast_rays(b):
r1, c1 = index_2d(b, head_val)
r2, c2 = index_2d(b, apple_val)
x_to_apple = c1 - c2
y_to_a... | The code evaluates a neural network's performance in a snake game by simulating gameplay, tracking rewards for eating apples, and penalizing repeated positions to prevent loops. It returns the total score based on survival and rewards, terminating when the snake crashes or exceeds max_ticks. | def test_net(net):
score = 0
played_situations = []
max_ticks = 50
board, snek = create_board()
while True:
chances = net.get_chances(cast_rays(board))
# print(chances)
action = convert_output_to_action(extreme(chances))
# print(action)
reward = score_board(bo... |
def refine_partition(graph, gamma, teta):
refined = Graph.partition_graph(graph[0],cardinality=graph[1],partition= graph[2])
def is_well_connected1(u):
i = graph[4][u]
c = graph[1][u]
threshold = gamma * c * (graph[3][int(i)] - c)
x = 0
for v in graph[2][int(i)]:
... | The code performs community detection on a graph using iterative refinement and aggregation. It refines the initial partition with parameters `gamma` and `teta`, adjusts nodes to optimize community structure, and aggregates the graph to reduce complexity. The process repeats until the number of communities matches the ... | def leiden1(graph,gamma,teta):
stack = []
refined = refine_partition(graph, gamma, teta)
while Graph.nc(refined) != Graph.ver(refined[0]):
move_nodes_fast(graph,gamma)
nv1 = Graph.ver(graph)
nc1 = Graph.nc(graph)
if nc1 != nv1:
refined = refine_partition(graph, g... |
def is_crc(self, radio_cs):
return not (self._read_u8(radio_cs,0x12) & 0x20) >> 5
def _read_u8(self, radio_cs, address):
self._read_into(radio_cs, address, self._BUFFER, 1)
return self._BUFFER[0]
def _write_u8(self, radio_cs, address, val):
radio_cs.value = False
self.spi.try_loc... | This function listens on multiple radios for a beacon signal within a timeout. It checks received packets' CRC, reads FIFO data, validates beacons, and returns the radio if a valid beacon is found. If no valid beacon is received within the timeout, it returns None. | def gs_rx(self, time_out=30) -> (pycubed_rfm9x.RFM9x | None):
'''
asd
'''
end_time = time.monotonic() + time_out
while time.monotonic() < end_time:
for radio in self.radios:
if radio.rx_done:
radio.idle()
packet... |
def rx_done(self, radio_cs):
return (self._read_u8(radio_cs, 0x12) & 0x40) >> 6
def set_to_idle(self, radio_cs):
self.last_rssi = self._read_u8(radio_cs, 0x1A)-164
# put into idle mode
reg = self._read_u8(radio_cs, 0x01)
reg &= ~7 # mask
reg |= (1 & 0... | This function reads data from a radio's RX buffer without reinitializing it, checks for CRC errors, and resets the radio to RX mode. It retrieves packet data if valid, handles errors by yielding 'CRC ERROR', clears IRQ flags, and restores the radio to listening mode for continued operation. | def get_msg2(self, radio_cs):
# hacky way of reading radio RX buffer without reinitalizing the radios
if not self.rx_done(radio_cs):
pass
else:
packet = None
error = 1
self.set_to_idle(radio_cs)
#if not (self._read_u8(radio_cs,0x12) & ... |
def main_menu():
menu = True
# clock = pygame.time.Clock()
bgX = 0
bgX2 = bg.get_width()
while menu:
try:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
menu = False
pygame.qu... | The code initializes a game loop using Pygame, handling events like quitting and TAB key presses for chat input. It prints the local IP address and renders different screens (main menu, create/join options, game, win/lose states) based on the 'state' variable. The loop continuously checks for user input and updates the... | def main():
run = True
print(socket.gethostbyname(socket.gethostname()))
while run:
# clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
elif event.type == pygame.K_TAB:
... |
def fetch_refseq(params):
data = []
for taxon in params.taxon:
json_filename = os.path.join(params.cache_dir, f'{taxon}.json')
data += _fetch_seq_data(taxon, True, json_filename, params.cache_dir)
if params.published:
# Note: no need for convertion in date type!
# For valid d... | The code initializes an object to process biological sequence data by fetching RefSeq data, grouping sequences by taxonomic ranks (order, family, genus, etc.), calculating taxonomic statistics, identifying outliers, and categorizing wide families/genera. It prepares structured data for downstream analysis of taxonomic ... | def __init__(self, params):
self.sequence_data = fetch_refseq(params) # Fetch RefSeq data
self.gbt_l = GroupByTaxonomy(self.sequence_data, filter_clades=params.clade,
ranks=('order', 'family', 'subfamily', 'tribe', 'subtribe', 'genus'))
self.gbt_s = GroupByT... |
def AssertExpectedXcodeVersion():
"""Checks that the user has a version of Xcode installed"""
version_output = subprocess.check_output(['xcodebuild', '-version'])
match = re.match(b"Xcode (\d+)", version_output)
message = "Xcode must be installed to run the iOS embedding unit tests"
assert match, message
def ... | This function runs Objective-C XCTest unit tests for iOS embedding by creating a temporary simulator, executing tests with specified parameters, and ensuring cleanup. It checks Xcode version, builds tests, creates a simulator, runs xcodebuild with the test scheme and destination, applies filters if provided, and delete... | def RunObjcTests(ios_variant='ios_debug_sim_unopt', test_filter=None):
"""Runs Objective-C XCTest unit tests for the iOS embedding"""
AssertExpectedXcodeVersion()
ios_out_dir = os.path.join(out_dir, ios_variant)
EnsureIosTestsAreBuilt(ios_out_dir)
new_simulator_name = 'IosUnitTestsSimulator'
# Delete simu... |
def IsLinux():
return sys.platform.startswith('linux')
def IsMac():
return sys.platform == 'darwin'
def BuildEngineExecutableCommand(
build_dir, executable_name, flags=[], coverage=False, gtest=False
):
unstripped_exe = os.path.join(build_dir, 'exe.unstripped', executable_name)
# We cannot run the unstrippe... | This function runs a specified executable in a controlled environment, handling OS-specific library paths and test configurations. It skips execution if filtered, sets up environment variables, executes the command, and handles failures by analyzing core dumps if present, generating reports for upload. | def RunEngineExecutable(
build_dir,
executable_name,
filter,
flags=[],
cwd=buildroot_dir,
forbidden_output=[],
expect_failure=False,
coverage=False,
extra_env={},
gtest=False
):
if filter is not None and executable_name not in filter:
print('Skipping %s due to filter.' % ex... |
def EnsureDebugUnoptSkyPackagesAreBuilt():
variant_out_dir = os.path.join(out_dir, 'host_debug_unopt')
message = []
message.append('gn --runtime-mode debug --unopt --no-lto')
message.append('ninja -C %s flutter/sky/packages' % variant_out_dir)
final_message = '%s doesn\'t exist. Please run the following comma... | The main task of the code is to gather Dart test files from a specified directory, applying a filter if provided, and yield test configurations with or without observatory support. It ensures dependencies are built, runs `dart pub get`, collects test files, and generates `GatherDartTest` instances for each test, handli... | def GatherDartTests(build_dir, filter, verbose_dart_snapshot):
dart_tests_dir = os.path.join(
buildroot_dir,
'flutter',
'testing',
'dart',
)
# This one is a bit messy. The pubspec.yaml at flutter/testing/dart/pubspec.yaml
# has dependencies that are hardcoded to point to the sky package... |
def get_lig_graph(mol, lig_coords, radius=20, max_neighbor=None):
################### Build the k-NN graph ##############################
num_nodes = lig_coords.shape[0]
assert lig_coords.shape[1] == 3
distance = spa.distance.cdist(lig_coords, lig_coords)
src_list = []
dst_list = []
dist_li... | The function generates a graph representation of a protein-ligand complex by creating separate graphs for the ligand and receptor (using either hierarchical or simplified methods) and combining them. It uses coordinates, atom types, and distance thresholds to construct ligand and receptor graphs, then merges them into ... | def complex_to_graph(lig, rec, rec_coords, c_alpha_coords, n_coords, c_coords, use_rec_atoms, lig_radius, rec_radius,
surface_graph_cutoff, surface_mesh_cutoff, c_alpha_max_neighbors=None, surface_max_neighbors=None,
lig_max_neighbors=None):
conf = lig.GetConformer()
li... |
def process_batch(self, batch, optim):
loss, loss_components, predictions, targets = self.forward_pass(batch)
if optim != None: # run backpropagation if an optimizer is provided
loss.backward()
if self.args.clip_grad != None:
torch.nn.utils.clip_grad_norm_(self.m... | The code performs prediction on a dataset using a neural network model, calculates evaluation metrics (loss and custom metrics), and optionally returns aggregated predictions and targets. It processes batches, accumulates metrics, logs training progress, and handles validation/test scenarios without optimization. The f... | def predict(self, data_loader: DataLoader, optim: torch.optim.Optimizer = None, return_pred=False):
total_metrics = {k: 0 for k in
list(self.metrics.keys()) + [type(self.loss_func).__name__, 'mean_pred', 'std_pred',
'mean_targets', '... |
def predict(self, data_loader: DataLoader, optim: torch.optim.Optimizer = None, return_pred=False):
total_metrics = {k: 0 for k in
list(self.metrics.keys()) + [type(self.loss_func).__name__, 'mean_pred', 'std_pred',
'mean_targets', '... | This code trains a neural network model using a training dataset and validates it on a validation dataset. It tracks a primary metric (e.g., accuracy) to determine model performance, implements early stopping if validation performance doesn't improve for a set number of epochs, saves checkpoints for the best and last m... | def train(self, train_loader: DataLoader, val_loader: DataLoader):
epochs_no_improve = 0 # counts every epoch that the validation accuracy did not improve for early stopping
for epoch in range(self.start_epoch, self.args.num_epochs + 1): # loop over the dataset multiple times
self.epoch = ... |
def plot_curve(c, name='', save=False, img_dir='images', iteration=None):
x, y = c
plt.plot(x, y)
plt.grid()
title = name
if iteration:
title = f"{title}_{iteration}"
plt.title(title)
if save:
os.makedirs(img_dir, exist_ok=True)
os.makedirs(os.path.join(img_dir, name)... | The code applies curvature flow to four curves (astroid, folium of Descartes, Talbot's curve, witch of Agnesi), iteratively evolving them and plotting results. It then computes arc-lengths during smoothing, visualizes curvature signatures for a cardioid, and generates Cartan signatures using curvature gradients. The ma... | def main():
logging.basicConfig(level=logging.INFO)
# 1.(a)
astroid = utils.get_astroid()
folium_of_descrates = utils.get_folium_of_descrates()
talbots = utils.get_talbots()
witch_of_agensi = utils.get_witch_of_agensi()
curves = [astroid, folium_of_descrates, talbots, witch_of_agensi]
... |
def vertex_face_adjacency(self):
num_vertices = self.v.shape[0]
num_faces = self.f.shape[0]
face_len = self.f.shape[1]
rows = np.concatenate(list(self.f))
cols = np.arange(num_faces * face_len) // face_len
assert np.shape(rows) == np.shape(cols)
data = np.ones_lik... | The code computes vertex normals by aggregating face normals weighted by their areas using vertex-face adjacency, then normalizes the result if specified. It first retrieves face normals and areas, scales normals by areas, accumulates them per vertex via matrix multiplication, and applies normalization to unit length i... | def get_vertex_normals(self, normalized=True):
vf_adj = self.vertex_face_adjacency()
face_normals = self.get_face_normals(normalized=False)
face_areas = self.get_face_areas()
face_normals_areas = face_normals * face_areas[:, None]
vertex_normals = vf_adj.dot(face_normals_areas)
... |
def vertex_face_adjacency(self):
num_vertices = self.v.shape[0]
num_faces = self.f.shape[0]
face_len = self.f.shape[1]
rows = np.concatenate(list(self.f))
cols = np.arange(num_faces * face_len) // face_len
assert np.shape(rows) == np.shape(cols)
data = np.ones_lik... | The function computes vertex normals by aggregating face normals weighted by their areas using vertex-face adjacency, then normalizes them if specified. | def get_vertex_normals(self, normalized=True):
vf_adj = self.vertex_face_adjacency()
face_normals = self.get_face_normals(normalized=False)
face_areas = self.get_face_areas()
face_normals_areas = face_normals * face_areas[:, None]
vertex_normals = vf_adj.dot(face_normals_areas)
... |
def laplacian(self, cls='half_cotangent'):
weighted_adj_mat = self.weighted_adjacency(cls=cls)
degree_vec = self.vertex_degree(cls=cls)
degree_mat = diags(degree_vec)
laplacian_mat = degree_mat - weighted_adj_mat
return laplacian_mat
def get_barycentric_vertex_areas(self):
... | The code computes the signed mean curvature of a mesh by first calculating the Laplacian, deriving the unsigned mean curvature from vertex normals and barycentric areas, and then applying a sign based on the alignment between vertex normals and the curvature direction. It optionally clips the curvature values using per... | def get_signed_mean_curvature(self, cls='half_cotangent', clip_values=(10, 90)):
laplacian = self.laplacian(cls=cls)
mean_curvature_normal = 0.5 * laplacian * self.v / self.get_barycentric_vertex_areas()[:, None]
unsigned_mean_curvature = np.linalg.norm(mean_curvature_normal, axis=1)
# c... |
def _init_sockets(self) -> bool:
"Attempt to initialize the sockets according to the current configuration"
#Real-time Socket initialization
socket_type = socket.AF_INET if self._args.use_ipv4 else socket.AF_INET6
if not self._args.disable_realtime:
try:
Adap... | This code initializes an adapter by parsing command-line arguments, configuring logging (with debug/quiet options and optional log file), initializing sockets, attempting login, and registering a callback for AMI messages. It ensures proper setup for the adapter's functionality and logging behavior. | def init(self, parser = argparse.ArgumentParser()):
"Initialize adapter class"
if self._rt_logged_in or self._logged_in:
return
if not Adapter.args_built:
Adapter._build_args(parser)
self._args = parser.parse_args()
#Configure log level
log_leve... |
def is_it_leaf(trees_given,t): #this function returns an array of the boolean value, telling if it is leaf of the tree t
tree=trees_given[t].tree_
n_nodes=tree.node_count
children_left = tree.children_left
children_right = tree.children_right
is_leaves = np.zeros(shape=n_nodes, dtype=bool)
stack... | This function traverses a decision tree structure to determine the leaf node reached by input data x_given in tree t. Starting at node 0, it follows left/right branches based on feature values in x_given until reaching a leaf node, returning its index. | def GETLEAF(trees_given,t,x_given): #this function determines the leaf to which tree t maps x
v=0
while is_it_leaf(trees_given,t)[v]==False:
if x_given[V(trees_given,t,v),C(trees_given,t,v)]==1:
v=trees_given[t].tree_.children_left[v]
else:
v=trees_given[t].tree_.children... |
def splits(trees_given,t): #return an array of splits(not leaf) of tree
return np.arange(trees_given[t].tree_.node_count)[is_it_leaf(trees_given,t)==False]
def V(trees_given,t,s): #this function returns variable that participates in split s
tree=trees_given[t].tree_
feature=tree.feature[s]
return featur... | This function processes input trees and observations to determine if each split condition is met. For every tree and its splits, it checks if the observed X value meets the split threshold, assigning 1 if the value is less than or equal to the split value for the corresponding class, otherwise 0. The result is a dictio... | def x_to_one(trees_given,x_given): #given an observation of X, x_V(s),j = 1 if j belongs to C(s)
x_one={}
for i in range(len(trees_given)):
for j in splits(trees_given,i):
if x_given[V(trees_given,i,j)] - split_values(trees_given,V(trees_given,i,j))[C(trees_given,i,j)] <= 0:
... |
def calculateMaxDepth(board):
return 3
def get_best_move(board, depth):
best_move = None
best_value = float('-inf')
alpha = float('-inf')
beta = float('inf')
legal_moves = list(board.legal_moves)
if board.turn == chess.WHITE:
color = 1
else:
color = -1
for move in legal_m... | This code implements a UCI chess engine that processes commands like "uci", "isready", "position", and "go". It sets up a chess board, handles position initialization, performs iterative deepening alpha-beta search with time control, and outputs the best move in UCI format. The engine parses parameters for depth and ti... | def main():
board = chess.Board()
uci_mode = False
wtime = 1000000
btime = 1000000
remainingtime = 1000000
while True:
input_line = input()
if input_line == "uci":
print("id name OfishV1H")
print("id author Chess123easy")
# Include any additi... |
def reset_last_square(self, game_object):
"""
After the character has moved to a new square, replaces the previous tile with None.
"""
if game_object.last is not None:
if (game_object.y, game_object.x) != game_object.last:
previous_y, previous_x = game_object.... | The main task of the code is to update the game state by handling Pacman's movement, collisions with objects/enemies, invulnerability mechanics, and ghost behavior, including teleportation, position resets, life loss, and state transitions, while managing interactions between Pacman, ghosts, and game elements like pell... | def update_game_state(self):
y, x = self.pacman.curr_loc()
# Pacman location
if (y == 14 and x == 0) or (y == 14 and x == 27):
self.pacman.teleport()
self.state[self.pacman.y][self.pacman.y] = self.pacman
else:
self.pacman.collision(self.state[y][x])
... |
def stats(self) -> tuple:
if self.state is not None:
return self.pacman.points, self.pacman.lives, self.pacman.level + 1, 45 - (5 * self.pacman.level)
else:
return 0, 3, 4, 45
def update_maze(self):
self.update_counter += 1
objects = set()
for rows in self... | This function initializes a new game level by constructing a maze layout using predefined mappings, placing game elements like walls, pellets, and characters, handling saved game data to restore positions and stats, and setting initial player attributes. It processes level overrides, creates game objects, and updates t... | def new_level(self, saved_game=None):
"""
Initialises a new level
"""
if saved_game is None:
saved_game = {}
points, lives, curr_level, def_boost_time = self.stats()
self.objects = set()
self.ghost = None
self.cheats = None
mapping = [... |
def bot_win_move(board, mark):
"""Tries to put the computer's mark in every free square
on the board, and checks whether is_win() returns True"""
# instead of removing the mark, make a copy board to make checks
board_cpy = []
for a in range(len(board)): # deep copy
row = [] ... | The function `bot_play` determines a bot's move in a game by first checking if there's an immediate winning move for the given `mark`. If not, it makes a random move. Finally, it prints the updated game board and legend to display the current state of the game. | def bot_play(board, mark):
print(mark)
if not bot_win_move(board, mark): # no such square for an immediate win
make_random_move(board, mark)
print_board_and_legend(board) |
def is_win(board, mark):
"""Returns True iff the mark mark won on the board board"""
for a in range(3):
if (is_diag_all_marks(board, mark) or is_col_all_marks(board, a, mark)
or is_row_all_marks(board, a, mark)):
print(f"The winner is: {mark}")
return True
if len(g... | The function `game_start` alternates between user and bot turns in a game, using the provided board and current player's mark. It continues the game loop until either the user or bot achieves a winning condition, at which point the loop breaks and the game exits. The function manages turn switching, executes player mov... | def game_start(game_end, board, mark):
while not is_win(board, mark):
if (mark == 'X'):
user_play(board, mark)
mark = 'O'
continue
if (mark == 'O'):
bot_play(board, mark)
if is_win(board, mark):
break
else:
... |
def convert_to_dict_total():
"""parse adfa_ld dataset and construct a dictionary of list"""
file_symbol_dict = {}
for dataset in dataset_list:
file_symbol_dict[dataset] = {}
if dataset == "Attack_Data_Master":
for attack_name in attack_folder_list:
file_symbol_di... | The main task of the code is to evaluate the performance degradation of a machine learning model (using an RBF kernel) on the ADFA_LD dataset when trained with adversarial samples from different attacks. It preprocesses data, trains models for each attack scenario, and stores accuracy metrics in a dictionary for compar... | def main():
kernel = "rbf"
ad_attack_sq_list = [0, 1, 2, 3, 4]
title_text = "Performance degradation with ADFA_LD dataset (TF, Gaussion Kernel, adversarial samples from different " \
"attacks))"
output = convert_to_dict_total()
feature_dict = unique_symbol_dict_generation(output)
... |
def dl4ld_db_processing(app_name, train_test_ratio, feature_extraction="TF"):
"""The default random seed is 10"""
n_gram_length = 3
segment_length = 30000
filter_flag = True
r_seed = 10
# train_test_ratio = 0.9
"""OUTPUT train_normal, train_attack, test_normal, test_attack"""
feature_di... | The main task of the code is to evaluate mitigation strategies for label flipping attacks in datasets by applying DBSCAN clustering and sanitization. It processes training and testing data for multiple applications, tests different attack operations (0, 2, 3, 4), and computes accuracy metrics for each scenario using sp... | def DL4LD_mitigation(app_name_list, portion_list, distance_metric, eqs, minP):
# eqs = 0.3
# minP = 100
op_acc_dict_total = {}
op_acc_dict_s_total = {}
dl4ld_dataset_split_para = {'couchdb': {'kernel': "rbf", 'ratio': 0.9},
'mongodb': {'kernel': "rbf", 'ratio': 0.9... |
def reset(self):
start_state = genRandomState(GRID_ROWS, GRID_COLS , WIN_STATE)
# print("new start state: ", start_state)
self.State = State(start_state)
self.action = self.chooseAction()
self.states = [(self.State.state[0],self.State.state[1],self.actions_lookup[self.action])]
d... | The code implements a reinforcement learning agent that plays a game for a specified number of episodes and steps. It updates state values using a semi-gradient Temporal Difference (TD) method, adjusting estimates based on immediate rewards and future rewards (via the Bellman equation). The agent backpropagates rewards... | def play(self, num_episodes=1, num_steps = 20):
i = 0
curr_steps = 0
rewards = []
while i < num_episodes:
# to the end of game back propagate reward
if (self.State.isEnd) or (curr_steps == num_steps):
# back propagate
reward = self.... |
def evaluate_a1(self,state, target_met, num_steps = 20):
try:
self.start_a1(state)
curr_steps = 0
isEnd = False
states_a1 = []
while not ((isEnd) or (curr_steps == num_steps)):
# print(self.State.isEnd, curr_... | The code simulates multiple episodes of two agents (A1, A2) interacting in an environment. It updates state-value estimates using Q-learning (alpha, gamma parameters), backpropagates rewards upon terminal states or step limits, and resets the environment for new episodes. The agents take actions, transition states, and... | def play(self, num_episodes=1, num_steps = 20):
i = 0
curr_steps = 0
rewards_a1 = []
rewards_a2 = []
flag_a1 = False
flag_a2 = False
while i < num_episodes:
# to the end of game back propagate reward
if (self.isEndA1) or (curr_steps == num_... |
def loadGraph(name):
ready = False
while not ready:
if name == "bruhat" or name == "Bruhat":
bruhat = [(0,1), (0,2), (0,4), (1,2), (1,7), (2,3), (2,20), (3,23), (4, 5), (4, 8), (5,6), (5,9), (6,7), (6,10), (7,11),
(8,9), (8,16), (9,12), (10,11), (10,13), (11, 19), (12, 13)... | This code provides an interactive platform for generating tree strategies in graph pebbling using MILP. It loads predefined graphs, sets a root vertex, and lets users choose between standard or symmetric tree strategy generation. Parameters like strategy count and maximum length are specified, then strategies are compu... | def interface():
print("Welcome to the Graph Pebbling Interactive MILP Platform!\n ")
print("To begin, select your pebbling graph from the following preloaded library: ")
graphName = input("[Lemke, Bruhat, n-cube, Petersen, Lemke square, apply (SNDlib network)] \n "
">>>> ")
graphRes = lo... |
def keepalive(self):
self._send_command(self.SENSOR_SERVICE_ID, [0x00])
def _set_device_params(self, ble_device):
"""
Get the device name and sensor ID from the BLE advertised name
Args:
ble_device (BLEDevice): The user selected BLE device
"""
self._address =... | The main task of the code is to connect to a Bluetooth Low Energy (BLE) device using the `BleakClient` library. It validates input parameters, ensures no existing connection exists, establishes an asynchronous connection, handles potential errors, and initializes sensor-specific configurations. If the connected device ... | def connect(self, ble_device: BLEDevice):
"""
Connect to a bluetooth device
Args:
ble_device (BLEDevice): Device object discovered up when doing scan
"""
if ble_device is None:
raise self.InvalidParameter
if self._client is not None:
... |
def Input(self):
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
self.running = False
if event.type == pygame.MOUSEBUTTONDOWN:
if self.CurrPlayer == 1 and self.Drop(pygame.mouse.get_pos()) and self.CanCheckResult():
... | The main task of the code is to advance the game's progress by processing input, checking for a win condition, updating the game state, and displaying it. If a player wins, it triggers the win handling. The loop pauses briefly before repeating, ensuring the game runs smoothly while checking for game-ending conditions a... | def Progress(self):
self.Input()
if not self.GameEnded:
Player = 0
if len(self.points) > 0:
if self.CanCheckResult():
Player = self.CheckIfSomeOneWin()
self.Update()
self.Show()
if Player != 0:
... |
def check_attribute(node, attr):
for child in node.get_children():
if child.kind == CursorKind.ANNOTATE_ATTR and child.spelling == attr:
return True
return False
def check_and_parse_actor_method(class_name, node):
if not node.access_specifier == AccessSpecifier.PUBLIC:
raise Runt... | This function processes a code node to extract and validate actor components. It collects methods marked with "actor:method" attribute, parses them, and ensures the actor inherits from exactly one base actor. It returns a sorted list of parsed methods and base information, raising an error if multiple base specificatio... | def traverse_actor_components(node):
methods = []
base_info = None
for child in node.get_children():
if child.kind == CursorKind.CXX_METHOD and check_attribute(child, "actor:method"):
methods.append(check_and_parse_actor_method(node.spelling, child))
elif child.kind == CursorKind... |
def check_attribute(node, attr):
for child in node.get_children():
if child.kind == CursorKind.ANNOTATE_ATTR and child.spelling == attr:
return True
return False
def traverse_actor_components(node):
methods = []
base_info = None
for child in node.get_children():
if child.... | This function traverses C++ AST nodes to identify actor implementations marked with "actor:impl". It assigns unique IDs to actors using a global counter, collects their methods and base class info, and tracks nested namespaces. The recursion processes child nodes in the specified file, maintaining namespace context via... | def traverse_actor_types(node, filepath, act_list, ns_list):
global global_act_tid
if node.kind in [CursorKind.CLASS_DECL, CursorKind.CLASS_TEMPLATE, CursorKind.STRUCT_DECL]:
if check_attribute(node, "actor:impl"):
act_tid_mutex.acquire()
tid = global_act_tid
global_a... |
def get_exists_index_from_pinecone(index_name):
# ids = [str(hash(text)) for text in all_splits]
# response = index.fetch(ids)
# vectorstore = {k: v["values"] for k, v in response.items()}
existing_indexes = [index_info["name"] for index_info in pc.list_indexes()]
if index_name in existing_indexes:
... | The main task of the code is to generate an answer to a question by querying a chat model. It retrieves relevant documents from a Pinecone index, combines them with the question as context, invokes the chat model to produce an answer, and appends the referenced documents to the output. The process involves vector embed... | def get_answer_from_chat_model(question, top_k=5):
index = get_exists_index_from_pinecone(index_name)
chat = create_chat_model(index, top_k)
query_vector = embedder.embed_query(question)
reference = ""
normalize_query_vector = normalized_query_vector(query_vector)
# print(normalize_query_vector... |
def find_last_date(database):
"""Find last date from database
:return: last date from database
"""
try:
data = func.json_reader(database)
logging.info('The last date from database was found')
return extract_date(data[-1])
except:
return datetime.strptime("0001/01/01"... | The main task of the code is to crawl data from a website, compare it with existing database records to identify new articles and authors, and update the JSON database with newly found entries. The process involves retrieving the last recorded date, fetching current data, checking for updates, and uploading new informa... | def do_crawler():
"""main function for crawling
"""
logging.info('********* STEP 3. Find last date from the database *********')
last_date = find_last_date(vars.FULL_FILENAME_DB_ART)
logging.info('********* STEP 4. Read the data from the site *********')
crawling()
logging.info('********* ... |
def MoldenPhaseChecker(molden_location):
ORDERED_MOLDEN_FILELIST=[]
startdir = os.getcwd()
os.chdir(molden_location)
file_list = G("*.molden.*")
file_list.sort(key=os.path.getmtime)
n_moldens = len(file_list)
os.makedirs("phased_molden_files/",exist_ok=True)
os.system(f"cp *.molden.* pha... | This function generates a VMD script file to visualize and convert molecular orbitals from Molden files into STL format. It initializes VMD, loads ordered Molden files, converts orbitals to STLs, and optionally loads protein structures from prmtop/trajectory files, converting them to STLs as well. The script ends with ... | def VMD_Job_Writer(moldenfiles,orbitalnumber,prmtop=None,trajectory=None,vmdcommandfile="orbital_trajectory.vmd"):
ORDERED_MOLDEN_FILELIST = MoldenPhaseChecker(moldenfiles)
VMDInitialize(vmdcommandfile)
VMDLoadMoldens(vmdcommandfile,ORDERED_MOLDEN_FILELIST,orbitalnumber)
if prmtop != None and trajectory... |
def auto_downsampling(self, X):
B, C, H, W = X.shape
stride = H // 1024
if stride > 0:
if stride == 1:
stride = 2
target_H = H // stride
target_W = W // stride
X = F.interpolate(X, size=(target_H, target_W),
... | This function computes the Structural Similarity Index (SSIM) between two input tensors X and Y, which represent images with shape (B, C, H, W). If auto_ds is True, it first downsamples both tensors using a predefined method. It then generates a Gaussian filter window and calculates the SSIM score using this window, re... | def SSIM(self, X, Y, auto_ds=True):
# X/Y.shape (B, C, H, W)
assert(X.shape == Y.shape), 'X.shape and Y.shape are unmatch'
if auto_ds:
X = self.auto_downsampling(X)
Y = self.auto_downsampling(Y)
with torch.no_grad():
win = self.fspecial_gauss(11, 1.... |
def normalization(self, X, y = None):
X = (X - np.full(X.shape, self.mean_X_train)) / \
np.full(X.shape, self.std_X_train)
if y is not None:
y = (y - self.mean_y_train) / self.std_y_train
return (X, y)
else:
return X
def init_weights(self, a0, b0)... | This code initializes a Bayesian neural network with SVGD (Stein Variational Gradient Descent) optimization. It sets up Theano symbolic variables, normalizes data, computes log-posterior gradients, trains particles via mini-batch updates, and selects optimal parameters using a development set. The model uses ReLU activ... | def __init__(self, X_train, y_train, batch_size = 100, max_iter = 1000, M = 20, n_hidden = 50,
a0 = 1, b0 = 0.1, master_stepsize = 1e-3, auto_corr = 0.9, h=-1, alpha = 0.9,
method = 'none',m=5, cf = False, uStat = True, regCoeff = 0.1, adver = False, adverMaxIter = 5,
maxTime = 20, numTimeSteps... |
def svgd_kernel_subset(self, theta, lnprob, h=-1, m=-1, cf = False):
if m == -1:
m = int(theta.shape[0]/5);
n,d = theta.shape
yInd = np.random.choice(n, m, replace=False)
y = theta[yInd]
pairwise_dists = cdist(theta, y)**2
if h < 0: # if h < 0, using median... | This code performs optimization using Stein Variational Gradient Descent (SVGD) with Adam updates, iteratively adjusting parameters (theta) to maximize a log-probability function (lnprob). It supports different kernel methods (subparticles, induced points) for gradient estimation, incorporates momentum and adaptive lea... | def update(self, x0, lnprob, n_iter = 1000, stepsize = 1e-3, bandwidth = -1,
alpha = 0.9, method='none',m=-1,cf=False, adver=False, adverMaxIter = 5, debug = False, regCoeff = 0.1):
# Check input
if x0 is None or lnprob is None:
raise ValueError('x0 or lnprob cannot be None!')
... |
def read_key():
LIST_KEY,list_key_question, list_key_answer = [], [], []
if not is_file_exist(KEY_FILE):
open(KEY_FILE, 'w', encoding='utf8').close()
quest_answer = open(KEY_FILE, 'r').read()
quest_answer = re.findall(r'(.+?)'+chr(10), quest_answer)
for line in quest_answer:
LIST_KEY... | The code processes a file by parsing questions and answers, detecting their type (1-4), generating corresponding keys using type-specific functions, and collecting non-duplicated keys into a list. Errors are logged if key generation fails. The main task is to classify and extract structured keys from question-answer pa... | def select_type(file_name):
key = ''
new_keys_list = []
LIST_KEY, list_key_question, list_key_answer = read_key()
list_questions, list_answers = parse_raw_text(file_name)
for i in range(len(list_questions)):
numberic_type = detector(list_questions[i], list_answers[i])
if numberic_typ... |
def auto_rpc_connect(self):
# check RPC connection
self.w3 = Web3(Web3.HTTPProvider(self.rpc_address))
if not self._test_rpc_connection(self.rpc_address):
for rpc in defi.rpc.bsc.rpc_endpoints:
self.rpc_address = rpc
self.w3 = Web3(Web3.HTTPProvider(se... | The function calculates the gas fees for a given transaction by retrieving the transaction receipt, fetching the current BNB price, and computing the total cost in BNB. It returns details including gas price, gas used, tokens consumed, and the monetary cost based on the BNB price. | def get_txn_gas_fees(self, txn_hash):
self.auto_rpc_connect()
receipt = self.await_transaction_receipt(txn_hash)
bnb_price = self.fetch_ticker(self.bnb_address)
tokens_amount = receipt['gasUsed'] * receipt['effectiveGasPrice']
return {
'gas_price': receipt['effectiveG... |
def auto_rpc_connect(self):
# check RPC connection
self.w3 = Web3(Web3.HTTPProvider(self.rpc_address))
if not self._test_rpc_connection(self.rpc_address):
for rpc in defi.rpc.bsc.rpc_endpoints:
self.rpc_address = rpc
self.w3 = Web3(Web3.HTTPProvider(se... | This function updates a trade's take profit (TP) and stop loss (SL) parameters on a blockchain. It first ensures RPC connection validity, then updates TP using `update_trade_tp` and optionally updates SL via `update_trade_sl` if provided. Both operations return transaction details, which are aggregated into a list `[tp... | def update_trade_tp_and_sl(self, order_hash, take_profit, stop_loss=None):
# verify the RPC connection and update block finality
self.auto_rpc_connect()
tp_txn = self.update_trade_tp(order_hash, take_profit)
sl_txn = None
if stop_loss is not None:
sl_txn = self.upd... |
def auto_rpc_connect(self):
# check RPC connection
self.w3 = Web3(Web3.HTTPProvider(self.rpc_address))
if not self._test_rpc_connection(self.rpc_address):
for rpc in defi.rpc.bsc.rpc_endpoints:
self.rpc_address = rpc
self.w3 = Web3(Web3.HTTPProvider(se... | The function creates a market order on a DeFi platform by interacting with a smart contract, handling token approvals, gas estimation, and transaction signing. It processes parameters like position type, collateral, quantity, price, and risk management settings, then executes the trade via a blockchain transaction. | def create_market_order(self, pair_base, is_long, token_in, amount_in, qty, price,
take_profit=0, stop_loss=0, broker=0):
"""
Open a new market order.
:param pair_base: Address of the base pair (e.g., WETH address)
:param is_long: Boolean indicatin... |
def auto_rpc_connect(self):
# check RPC connection
self.w3 = Web3(Web3.HTTPProvider(self.rpc_address))
if not self._test_rpc_connection(self.rpc_address):
for rpc in defi.rpc.bsc.rpc_endpoints:
self.rpc_address = rpc
self.w3 = Web3(Web3.HTTPProvider(se... | This function creates a limit order on a blockchain by verifying RPC connection, checking token spending limits, interacting with a smart contract, estimating gas, and sending a signed transaction to open a long/short position with specified parameters like price, quantity, and risk management settings. | def create_limit_order(self, pair_base, is_long, token_in, amount_in, qty, price,
stop_loss=0, take_profit=0, broker=0):
"""
Open a new limit order.
:param pair_base: Address of the base pair (e.g., WETH address)
:param is_long: Boolean ... |
def CheckChangedPR(pr, repo, counter):
"""
Check if PR (still open) has been changed since creation time
"""
print(f"Checking PR:{pr}")
pr = repo.get_pull(counter)
CREATED = pr.created_at
commits = pr.get_commits()
# Sort the commits by the commit timestamp in descending order
sorted... | The code checks for new or modified open pull requests (PRs) in a GitHub repository by comparing them against a list of already built PRs stored in a file. It authenticates using a token, retrieves open PRs from the main branch, identifies unprocessed PRs, and triggers builds for new/changed ones. It also handles file ... | def Finder():
"""
Check if any new (not built) pull requests exists in defined repo (fro main branch
"""
print("------------------------------------------------------------------------------------------")
#########################################################################
# Authorization... |
def shrink_fan(self, fan_center, fan_center_parent):
leaves = [node for node in self.graph.neighbors(fan_center) if node != fan_center_parent]
current_fan = self.graph.subgraph([fan_center] + leaves).copy()
side_edges = []
counter = 0
for i in range(-1, len(leaves) - 1):
... | This function recursively checks if a node is a leaf in a graph. If it is, it returns True. Otherwise, it processes non-center nodes by shrinking their fans and handles the center node by solving TSP for a wheel structure. The method contributes to solving the Traveling Salesman Problem by traversing the graph's tree s... | def solve_tsp_recursively(self, current_node, current_node_parent=-1):
leaf = True
for child in self.tree.neighbors(current_node):
if child == current_node_parent:
continue
leaf = False
child_is_leaf = self.solve_tsp_recursively(child, current_node)
... |
def _refresh_tree_ref(self):
"get reference to new tree if it has changed"
self._tree_ref = BinaryNodeRef(
address=self._storage.get_root_address())
def _follow(self, ref):
"get a node from a reference"
#calls BinaryNodeRef.get
return ref.get(self._storage)
def _delet... | This method deletes a node with the specified key from a tree structure. It locks the storage for thread safety, refreshes the tree reference, traverses to the target node, and calls a helper method to perform the deletion, updating the tree reference afterward. | def delete(self, key):
"delete node with key, creating new tree and path"
if self._storage.lock():
self._refresh_tree_ref()
node = self._follow(self._tree_ref)
self._tree_ref = self._delete(node, key) |
def check_path_hash(self, path, name):
with open(self.file_hashes_path, "r") as f:
file_hashes = yaml.safe_load(f)
if name in file_hashes:
# If folder does not exists return False (means: not downloaded) and remove the checksum for this dataset from the checksum file
... | This code manages dataset processing by checking for existing data, downloading, converting to BIDS format, executing modules, compressing data, and adding checksums. It ensures efficient handling by avoiding redundant operations when data already exists or requires compression/decompression. | def run(self):
# Check if data already exists
# TODO check for bugs
if self.check_path_hash(self.dataset_output_name_path, self.dataset_output_name):
self.logger.info(f"Dataset {self.dataset_output_name} already existing in the output folder")
return
# Check if ... |
def download_series_metadata(self, csv_filename):
self.logger.debug("Downloading metadata")
series_metadata_df = self.tcia_api.getSeriesMetadataDF(self.seriesDF)
self.series_metadata_df = series_metadata_df
series_metadata_df.to_csv(csv_filename, index=False)
return
def add_paths... | The main task of the code is to download and organize medical imaging data from the TCIA API. It creates a temporary directory, retrieves series metadata as a DataFrame, saves metadata to a CSV, adds file paths to series entries, removes unknown instances, downloads the series data, and renames patient directories for ... | def run(self):
os.makedirs(self.temp_dir, exist_ok=True)
# Get series from tcia api as dataframe
self.seriesDF = self.tcia_api.getSeriesDF(self.dataset)
# Download metadata
self.download_series_metadata(csv_filename=path.join(self.temp_dir, "metadata.cs... |
def xy2ColRow(x, y):
startX = -BOARD_WIDTH / 2
startY = -BOARD_WIDTH / 2
col = int((x - startX) / CELL_SIZE)
row = int((y - startY) / CELL_SIZE)
return col, row
def dropXPiece(col, row):
x = -BOARD_WIDTH / 2 + col * CELL_SIZE + CELL_SIZE / 2
y = -BOARD_WIDTH / 2 + row * CELL_SIZE + CELL_S... | This function handles a player's click on a board game grid. It validates the click's position, places the current player's piece if the cell is empty, switches players, checks for a win, and prompts the user to restart or exit the game if a winner is declared. | def handleClick(x, y):
# if click is outside the board, ignore it
if x < -BOARD_WIDTH / 2 or x > BOARD_WIDTH / 2 or y < -BOARD_WIDTH / 2 or y > BOARD_WIDTH / 2:
return
global cur_player
# convert x, y to col, row
col, row = xy2ColRow(x, y)
# if piece already exists, ignore it
if ... |
def draw_surfaces(self):
for s in self.surfaces:
self.win.blit(s.surf1, s.rect)
def update_sprite_pos(self):
pressed_key = pygame.key.get_pressed()
self.player1.update(pressed_key)
self.projects.update()
self.enemies.update()
def check_for_collisions(self):
se... | The code updates the game screen by clearing it, displaying the current game status text, and either updating game elements (drawing surfaces, moving sprites, checking collisions) when the game is active (status 0) or removing sprites when inactive. It then refreshes the display and maintains a 60 FPS frame rate. | def update(self):
self.win.fill(self.win_rgb)
self.text.update_text(self.game_status)
if self.game_status == 0:
self.draw_surfaces()
self.update_sprite_pos()
self.check_for_collisions()
else:
self.remove_sprites()
pygame.display.fli... |
def get_movement_frames(self, side = "none"):
if (side == "none"):
return self.character_walk[4]
if (side == "left"):
return self.character_walk[0]
if (side == "right"):
return self.character_walk[1]
if (side == "up"):
return self.character... | This code initializes a player's visual component with walking and running animations, sets movement parameters, and prepares the sprite for rendering. It configures frame counters, direction handling, and animation speed settings to manage character movement and visual updates in a game environment. | def __init__(self, character_walk, character_run):
super(PlayerVisual,self).__init__()
self.character_walk = character_walk
self.character_run = character_run
self.frame = 0
self.image = (self.get_movement_frames("down")[self.frame])
self.set_properties()
self.ima... |
def ConstructTree():
current_node = Node("dir", "/", None)
top_node = current_node
with open("./2022/7/input.txt", "r") as file:
for line in file.readlines():
line = line.strip('\n')
if line.startswith("$ cd"):
specified_name = line[5:]
i... | The code constructs a tree, calculates the total size of directories with sizes ≤100,000, and identifies the smallest directory size ≥30,000,000, using the tree's total used size to determine the threshold. | def main():
tree = ConstructTree()
#tree.print()
used_size = FindAndPopulateSizes(tree)
print(SumDirSizesLessOrEqualMax(tree, 100000))
print(SmallestSizeDirGreaterOrEqualMin(tree, 30000000-(70000000-used_size))) |
def getPackets():
packets = []
with open("./2022/13/input.txt", "r") as file:
for line in file.read().splitlines():
if line:
packets.append(eval(line))
return packets
def inOrderPacketPairs(packets):
in_order_indexes = []
for packet_index in range(0, len(packets),... | The code's main tasks are: retrieve packets, count the number of valid in-order packet pairs, and determine a decoder key from the packets. It prints the sum of valid pairs and the decoder key. | def main():
packets = getPackets()
print(sum(inOrderPacketPairs(packets)))
print(getDecoderKey(packets)) |
def update_p1hand_and_current_turn(self, hand):
"""
Updates hand thrown by player 1 and passes the turn to player 2.
Parameters:
hand(str): player 1's thrown hand.
Returns:
- None.
"""
self.player1_hand = hand
self.current_turn = False # Pas... | This function handles a player's move in a Rock-Paper-Scissors game by updating their thrown hand, setting the opponent's hand (randomly in single-player mode), displaying both hands, and determining the round winner. It supports both single-player (vs AI) and multi-player modes by updating respective hands and trigger... | def throw_hand(self, hand):
"""
Sets players current thrown hand
Parameters:
hand(str): player's thrown hand.
Returns:
- None.
"""
hand = hand.lower()
if self.mode == self.MODE_1P:
self.update_p1hand_and_current_turn(hand)
... |
def scale_down(self,z):
z = 2*(z- self.min)/(self.max-self.min) - 1
return z
def generate_targets(self,x0,t,device):
alphas,alphas_cumprod,betas,alphas_cumprod_prev = self.generate_alpha(device = device)
alphas_cumprod_t = self.extract(alphas_cumprod.to(device), t.squeeze(dim=1) - 1,x0... | This function calculates the loss for a diffusion model by predicting added noise. It scales input data, generates noisy targets at random time steps, processes context and conditioning embeddings, predicts the noise from the corrupted data, and computes the loss between predicted and actual noise. | def calculate_loss(self,x0,context,conditioning,drop_probs):
x0 = self.scale_down(x0)
device = x0.device
t = torch.randint(1,self.num_timesteps + 1, (x0.shape[0],1)).to(device)
t = t.type(torch.int64)
#Apply noise to certain timeframes
noise,data = self.ge... |
def Qy_graph(self, x):
"""
Q(y|x) computation graph
inputs: x (data)
returns Qy_x or the probability of the datapoint to be in each class (cluster)
"""
print('Defining Q(y|x)')
reuse = len(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Qy_x')) > 0
with tf.variable_scope('Qy_x'):
Qy_x = tf.... | The code constructs a probabilistic neural network by defining encoder and decoder components. It generates latent variables (z) and their distributions (zm, zv) from input data (x_batch) and auxiliary variables (y). The network computes prior distributions for z (zm_prior, zv_prior) and reconstructs inputs (px_logit, ... | def build_network(self):
self.qy_logit, self.qy, self.y = self.Qy_graph(self.x_batch)
self.z, self.zm, self.zv = self.Qz_graph(self.x_batch, self.y)
self.zm_prior, self.zv_prior = self.Pz_graph(self.y)
self.px_logit, self.output = self.Px_graph(self.z) |
def fetch(self):
self.ins = rom[reg['pc']]
def decode(self):
try:
self.ops = Ops(self.bits(6,0))
except:
dump()
print('Invalid opcode {:07b}'.format(self.bits(6,0)))
exit(0)
self.imm_i = se(self.bits(31,20),11)
self.imm_s = se(self.bits(31,25,5)|self.bits(11,7),11)
... | The code's main task is to perform a single processing step by sequentially fetching data, decoding it, and executing the corresponding operation, typically part of a fetch-decode-execute cycle in computing systems. | def step(self):
self.fetch()
self.decode()
return self.execute() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.