dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def read_sph(self):
with open(self.input_fn, "r+") as f:
while True:
try:
line = next(f)
if line[0] != ' ':
self.sph_header.append(line)
else:
self.sph_lines.append(line)
... | The code's main task is to process data by reading input via `read_sph()`, performing clustering with `cluster()`, and writing output using `write_sph()`. If verbose logging is enabled, it also records progress via `self.log()`. The method sequentially executes these steps to handle data processing and analysis tasks. | def run(self):
self.read_sph()
self.cluster()
self.write_sph()
if self.verbose:
self.log() |
def output_tracks(def_info):
"""
Method to write/output TRACKS to DEF file.
:param def_info: DEF data
:return: a string that contains TRACKS info in DEF format.
"""
s = ""
for track in def_info.tracks:
if track.get_layer() in GOOD_LAYERS:
s += track.to_def_format()
... | The main task of the code is to generate a new DEF (Design Exchange Format) file content string by selecting specific metal layers (from `GOOD_LAYERS`) and assembling DEF sections like design info, die area, rows, tracks, components, pins, and nets from `def_info` and `lef_info`. It constructs the output string by conc... | def output_new_def(def_info, lef_info):
"""
Output DEF data to new DEF file with selected metal layers.
:param def_info: DEF data
:param lef_info: LEF data
:return: a string that contains new DEF data in DEF format.
"""
s = ""
s += "# Generated by thxgo@example.com for testing only.\n"
... |
def conn_matches_adapter(conn, adapter):
"""Return True if the connection is applicable for the given adapter.
There seem to be two ways for a connection specify what interface it belongs
to:
- By setting 'mac-address' in [wifi] to the adapter's MAC
- By setting 'interface-name` in [connection] to... | The code processes activating/deactivating a network connection (nm_ap) based on the 'is_active' flag. If deactivating, it calls async deactivation. If activating, it filters existing connections matching the adapter, raises an error for multiple matches, and creates a new connection with a password if required by the ... | def process_ap(nm_ap, is_active, adapter):
"""Activate/Deactivate a connection and get password if required"""
if is_active:
CLIENT.deactivate_connection_async(nm_ap, None, deactivate_cb, nm_ap)
else:
conns_cur = [i for i in CONNS if i.get_setting_wireless() is not None and conn_matches_adap... |
def check_forwarding_time(self):
from time import perf_counter
input_shape = self.ae.input_shape[1:]
mul = 1
for val in input_shape:
mul *= val
forward_count = 32
noise = np.random.uniform(0.0, 1.0, mul * forward_count)
noise = np.asarray(noise).resha... | The main task of the code is to train a machine learning model using a custom data generator, adjusting the learning rate via a scheduler, computing gradients for each batch, and periodically validating performance while saving checkpoints. The training loop runs for a predefined number of iterations, updating the mode... | def train(self):
self.model.summary()
self.check_forwarding_time()
print(f'\ntrain on {len(self.train_image_paths)} samples.')
print(f'validate on {len(self.validation_image_paths)} samples.')
print('start training')
iteration_count = self.pretrained_iteration_count
... |
def findPossiblePlatesContours(self):
img = cv2.imread(self.imageSource)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
sobelx = cv2.Sobel(blurred,cv2.CV_8U,1,0,ksize=3,scale=1,delta=0,borderType=cv2.BORDER_DEFAULT)
isobelx = cv2.Sobel(blurred, cv2.CV... | The code processes an image to detect and extract license plate information. It identifies potential plate contours, locates the license plate, handles errors, cleans temporary files, and returns the detected plate as a string or an empty string if none are found. | def exec(self, imgSource):
foundPlate = []
try:
self.imageSource = imgSource
contours = self.findPossiblePlatesContours()
foundPlate = self.findLicensePlate(contours)
except Exception as e:
print("falha no processo de leitura: " + str(e))
self.cleanFiles()
return str(foun... |
def print_grid(grid: TicTacToeGrid) -> None:
print('\033c', end='')
print(
textwrap.dedent(
"""\
A B C
------------
1 ┆ {0} │ {1} │ {2}
┆ ───┼───┼───
2 ┆ {3} │ {4} │ {5}
┆ ───┼───┼───
3 ┆ {6} │ {7} │ {8}
"""
... | The code simulates a Tic Tac Toe game where 'X' (a dumb computer) and 'O' (a smart computer) take turns making moves. It prints the grid after each move, checks for a win/tie, and ends when either occurs. 'X' uses a basic strategy, while 'O' employs an optimized approach to win or force a tie. | def play_tictactoe():
grid = TicTacToeGrid()
print_grid(grid)
while not grid.won and not grid.tie:
#X's turn - the Human
""" try:
grid = grid.move(grid_input('Your turn, X: '), 'X')
except ValueError:
print('Invalid move')
continue """
#x'... |
def my_cx(qc, control, target):
if control > target:
my_circ(qc, target, control - 1)
qc.cx(control, control - 1)
my_circ(qc, control - 1, target)
elif control < target:
my_circ(qc, target, control + 1)
qc.h(control)
qc.h(control + 1)
qc.cx(control + 1,con... | This function applies a controlled quantum gate between a control and target qubit based on the specified gate type. If control_gate_to_use is 0, it applies a controlled-X (CX) gate; if 1, a controlled-Z (CZ) gate; otherwise, a controlled-Y (CY) gate. The function modifies the provided quantum circuit (qc) by adding th... | def apply_control_gate_from_key_clifford(qc,control,target,control_gate_to_use):
if control_gate_to_use == 0:
my_cx(qc,control,target)
elif control_gate_to_use == 1:
my_cz(qc,control,target)
else:
my_cy(qc,control,target) |
def validate_subkey_a_size(key, num_qubits, verbose = False):
max_key, _ = determine_max_subkey_a(num_qubits)
if verbose:
if max_key != len(key):
print("Invalid key with " + str(len(key)) + " bits. Key must have " + str(max_key) + " bits.")
else:
print("Valid key wit... | The main task of the code is to generate a quantum encryption circuit using block Clifford operations. It constructs a QuantumCircuit by applying controlled gates (CX, CY, CZ) between data and signature qubits based on subkeys, then applies unitary transformations to data qubits and repositions signature qubits via per... | def block_clifford_encryption(num_total_qubits, num_signature_qubits,subkey_a=None,subkey_b=None,subkey_a_base=2):
subkey_a_gates = []
if subkey_a == None:
for i in range(num_total_qubits):
subkey_a_gates.append(random.randint(0, 2))
else:
if subkey_a_base == 3:
subke... |
def validate_subkey_a_size(key, num_qubits, verbose = False):
max_key, _ = determine_max_subkey_a(num_qubits)
if verbose:
if max_key != len(key):
print("Invalid key with " + str(len(key)) + " bits. Key must have " + str(max_key) + " bits.")
else:
print("Valid key wit... | The code generates a quantum encryption circuit using Clifford gates, applying subkeys to determine gate operations and qubit permutations. It constructs a QuantumCircuit by moving signature qubits, applying data-qubit unitaries, and adding controlled operations between data and signature qubits, then returns the Cliff... | def block_clifford_decryption(num_total_qubits, num_signature_qubits,subkey_a=None,subkey_b=None,subkey_a_base=2):
subkey_a_gates = []
if subkey_a == None:
for i in range(num_total_qubits):
subkey_a_gates.append(random.randint(0, 2))
else:
if subkey_a_base == 3:
subke... |
def create_app_heading_frame(self):
frame = Frame(self, height = 50, bg = "#2b2e30")
frame.pack(fill = X)
return frame
def create_heading_label(self):
label = Label(self.app_heading_frame, text = "Password Generator", font = ("Helvetica", 23, "bold"), fg = "#F0FFFF", bg... | This code initializes a password generator GUI application by centering the window on the screen, setting its size and title, and creating UI components such as frames, labels, input fields, and buttons for password generation. | def __init__(self):
super().__init__()
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
app_width = 500
app_height = 200
set_x = int((screen_width / 2) - (app_width / 2))
set_y = int((screen_height / 2) - (app_height / 2))
... |
def __set_theme(self) -> dict:
# Check if config/themes directory exists
try:
if not os.path.exists("config/themes"):
os.mkdir("config/themes")
except Exception as e:
SelftosUtils.printf(f"{self.PREFIX} [orange1]Warning:[/orange1] Failed to create themes d... | The code initializes an object's theme and color configurations by setting attributes like theme, prefix, user, plugin, success, warning, error, and indicator colors using private methods. It also applies these settings to override the default theme, likely for customizing visual styles in a UI or logging system. | def __init__(self):
self.__theme_path = "config/themes/"
self.theme = self.__set_theme()
self.prefix = self.__set_prefix_color()
self.users = self.__set_user_colors()
self.plugins = self.__set_plugins_color()
self.success = self.__set_success_color()
self.warning ... |
def get_num_qubits(algorithm):
"""
Determine the max qubit value used in the algorithm.
algorithm: iterable, each element must be a string gate, as in
apply_string_gate above.
ie, algorithm = ["h(0)", "cx(0, 1)", "rx(pi/4, 1)",..]
ret... | The code executes quantum algorithms using Qiskit, creating circuits for given gate sequences, handling multiple algorithms, and running them on specified backends (simulators or IBM hardware). It manages job status, requeues if errors occur, and returns probability distributions of quantum states, adjusting bit orderi... | def run(algorithm, num_qubits=None, num_samples=8000, backend=simulator):
"""
Create a quantum circuit, run the algorithm, return the resulting
probability distribution.
algorithm: algorithm (list of strings) or list of algorithms,
each string is a gate in GATE_ARGUMENTS.keys() with... |
def get_num_qubits(algorithm):
"""
Determine the max qubit value used in the algorithm.
algorithm: iterable, each element must be a string gate, as in
apply_string_gate above.
ie, algorithm = ["h(0)", "cx(0, 1)", "rx(pi/4, 1)",..]
ret... | This function converts a list of quantum gates into a unitary matrix by constructing a Qiskit quantum circuit, adjusting qubit indices for Qiskit's bit ordering, and simulating the circuit's unitary evolution. It handles gate parsing, qubit index inversion, circuit construction, and returns the resulting unitary matrix... | def algorithm_unitary(algorithm, num_qubits=None):
"""
Find the unitary corresponding to the algorithm.
algorithm: list of strings, each string is a gate in GATE_ARGUMENTS.keys()
with whatever arguments required to define the
gate.
nu... |
def get_num_qubits(algorithm):
"""
Determine the max qubit value used in the algorithm.
algorithm: iterable, each element must be a string gate, as in
apply_string_gate above.
ie, algorithm = ["h(0)", "cx(0, 1)", "rx(pi/4, 1)",..]
ret... | The function `run` executes quantum algorithms using Cirq, simulating quantum circuits to generate probability distributions of quantum states. It accepts a list of quantum gates (or algorithms), determines the required number of qubits, constructs corresponding circuits, and runs simulations with a specified number of... | def run(algorithm, num_qubits=None, num_samples=8000):
"""
Create a quantum circuit, run the algorithm, return the resulting
probability distribution.
algorithm: algorithm (list of strings) or list of algorithms,
each string is a gate, ie "cx(0, 1)" or rz(pi/2, 0)
num_qubits: in... |
def get_num_qubits(algorithm):
"""
Determine the max qubit value used in the algorithm.
algorithm: iterable, each element must be a string gate, as in
apply_string_gate above.
ie, algorithm = ["h(0)", "cx(0, 1)", "rx(pi/4, 1)",..]
ret... | The function `markovian_sample` generates a list of quantum states by iteratively executing a given quantum algorithm. Each subsequent run uses the measured result of the previous execution as the initial state. It takes parameters like the algorithm (as a list of gates), number of qubits, number of samples, and a back... | def markovian_sample(algorithm, num_qubits=None,
num_samples=1, backend=simulator):
"""
Get a list of all the outputs from an algorithm, where the previous output
is prepared as the starting point for the next algorithm; ie the
measurement of the algorithm is input to run the algor... |
def setup_logging(log_level):
logger = logging.getLogger(__name__)
logger.setLevel(log_level)
json_handler = logging.StreamHandler()
formatter = jsonlogger.JsonFormatter(
fmt='%(asctime)s %(levelname)s %(name)s %(message)s'
)
json_handler.setFormatter(formatter)
logger.addHandler(jso... | The code induces controlled chaos in an AWS environment by isolating a specified Availability Zone (AZ). It creates a network ACL (NACL) to block traffic, limits Auto Scaling Groups (ASG) from using the failed AZ, and initiates failover for RDS and ElastiCache if enabled. After a set duration, it rolls back changes, re... | def run(region, az_name, vpc_id, duration, limit_asg, failover_rds, failover_elasticache, log_level='INFO'):
setup_logging(log_level)
logger = logging.getLogger(__name__)
logger.info('Setting up ec2 client for region %s ', region)
ec2_client = boto3.client('ec2', region_name=region)
autoscaling_clie... |
def setup_logging(log_level):
logger = logging.getLogger(__name__)
logger.setLevel(log_level)
json_handler = logging.StreamHandler()
formatter = jsonlogger.JsonFormatter(
fmt='%(asctime)s %(levelname)s %(name)s %(message)s'
)
json_handler.setFormatter(formatter)
logger.addHandler(jso... | The code performs a forced failover on an Amazon RDS instance. It initializes an RDS client for a specified region, then executes either `force_failover_rds_id` (if an RDS ID is provided) or `force_failover_rds` (using VPC and AZ parameters) to trigger failover. Logging is configured based on the input log level, and t... | def run(region, rds_id=None, az_name=None, vpc_id=None, log_level='INFO'):
setup_logging(log_level)
logger = logging.getLogger(__name__)
logger.info('Setting up rds client for region %s ', region)
rds_client = boto3.client('rds', region_name=region)
if rds_id:
response = force_failover_rds_i... |
def setup_logging(log_level):
logger = logging.getLogger(__name__)
logger.setLevel(log_level)
json_handler = logging.StreamHandler()
formatter = jsonlogger.JsonFormatter(
fmt='%(asctime)s %(levelname)s %(name)s %(message)s'
)
json_handler.setFormatter(formatter)
logger.addHandler(jso... | The code initiates an AWS Elasticache failover operation in a specified region. It uses boto3 to create an Elasticache client, then triggers a failover either for a specific cluster (if a name is provided) or for an availability zone (if an AZ name is given). Logging is configured based on the input log level to track ... | def run(region, elasticache_cluster_name=None, az_name=None, vpc_id=None, log_level='INFO'):
setup_logging(log_level)
logger = logging.getLogger(__name__)
logger.info('Setting up elasticache client for region %s ', region)
elasticache_client = boto3.client('elasticache', region_name=region)
if elast... |
def save_song(self, _, clear=True):
song = self.get_selected_song()
if song == None: return
if self.song_is_mp3(song):
song.set_tag("artist", self.song_data["Artist"].get())
song.set_tag("album", self.song_data["Album"].get())
song.set_tag("title", self.song_... | This code saves the current song and selects the next song in the list. If no songs are present, it clears the selection. If the current song is the last one, it also clears the selection. Otherwise, it updates the selected song to the next item in the list. | def save_and_next_song(self, _):
self.save_song(_, False)
if len(self.songs) == 0:
self.selected_song.set("")
return
song = self.get_selected_song()
if song == None:
song = self.songs[0]
else:
i = self.songs.index(song.filename)
... |
def get_object_pose(self, sample, obj_root):
seq_path = os.path.join(obj_root, sample['subject'], sample['action_name'],
sample['seq_idx'], 'object_pose.txt')
with open(seq_path, 'r') as seq_f:
raw_lines = seq_f.readlines()
raw_line = raw_lines[sample[... | The code preprocesses data by converting 3D object and hand poses into 2D projections using camera parameters, generates tensors for object/hand positions, masks, and action labels, then returns these along with images and metadata for training models in object-hand interaction tasks. | def preprocess(self, idx):
sample = self.samples[idx]
object_category = {
'juice': 0,
'liquid_soap': 1,
'milk': 2,
'salt': 3
}
action_category = {
'open_milk': 0,
'close_milk': 1,
'pour_milk': 2,
'open_juic... |
def load_objects(self, obj_root):
object_names = ['juice', 'liquid_soap', 'milk', 'salt']
all_models = {}
for obj_name in object_names:
obj_path = os.path.join(obj_root, '{}_model'.format(obj_name),
'{}_model.ply'.format(obj_name))
mesh... | This code initializes a data loader for action recognition, organizing video frames into structured samples. It maps actions to objects, filters valid sequences across subjects, and generates frame-level samples with metadata (subject, action, object, etc.). When `loadit=False`, it builds a dataset by iterating through... | def __init__(self, mode='train', root='../data/First_Person_Action_Benchmark', loadit=False, name=None):
self.loadit = loadit
self.temp = 0
if name is None:
self.name = mode
else:
self.name = name
self.root = root
if mode=='train3':
... |
def check_exists_with_error():
"""checks if git exists, and if not throws a fatal error"""
if not check_exists():
log.error("git not found, please run and fix './fips diag tools'")
return False
def has_local_changes(proj_dir):
"""checks if a git repo has uncommitted or unpushed changes (basi... | (The function updates a git repository by pulling the latest changes and updating submodules, but only if there are no uncommitted changes. It checks for local modifications; if absent, it executes `git pull` and submodule updates, returning True. If local changes exist, it logs a warning and returns False to prevent o... | def update(proj_dir):
"""runs a git pull && git submodule update [--recursive] on the
provided git repo, but only if the repo has no local changes
:param proj_dir: a git repo dir
"""
check_exists_with_error()
if not has_local_changes(proj_dir):
subprocess.call('git pull', cwd=proj_di... |
def get_blobs_dynamic(frame):
params = cv2.SimpleBlobDetector_Params()
circularity = cv2.getTrackbarPos("circularity", "params") / 100.0
params.filterByCircularity = True
params.minCircularity = circularity
area = cv2.getTrackbarPos("blob_area_min", "params")
maxarea = cv2.getTrackbarPos("blo... | The main task of the code is to detect and count dice pips (dots) in an image using morphological operations, blob detection, and contour analysis. It processes the image through steps like blurring, edge detection, blob filling, convex hulls, dilation/erosion, and binary thresholding to isolate dice and their pips, ul... | def detect_dices_with_morph(cap, show_all=False, show_first_last=False):
success, frame = cap.read()
contour_image = frame.copy()
if not success:
cap = cv2.VideoCapture(device_id)
success, frame = cap.read()
#Convert original image to gray
gray = cv2.cvtColor(frame, cv2... |
def get_cap(device_id):
cap = cv2.VideoCapture(device_id)
if not cap.isOpened():
print(f'Could not open camera {device_id}')
return
else:
print(f'Successfully opend camera {device_id}')
return cap
def detect_dices_with_morph(cap, show_all=False, show_first_last=False):
... | The code implements a real-time Yahtzee (Yatzi) game using camera input and OpenCV. It detects dice via adjustable image processing parameters (blob/contour analysis, morphology), updates game state based on detected dice, and displays results in two windows. The user can reset the game or quit, with logic handling up ... | def yatzi():
#Get camera
device_id = 0
cap = get_cap(device_id)
#Create params window
cv2.namedWindow("params")
cv2.resizeWindow("params", 200, 200)
cv2.createTrackbar("blob_area_min", "params", 115, 10000, PASS)
cv2.createTrackbar("blob_area_max", "params", 1000, 10000, PASS)
cv2.c... |
def git_search(start_path):
if start_path == "/":
print("Not inside a Git Repository", file=sys.stderr)
sys.exit(1)
if ".git" in os.listdir(start_path):
return os.path.join(start_path, ".git")
return git_search(os.path.abspath(os.path.join(start_path, os.pardir)))
def get_branch(git... | The main task of the code is to generate a topological order of commits in a Git repository by building a commit graph, mapping branch-commit relationships, and printing the sorted commits with their branch associations. It processes git data, decodes commit contents, constructs dependencies, and outputs a structured v... | def topo_order_commits():
git_dir = git_search(os.getcwd())
branch_paths = get_branch(git_dir)
commit_list = get_commits(branch_paths)
decoded_contents = decode(commit_list, git_dir)
graph = create_commit_graph(decoded_contents, commit_list, git_dir)
topo_sorted_commits = toposort(graph)
bra... |
def load_vendors(vendors) -> None:
"""Initializes a database with patterns to match expenses to vendors"""
with engine.connect() as conn:
try:
conn.execute(insert(Vendors), vendors)
except exc.IntegrityError:
session.rollback()
print("Vendors are loaded")
def ... | The main task of the code is to load banking data, budget plans, and vendor information from YAML files, import transactions into an SQLite database, and validate budget plans against predefined checks for consistency, such as duplicate-free entries, percentage sums, and tag completeness. | def main():
folder_path = "./banking_csvs/"
engine = create_engine("sqlite:///budget.db")
# Load bank profiles
with open("bank_profiles.yml", "r") as bp:
bank_profiles = yaml.safe_load(bp)
# Load budget plans
with open("budget_plans.yml", "r") as budp:
budget_plans = yaml.safe... |
def clear():
clr = os.system('cls' if os.name in ('nt', 'dos') else 'clear')
return clr
def diskCleanup(diskCleanup, sickbay):
if diskCleanup is True or sickbay is True:
print(shutil.disk_usage("C:/"))
diskCleanupYorN = input("Do you want to run disk cleanup? (y/n) \n")
if diskCleanupYorN == 'y':
... | The main task of PHASE_2 is to inform users of a detected malicious folder, offer system preparation via disk cleanup and Windows Update, then prompt for threat removal via SafteyScan. It logs actions, handles user input (y/n), executes cleanup/scanning functions, and transitions to PHASE_3 if confirmed. Skipping steps... | def PHASE_2():
# This will run diskcleanup after that ask to run windowsUpdate and tron
clear()
print(Fore.YELLOW + "PHASE-2")
# Log
with open(Files.logFile, "a") as f:
f.write("SafeGuard PHASE-2 initalized - AT:" + now)
if debug:
print(Fore.BLUE + "SafeGuard PHASE-2 initalized - AT:" + now + Styl... |
def checkDirectorys():
for iteam in data_into_list:
if os.path.isdir(iteam) is True:
# User notification
print(Fore.RED + "Directory detected" + Style.RESET_ALL)
# Log directory detected
with open(Files.logFile, "a") as f:
f.write("[" + iteam + "] Directory !DETECTED! - AT:" + no... | The code initializes Phase 1 of a security protocol by logging the start, checking for malicious directories, and triggering an emergency system restore if threats are detected. It prompts the user to confirm proceeding to Phase 2 for further action or exits gracefully. The function ensures system safety through direct... | def PHASE_1():
# This will run checkDirectory and systemRestore
print(Fore.GREEN + "PHASE-1")
# Log
with open(Files.logFile, "a") as f:
f.write("SafeGuard PHASE-1 initalized - AT:" + now)
if debug:
print(Fore.BLUE + "SafeGuard PHASE-1 initalized - AT:" + now + Style.RESET_ALL)
# If checkDirectory... |
def __read_diagnostic_file(self):
with open('inputFiles/day3_input.txt') as f:
for x in f:
self.rawDiagnostics.append(int(x, 2))
f.close()
def __calculateGammaRate(self):
gammaString = ""
for i in range(len(self.diagMask)):
count = self.__countBits... | The code processes diagnostic data by reading a file, calculating gamma and epsilon rates for power consumption, determining oxygen and CO₂ scrubber ratings, and ultimately computing the life support rating by combining these values. | def readDiagnostics(self):
self.__read_diagnostic_file()
self.__calculateGammaRate()
self.__calculateEpsilonRate()
self.__calculatePowerConsumption()
self.__calculateOxygenGeneratorRating()
self.__calculateCO2ScrubberRating()
self.__calculateLifeSupportRating() |
def initialize_board():
board = np.full((ROWS, COLS), EMPTY)
board[2][3] = X # FIRST MOVE
board[2][2] = O # FIRST MOVE
# example configuration for HW4 doc
# (X h-value should be 84, O h-value should be 160)
'''board[1][3] = X
board[1][2] = O
board[2][2] = O
board[2][3] = O
b... | The main task of the code is to initialize a game board, display its current state, and calculate/print a heuristic value for the board configuration using symbols X and O, likely for a game like Tic-Tac-Toe or similar AI-driven decision-making scenario. | def main():
print("Board:")
board = initialize_board()
display_board(board)
print_heuristic(board, X, O) |
def initialize_board():
board = np.full((ROWS, COLS), EMPTY)
board[2][3] = X # FIRST MOVE
board[2][2] = O # FIRST MOVE
# example configuration for HW4 doc
# (X h-value should be 84, O h-value should be 160)
# board[1][3] = X
# board[1][2] = O
# board[2][2] = O
# board[2][3] = O
... | The main task of the code is to simulate a two-player game on a board, where each player (X and O) alternately selects the best move using a heuristic evaluation function. The game continues until a player achieves a winning condition (heuristic value 1000) or all moves are exhausted, resulting in a tie. The board is d... | def main():
print("Board:")
board = initialize_board()
display_board(board)
#print_heuristic(board, X, O)
# for i in range(5) :
# for j in range(6) :
# if(board[i][j] == EMPTY) :
# board[i][j] = O
# h = heuristic(board,O, X)
# ... |
def move_left(self):
# Move the board left, combining tiles as they move
for row in self.array:
for x in range(self.size):
last_tile = 0
for i in range(x-1, last_tile-1, -1):
if row[i] == 0:
if i == last_tile:
... | The code handles keyboard input to move a game board in the direction of the arrow keys, but only if the move results in a change to the board's state. It creates a temporary board to simulate the move, checks if the new state differs from the original, and applies the move to the actual board if valid. This ensures th... | def move(self):
# Move the board based on the current key being pressed
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
temp_board = Board(array = copy.deepcopy(self.array), temp = True)
temp_board.move_left()
if temp_board.array != self.array... |
def restart(self):
# Create a fresh board and place two starting tiles
self.score = 0
self.array = []
for i in range(self.size):
self.array.append([0] * self.size)
self.add_tile()
self.add_tile()
def move_left(self):
# Move the board left, combining ti... | This code runs a game loop handling user input to control tile movement in a grid-based game (likely 2048). It processes directional inputs from a queue, updates the game state by moving tiles left/right/up/down, and continuously redraws the game window at 10 FPS. The loop checks for quit events, manages grid size, and... | def run(self, input):
clock = pygame.time.Clock()
# Changes grid size
current_size = 4
# Creates a board an populates it with 2 starting tiles
self.restart()
# Main loop
while True:
clock.tick(10)
for event in pygame.event.g... |
def part1(bag_name, bags):
return len(set.union(*get_parents(bags[bag_name])))
def parse(data) -> tp.Dict[str, Bag]:
bags = {}
for line in data:
match = parent_pattern.match(line)
parent_name = match["parent"]
if parent_name not in bags:
bags[parent_name] = Bag(parent_na... | The code reads input from a file, parses it, and computes two results related to "shiny gold" bags using part1 and part2 functions, then prints them. The main task involves processing bag containment rules to determine dependencies and quantities. | def main():
with open(get_filename()) as file:
inp = [line.strip() for line in file]
print(part1("shiny gold", parse(inp)))
print(part2("shiny gold", parse(inp))) |
def GetAccountNumber(Message_Dict):
if CheckIfCustomer(Message_Dict):
url = "http://api.reimaginebanking.com/customers?key={}".format(apiKey)
Result = json.loads(requests.get(url).text)
for i in Result:
if i["first_name"] == Message_Dict["From"]:
url = "http://api... | The code facilitates fund transfer between accounts via an API. It retrieves account numbers, validates sufficient balance, constructs a transaction request, and handles API responses. If the payee is invalid or the balance is low, it returns error messages; otherwise, it returns the payee's account ID after a successf... | def TransferFunds(To, From, Amount):
# Assuming From is a message and To & Amount is a number taken from a database
PayerAccountID = GetAccountNumber(From)
PayeeAccountID = GetAccountNumberFromNumber(To)
url = "http://api.reimaginebanking.com/accounts/{}/transfers?key={}".format(PayerAccountID, apiKey)... |
def cbStop(self):
self.partyTwist.linear.x = 0.0
self.partyTwist.linear.y = 0.0
self.partyTwist.linear.z = 0.0
self.partyTwist.angular.x = 0.0
self.partyTwist.angular.y = 0.0
self.partyTwist.angular.z = 0.0
self.partyTwist_pub.publish(self.partyTwist)
def cbRotateR(self):
self.partyTwist.linear.x = ... | The code manages two tasks based on AprilTag detection. Task 1 (searching for AprilTag ID 0) triggers movement and encoder reset upon detection or distance traveled. Task 2 (tracking AprilTag ID 1) initiates error correction if detected, otherwise halts. The function transitions between tasks, logs warnings for invalid... | def cbParty(self):
if self.apriltag_detection_ID == 0:
self.taskONE = True
elif self.apriltag_detection_ID == 1 and self.taskONE == False:
self.taskTWO = True
else:
self.cbStop()
rospy.logwarn("Waiting For Instruction!")
# Task 1: Search for the ArptilTag
if self.taskONE == True:
if (self.apr... |
def switch(self):
if self.is_on:
self.toggle_btn.config(image = self.off_img)
self.status['text'] = "Off"
self.is_on = False
else:
self.toggle_btn.config(image = self.on_img)
self.status['text'] = "On"
self.is_on = True
def upload_f... | This code initializes a webcam GUI interface with features like video capture, toggle buttons, image uploads, snapshot functionality, and dropdown menus for selecting face detection methods. It sets up layout configurations, loads images for UI elements, and prepares interactive components for user interaction with the... | def __init__(self, parent, controller):
super().__init__(parent)
self.video_source = 0
try:
self.vid = video_capture(self.video_source)
except ValueError:
self.destroy()
messagebox.showerror('Error', "Unable to open this camera \n Select another video ... |
def depthEfficient(ArrStore,Arr):
global puzzle
#depth = 0
current = Arr[len(Arr)-1]
#copying( abc = puzzle, cde = current[0])
temp = current[0]
for i in range(3):
for j in range(3):
puzzle[i][j] = temp[i][j]
depth = current[1]
h = current[2]
if depth >=... | The code implements a depth-first search (DFS) algorithm for solving a puzzle, using backtracking. It recursively explores paths by checking if a solution exists via `depthEfficient`, then modifies the current path (`Arr`) and state store (`ArrStore`) to backtrack when a solution is found. If a valid state (`temp[2] ≤ ... | def depthNonEfficient(ArrStore,Arr):
global puzzle
#foundOrNotFound,Arr,ArrStore = depthEfficient(ArrStore = ArrStore, Arr = Arr)
#Abcde = []
#Abcde = depthEfficient(ArrStore = ArrStore, Arr = Arr)
#Arr = Abcde[1][0]
#ArrStore = Abcde[2][0]
#foundOrNotFound = Abcde[0][0]
foundOrNotFound ... |
def efficient(Arr,Auxarr):
global puzzle,result
#puzzle = Arr[len(Arr)-1][0]
depth = Arr[len(Arr)-1][1]
h = Arr[len(Arr)-1][2]
action = Arr[len(Arr)-1][3]
print("Putting in Arr")
#printed(Arr[len(Arr) -1][0])
#puzzle = [[0,0,0],[0,0,0],[0,0,0]]
#temp = Arr[len(Arr)-1]
#puz = temp... | The code implements a backtracking algorithm to solve a puzzle by recursively exploring paths. When a valid solution is found (flag=True), it prints the path and returns True. If not, it backtracks by removing elements from the current path (Arr) and incorporating the next possible step from the auxiliary stack (Auxarr... | def inefficient(Arr,Auxarr):
global puzzle,result
flag = efficient(Arr = Arr, Auxarr = Auxarr)
print(flag)
if flag==True:
printing(Arr=Arr)
print("found")
print(len(Arr))
#printing(Auxarr)
return True
elif flag==False:
if len(Auxarr)==0:
... |
def duplicate(arr):
newarr = [[0,0,0],[0,0,0],[0,0,0]]
for i in range(3):
for j in range(3):
newarr[i][j] = arr[i][j]
return newarr
def compare(puz):
global result
count = 0
for i in range(3):
for j in range(3):
if puz[i][j]!=-1:
(iresult,j... | The code implements a depth-first search algorithm to solve a puzzle. It initializes a queue (`Arr`) with the starting puzzle state, depth 0, and comparison result. The `inefficient` function checks if the search should proceed; if not, it prints "Couldn't find" and exits. The main task is to explore puzzle states recu... | def depth ():
global puzzle,result
#printed(puzzle)
Arr = []
puz = duplicate(puzzle)
Arr.append([puz,0,compare(puz),'_'])
#Arr = [[puzzle,0,compare(puz),'_']]
Auxarr = []
#printing(Arr)
if inefficient(Arr = Arr, Auxarr = Auxarr)==False:
print("Couldn't find")
return |
def import_node_tree(file_path,node_tree = None):
with open(file_path, 'r') as file:
data = json.load(file)
# Get the active object
obj = bpy.context.active_object
# Check if there is an active object and if it has an active material
if obj == None or obj and obj.active_material == None... | This function sets up a node tree by clearing existing nodes if specified, importing a predefined node structure from a JSON file, and assigning texture images to ShaderNodeTexImage nodes. It uses properties to determine the file type, structure, and texture paths, dynamically loading textures based on node names and s... | def nTreeSetup(node_tree, textures_dir, material_name, properties):
if properties.clearNodes:
for node in node_tree.nodes:
node_tree.nodes.remove(node)
# Properties
file_type = properties.image_file_type
node_structure = properties.node_structure
script_directory = os.path.dirna... |
def mobility_score(g: Game, player: int, oth_player: int) -> float:
my_mobility = len(g.find_valid(player))
oth_mobility = len(g.find_valid(oth_player))
total_mobility = my_mobility + oth_mobility
return (my_mobility - oth_mobility) / max(total_mobility, 1)
def corner_score(g: Game, player: int, oth_pla... | The function `heuristic_score` calculates a weighted composite score for a player in a game (likely Othello/Reversi) by combining five factors: mobility, corners, frontier, weight, and stability. Each sub-score (0–100) is adjusted dynamically based on the game turn: corners and frontier/mobility are prioritized early, ... | def heuristic_score(g: Game, player: int) -> int:
rating = 0
oth_player = (player + 1) % 2
# Each of these score functions will retrun a value out of 100
# A bigger value = better for the player
mobility = mobility_score(g, player, oth_player)
corner = corner_score(g, player, oth_player)
fr... |
def find_score(g: Game, priority: int) -> tuple[float, int, int]:
key = zobrist_key(g)
if key[0] in transposition_table:
if key[1] in transposition_table[key[0]]:
score = transposition_table[key[0]][key[1]]
else:
score = heuristic_score(g, priority)
transposit... | This function implements the minimax algorithm with alpha-beta pruning to determine the optimal move in a game. It evaluates valid moves recursively, prioritizing heuristic-sorted options, and updates best evaluation values (alpha/beta) to prune suboptimal branches. The function returns the best score and move coordina... | def minimax(
g: Game,
priority: int,
alpha: float,
beta: float,
depth: int
) -> tuple[float, int, int]:
if g.over() or depth == 0:
return find_score(g, priority)
valid_moves = heuristic_sort(g, g.find_valid(g.p))
best_y, best_x = valid_moves[0]
best_eval = -math.inf if g.p ... |
def listing_files_for_renaming(directory_path):
is_existing_directory(directory_path)
for file_name in os.listdir(directory_path):
if (file_name.endswith(".jpg") or file_name.endswith(".JPG") or file_name.endswith(".jpeg")):
snap_file_names.append(file_name)
if (file_name.ends... | The main task of the code is to rename test images and related files in a directory, handling both single directories and subfolders. It checks for subfolders, lists files for renaming, and applies renaming based on test type, start index, and count. It prints the number of renamed snapshots, raws, and videos, ensuring... | def rename_test_images(directory, dir, start_idx, count, test_type):
### check for subfolders \\ a.k.a if there is testing from multiple devices
list_subfolders_with_paths = [f.path for f in os.scandir(directory) if f.is_dir()]
if(len(list_subfolders_with_paths) == 0):
listing_file... |
def print_(string, fname='', verbose=False, bold=False):
if verbose:
if bold:
print(f"{color.bold} [{fname}] {string} {color.none}")
else:
print(f"[{fname}] {string}")
def get_rms(infile, verbose=False):
"""
Calculate the standard deviation of an fits file
by obtaining it within four rectangular regio... | The function calculates column density of a molecular species from intensity/flux density data by integrating optical depth over velocity channels, converting input data to brightness temperature, applying FWHM and velocity resolution, and outputting results as a FITS file with derived column density values in cm⁻². | def column_density(infile, outfile='', mol='', nu=0, fwhm=0, Tex=15, mu=0, J=1, E=0, g=0, A=0, Q=0, d_v=None, chans=None, threshold=None, fliplr=False, flipud=False, overwrite=False, verbose=False):
"""
Reads intensity or flux density [Jy] values.
Intensity must be in [Jy/beam], flux density must be in [Jy].
Optic... |
def print_(string, fname='', verbose=False, bold=False):
if verbose:
if bold:
print(f"{color.bold} [{fname}] {string} {color.none}")
else:
print(f"[{fname}] {string}")
def brightness_temperature(infile, outfile='', unit='jy/beam', nu=0, fwhm=0, pixel_size=0, overwrite=False, verbose=False):
"""
Convert i... | The function `apply_beam` convolves input images or data cubes with a Gaussian beam to simulate telescope observations. It bins data, applies a Gaussian kernel based on FWHM and orientation, rescales intensities from Jy/px to Jy/beam, and optionally converts to brightness temperature (Tmb). It supports flipping, log sc... | def apply_beam(infile, fwhm, pa=0, nu=0, outfile='', bin_img=1, bin_spec=1, eff=1, telescope='APEX', pixel_size=None, output_Tmb=False, flip_lr=False, flip_ud=False, log_scale=False, overwrite=False, verbose=False):
"""
Function used to convolve images by single-beams.
This does not apply for interferometers, in suc... |
def connectToDb() -> tuple:
connection = sql.connect("/Users/ghazshahbaz/documents/tools/eventsdatabase/events.db") # sql.Connection
cursor = connection.cursor() # sql.Cursor
return connection, cursor
def printRow(row) -> None:
if row[4] == "None" or not row[4]:
return
e... | The function `performQuery` executes SQL queries on a database, handling three modes: "select" (fetches and prints filtered/event data with grouping/sorting), "calculate" (processes free time calculations), and default (executes queries). It connects to the database, processes results, and prints outputs or commits cha... | def performQuery(query, selectType) -> None:
connection, cursor = connectToDb()
if selectType == "select":
data = cursor.execute(query + " limit 1")
filterType = None
try:
filterType = query.split()[1]
except:
print("Error")
return
pr... |
def isWinning(self, board):
return self.boardObject.winning_move(board, self.currentPiece)
def evaluation(self, board, piece):
oppentPiece = 1
score = 0
# Check for horizontal
for row in range(GRID_SIZE):
rowArray = [int(i) for i in list(board[row, :])]
f... | The code implements the minimax algorithm with alpha-beta pruning to determine the optimal move for a player (AI or human) in a game. It evaluates all possible future moves up to a given depth, recursively calculating scores for each state. The maximizing player (AI) seeks to maximize the score, while the minimizing pl... | def minimax(self, board, depth, isMaxizingPlayer, alpha, beta):
if self.isWinning(board):
return (10000, None) if self.currentPiece == self.piece.AI else (-1000, None)
elif depth == 0:
return (self.evaluation(board, self.piece.AI), None)
if isMaxizingPlayer:
... |
def height(self, node):
if node == None:
return -1
else:
return node.height
def rotate(self, node) -> Node:
if self.height(node.left) - self.height(node.right) > 1:
# LEFT HEAVY
if (self.height(node.left.left) - self.height(node.left.right) > 0):
... | This function recursively inserts a value into a binary tree, updates the node's height, and ensures balance by rotating the node. It handles insertion into left or right subtrees based on value comparison, adjusts heights, and returns the rotated node to maintain tree balance. | def insert_helper(self, node, val) -> Node:
if node == None:
return Node(val)
if val < node.val:
node.left = self.insert_helper(node.left, val)
if val > node.val:
node.right = self.insert_helper(node.right, val)
node.height = max(self.height(node.le... |
def get_destination_coordinates(testing=False):
logger.info("edcm.navigation.get_destination_coordinates()")
coordinates = (0, 0)
destination_template = cv2.imread(resource_path("..\\templates\\destination.png"), cv2.IMREAD_GRAYSCALE)
destination_width, destination_height = destination_template.shape[:... | The function calculates destination coordinates by polling multiple times, accumulating results, and returning either the average (if enabled) or the latest valid coordinates. It retries up to 15 times, resets every 3 attempts, and returns None on failure. | def get_destination_offset(testing=False, average=False):
logger.info("edcm.navigation.get_destination_offset(testing=%s,average=%s)" % (testing, average))
retries = 15
minimum = 5
tries = 1
avg = {'x': 0, 'y': 0}
total = {'x': 0, 'y': 0}
while tries <= retries:
pt = get_destination_... |
def get_compass_image(testing=False):
logger.info("edcm.navigation.get_compass_image(testing=%s)" % testing)
# left and top coordinate point for matched compass template
pt = None
# additional pixels to match boundary
doubt = 10
windows.set_elite_active_window()
# read high resolution na... | The main task of the code is to locate the "navball" template within a compass image, adjust its coordinates relative to the compass's center, and return the normalized position as a dictionary. It processes the compass image, detects matches using a template, applies thresholds, handles edge cases like reversed orient... | def get_navpoint_coordinates(testing=False):
logger.info("edcm.navigation.get_navpoint_coordinates()")
compass_image, compass_width, compass_height = get_compass_image()
if check_reverse(compass_image):
logger.warning("Matched NavCircle, must turn around")
reverse_direction()
return... |
def sun_percent():
logger.info("edcm.navigation.sun_percent()")
screen_size = get_elite_size()
logger.info("screen_size: left = %s, top = %s, width = %s, height = %s"
% (screen_size['left'], screen_size['top'], screen_size['width'], screen_size['height']))
# capture canopy view
scre... | The main task of the code is to align a spacecraft's orientation to a destination by adjusting yaw and pitch using keyboard commands. It checks the ship's status, reduces solar exposure, sets maneuvering speed, and continuously adjusts heading based on offset calculations until both X and Y axes are aligned with the ta... | def destination_align():
logger.info("edcm.navigation.align()")
center = {'x': 0, 'y': 0}
ship_status = get_ship_status()['status']
if not (ship_status == 'in_supercruise' or ship_status == 'in_space'):
logger.error('align=err1')
raise Exception('align error 1')
while sun_percent... |
def get_navpoint_coordinates(testing=False):
logger.info("edcm.navigation.get_navpoint_coordinates()")
compass_image, compass_width, compass_height = get_compass_image()
if check_reverse(compass_image):
logger.warning("Matched NavCircle, must turn around")
reverse_direction()
return... | This function retrieves navigation point coordinates by polling repeatedly (up to 15 attempts). It calculates either a rolling average (if enabled) or returns the latest valid coordinates. If coordinates are invalid, it resets and retries. On failure after all attempts, it returns None. The function logs progress and u... | def get_navpoint_offset(testing=False, average=False):
logger.info("edcm.navigation.get_navpoint_offset(testing=%s, average=%s)" % (testing, average))
retries = 15
minimum = 5
tries = 1
avg = {'x': 0, 'y': 0}
total = {'x': 0, 'y': 0}
while tries <= retries:
pt = get_navpoint_coordin... |
def sun_percent():
logger.info("edcm.navigation.sun_percent()")
screen_size = get_elite_size()
logger.info("screen_size: left = %s, top = %s, width = %s, height = %s"
% (screen_size['left'], screen_size['top'], screen_size['width'], screen_size['height']))
# capture canopy view
scre... | The function aligns a ship's orientation with a target navigation point by adjusting pitch and roll based on offset directions. It checks the ship's status, reduces sun exposure, sets maneuvering speed, and uses loops to correct alignment via key inputs until both X and Y axes are aligned with the target. | def navigation_align():
logger.info("edcm.navigation.navigation_align()")
center = {'x': 0, 'y': 0}
ship_status = get_ship_status()['status']
if not (ship_status == 'in_supercruise' or ship_status == 'in_space'):
logger.error('align=err1')
raise Exception('align error 1')
while s... |
def sun_percent():
logger.info("edcm.navigation.sun_percent()")
screen_size = get_elite_size()
logger.info("screen_size: left = %s, top = %s, width = %s, height = %s"
% (screen_size['left'], screen_size['top'], screen_size['width'], screen_size['height']))
# capture canopy view
scre... | The code aligns a spacecraft to a destination by adjusting pitch, roll, and yaw using sensor data and keyboard inputs. It checks the ship's status, avoids the sun, adjusts speed, corrects compass orientation, and iteratively aligns the ship's position relative to a navigation point. If misaligned, it sends commands to ... | def align():
logger.info("edcm.navigation.align()")
center = {'x': 0, 'y': 0}
ship_status = get_ship_status()['status']
if not (ship_status == 'in_supercruise' or ship_status == 'in_space'):
logger.error('align=err1')
raise Exception('align error 1')
while sun_percent() > 5:
... |
def import_shopping_list(file_name):
'''
Returns the contents of the text file with the supplied name parsed to a list object.
'''
return parse_list(io_helper.import_file(file_name))
def valid_shopping_list(user_input):
'''
Returns True if the supplied string is a valid shopping list. Otherwise ... | The main task of the code is to display a menu of available text files for importing a shopping list, allowing the user to select one. It then validates the selected file's contents and returns the shopping list as a list of strings. The function leverages `print_menu` to show options generated from files in the import... | def import_shopping_list_menu():
'''
Prompts the user to select a text file from which to import the shopping list. Returns a list of strings representing the shopping list.
'''
menu_options = list(map(
lambda f: MenuOption(f, lambda: import_shopping_list(f), lambda: valid_shopping_list(io_helpe... |
def prep_items(stores, shopping_list):
'''
Filters out items that are not of the predominant type to facilitate easier comparison.
'''
for item_name in shopping_list:
item_type = get_predominant_item_type(stores, item_name)
for store in stores:
store_items = store.items.get(i... | The main task of the code is to generate a stacked bar chart comparing product prices for items in a shopping list across multiple stores. It prepares data, retrieves price information using analysis options, creates a chart title, and renders the visualization to display price comparisons. | def build_chart(stores, shopping_list, analysis_options):
'''
Creates and displays a stacked bar chart comparing product prices for items in the shopping list
at the provided stores using the AnalysisOptions instance.
'''
prep_items(stores, shopping_list)
data = get_data(stores, shopping_list, a... |
def recover_tree(vecs, parent, start_idx):
if len(vecs) == 0:
return vecs, start_idx
if vecs[0] == None:
return vecs[1:], start_idx + 1
node = TreeNode(vecs[0], parent, start_idx, -1)
while True:
vecs, start_idx = recover_tree(vecs[1:], node, start_idx + 1)
parent.add_chi... | The function encodes a hierarchical plan into structured representations by traversing a tree, grouping nodes by levels, and extracting operators, extra information, conditions, and child mappings for each node. It processes the plan to generate level-wise encoded data for further analysis or execution. | def encode_plan_job(plan, parameters):
#operators, extra_infos, conditions, condition_masks = [], [], [], []
operators, extra_infos, conditions = [], [], []
mapping = []
nodes_by_level = []
node = TreeNode(plan[0], None, 0, -1)
recover_tree(plan[1:], node, 1)
dfs_tree_to_level(node, 0, nodes... |
def createReadPieFigure(irma_path, read_df):
print(f"Building barcode distribution pie figure")
read_df = read_df[read_df["Record"] == "1-initial"]
fig = px.pie(read_df, values="Reads", names="Sample")
fig.update_traces(textposition="inside", textinfo="percent+label")
fig.write_json(f"{irma_path}/..... | The main task of the code is to generate multiple visualizations (pie chart, Sankey diagram, heatmaps, and coverage plots) from input dataframes and parameters, saving them in the specified directory. It orchestrates the creation of these figures using helper functions for different plot types, leveraging coverage data... | def generate_figs(irma_path, read_df, coverage_df, segments, segcolor, pass_fail_df):
createReadPieFigure(irma_path, read_df)
createsankey(irma_path, read_df, virus)
createheatmap(irma_path, pivot4heatmap(coverage_df))
create_passfail_heatmap(irma_path, pass_fail_df)
createcoverageplot(irma_path, co... |
def getStopWords():
df = pandas.read_csv('../data/stoplist-en.csv')
sw = df.word.to_list()
new_sw = []
for w in sw:
tags = []
try:
for x in wn.synsets(w):
tags.append(x.pos())
except:
tags = ['']
if not 'a' in tags:
new_... | The code preprocesses a comment by converting it to lowercase, removing punctuation, handling negations, eliminating digits, and removing stopwords to clean and normalize the text for further analysis. | def preprocessing(komentar):
stopWords = getStopWords()
# lemmatizer = WordNetLemmatizer()
hsl = preprocess_tweet(komentar)
hsl = hsl.lower() #case folding
hsl = punctuation_removal(hsl)
hsl = negation_tag(hsl)
# hsl = rm_html(hsl)
hsl = hsl.translate(str.maketrans('','',string.digits))... |
def simulate_random(self,board):
i = 0
if not self.endofGame(board):
moves = GoBoardUtil.generate_legal_moves_gomoku(board)
random.shuffle(moves)
while not self.endofGame(board):
board.play_move_gomoku2(moves[i],board.current... | The code evaluates the strength of a move in a Gomoku game by simulating multiple random games from the current board state. It records outcomes (win, loss, draw) across simulations, computes a score based on win rates, and adjusts it for the current player's perspective. The result is a normalized evaluation value ind... | def simulate(self,board,move):
stats = [0] * 3
board.play_move_gomoku2(move,board.current_player)
moveNr = len(board.move)
for _ in range(self.numSimulations):
winner, _ = self.simulate_random(board)
stats[winner] += 1
self.resetToMoveNumber(b... |
def __build_views(self):
'''There are 4 possible top left positions of a Rubiks Cube.
Each 3 x 3 side cell is labeled 0 through 8, so the 4 corners are:
0, 2, 6, and 8.
Each of the 3 x 3 arrays per side contain a tuple that relates
to the [row][column] position of the side in vie... | The code initializes a class instance by setting up debug mode, defining initial side and orientation, building views and sides for a 3D structure (likely a cube), filling squares with data, and shuffling them. It prepares the object's state for operations involving spatial views and randomized configurations. | def __init__(self, debug=False):
'''Do all initializations and set the current view to side 0'''
self.__DEBUG = debug
self.__side = 0
self.__orientation = 0
self.__views = defaultdict(list)
self.__build_views()
self.__sides = defaultdict(dict)
for i in ran... |
def message_display(text, text_size, x_cord, y_cord):
'''Displays a text object'''
text_font = pygame.font.Font('freesansbold.ttf', text_size)
text_surface, text_rect = text_objects(text, text_font)
text_rect.center = ((x_cord, y_cord))
gameDisplay.blit(text_surface, text_rect)
def put_square(image_... | The code renders a Rubik's cube display by drawing the current side's colors on a white background, displaying orientation labels, user instructions, and status messages. It loops through the cube's 3x3 grid to render each colored square, checks if all sides are uniformly colored, and shows "ALL MATCHED!" if true. Fina... | def draw_display():
'''Draws the display area within the white background.'''
side, orientation, side_colors = cube.get_view()
gameDisplay.fill(WHITE_BG)
gameDisplay.fill(GREY_BG, rect=BOTTOM_GREY_RECT)
msg_string = 'Side: {} - Top Left: {}'.format(side, orientation)
message_display(msg_string, ... |
def load_image(img):
exact_image = False
if type(img).__module__ == np.__name__:
exact_image = True
base64_img = False
if len(img) > 11 and img[0:11] == "data:image/":
base64_img = True
#---------------------------
if base64_img == True:
img = loadBase64Img(img)
elif exact_image != True: #image ... | This function preprocesses an image for face recognition by detecting and aligning faces, converting to grayscale if specified, resizing to 224x224, normalizing pixel values, and returning the processed image as a numpy array. It handles inputs as paths, base64, or arrays, enforces face detection by default, and raises... | def preprocess_face(img, target_size=(224, 224), grayscale = False, enforce_detection = True, detector_backend = 'opencv'):
#img_path = copy.copy(img)
#img might be path, base64 or numpy array. Convert it to numpy whatever it is.
img = load_image(img)
base_img = img.copy()
img = detect_face(img = img, detect... |
def loadBrandsData(path, filename):
# load the brand data from csv
df = pd.read_csv(os.path.join(path, filename + ".csv"))
return df
def crawlAllDeviceUrlOfAllBrand(config, Brands_data):
res = []
BrandsName = Brands_data['BrandName']
BrandUrls = Brands_data['BrandUrl']
NumberOfPhones = Brand... | The main task of the code is to crawl all device URLs for every brand listed in the configuration, time the crawling process, and save the collected URLs. It loads brand data from a CSV file, retrieves device URLs using a dedicated function, and stores the results as specified in the configuration. | def crawlDevicesUrl(config):
# load the brand data from csv
Brands_data = loadBrandsData(
config['SavePath'], config['BrandsListFileName'])
print("Start crawling devices url")
startTime = time.time()
# crawl all device url of all brand
Devices_urls = crawlAllDeviceUrlOfAllBrand(config,... |
def easy_move(board):
"""
Choose a move randomly from the available empty cells for the EASY difficulty level.
Args:
board (Board): The current state of the board.
Returns:
tuple: The row and column of the chosen empty cell or (None, None) if no empty cells.
... | The main task of the code is to determine and return the AI's next move on a board by delegating the decision to different methods (`easy_move`, `normal_move`, `hard_move`) based on the AI's difficulty level. The function routes the board state to the appropriate method, which calculates the move, and returns the resul... | def make_move(self, board):
"""
Make a move on the board based on the AI's difficulty level.
Args:
board (Board): The current state of the board.
Returns:
tuple: The row and column where the AI has decided to make a move.
"""
if self.difficulty =... |
def mse_f(model, x_f, t_f):
"""
This function calculates the MSE for the PDE.
"""
f_u, f_v = f(model, x_f, t_f)
return (f_u**2 + f_v**2).mean()
def mse_0(model, x_0, u_0, v_0):
"""
This function calculates the MSE for the initial condition.
"""
# creating a t_0 variable to be the sam... | The closure function computes the total loss by summing mean squared errors (MSE) from PDE residuals, initial conditions, and boundary conditions. It performs backpropagation, tracks iterations, prints loss values, and saves model checkpoints every 30 iterations for L-BFGS optimization. | def closure(model, optimizer, x_f, t_f, x_0, u_0, v_0, h_0, t):
"""
The closure function to use L-BFGS optimization method.
"""
optimizer.zero_grad()
# evaluating the MSE for the PDE
loss = mse_f(model, x_f, t_f) + mse_0(model, x_0, u_0, v_0) + mse_b(model, t)
loss.backward(retain_graph=True... |
def keygen(L, n, q):
sks = [regev_secret_keygen(n, q) for _ in range(L + 1)] # NOTE: We're adding `+ 1` here because range is exclusive
pk = regev_public_keygen(sks[0], n, q)
evks = []
for i, _ in enumerate(sks):
# Shifting one index such that we omit the first `sk` which we've explicitly compu... | This code tests a homomorphic encryption scheme by verifying addition and multiplication operations on encrypted bits. It generates keys, switches encryption keys, and checks if encrypted values (0/1) correctly compute (add/mult) and decrypt to expected results modulo 2. Assertions validate ciphertext shapes and decryp... | def tests():
n = 3
q = 2 ** 16
L = 1
# --- Key Switching ---
# `s` is the secret key we use for our "original" encryption
_, _, sk = keygen(L, n, q)
# `t` is the new key we want to encrypt our ciphertext under
_, _, tk = keygen(L, n, q)
evk = switch_keygen(sk, tk, q)
assert evk.s... |
def xy_train_validate_test(train, validate, test, target_var):
id= 'customer_id'
x_train = train.drop(columns=[target_var, id])
y_train = train[target_var]
x_validate = validate.drop(columns=[target_var, id])
y_validate = validate[target_var]
X_test = test.drop(columns=[target_var, id])
... | The code trains multiple random forest models with varying depths (1 to `depth`) and adjusts `min_samples_leaf` inversely if `inverse=True`. It evaluates each model on training and validation sets, collects performance metrics, and returns a DataFrame of models along with evaluation reports for each configuration. | def random_forests(train, validate, test, target_var,
min_sample_leaf=3, depth=15, inverse=True):
x_train, y_train, x_validate, y_validate, X_test, Y_test = xy_train_validate_test(train,
validate,
... |
def xy_train_validate_test(train, validate, test, target_var):
id= 'customer_id'
x_train = train.drop(columns=[target_var, id])
y_train = train[target_var]
x_validate = validate.drop(columns=[target_var, id])
y_validate = validate[target_var]
X_test = test.drop(columns=[target_var, id])
... | This code trains and evaluates multiple k-nearest neighbors (KNN) models with varying 'k' values (1-14) and weight schemes ('uniform', 'distance') on provided datasets. It splits data into training/validation/test sets, fits models, calculates performance metrics, and returns results as a DataFrame and evaluation repor... | def knearest_neightbors(train, validate, test, target_var, n_neighbors=list(range(1,15))):
x_train, y_train, x_validate, y_validate, X_test, Y_test = xy_train_validate_test(train,
validate,
... |
def xy_train_validate_test(train, validate, test, target_var):
id= 'customer_id'
x_train = train.drop(columns=[target_var, id])
y_train = train[target_var]
x_validate = validate.drop(columns=[target_var, id])
y_validate = validate[target_var]
X_test = test.drop(columns=[target_var, id])
... | The function trains and evaluates decision trees with varying depths (1 to `depth`) on provided datasets, returning model summaries and performance metrics. If `loop=True`, it iterates through depths, otherwise uses a single depth. It splits data, fits classifiers, and stores results in DataFrames for comparison. | def decision_tree(train, validate, test, target_var, depth=10, loop=True):
x_train, y_train, x_validate, y_validate, X_test, Y_test = xy_train_validate_test(train,
validate,
... |
def xy_train_validate_test(train, validate, test, target_var):
id= 'customer_id'
x_train = train.drop(columns=[target_var, id])
y_train = train[target_var]
x_validate = validate.drop(columns=[target_var, id])
y_validate = validate[target_var]
X_test = test.drop(columns=[target_var, id])
... | The code performs logistic regression with varying regularization strengths (C values) on training data, evaluates models on validation data, and returns a DataFrame of model results along with evaluation reports. It uses different solvers and adjusts fit_intercept based on solver type, iterating through C values to co... | def logistic_regression(train, validate, test, target_var, c=10, solver='lbfgs'):
x_train, y_train, x_validate, y_validate, X_test, Y_test = xy_train_validate_test(train,
validate,
... |
def mannshitneyu_for_quant_by_target(target_col, training_df,
quantitative_col):
predictors = {}
subsets, combos = combinations_of_subsets(target_col, training_df)
p_exceeds_alpha = []
for i, pair in enumerate(combos):
#print(f'{pair[0... | Your return
The function `print_quant_by_target` analyzes training data to identify significant predictors using the Mann-Whitney U test for quantile-based targets. It processes input data, computes statistical results, prints predictors and failure thresholds, and organizes predictors into combinations. The output i... | def print_quant_by_target(target_col, training_df, quant_col):
subsets, predictors, p_exceeds_alpha, combos = mannshitneyu_for_quant_by_target(target_col,
training_df,
... |
def decision_tree(train, validate, test, target_var, depth=10, loop=True):
x_train, y_train, x_validate, y_validate, X_test, Y_test = xy_train_validate_test(train,
validate,
... | The function `all_reports` trains and evaluates four machine learning models (decision tree, random forest, k-nearest neighbors, logistic regression) on provided datasets, compiles their performance reports, and returns encapsulated results using the `Results` class for each model type. | def all_reports(train, validate, test, target_var):
models, reports = decision_tree(train, validate, test, target_var)
dt_mods = Results(models, reports, target_var)
models, reports = random_forests(train, validate, test, target_var)
rf_mods = Results(models, reports, target_var)
models, r... |
def quantitative_hist_boxplot_describe(training_df, quantitative_col_names,separate=True):
plots, fig = create_subplots(quantitative_col_names)
for i, col in enumerate(quantitative_col_names):
plots[i].hist(training_df[col])
plots[i].set_xlabel(col)
plots[i].set_ylabel('count')
plt.s... | The code performs exploratory data analysis on a dataset, generating visualizations (histograms, boxplots, bar charts) and statistical summaries for quantitative variables, analyzing their relationship with the target variable. It identifies significant predictors, explores pairwise relationships, and reduces the datas... | def overview(train_df, categories,
quant_cols, target_var):
quantitative_hist_boxplot_describe(train_df, quant_cols,separate=True)
target_freq_hist_count(train_df, target_var)
quant_vs_target_bar(train_df, target_var, quant_cols, mean_line=True)
describe_quant_grouped_by_target(train_df, qu... |
def number_of_prime_divisors(n):
count = 0
for i in range(2, int(n + 1)):
if divides(i, n) and is_prime(i):
count += 1
return count
def is_prime(x):
if x < 2:
return False
for i in range(2, int(math.sqrt(x)) + 1):
if divides(i, x):
return False
ret... | The function checks if a given integer `n` is the product of exactly two distinct prime numbers by verifying that it has exactly two prime divisors and that dividing `n` by its smallest prime divisor results in another prime number. | def is_product_of_two_primes(n):
if number_of_prime_divisors(n) == 2 and is_prime(int(n / smallest_prime_divisor(n))):
return True
else:
return False |
def proper_divisors(k):
# Define D to be an empty list. It will represent the list of all proper divisors
# of k.
D = []
for i in range(1, k):
if divides(i, k):
D.append(i)
return D
def divides(x, y):
return y % x == 0
def corresponding_sum_total(x, k):
D = proper_divisor... | The function `admits_subsum_with_total_dividing_k` checks whether there exists a non-trivial subsum (from the Cartesian product of intervals defined by proper divisors of $ k $) whose total divides $ k $. It generates intervals for each proper divisor of $ k $, computes all possible combinations of values from these in... | def admits_subsum_with_total_dividing_k(x, k):
D = proper_divisors(k)
n = len(D)
I = [] # The entries of the list I will be the closed intervals [1, x_i] for 0<=i<=n.
for i in range(0, n):
I.append([*range(0, x[i] + 1)])
X = list(itertools.product(*I)) # A list representing the cartesian p... |
def proper_divisors(k):
# Define D to be an empty list. It will represent the list of all proper divisors
# of k.
D = []
for i in range(1, k):
if divides(i, k):
D.append(i)
return D
def divides(x, y):
return y % x == 0
def corresponding_sum_total(x, k):
D = proper_divisor... | The function checks if there exists a non-trivial subsum of integers from intervals defined by proper divisors of $ k $, such that the total sum is a divisor of $ k $. It constructs Cartesian products of intervals, filters out trivial cases, and verifies if any resulting combination meets the divisibility condition. | def admits_subsum_with_total_dividing_k(x, k):
D = proper_divisors(k)
n = len(D)
I = [] # The entries of the list I will be the closed intervals [1, x_i] for 0<=i<=n.
for i in range(0, n):
I.append([*range(0, x[i] + 1)])
X = list(itertools.product(
*I)) # A list representing the ca... |
def number_of_prime_divisors(n):
count = 0
for i in range(2, int(n + 1)):
if divides(i, n) and is_prime(i):
count += 1
return count
def is_product_of_two_primes(n):
if number_of_prime_divisors(n) == 2 and is_prime(int(n / smallest_prime_divisor(n))):
return True
else:
... | The function calculates the maximum total of weak minimally $k$-irreducible sums. For prime powers or products of two primes, it applies direct formulas; otherwise, it generates all valid sums, computes their totals, and returns the maximum. | def max_weak_k_irreducible_sum_total(k):
# In the case where k is a prime power or a product of two primes, we apply a known
# formula to obtain the maximum total.
if number_of_prime_divisors(k) == 1:
return k - 1
if is_product_of_two_primes(k):
p = smallest_prime_divisor(k)
q = ... |
def importExcel(filename, sheetname, usecols=None, header=0, nrows=None):
import pandas as pd
return pd.read_excel('resources/{}.xlsx'.format(filename), header=header, sheet_name=sheetname, usecols=usecols,
nrows=nrows)
def populating(self):
import os
file = ... | The code's main task is to initialize an object by importing and cleaning Excel data, separating population results and failures, processing the data, and filling dimensions to prepare for analysis or further operations. | def __init__(self, excel_name='data'):
self.__all = self.importExcel(excel_name, 0).dropna()
self.__popRes, self.__popFail = self.populating()
self.__generateExcelProcess()
self.fillDimension() |
def get_all_playlist_tracks(sp, username, playlist_id):
results = sp.user_playlist(username, playlist_id)
while results['tracks']['next']:
# https://github.com/plamere/spotipy/issues/246#issuecomment-359128303
# note that tmpResults has exact same format as results['tracks']
# ._get... | The function creates a new Spotify playlist by copying tracks from a source playlist, adding up to three top tracks from each artist found in the source, then adds these tracks to a new or existing destination playlist, handling API limits and optionally deleting the source after. | def cool_artists(sp, username, source_uri, dest_uri, copy_num=3, delete_after=False):
source_id = source_uri.split(':')[2]
results = get_all_playlist_tracks(sp, username, source_id)
#print(json.dumps(results, indent=4))
if dest_uri == "": # create new playlist for user
pname = results["name"] + ... |
def video_is_recording_on_device():
"""Function to detect when video is recording on the Android device, returns
true or false."""
if RECORD_DETECTION_METHOD == "directory size increasing":
return adb.directory_size_increasing(args.camera_save_dir[0],
wai... | This function synchronizes DAW transport with Android video recording by starting/stopping DAW recording when video recording begins/ends. It runs in a background loop, checking device status, and toggles DAW transport state accordingly. The process continues until a stop flag is triggered, with a sleep interval betwee... | def sync_daw_transport_bg_process(stop_flag_fun):
"""Start the DAW transport when video recording is detected on the Android
device. Meant to be run as a thread or via multiprocessing to execute at the
same time as the scrcpy monitor."""
daw_transport_rolling = False
while True:
vid_recordi... |
def raise_daw_in_window_stack():
"""Run the command to raise the DAW in the window stack."""
print_info("\nRaising DAW to top of Window stack.")
# Allow the command to fail, but issue a warning.
returncode, stdout, stderr = run_local_cmd_blocking(args.raise_daw_to_top_cmd[0],
... | This function automates Android device interaction to capture and process videos. It wakes the device, unlocks it, opens the camera, records videos starting from a specified number, then processes each video by displaying metadata, previewing, extracting audio, and post-processing. Finally, it returns the last video nu... | def startup_device_and_run(video_start_number):
"""Main script functionality."""
# Note first adb call must raise exception, not just call sys.exit.
adb.device_sleep(exit_on_error=False) # Get a consistent starting state for repeatability.
adb.device_wakeup()
adb.unlock_screen()
adb.open_video_c... |
def open_things(self, command):
# Will need to expand on "open" commands
if command == "open youtube":
self.speak("Opening YouTube.")
webbrowser.open("https://www.youtube.com")
pass
elif command == "open facebook":
self.speak("Opening Facebook.")
... | This code processes voice commands by checking the input against various conditions and triggering corresponding actions, such as opening applications, providing information, telling jokes, or terminating the program. It uses conditional logic to handle specific commands, randomizes responses for certain queries, and i... | def analyze(self, command):
print(command)
try:
if command.startswith('open'):
self.open_things(command)
elif command == "":
print("Awaiting command...")
elif command == "introduce yourself":
self.speak("I... |
def get_computer_choice(self):
return random.choice(["Rock", "Paper", "Scissors"])
def get_user_choice(self):
return self.capture_user_choice()
def get_winner(self, computer_choice, user_choice):
print(f"in get_winner: {user_choice}")
if computer_choice == user_choice:
pr... | The code simulates a game where the user and computer play rounds, tracking wins. The loop continues until either the user or computer reaches 3 wins, or all rounds are played. After each round, it updates scores and declares a winner if either reaches 3 wins; otherwise, it ends with "Game over!". | def play(self):
winning_rounds = ceil(self.n_rounds / 2)
rounds_played = 0
computer_wins = 0
user_wins = 0
while rounds_played < self.n_rounds: # and user_wins < 3 and computer_wins < 3:
computer_choice = self.get_computer_choice()
user_choice = self.get_u... |
def _set_count_histogram_attributes(self):
"""Set the count histograms as attributes accessible by their name."""
self._count_histograms = []
# Aggregate the count histograms across all files.
with contextlib2.ExitStack() as stack:
files = [stack.enter_context(root_open(filen... | The main task of the code is to initialize a context by setting histogram attributes, loading files (either by downloading or using existing filenames), adding each file to the context, applying a selection if specified, deactivating ignored branches, and returning the instance for context management. | def __enter__(self):
self._set_count_histogram_attributes()
filenames = self._download_files() if self.download else self.filenames
for filename in filenames:
self.Add(filename)
if self.selection:
self.select(self.selection)
self.deactivate(*self.ignore_br... |
def projectileIntersectsWall(app,p):
pX=p.getX()
pY=p.getY()
for key in app.walls:
if(app.walls.get(key)!=0):
centerX=key[0]
centerY=key[1]
x0=centerX-50
y0=centerY-25
x1=centerX+50
y1=centerY+25
#Closest point in wa... | This function updates projectile positions, removes those that collide with walls, turrets, tanks, or enemy tanks, or have moved out of bounds, and adjusts tracking projectiles. | def moveProjectiles(app):
for p in app.projectiles:
if(not p.move(app) or projectileIntersectsWall(app,p) or projectileIntersectsTurret(app,p) or projectileIntersectsTank(app,p) or projectileIntersectsEnemyTank(app,p)):
app.projectiles.remove(p)
if(p.tracking):
adjustProjecti... |
def __get_value(self, card, high=True):
# Return the value of a single card, with either seeing ACES as 1 or 11 (parameter high)
values_of_cards = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10, "JACK": 10,
"QUEEN": 10, "KING": 10, "ACE": 11 if high ... | The code processes user actions in a card game, applying "STAND," "HIT," "DOUBLEDOWN," or "SPLIT" to each hand, updating card states and terminating hands based on rules (e.g., exceeding 21). It verifies action validity, manages game termination, and triggers the dealer's turn if all player hands are finished, where th... | def do_action(self, actions):
# Applies users action to the game
# Check that for each hand an action is provided
if len(actions) != len(self.ownCards):
raise Exception("You have to submit an action for each hand you play")
# Go through each hand and apply the action
... |
def extract_words(self, result_list, query_terms):
"""
parses the results to convert all words to lowercase and eliminate any stop words in the results.
Returns a dictionary of the same format as results (dict with "title" and "summary" keys).
"""
documents = []
vocab = s... | The main task of the code is to enhance a search query by incorporating feedback and result analysis. It extracts query terms, builds an inverse list from document vocabulary, identifies candidate words, ranks them using Gini coefficients with frequency and dependency weights, and generates a new query with optimized t... | def augment_query(self, current_query, current_results, current_feedback):
'''
augments a query based on feedback and the results.
'''
# terms in the query
query_terms = [w.lower().strip() for w in re.findall(self.pattern, current_query)]
# filtered words and the vocab i... |
def init_the_map(map_size): # create a new map with the size that you set up
map = [[0 for j in range(map_size)] for i in range(map_size)]
return map
def create_path(minimum_len_of_path, map, position_to_start_the_path_from, path_row,map_size,max_path_length):
chance_to_continue_path = 0.5 # probability f... | The code generates a map grid with randomized paths of varying lengths. It initializes a map, iterates over its size to create alternating path rows, and uses functions to draw paths while toggling directions. The map_size determines grid dimensions, and path lengths are constrained by min_path_length and max_path_leng... | def create_map():
min_path_length = 3
position = Position(0,0)
path_row = True
map_size = int(input("Enter the number of map_size: "))
max_path_length = map_size/2
map = init_the_map(map_size)
random_path_row = path_row
for x in range(int(map_size)):
map,position = create_path(mi... |
def check_privileges() -> None:
if not os.environ.get("SUDO_UID") and os.geteuid() != 0:
warn("You need to run this script with sudo or as root.")
sys.exit(1)
def setup() -> None:
info("Setup all docker images and repos for the experiments...")
# clone repository for flame graphs
remove... | The main task of the code is to execute a series of steps for experimental setup and visualization: check user privileges, initialize the environment, install required packages, generate graphs for specified experiments ('basic', 'select', 'poll', 'epoll'), and collect the resulting plots for analysis or output. | def main() -> None:
check_privileges()
experiments = ['basic', 'select', 'poll', 'epoll']
setup()
install_required_packages()
generate_graphs(experiments=experiments)
collect_generated_plots(experiments=experiments) |
def find_arduino(port=''):
"""Locates Arduino and returns port and device."""
comports = [tuple for tuple in list_ports.comports() if port in tuple[0]]
for port, desc, hwid in comports:
for identifier, arduino in arduinos:
if hwid.startswith(identifier):
return port, ardu... | This code initializes a serial connection to an Arduino device by searching for it on a specified port, attempting connections at two baud rates (115200 then 9600), handling errors, retrieving device version info, and setting up parameters like labtime, PID values (_P, Q), and sensor sources. It ensures proper connecti... | def __init__(self, port='', debug=False):
self.sp = None
self.baud = None
global _connected
self.debug = debug
print('Limonata version 0.0.0')
self.port, self.arduino = find_arduino(port)
if self.port is None:
raise RuntimeError('No Arduino device foun... |
def Darknet(name=None):
x = inputs = Input([None, None, 3])
x = DarknetConv(x, 32, 3)
x = DarknetBlock(x, 64, 1)
x = DarknetBlock(x, 128, 2)
x = x_36 = DarknetBlock(x, 256, 8)
x = x_61 = DarknetBlock(x, 512, 8)
x = DarknetBlock(x, 1024, 4)
return tf.keras.Model(inputs, (x_36, x_61, x), n... | The code defines a YOLOv3 model that processes input images through a Darknet backbone, generates multi-scale feature maps (x_36, x_61, x), applies convolutional layers (YoloConv) with varying filters (512→256→128), and outputs bounding box predictions (YoloOutput) for three scales. It then transforms these outputs int... | def YoloV3(size, channels, anchors,
masks, classes):
x = inputs = Input([size, size, channels], name='input')
x_36, x_61, x = Darknet(name='yolo_darknet')(x)
x = YoloConv(512, name='yolo_conv_0')(x)
output_0 = YoloOutput(512, len(masks[0]), classes, name='yolo_output_0')(x)
x = YoloConv... |
def create_cells():
'''Creates all 81 cells with RectCell class.'''
cells = [[] for _ in range(9)]
# Set attributes for for first RectCell
row = 0
col = 0
left = buffer + major_grid_size
top = buffer + major_grid_size
while row < 9:
while col < 9:
cells[row].append(... | The code implements a playable Sudoku game using Pygame, allowing users to input numbers, reset the board, and visually solve the puzzle. It handles mouse clicks for cell selection, keyboard input for number entry, and displays a "Solved!" message upon completion. The game features a reset button to restart and a visua... | def play():
'''Contains all the functionality for playing a game of Sudoku.'''
easy = [
[0, 0, 0, 9, 0, 0, 0, 3, 0],
[3, 0, 6, 0, 2, 0, 0, 4, 0],
[2, 0, 4, 0, 0, 3, 1, 0, 6],
[0, 7, 0, 0, 5, 1, 0, 8, 0],
[0, 3, 1, 0, 6, 0, 0, 5, 7],
[5, 0, 9, 0, 0, 0, 6, 0, 0],
... |
def get_contract_by_id(id):
query = textwrap.dedent("""{0}
SELECT *
WHERE {{
?Contract a :contractID;
:hasContractStatus ?ContractStatus;
:forPurpose ?Purpose;
:contractTyp... | The main task of the code is to update an existing contract in a triple store by replacing its data if it is not yet signed. It retrieves the contract by ID, checks its status, deletes the old entry if unsigned, and inserts new contract details using SPARQL. The update is conditional on the contract not being signed, r... | def contract_update(id):
request_data = request.get_json()
ContractId = id
# check if contract already exist with this id
result = get_contract_by_id(ContractId)
my_json = result[0].data.decode("utf-8")
decoded_data = json.loads(my_json)
if decoded_data["success"]["bindings"]:
contra... |
def check_every_time():
if personal_chat() == "pm" or snap_homepage() == "yes":
return False
else:
return True
def long_press():
pyautogui.moveTo(675, 400)
pyautogui.mouseDown()
time.sleep(0.4)
pyautogui.mouseUp()
time.sleep(1)
def save_chat():
try:
save_in_chat_b... | This code automates processing snaps by repeatedly checking, long-pressing, attempting to save chats, and tracking success/failure counts. It increments 'total' and 'saved' on successful saves, or 'total' and 'not_saved' on failures with a 9-second delay. The loop continues as long as 'check_every_time()' returns true,... | def peoplewise_snaps():
while check_every_time():
long_press()
global total, saved, not_saved
if save_chat()=="success":
total = total+1
saved = saved + 1
next_snap()
else:
back_to_received_snap()
time.sleep(9)
t... |
def person_name():
pytesseract.pytesseract.tesseract_cmd = path_of_tesseract
cap = pyautogui.screenshot(region=(personname))
tesstr = pytesseract.image_to_string(cap,lang ='eng+nep')
scan = tesstr
chars =r'[\n]'
chat_name = (re.sub(chars, '', scan))
formatted_chat =('\033[1m' + '%20s' % chat... | This function checks for new snaps or chats using image recognition. If new snaps are detected, it logs and returns "new_snaps". For new chats, it triggers a 30-second interaction, clears chats via mouse actions, and recurses. If intra-chats are found, it calls is_inside_chats. Otherwise, it checks conditions to either... | def new_snap_check():
time.sleep(1)
if pyautogui.locateOnScreen('new_snap.png', region=(new_snap_chat),confidence=0.9,grayscale=True):
print("There are new snaps from : " + person_name())
logger.info("There are new snaps from : " + person_name())
return "new_snaps"
elif pyautogui.loc... |
def main_bool():
a = bool(check_chat_button() == "moved_to_chatpage" or check_chat_button() == "already_in_chatpage")
return a
def new_snap_check():
time.sleep(1)
if pyautogui.locateOnScreen('new_snap.png', region=(new_snap_chat),confidence=0.9,grayscale=True):
print("There are new snaps from : ... | The main task of the code is to repeatedly process snaps by checking for new snaps, clicking the first snap, and handling snaps for each person until a condition (`main_bool()`) is met. It logs and prints a completion message for each person's snaps, iterating continuously until the loop terminates. | def main():
while main_bool():
new_snap_check()
click_first_snap()
peoplewise_snaps()
print("Watching all loaded snaps from {} completed.".format(person_name()))
logger.info("Watching all loaded snaps from {} completed.".format(person_name()))
print("\n") |
def Z_from_z(self, z):
Z = self.find_Z_from_z(z).x
if Z[1] < 0:
Z[1] = -Z[1]
return array_to_complex(Z)
def M_from_Z(self, Z):
return (self.eigvals / (Z - self.eigvals)).sum() / self.N
def dMdZ_from_Z(self, Z):
return -(self.eigvals / (Z - self.eigvals)**2).sum() / se... | The code computes a quantity $ Q $ and its derivative $ \frac{dQ}{d\Lambda} $, likely modeling a physical or statistical system. It processes complex-valued parameters ($ z, Z, MZ $), computes derivatives via chain rules, constructs probability density functions (pdf), cumulative distribution functions (CDF), and inter... | def Q(self):
dk = np.diff(self.k)
z = np.array([complex(_k, 1e-10) for _k in self.k])
Z = np.array([self.Z_from_z(_z) for _z in z])
MZ = np.array([self.M_from_Z(_Z) for _Z in Z])
N = np.sqrt(1.0 + self.r**2 * MZ**2 * (self.gamma**2 - 1.0))
dMdZ = np.array([self.dMdZ_... |
def valid_moves(id: int, gstate: List[int], school_layout):
moves = []
for key in school_layout[id][1].keys():
if key in gstate:
continue
else:
if key == id:
continue
else:
moves.append(key)
return moves
def findSpot(tree_no... | This code implements a Monte Carlo Tree Search (MCTS) algorithm to find the shortest path from a start point to an end point in a school layout. It builds a tree of possible moves, simulates random paths (rollouts), and backpropagates results to update node values. The algorithm iteratively explores paths, prioritizing... | def MCTS(school_layout: Dict[int, Tuple[AnyStr, Dict[int, int]]], start, end):
start_state = [start]
start_moves = list(school_layout[start][1].keys())
root = TreeNode(start, start, end, gstate=start_state, valid_move_list=start_moves, school_layout=school_layout,
parent_node=None, last... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.