dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def filtered_average(color, data, dev=False):
"""
Uses the average function above to intelligently guess the actual average from
reliable data. Basically, ignores points that were missed or are obviously wrong
"""
#First, need to find the origin
avs, dvs = get_stats(color, data)
#So next, r... | The main task of the code is to process input data by inverting the y-axis, calculating a reference origin, converting detected inner points (pink, dark green, yellow) to polar coordinates, and handling missing points. If align is True, it fixes false detections before processing. It then computes polar coordinates for... | def main(align=False):
"""
QUESTIONS:
What was align and why is fix glitches where it is
Organizes all of the functions above in order. Here's how it works:
- First, we make sure there are files specified.
- Next, uninvert the y axis because screens are terrible and y is always
upside down.... |
def get_stress(src, tar):
return np.abs(src-tar)
def get_required_neighbors(rng, src, tar, stress):
# get indexes of fixed cells
loc_x, loc_y = np.where(stress == 0)
fixed_idxs = list(zip(loc_x, loc_y))
rng.shuffle(fixed_idxs)
# for each fixed idx, get neighbor list
neighbor_needs = {}
... | This function applies a competency-based movement process to adjust 'src' toward 'tar' by iteratively calculating stress, determining neighbor requirements, and moving cells while managing plasticity constraints. It repeats until movement count reaches 'comp_value' or no active cells remain, returning total movement an... | def apply_competency_single_idv(src, tar, comp_value, plasticity_flag, rng):
overall_mvs = 0
overall_dist = 0
stressed_dict_copy = [-9999] #initialize with a single element so that the while loop runs atleast once
while ((overall_mvs < comp_value) and (len(stressed_dict_copy))):
stress = get_st... |
def der_E(label, y2):
"""derivative of E over y2"""
return y2 - label
def der_f2_W2(f1, y2, W2):
"""derivative of f2 over W2"""
len_y2 = len(y2)
row_W2, col_W2 = np.shape(W2)
f2_W2 = []
for l in range(len_y2):
der_mat = np.zeros_like(W2, float)
for i in range(row_W2):
... | The code performs backpropagation to update weights (W1, W2) and biases (b1, b2) of a neural network using gradient descent. It computes gradients for each sample, applies learning rate updates, collects updated parameters in lists, and returns the average of these updated parameters across the batch. | def backprop(X_in, Label, y1, f1, y2, f2, W2, b2, W1, b1, lr=10e-2):
"""back propagation"""
# update W2 & b2
W2_lst = []
b2_lst = []
W1_lst = []
b1_lst = []
num_sample = len(X_in)
for i in range(num_sample):
label_i = np.array(Label[i])
X_i = np.array(X_in[i, :])
... |
def convert(self, board):
"""for each square, list all possible nums"""
state = copy.deepcopy(board)
for i in range(N):
for j in range(N):
cell = state[i][j]
if cell == 0:
state[i][j] = set(range(1,10)) # make all zeros a set of pos... | The code's main task is to solve a board puzzle by converting the board into a solvable state, displaying the original board, applying the solve_board method to find the solution, and then printing and displaying the solved state. It involves visualizing the initial and solved configurations, likely for puzzles like Su... | def solve(self):
state = self.convert(self.board)
self.display_board(self.board) # display board before solve
state = self.solve_board(state) # solve board
self.print_board(state)
self.display_board(state) |
def CMOV(x, y, b):
"""
Returns x if b=False; otherwise returns y
"""
return int(not bool(b))*x + int(bool(b))*y
def square_root(x):
"""
Returns a square root defined through fixed formulas.
(non-constant-time)
"""
F = x.parent()
p = F.order()
if p % 16 == 1:
return t... | The main task of the code is to compute a point (x, y) on an elliptic curve using coordinate transformations, conditional moves (CMOV), and square root operations. It processes input `u` through field operations, evaluates polynomial expressions, checks for square roots, and adjusts signs to return valid curve coordina... | def straight_line(self, u):
inv0 = self.inv0
is_square = self.is_square
u = self.F(u)
A = self.A
B = self.B
Z = self.Z
c1 = self.c1
c2 = self.c2
tv1 = Z * u**2
tv2 = tv1**2
x1 = tv1 + tv2
x1 = inv0(x1)
e1 = x1 == 0
... |
def _get_Z_val(F):
global _s_vals
if F in _s_vals:
return _s_vals[F]
pe = find_Z(F)
_s_vals[F] = pe
return pe
def _get_consts(F, Z):
global _consts
if (F, Z) in _consts:
return _consts[(F, Z)]
q = F.order()
(l, o) = _get_lo(q)
# c1, the largest integer such that 2... | This function computes the square root of the ratio u/v in a structured algebraic context using predefined constants and conditional operations. It applies transformations via function F, calculates intermediate values through exponentiation and multiplication, iterates to refine results, and validates correctness agai... | def sqrt_ratio_straightline(F, u, v, Z=None):
u = F(u)
v = F(v)
if Z is None:
Z = _get_Z_val(F)
(c1, c3, c4, c5, c6, c7) = _get_consts(F, Z)
tv1 = c6
tv2 = v ** c4
tv3 = tv2 ** 2
tv3 = tv3 * v
tv5 = u * tv3
tv5 = tv5 ** c3
tv5 = tv5 * tv2
tv2 = tv5 * v
tv3 = ... |
def _LNode(item, levelRef, SubEquipment,scl):
#list of items that should be measured during simulation
measurantsV = {}
measurantsA = {}
#list of items that can be switched during simulation
actuators = {}
lItem = None
if 'LNode' in item:
lItem = item
elif SubEquipment is not None and 'LNode' in Su... | The function parses a substation's structure from an SCL file, extracting measurement points (voltage/current), actuators, and generating a netlist for simulation. It processes Substation, VoltageLevel, Bay, and ConnectivityNode elements, building dictionaries for measurable parameters, controllable devices, and simula... | def _parse_substation(scl):
#list of items that should be measured during simulation
measurantsV = {}
measurantsA = {}
#list of items that can be switched during simulation
actuators = {}
# netlist of substation
netlist = ""
#parameters that can be altered during simulation
simulation_nodes = {} #
... |
def _set_headers(self, contenttype='application/json'):
"""
Set default headers
"""
self.send_response(200)
self.send_header('Content-type', contenttype)
try:
self.send_header('X-Instance', '{}'.format(socket.gethostname()))
except:
pass
... | This code handles GET requests by serving a simple health check response for the root path ('/'), validating the content type for other API requests, and serving the requested path if the content type is correct. It returns a 415 error for invalid content types, ensuring only JSON is accepted for non-root endpoints. | def do_GET(self):
"""
Process GET request
"""
# Default web path to handle ELB health checks
if self.path == '/':
self._set_headers(contenttype='text/html')
self.wfile.write('There is nothing here'.encode('utf-8'))
# Any other requests are consider... |
def new_order(ahead=(), appQ=9):
"""
====== inner func ======
create new order with `ahead' ahead
ahead: index of app want to ahead in each axes
so that can be easily obsevered in the Karnaugh Map
start from 0, used directly as index
at most two items
empt... | The function `do_plot` generates and saves Karnaugh Map (EKMap) visualizations from input data (`data2`), supporting both single and multiple datasets. It reorders appliance indices based on the `ahead` parameter for clarity, applies color maps, and handles figure saving with specified types. The function calls auxilia... | def do_plot(data2, ahead=(), cmap='inferno', fig_types=(), do_show=True,
titles="", pats=[]):
"""
do plot, save EKMap figs
data2: a dict of EKMap
or a list of dict of EKMap
appQ: integer, the number of appliance
reorder: put at least two app ahead in each axes
... |
def create_git_diff_staged(driver_path):
output_file = "staged.diff"
file_path = os.path.join(os.getcwd(), output_file)
cd_cmd = "cd " + driver_path
git_cmd = "&& git diff --staged -U100 > " + file_path
cmd = cd_cmd + git_cmd
os.system(cmd)
return output_file
def look_for_new_file_in_diff(di... | The code checks if newly staged files in a Git repository (identified by their path) match the expected source path of a graphics driver. It generates a staged diff, identifies new files, verifies their paths against the provided source directory, and logs success or failure. The result is returned as a boolean indicat... | def check_diff_staged(gfx_driver_source_path, commit_before="HEAD~1", commit_after="HEAD"):
current_path = os.getcwd()
file = create_git_diff_staged(gfx_driver_source_path)
new_added_file = look_for_new_file_in_diff(file)
DiffCheck = search_path(new_added_file, gfx_driver_source_path)
if DiffCheck:
... |
def create_git_diff(commit_sha_1, commit_sha_2, driver_path):
output_file = commit_sha_2[:4] + ".diff"
file_path = os.path.join(os.getcwd(), output_file)
cd_cmd = "cd " + driver_path
git_cmd = "&& git diff " + commit_sha_1 + " " +commit_sha_2 + " -U100 > " + file_path
cmd = cd_cmd + git_cmd
os.s... | The main task of the code is to check if any new files introduced between two Git commits (commit_before and commit_after) exist in the specified graphics driver source path. It generates a Git diff, identifies new files, searches for them in the source directory, and returns a boolean indicating success or failure, lo... | def check_diff(gfx_driver_source_path, commit_before="HEAD~1", commit_after="HEAD"):
current_path = os.getcwd()
file = create_git_diff(commit_before, commit_after, gfx_driver_source_path)
new_added_file = look_for_new_file_in_diff(file)
DiffCheck = search_path(new_added_file, gfx_driver_source_path)
... |
def add_found_by_dcc_column(db_file):
table_name = get_table_name(db_file)
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# Check if the column exists
cursor.execute(f"PRAGMA table_info({table_name})")
columns = cursor.fetchall()
found_by_dcc_exists = any(column[1] == 'found_by_dcc'... | The main task of the code is to process log data from a file and append it to a SQLite database. It reads command-line arguments for the database and log files, adds a "found_by_dcc" column to the database if it doesn't exist, parses the log content, inserts the parsed data into the database, and confirms successful in... | def main():
if len(sys.argv) != 3:
print("Usage: ./appendDccData.py <database_file.db> <log_file.log>")
sys.exit(1)
db_file = sys.argv[1]
log_file = sys.argv[2]
with open(log_file, 'r') as file:
log_content = file.read()
add_found_by_dcc_column(db_file) # Add the new colu... |
def load_base_strings(self):
with open(self.configFile, 'r') as config_file:
config_data = json.load(config_file)
base_strings = config_data.get('base_strings', [])
#self.logger.info("Grabbed Base Strings from config data" + str(base_strings))
expanded... | The main task of the code is to execute a run process that logs timestamps, loads test data and substitution rules, generates combinations using `generate_2_deep`, counts found sites, and appends structured results to an output file. It tracks execution duration, records findings, and maintains a log with start/end mar... | def run(self):
ct = datetime.now()
ct = str(ct)
with open(self.outputFile, "a") as file1: # append mode
file1.write("\n############# START OF RUN #############\n")
file1.write("TimeStamp: " + ct + "\n")
self.tests = self.load_base_strings()
self.substitut... |
def create_objects(self):
self.layout = QVBoxLayout()
self.my_widget = QWidget(self)
self.name_label = QLabel(self.my_widget)
self.start_label = QLabel(self.my_widget)
self.last_label = QLabel(self.my_widget)
self.status_label = QLabel(self.my_widget)
def update_objects(self):
self.name_label.setText(self... | This code initializes a GUI window by setting up a central widget with a layout containing labels for name, start, and last. It assigns a model and application instance, fixes the window size, sets the title, and updates UI elements. The main task is to configure a graphical interface with specific components and initi... | def __init__(self, model, app):
super().__init__()
self.my_model = model
self.my_app = app
self.create_objects()
self.setWindowTitle(DefaultName)
self.setFixedSize(self.DefaultSize, self.DefaultSize)
self.setCentralWidget(self.my_widget)
self.my_widget.setLayout(self.layout)
self.layout.addWidget(... |
def traverse (node, step):
while fully_expansion(node.parent if node.parent else node):
node = best_uct(node)
if len(node.children) == 0:
break
done, result = check_for_done(node.state)
if done:
return node
if node.parent is not None:
if find_unvisited(node.pa... | The code implements Monte Carlo Tree Search (MCTS) to explore a tree structure within a time limit. It repeatedly selects unvisited nodes (leaf), simulates outcomes (rollout), updates node values (backpropagation), and tracks simulations. After the time limit, it returns the best child node based on accumulated results... | def monte_carlo_tree_search(root, end_seconds, step):
time_start = time.time()
simulation_times = 0
while True:
if time.time() - time_start > end_seconds:
break
leaf = traverse(root, step) # leaf = unvisited node
simulation_result = rollout(leaf, step)
backpropag... |
def updateAllFunctions(tu, src, funcs={}):
def handleFunction(a):
if not a.location.file: return;
if a.location.file.name != src:return;
if a.kind == CursorKind.FUNCTION_DECL \
or a.kind == CursorKind.CXX_METHOD:
res_type = a.result_type.get_canonical().spelling;... | This script converts C/C++ modules to TypeScript modules by parsing source files with Clang, extracting symbols/functions/structs, optionally analyzing binary files (PE/ELF) with LIEF, merging JSON symbol data, resolving naming conflicts, and generating TypeScript output via Jinja2 templates. It supports custom flags, ... | def main():
parser = argparse.ArgumentParser(description="A utility for convert a module to a typescript module ")
parser.add_argument('-b', "--binary", type=str)
parser.add_argument('-I', "--info", type=str)
parser.add_argument('-o', '--output', default='/tmp/tt.ts')
parser.add_argument('-n', '--na... |
def E(self, t):
return np.sum(np.asarray([[self.dE(t, i, j) for i in range(self.nrows)] for j in range(self.ncols)])) / self.size
def E_sqr(self, t):
return np.sum(np.asarray([[self.dE(t, i, j) ** 2 for i in range(self.nrows)] for j in range(self.ncols)])) / self.size
def M(self, t):
return np.s... | The main task of the code is to gather physical quantities (energy, magnetization, specific heat, etc.) over a specified number of frames by iterating through each frame, calculating their values using instance methods, and storing them in corresponding attributes. The `verbose` parameter controls progress bar visibili... | def gather_data(self, verbose=True):
for _ in trange(self.frames, desc='Gathering Data', leave=False) if verbose else range(self.frames):
self.energy[_] = self.E(_)
self.energy_sqr[_] = self.E_sqr(_)
self.magnetization[_] = self.M(_)
self.magnetization_sqr[_] = se... |
def reset(self):
self.at[0, :, :] = 2 * self.rng.integers(low=0, high=2, size=(self.nrows, self.ncols)) - 1
return None
def quench(self, beta=None, h=None, method=None, verbose=True):
if beta is None:
beta = self.beta
else:
self.beta = beta
self.T = 1 ... | This code performs Monte Carlo simulations of a spin system (e.g., Ising model) using the Wolff algorithm. It varies external magnetic field (h) and inverse temperature (β) across specified ranges, running multiple samples per parameter pair. For each configuration, it calculates thermodynamic observables (energy, magn... | def simulate(self, beta_range, h_range, sample_size=30, method='wolff'):
self.sample_size = sample_size
energy_sample, specific_heat_capacity_sample = np.zeros(sample_size), np.zeros(sample_size)
magnetization_sample, magnetic_susceptibility_sample = np.zeros(sample_size), np.zeros(sample_size)... |
def kvprint(self, *args, log='d'):
message = ' '.join(str(arg) for arg in args)
# message = self.cli + message
message = f'[{datetime.datetime.now().strftime("%H:%M:%S")}] {self.cli} {message}'
if log == 'd':
self.kvs.log.debug(message)
elif log == 'i':
... | The function updates replicas by comparing existing ones with new data, closing outdated connections, and establishing new ones. It ensures the node knows its replica relationships, raising an error if it fails to become a replica. | def update_replicas(self):
if self.kvs.ring_mine_replicas:
self.kvprint(f'Updating replicas .... We have already replicas')
self.kvs.i_am_replica_of = {}
# big todo, if it is connected but type is different
for value in self.kvs.ring_replicas:
if... |
def key_check_coordinators(self, hash):
int_hash = int(hash, 16)
if len(self.kvs.ring_metadata) == 1:
return True
elif len(self.kvs.ring_metadata) > 1:
list_hash = list(self.kvs.ring_metadata).copy()
sorted_hash_list = sorted(list_hash, key=lambda x: int(x, 16... | This method processes incoming messages based on shutdown status, handling commands like 'put', 'delete', 'get', etc. It checks server responsibility for keys, manages write locks, and routes requests to appropriate handlers. During shutdown, it restricts operations and returns 'server_stopped' for unauthorized command... | def handle_RECV(self, msg, shutdown):
method, *args = msg.split()
if shutdown is False:
if method in ['put', 'delete'] and self.kvs.write_lock is False:
key = args[0]
if self.key_check_coordinators(self.hash(key)) is False:
self.handle_RESP... |
def ecsprint(self, *args, log='d'):
message = ' '.join(str(arg) for arg in args)
# message = self.cli + message
message = f'[{datetime.datetime.now().strftime("%H:%M:%S")}] {self.cli} {message}'
if log == 'd':
self.log.debug(message)
elif log == 'e':
self.... | This code handles incoming requests from Key-Value Servers (KVS), managing server data storage, heartbeat tracking, ring metadata synchronization, and shutdown processes. It updates server information in a hash ring, broadcasts status changes, and coordinates node additions/removals while maintaining active server stat... | def handle_REQUEST(self, sock, request, parsedata):
if request != 'heartbeat':
self.ecsprint(f'\tReceived message from KVS{self.kv_id(sock)}: {request}')
# REQUESTS
if request == 'kvserver_data': # New kvserver sending personal data
self.broadcast('write_lock_act', f'-> ... |
def kv_id(self, sock):
try:
for key, values in self.kvs_data.items():
if values['sock'] == sock:
return key
except:
self.ecsprint(f'Error kv_id {sock.getpeername()}')
return sock.getpeername()
def ecsprint(self, *args, log='d'):
... | This function closes a KV server socket by removing it from the connected list, updating the hash ring if it was a coordinator, broadcasting metadata changes, and closing the socket. It handles errors for missing sockets and non-coordinator nodes, ensuring proper cleanup and ring consistency. | def closing_kvserver(self, sock): # Closing without backup process
id = self.kv_id(sock)
# self.ecsprint(f'Removing KVS{id}... ')
try:
del self.kvs_connected[sock]
except:
self.ecsprint(f'Error. Check, deleted socket not in connected socket')
if self.kvs... |
def connect_to_ECS(self):
self.ecs_connected = False
RETRY_INTERVAL = 0.5
connect_to_ECS_try = 0
self.kvprint(f'Connecting to ECS {self.ecs_addr}:{self.ecs_port}....')
while True:
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
... | This code handles communication with an ECS (Elastic Compute Service) by maintaining a socket connection, receiving and parsing JSON messages, managing message fragmentation, and triggering reconnections when necessary. It processes incoming data, splits it into complete messages, handles errors, and invokes a handler ... | def handle_CONN(self):
self.connect_to_ECS()
incomplete_msg = None
while self.ecs_connected:
try:
data = self.sock.recv(128 * 1024).decode() # todo max size 128 * 1024
if data:
if data.endswith('\r\n'): # If it ends, it is a comple... |
def init_log(self, log_level, log_file, directory):
if directory == '.':
directory = os.getcwd() # Use current path
os.makedirs(directory, exist_ok=True)
log_dir = os.path.join(directory, log_file)
if log_level == 'INFO':
logging.basicConfig(filename=log_dir,
... | This code initializes a distributed key-value server, configuring parameters like address, port, cache settings, and network timeouts. It sets up ring metadata for data replication, starts logging and storage systems, and launches an ECS handler thread for coordination. The server prepares to handle client connections ... | def __init__(self, addr, port, ecs_addr, id, cache_strategy, cache_size, log_level, log_file, directory, max_conn):
# Server parameters
# self.id = id
self.id = addr[-1]
# self.id = str(port)[-1]
self.name = f'KV{self.id}'
# Time parameters
self.kvs_timeout = 15
... |
def kvprint(self, *args, log='d'):
message = ' '.join(str(arg) for arg in args)
# message = '\t' + self.cli + message
message = f'[{datetime.datetime.now().strftime("%H:%M:%S")}] {self.cli} {message}'
if log == 'd':
self.kvs.log.debug(message)
elif log == 'i':
... | This function handles client connections by receiving and processing incoming data. It decodes messages, checks server status, and routes requests to handle_RECV if active. It manages timeouts, errors, and shutdowns, logging events and closing the socket appropriately. If the server is stopped, it sends a response. Fin... | def handle_CONN(self, shutdown=False):
while Client_handler.conn_status:
try:
data = self.client_fd.recv(128 * 1024)
if data:
request = data.replace(b'\\r\\n', b'\r\n')
messages = request.decode().split('\r\n')
... |
def handle_REQUEST(self, sock, request, parsedata):
if request != 'heartbeat':
self.ecsprint(f'\tReceived message from KVS{self.kv_id(sock)}: {request}')
# REQUESTS
if request == 'kvserver_data': # New kvserver sending personal data
self.broadcast('write_lock_act', f'-> ... | The code processes incoming data by splitting it into messages, parsing JSON requests, and handling them via the `handle_REQUEST` method, while logging errors during JSON parsing. | def handle_RECV(self, data, sock):
messages = data.replace('\\r\\n', '\r\n').split('\r\n')
for msg in messages:
if msg is None or msg == " " or not msg:
break
else:
try:
parsedata = json.loads(msg)
request = ... |
def ecsprint(self, *args, log='d'):
message = ' '.join(str(arg) for arg in args)
# message = self.cli + message
message = f'[{datetime.datetime.now().strftime("%H:%M:%S")}] {self.cli} {message}'
if log == 'd':
self.log.debug(message)
elif log == 'e':
self.... | This function sets up a server socket to listen for connections from KVS servers, manages incoming data via select(), accepts new connections, handles data reception, and manages shutdown processes. It maintains active connections, processes shutdown queues, and terminates the server if no active KVS servers are detect... | def listen_to_kvservers(self):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.settimeout(self.sock_timeout)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((self.host, self.port))
server_socket.listen()
... |
def upload_file(content, vm, credentials, destination, source):
try:
file_attribute = vim.vm.guest.FileManager.FileAttributes()
dest_path = get_directory_path(destination)
try_create_folder(content, vm, credentials, dest_path)
with open(source, 'rb') as file:
file = file.... | This code implements an Ansible module for transferring files/folders between a local system and a VMware guest VM via pyvmomi. It supports 'upload' and 'download' operations, validating parameters, checking VM existence/tools status, and handling file/directory transfers with error handling for path validity and opera... | def main():
argument_spec = get_connection_argument_spec()
operation_choices = ['upload', 'download']
argument_spec.update(
dict(
vm=dict(required=True),
source=dict(required=True),
destination=dict(required=True),
guest_username=dict(required=True),
... |
def create_instance_to_be_duplicated_on_post(self):
return self.create_instance()
def get_serializer_class(self):
return getattr(self, "serializer_class")
def get_full_data(self):
return getattr(self, "full_data") | This test checks if a serializer correctly raises a ValidationError when attempting to save data with duplicated unique fields. It creates a duplicate instance, validates the data, and expects an error on save. If the model lacks unique fields, the test is skipped. | def test_is_invalid_with_duplicated_unique_data(
self,
):
if getattr(self, "unique_fields"):
self.create_instance_to_be_duplicated_on_post()
serializer = self.get_serializer_class()(
data=self.get_full_data(), many=False
)
serializer.i... |
def legalMoves(board):
# return all available moves
topRow = board[0:7]
legMovArr= []
for cell in range(0,7):
if topRow[cell] == 'e':
legMovArr.append(cell)
return legMovArr
def makeMove(turn,col, tempBoard):
bottom = (7 * 5 ) + col
for i in range(0,6):
... | The function processes a game move request by validating the user's move, updating the game state, checking for immediate win/draw, calculating the AI's response using playouts, and returning the result with the updated board state and move details. | def move():
#AI is always black
req = request.get_json()
# find playouts based on difficulty
max = 80
if req['difficulty'] == "auto":
playouts = example.calculate_difficulty(max)
else:
playouts = max
actualBoard = req['board']
for i in range(0,len(actualBoard)... |
def _login_ftp(self):
# set up secure connection
self.ftp_account_lock.acquire()
if self.use_plain:
ftps = FTP(self.addr, self.username, self.password)
else:
ftps = FTP_TLS(self.addr, self.username, self.password)
ftps.prot_p()
# verify that ... | The code initializes a secure tunnel by connecting to an FTP server, searching for valid proxies, negotiating session keys via handshake files, and establishing communication through a selected proxy. It handles threading synchronization, heartbeat validation, and cleanup of temporary files, ultimately setting up a tun... | def __init__(self, server_addr, username, password, use_plain, tunnel_dir):
"""Set up tunnel when this class is instantiated"""
# basic set up
print("Client started")
sys.stdout.flush()
super().__init__()
self.alive = True
self.alive_lock = threading.Lock()
... |
def choose_features(examples, features):
optimal_feature = 0
optimal_split = -10000000
max_info_gain = -1
for index in features:
tmp_split, tmp_info_gain = choose_split(examples, index)
if tmp_info_gain > max_info_gain:
max_info_gain = tmp_info_gain
optimal_featu... | This function recursively constructs a decision tree by partitioning examples based on optimal features and splits. It checks if all examples in a node share the same class label; if so, it creates a terminal node. Otherwise, it selects the best feature/split, splits the data, and creates a decision node with the featu... | def generate_tree(examples, parent_node, symbol):
family_type = set()
for item in examples:
family_type.add(item[-1])
if len(family_type) == 1:
return AnyNode(name=str(family_type.pop()), parent=parent_node, symbol=symbol)
else:
optimal_feature, optimal_split = choose_features(ex... |
def choose_features(examples, features):
optimal_feature = 0
optimal_split = -10000000
max_info_gain = -1
for index in features:
tmp_split, tmp_info_gain = choose_split(examples, index)
if tmp_info_gain > max_info_gain:
max_info_gain = tmp_info_gain
optimal_featu... | This function constructs a decision tree with early stopping. It checks if all examples in a node share the same class label, creating a leaf node if true. Otherwise, it selects the optimal feature to split data, halting further splits if information gain falls below a threshold. If splitting continues, it creates inte... | def stop_early_tree(examples, parent_node, limit, symbol):
family_type_set = set()
family_type = list()
for item in examples:
family_type_set.add(item[-1])
family_type.append(item[-1])
if len(family_type_set) == 1:
curNode = Node(str(family_type_set.pop()),
... |
def choose_features(examples, features):
optimal_feature = 0
optimal_split = -10000000
max_info_gain = -1
for index in features:
tmp_split, tmp_info_gain = choose_split(examples, index)
if tmp_info_gain > max_info_gain:
max_info_gain = tmp_info_gain
optimal_featu... | The code recursively constructs a decision tree by splitting examples based on optimal features. If all examples share the same class, it creates a leaf node. Otherwise, it selects the best feature and split value, generates a tree node, and recursively processes the split subsets with '-' and '+' symbols to form child... | def generate_tree(examples, parent_node, symbol):
family_type = set()
for item in examples:
family_type.add(item[-1])
if len(family_type) == 1:
cur_node = myNode(name=str(family_type.pop()), parent=parent_node, symbol=symbol, children=None, value=None, examples=None, feature=None,
... |
def read_data(type):
if type == "train":
df = pandas.read_csv('frogs-small.csv')
else:
df = pandas.read_csv('Frogs_MFCCs.csv')
np_array = df.to_numpy()
return np_array
def choose_features(examples, features):
optimal_feature = 0
optimal_split = -10000000
max_info_gain = -1
... | The main task of the code is to build and visualize a decision tree using training data. It reads input data, selects features, splits examples based on thresholds, constructs a tree with branches for different splits, exports the tree as an image, and calculates/trains the model's accuracy. The code focuses on trainin... | def main():
arr = read_data("train")
feature, split = choose_features(arr, feature_set)
blist, alist = split_examples(arr, feature, split)
parent_node = AnyNode(name='MFCCs_' + str(feature + 1), value=split, foo=feature)
generate_tree(blist, parent_node, '-')
generate_tree(alist, parent_node, ... |
def choose_features(examples, features):
optimal_feature = 0
optimal_split = -10000000
max_info_gain = -1
for index in features:
tmp_split, tmp_info_gain = choose_split(examples, index)
if tmp_info_gain > max_info_gain:
max_info_gain = tmp_info_gain
optimal_featu... | The main task of the code is to perform 5-fold cross-validation on decision tree models with varying pruning thresholds (0.1 to 1.0). It evaluates both stop-early and post-pruned trees, calculating training/testing accuracies for each fold. The results are aggregated, plotted, and the optimal pruning threshold (yieldin... | def five_cross_validation(data, file_path):
st_test_average_acc = list()
st_train_average_acc = list()
p_test_average_acc = list()
p_train_average_acc = list()
piece = len(data) // 5
for limit in np.arange(0.1, 1.1, 0.1):
i = 0;
j = 40
st_test_acc = list()
st_trai... |
def read_data(type):
if type == "train":
df = pandas.read_csv('frogs-small.csv')
else:
df = pandas.read_csv('Frogs_MFCCs.csv')
np_array = df.to_numpy()
return np_array
def choose_features(examples, features):
optimal_feature = 0
optimal_split = -10000000
max_info_gain = -1
... | The code constructs a decision tree using information gain for feature selection, splits data recursively, performs post-pruning based on cross-validation results, converts the tree to a visual format, and evaluates accuracy on the training dataset. | def main():
arr = read_data("train")
feature, split, info_gain = choose_features(arr, feature_set)
blist, alist = split_examples(arr, feature, split)
limit = five_cross_validation(arr, './cv-min-info-gain.png')
# # post-pruning strategy
parent_node = myNode(name='MFCCs_' + str(feature + 1),
... |
def run_setup():
style = style_from_dict({
Token.Separator: '#cc5454',
Token.QuestionMark: '#673ab7 bold',
Token.Selected: '#cc5454', # default
Token.Pointer: '#673ab7 bold',
Token.Instruction: '', # default
Token.Answer: '#f44336 bold',
Token.Question: '',
... | This code is a utility that runs a bash command and controls Philips Hue bulbs based on the command's outcome. It uses argparse to accept a command to execute (-r) or run setup (-s). If setup is triggered, it initializes configurations. When running a command, it checks for stored settings, executes the command, and ch... | def main():
parser = argparse.ArgumentParser(description='Utility for use hue bulbs to set the outcome of a bash command')
parser.add_argument('-r', '--run', nargs='+', help='Accepts command to be run')
parser.add_argument('-s', '--setup', action='store_true', help='Runs utility setup', required=False)
... |
def get_download_location(fn_mode: str) -> Path:
"""
Retrieves the download location based on the show mode.
Args: fn_mode: show | ia | archivist
Returns:
Path: A pathlib.Path object
"""
script_path = Path.cwd()
if fn_mode == "show" or fn_mode == "archivist":
download_path ... | The main task of the code is to download a high-quality thumbnail image from a given URL or alternative source, saving it to a structured directory based on the specified mode (show, ia, archivist). It handles errors, avoids duplicates, sanitizes filenames, and uses a fallback method if the primary download fails. | def download_thumbnail(thumbnail_url, episode_data, fn_mode):
print("Attemping to download HQ thumbnail...")
try:
# Ensure the download location exists
dl_path = Path(get_download_location(fn_mode=fn_mode))
dl_path.mkdir(parents=True, exist_ok=True)
# Generate the file name and ... |
def get_archive_log_filename():
"""
Gets the path to the archive log file using pathlib.
Returns:
Path: The path to the archive log file.
"""
script_path = Path.cwd()
archive_log_path = script_path / "logs" / "archive.log"
return archive_log_path
def is_tool(name):
"""Check whe... | The main task of the code is to download a video from a given URL using yt-dlp with customizable options (e.g., concurrency, retries, aria2c integration), generate filenames/directories based on episode data, download thumbnails, and upload the resulting video (and metadata) to the Internet Archive if specified. It als... | def downloader(
username,
password,
vod_url,
episode_data,
concurrent_fragments,
use_aria,
fn_mode,
fragment_retries,
fragment_abort,
keep_after_upload,
ignore_existing,
):
video_options = {
"username": username,
"password": password,
"restrictedfi... |
def _process_footnote_references(self):
"""Process footnot references.
.. todo: Nested for loops are bad.
:param self: Current instance.
"""
footnotes = self._collect_footnotes()
for ref_name in self.document.footnote_refs:
if ref_name in footnotes:
... | The main task of the code is to complete the parsing process by calling the parent class's finish_parse method, then processing footnote references, cleaning unrecognized internal references, and removing unrecognized substitutions to finalize parsed content. | def finish_parse(self) -> None:
"""Complete the parsing process.
:param self: Current instance.
:return None:
"""
super().finish_parse()
self._process_footnote_references()
self._clean_unrecognized_internal_references()
self._clean_unrecognized_substituti... |
def ubbindKeys():
global root
# Bind out keys...
root.unbind("<ButtonPress-1>")
root.unbind("<ButtonPress-2>")
root.unbind("<Motion>")
root.unbind("<space>")
root.unbind("l")
def drawLine(self, line):
# increase line length slightly
line = self.extendLine(line, 3)
# ... | This code initializes a graphical interface for an art-drawing application, setting up a canvas for user interaction, configuring screen dimensions, saving directories, and data structures to track lines, intersections, polygons, and session metrics. It binds keyboard events, initializes experiment parameters based on ... | def __init__(self, root, artist_name):
self.root = root
ubbindKeys()
self.cover_id = None
self.button_id = None
if operant_box_version:
self.width, self.height = 1024, 768
self.root.geometry(f"{self.width}x{self.height}+{self.width}+0")
self.ro... |
def DEL(self, q1,q2,q3,lamb,F1,F2):
"""
q1/q2/q3: (14,) tensor
lamb: (8,) tensor
F1/F2: (12,) tensor
return (12,) tensor
"""
H = self.H
T = self.T
m1 = self.LINK_MASS_1
m2 = self.LINK_MASS_2
J1 = self.J1
J2 = self.J2
... | This function computes the next state s3 by iteratively solving a constrained optimization problem using Newton-Raphson method. It updates s3 and Lagrange multipliers λ until residual errors (from DEL and constraints) fall below 1e-5, applying rotation corrections and matrix inversions to satisfy dynamic and kinematic ... | def maximal_coord_nextstate(self,s1,s2,F1,F2):
"""
Args:
s1: (14,) tensor
s2: (14,) tensor
F1: (12,) tensor
F2: (12,) tensor
Returns:
s3: (14,) tensor
"""
h = self.dt
s3 = copy.deepcopy(s2)
lamb = torch.z... |
def maximal_coord_nextstate(self,s1,s2,F1,F2):
"""
Args:
s1: (14,) tensor
s2: (14,) tensor
F1: (12,) tensor
F2: (12,) tensor
Returns:
s3: (14,) tensor
"""
h = self.dt
s3 = copy.deepcopy(s2)
lamb = torch.z... | This code simulates a robotic arm's dynamics by applying torque 'a' to compute forces, update states via maximal coordinates, and calculate rewards based on tip position and cosine-based criteria. It returns observations, reward (1/-1 for success/failure), terminal status, and empty info, advancing the environment step... | def step(self, a):
"""
Args:
a: (1,), torque
"""
q1 = self.prev_state
q2 = self.state
prev_a = self.prev_a
g = 9.8
F1 = torch.Tensor([0,-g * self.LINK_MASS_1,0,0,0,-prev_a,0,-g * self.LINK_MASS_1,0,0,0,+prev_a]) #(12,)
F2 = to... |
def load_data(self):
if getattr(sys, 'frozen', False):
spreadsheet = os.path.join(sys._MEIPASS, "CrosswordData.xlsx")
else:
spreadsheet = "./CrosswordData.xlsx"
self.df = pd.read_excel(spreadsheet)
def create_widgets(self):
frame = tk.Frame(self.root)
fram... | This code initializes a crossword game GUI, setting up the main window, tracking game statistics (correct answers, streaks), loading data, creating interactive widgets, and starting the game by triggering the "Next Clue" functionality to begin the puzzle-solving process. | def __init__(self, root):
self.root = root
self.root.title("Crossword Game")
self.root.geometry("1440x900") # Adjusted the window size
self.total_correct = 0
self.current_streak = 0
self.total_tried = 0
self.load_data()
self.create_widgets()
se... |
def start_btcd(mining_address=None):
btcd = f'btcd --txindex --simnet --rpcuser=kek --rpcpass=kek --datadir={btcd_dir}'
if mining_address:
btcd += f' --miningaddr={mining_address}'
btcd += f' &> {btcd_log} &'
os.system(btcd)
def start_lnd(node, neutrino, uri):
lnd = [
'lnd',
... | The code initializes COUNT Lightning Network (LND) nodes using neutrino and URI parameters, starts a Bitcoin daemon (btcd), sets up each node's certificate and macaroon files, connects the first node, and configures a mining node to generate 400 blocks for blockchain confirmation requirements. | def init(count, neutrino, uri):
"""Start and initialize COUNT nodes"""
if not os.path.exists(root):
os.makedirs(root)
click.echo('starting btcd')
start_btcd()
for index in range(0, count):
node = Node.from_index(index)
start_lnd(node, neutrino, uri)
wait_for_fi... |
def is_valid_movement(self, origin, destination):
adjacent_rules = {
"A1": ["B1", "A2"],
"A2": ["A1", "B2", "A3"],
"A3": ["A2", "B3", "A4"],
"A4": ["A3", "B4", "A5"],
"A5": ["A4", "B5", "A6"],
"A6": ["A5", "B6", "A7"],
"A7": ["A... | The code validates soldier movement between coordinates in a game. It checks if movement is allowed, ensures the origin isn't an HQ, and determines if an assault or move action is needed based on the destination's occupant. If invalid, it returns an error; otherwise, it executes the action and confirms success with a s... | def move_soldier(self, origin, destination, game_id):
if not self.is_valid_movement(origin, destination):
return {"message": "Invalid Movement", "status_code": 403}
origin_content = self.get_content(origin, game_id)
if origin_content.soldier == "hq":
return {"message": ... |
def get_from_config(config_file):
"""
Performs config validation, and returns values from config.
If config validation fails (but not path validation), assume it's corrupt, make a new config file.
:returns: PARAGON_CHAT_DB, COSTUME_FILE if successful
"""
from configparser import ConfigParser
... | The main task of the code is to initialize and run a utility that processes a costume CSV file and a ParagonChat database. It loads configuration from 'jerrichas.ini', validates file paths, reads the costume data, connects to the database, and executes an event loop to handle interactions between the database and costu... | def main():
print("### <3 Jerricha's ParagonChat DB Costume Utility v{} <3 ###".format(VERSION))
config = get_from_config('./jerrichas.ini')
test_path(config)
from jerrichas import CostumeCSV, ParagonChatDB
try:
costumesave = CostumeCSV(open(config['COSTUME_FILE'], 'r'))
except Exceptio... |
def get_lines(city):
lines = []
with open(f'static/{city}.txt', 'r') as f:
for line in f:
lines.append(line.strip().split())
return lines
def which_line(s, city):
lines = get_lines(city)
in_lines = list()
for i, l in enumerate(lines):
if s in l:
in_lines.a... | The code generates and returns multiple transit routes between start and end stations in a city, considering direct lines, one-transfer, two-transfer, and three-transfer paths. It calculates each route's total time using station counts, transfer costs, and predefined parameters, then sorts routes by total time for opti... | def route(s, e, city, get_in=10, get_out=7, change_line=5, station_time=2):
lines = get_lines(city)
s_lines = which_line(s, city)
e_lines = which_line(e, city)
routes = []
for sl in s_lines:
if sl in e_lines:
route = []
stations_count = abs(lines[sl].index(s) - line... |
def update(player, out, shoals):
player.rect[1] -= player.movement[0]
player.rect[1] += player.movement[1]
player.rect[0] -= player.movement[2]
player.rect[0] += player.movement[3]
if player.rect[0] < 0:
player.rect[0] = 0
elif player.rect[0] > 1346:
player.rect[0] = 1346
eli... | The code implements a game loop managing player interaction, shoal collision detection, time-based challenges, and level progression using a knapsack algorithm. It handles input for movement and item management, updates game state, spawns obstacles, checks exit conditions, and advances levels when quota requirements ar... | def game_loop():
global level
# defines max_load and required quota in each level
levels = {
1: [50, 60],
2: [48, 65],
3: [45, 70],
4: [43, 75],
5: [40, 80]
}
level_timer = time.perf_counter()
show_timer = 80
elapsed = time.perf_counter()
player = ... |
def onClickProjectMenu(VarProj, typeIn, frmIn, frmCanvas, frmTop):
VarProj.typeProj.set(typeIn)
openProject(VarProj, typeIn, frmIn, frmCanvas, frmTop)
def openProject(VarProj, fileNameIn, frmIn, frmCanvas, frmTop):
# Set directory and filename depending on typeProj
if VarProj.typeProj.get() == 'New':
... | This code initializes a GUI component for project management, creating a menu with options to "New", "Open from file", or "Open demo". It sets up interactive elements like labels, buttons, and menus, linking each menu option to specific functions (`onClickProjectMenu`) that handle project creation/loading. Conditional ... | def __init__(self, parent=None, nameInput=[], VarProj=[], frmCanvas=[], frmTop=[]):
Frame.__init__(self, parent)
self.pack(expand=YES, fill=BOTH)
self.title = FrameLabel(self, nameInput)
self.frmLabelMenu = Frame(self)
self.frmLabelMenu.config(
bd=1,
rel... |
def onClickOpen(VarProj):
VarProj.typeProj.set('Open')
editProject()
def onClickOpenDemo(VarProj):
path = os.path.join(dirRecent, fileRecent)
VarProj.typeProj.set('Open demo')
VarProj.inputLabelsCreated.set(True)
editProject()
def editProject():
... | The main task of the code is to create a graphical user interface (GUI) with a main menu and toolbar for a project management application. It constructs menus for File, Edit, Run, View, and Help, linking actions like opening projects, editing settings, and viewing files. A toolbar includes buttons for opening demos, qu... | def mainMenu(FrameIn, VarProj):
"""Creates main menu, and toolbar.
"""
frm = Frame(FrameIn)
frm.pack(expand=YES, fill=BOTH)
frm.master.title('iH2O')
frm.master.iconbitmap(bitmap='gray50')
frm.menubar = Menu(frm.master)
frm.master.config(menu=frm.menubar)
... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-o", "--output-dir", help="output directory to use", default="."
)
parser.add_argument(
"action",
choices=["collect", "clean"],
help="Action to perform",
default="collect",
nargs="?... | The main task of the code is to execute different actions based on command-line arguments. It parses input arguments, then triggers either the 'collect' or 'clean' function, both operating on a specified output directory, to process or organize data accordingly. | def main(output_dir="."):
args = parse_args()
if args.action == "collect":
collect(output_dir=args.output_dir)
elif args.action == "clean":
clean(output_dir=args.output_dir) |
def start_epoch_selection_phase(self):
old_epoch_number = self.development_internal_parameters["oldNumberOfEpochs"]
new_epoch_number = self.development_configuration["numberOfEpochs"]
if old_epoch_number == new_epoch_number:
self.update_internal_file("grid_search", None, None)
... | The code manages a machine learning workflow by executing different phases based on the "status" parameter. It starts a server thread for communication, handles epoch selection, initiates grid search or testing phases, and finalizes tasks by sending results or updating configurations. The loop waits indefinitely in "st... | def run(self):
status = self.development_internal_parameters["status"]
if status == "start":
self.server_thread = threading.Thread(target=self.communication_handler.run, args=("127.0.0.1", 5001))
self.server_thread.daemon = True
self.server_thread.start()
... |
def update_internal_file(self, status, old_number_of_epochs, json_dataset):
if status is not None:
self.development_internal_parameters["status"] = status
if old_number_of_epochs is not None:
self.development_internal_parameters["oldNumberOfEpochs"] = old_number_of_epochs
... | The code's main task is to process a JSON dataset by updating internal state with the dataset, retrieving it for use, and initiating the epoch selection phase, likely for machine learning training. It manages dataset handling and prepares for training iterations. | def handle_json(self, json_dataset, json_type):
self.update_internal_file("epoch_selection", None, json_dataset)
self.retrieve_dataset(json_dataset)
self.start_epoch_selection_phase() |
def canParseData(self, data):
return (data.IsChatMessage() and self.is_live())
def add_count(self, count):
self.current_count += count
self.write_count()
if self.current_count > self.max_count:
self.max_count = self.current_count
self.write_max_count()
def isOnCoo... | The main task of the code is to parse incoming data from a bot, check for a specific command, count regex matches in the message, and publish statistics if the command is valid and not on cooldown. It processes data to determine if an action is required based on predefined patterns and settings, ensuring cooldown restr... | def execute(self, data):
"""
Parse the data sent from the bot to see if we need to do something.
"""
# If it's from chat and the live setting correspond to the live status
if self.canParseData(data):
count = len(re.findall(self.pattern, data.Message))
... |
def draw_background():
img = load_image("Images/world.png")
draw_image(img, 0, 0)
def delay():
global time, counter
counter = False
if time == 40:
time = 0
counter = True
time = time + 1
def main_menu():
main_menu_draw()
main_menu_space()
main_menu_delay()
main... | The main task of the code is to manage game state transitions by rendering appropriate UI elements based on the 'start', 'legacy', and 'search_mode' flags. It initializes the main menu when not started, handles legacy mode with delayed city rendering, and switches to search mode with a white background clearing, coordi... | def main():
global start
if not start:
draw_background()
delay()
main_menu()
if start:
draw_background()
legacy_or_search()
if legacy:
draw_background()
delay_legacy(50)
draw_cities()
if search_mode:
... |
def get_updates(offset=None):
url = URL + "getUpdates?timeout=100"
if offset:
url += "&offset={}".format(offset)
js = get_json_from_url(url)
return js
def get_last_update_id(updates):
update_ids = []
for update in updates["result"]:
update_ids.append(int(update["update_id"]))
return max(update_ids)
def handl... | The main task of the code is to run a bot that continuously checks for new updates from a server, processes them, and updates the last known update ID to avoid reprocessing. It initializes the database, enters an infinite loop to fetch updates, and handles them using the `handle_updates` function, ensuring the bot rema... | def main():
print ("server easymeeting bot dijalankan...")
db.setup()
last_update_id = None
# ngecek apakah pesan yang terbaru adalah last_textchat
while True:
print("getting updates")
updates = get_updates(last_update_id)
if len(updates["result"]) > 0:
last_update_id = get_last_update_id(updates) + 1
... |
def display_map(self, link):
try:
response = requests.get(link)
self.map_img = Image.open(BytesIO(response.content))
self.map_img = self.map_img.resize((800, 450), Image.ANTIALIAS)
self.map_img = ImageTk.PhotoImage(self.map_img)
self.map_panel.configur... | The main task of the code is to initialize the interface by displaying a placeholder map image, a local QR code, a text prompt instructing the user to say "Hello, RamNav" to start searching, and recording audio input with the same prompt. This sets up the default user interaction flow for the application. | def show_defaults(self):
self.display_map('http://ramnav.westeurope.cloudapp.azure.com/images/map/placeholder.png')
self.display_local_qr('assets/qr_placeholder.png')
self.display_text("Say 'Hello, RamNav' to start searching.")
self.get_audio("Say 'Hello, RamNav' to start searching.") |
def seeds_coefficients(seed_pattern = "NNNnNnnNnNnnNNnNNN", alignment_length = 64):
"""
Extracting the iedera polynomial coefficients or counts from iedera (they are only given with the "-pF" option applied)
This function runs "iedera (>= v1.7)" on the given "seed pattern (iupac notation)" with an "alignme... | This function plots the frequency and probability distributions of a seed pattern's occurrence using rational numbers and polynomial calculations. It computes coefficients, generates rational number ranges, and plots frequency (as discrete points) and probability (as polynomial curves) on the provided matplotlib axes. ... | def plot_for_seed(plt = None, seed_pattern = "NNNnNnnNnNnnNNnNNN", color_plot = 'gray', alignment_length = 64):
"""
Plot (and compute before ...) on the current plt the frequency and probability for the seed to hit
"""
y_pos_coef,y_pos_frac = seeds_coefficients(seed_pattern,alignment_length)
# (1) ... |
def parse_sentence(self, text, stemming=False, tweet_urls=None):
"""
This function tokenize, remove stop words and apply lower case for every word within the text
:param tweet_urls:
:param stemming:
:param text:
:return:
"""
list_of_parsed_terms = []
... | The function `parse_doc` processes a tweet list into structured fields, tokenizes text (with optional stemming), identifies entities and terms, counts term frequencies, determines the most frequent term (from text or entities), and constructs a `Document` object with metadata like term counts, max term frequency, and d... | def parse_doc(self, doc_as_list, stemm=False):
"""
This function takes a tweet document as list and break it into different fields
:param stemm:
:param doc_as_list: list re-presenting the tweet.
:return: Document object with corresponding fields.
"""
tweet_id = do... |
def press_multiple(count=3, symbol='enter'):
for i in range(count):
log.debug(f"Pressing {i}: {symbol}")
keyboard.press_and_release(symbol)
time.sleep(PRESS_INTERVAL)
def emulate_word(word):
is_first_press = True
start_symbol = '#' # first symbol is save button default
for chara... | The code automates adding TOTP secrets to a Google Authenticator app by loading secrets from a text file, iterating through each entry to simulate entering names and secrets via keyboard inputs, and confirming additions with directional key presses and Enter.) | def google_authenticator():
# use txt output https://github.com/krissrex/google-authenticator-exporter
str_array = totp_text_to_dict()#load secrets
for keywords in str_array:
log.debug(keywords[0:2])
# enter to add new totp screenand enter to new token field and enter to name field
... |
def press_multiple(count=3, symbol='enter'):
for i in range(count):
log.debug(f"Pressing {i}: {symbol}")
keyboard.press_and_release(symbol)
time.sleep(PRESS_INTERVAL)
def emulate_word(word):
is_first_press = True
start_symbol = '#' # first symbol is save button default
for chara... | The main task of the code is to automate saving a TOTP secret by simulating keyboard interactions: pressing Enter to navigate to input fields, typing the secret's title and value, and confirming the entry. It handles GUI navigation for adding a new TOTP token in an application. | def save_single_secret(title, secret):
# enter to add new totp screenand enter to new token field and enter to name field
press_multiple(3, 'enter')
emulate_word(title) # emulate name
#move to secret field
move_down()
press_enter()
emulate_word(secret) # emulate secret
#click ... |
def checking_availability(model):
"""
This function will check,
if GPTs models are available,
there token limit, etc.
"""
models_available = [x["id"] for x in openai.Model.list()["data"]]
if model not in models_available:
cprint(
f"Model {model} is not available.Try rerun... | The main task of the code is to run a script while handling errors by using a model (e.g., GPT) to generate fixes. It creates a backup of the original script, checks model availability, and enters a loop: if the script fails, it sends errors to the model, applies suggested changes (with confirmation), and reruns the sc... | def main(script_name, *script_args, revert=False, model=default_gpt_model, confirm=True):
"""
main function for running
"""
if revert:
backup_file = script_name + ".bak"
if os.path.exists(backup_file):
shutil.copy(backup_file, script_name)
print(f"Reverted change... |
def export_clf_report(to_csv=False):
report = classification_report(y_actual, model_xgbt.predict(test_df[feats]), output_dict=True)
df_report = pd.DataFrame(report).transpose()
return df_report.to_csv('classification_report.csv', sep=';', index=True)
def confusion_matrix_plot(save_plot=False):
plt.figur... | The main task of the code is to export machine learning evaluation metrics, including a classification report (to CSV), confusion matrix plot (saved as an image), score band plot (displayed), and score band table (generated). It systematically executes these tasks with print statements for progress tracking, concluding... | def main():
print("Export classification report ...")
export_clf_report(to_csv=True)
print("Export confusion matrix plot ...")
confusion_matrix_plot(save_plot=True)
print("Export score band plot ...")
score_band_plot()
print("Export score band table ...")
extract_score_band()
print("... |
def _get_names_list(self):
return os.listdir(self.lfw_dataset_path)
def _get_names_multiple_images(self):
"""
@description
Get name list of person with more than one image
"""
names = self._get_names_list()
names_multiple_images = []
for name in names:
... | The code's main task is to generate a summary of a dataset's composition by counting total names, names associated with multiple images, and names with single images, returning these counts in a dictionary for analysis or reporting. | def dataset_info(self):
names = self._get_names_list()
names_multiple_images = self._get_names_multiple_images()
names_single_images = self._get_names_single_images()
info = {
"count_names": len(names),
"count_names_multiple_images": len(names_multiple_images),
... |
def _get_positive_pairs(self):
anchors = []
positives = []
inputs = self._get_names_multiple_images()
for name in inputs:
name_path = self._get_name_path(name)
name_listdir = os.listdir(name_path)
listdir_length = len(name_listdir)
for idx... | The main task of the code is to generate balanced anchor-positive-negative triplets for training. It retrieves paired anchor/positive images, constructs negative samples from single-image names, and truncates lists to ensure equal lengths, returning triplets for model training. | def create_triplets(self):
(anchors, positives) = self._get_positive_pairs()
negatives = [self._get_image_path(name, "{}_0001.jpg".format(name)) for name in self._get_names_single_images()]
length = min(len(positives), len(negatives))
return (anchors[:length], positives[:length], negat... |
def playerWallet():
money = db.readFile()
buyChips = 0
if money < 5:
print(f"\nYour money amount (${money}) dropped below the minimum bet ($5.0).")
while buyChips < 5:
try:
buyChips = float(input("You must buy a minimum of 5 chips. Please enter number of chips: ")... | The code simulates a single round of a Blackjack game. It initializes player and dealer hands, handles betting, alternates dealing cards, allows the player to hit/stand, processes the dealer's turn, calculates scores, determines the winner, and updates the player's money based on the outcome. | def startBlackjackGame(deck):
dealerScore = 0
dealerHand = []
playerScore = 0
playerHand = []
money = playerWallet()
playerBet = placeBet(money)
for i in range(1, 5):
if i % 2 != 0:
turn = "player"
playerScore = dealCard(deck, playerHand, playerScore, turn)
... |
def cardDeck():
deck = []
suits = ["Spades", "Clubs", "Hearts", "Diamonds"]
ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
points = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
for suit in range(len(suits)):
for rank in range(len(ranks)):
c... | The main task of the code is to run a Blackjack game loop, allowing players to repeatedly play the game by prompting for "y" (continue) or "n" (quit) after each session, while validating user input and displaying appropriate messages for game start, continuation, and exit. | def main():
keepPlaying = "y"
while keepPlaying.lower() == "y":
deck = cardDeck()
showHeader()
startBlackjackGame(deck)
while True:
keepPlaying = input("\nPlay again? (y/n): ")
if keepPlaying.lower() != "y" and keepPlaying.lower() != "n":
p... |
def subsetData(self, aDataSet, yearList, geoList, indicatorList, geoType="Country"):
"""Subsets the data
Parameters
----------
aDataSet : dataFrame
a dataFrame to be subsetted
yearList: a list of int
a list of years to include in the subse... | The main task of the code is to subset and merge labels and metadata from a BDDS archive dataset into a single DataFrame based on specified parameters (years, regions, indicators). It processes national or regional data, combines labels and metadata (if available), and returns the merged DataFrame in either column or d... | def allLabelMetaMerge(self, dataTableDict, yearList, geoList, indicatorList, geoType="Country", metaForm='Col'):
"""Subset and merge all labels and metadata in a single process
Parameter
----------
dataTableDict: Dict
a dictionary containing all the dataFrame of a sp... |
def display_title(self):
self.stdscr.clear()
title = f"Arena Cards ({self.version})"
maxyx = self.stdscr.getmaxyx()
y = maxyx[0] // 2
x = maxyx[1] // 2 - len(title) // 2
self.stdscr.addstr(y, x, title)
prompt = "< any key to continue >"
y += 1
x = ... | The code's main task is to manage a game loop where the player progresses through stages, battles content, checks for game over conditions, rewards progress, updates high scores, and displays victory statistics upon winning. | def play(self):
self.display_title()
self.current_stage = self.stage_graph[0]
while not self.player_wins():
self.display_stage_graph()
self.current_stage.contents.battle()
self.check_game_over()
self.stages_cleared += 1
self.rewards_loo... |
def step_one(primer_file: str, assembly_file: str) -> list[list[str]]:
hits = find_annealing(primer_file, assembly_file)
good_hits = filter_blast(hits)
sorted_hits = sorted(good_hits, key=lambda x: (x[1], int(x[8])))
return sorted_hits
def step_two(
sorted_hits: list[str],
max_amplicon_size: int
) -> list[tuple[... | The main task of the code is to perform an in silico PCR process by executing three steps: identifying primer hits in an assembly, filtering valid amplicon pairs based on size constraints, and generating final amplicon sequences. The function integrates primer-assembly alignment, size-based filtering, and amplicon reco... | def ispcr(primer_file: str, assembly_file: str, max_amplicon_size: int) -> str:
'''
performs the whole ispcr process, taking all the three steps
'''
sorted_hits = step_one(primer_file, assembly_file)
hit_pairs = step_two(sorted_hits, max_amplicon_size)
amplicons = step_three(hit_pairs, assembly_... |
def add_room(database, cursor):
room = create_room()
query = "insert into {0}(room_no,floor,beds,available) values({1},'{2}',{3},{4})".\
format(TABLE_NAME, room.room_no, room.floor, room.beds, room.available)
try:
cursor.execute(query)
database.commit()
except mysql.connector... | The code provides a menu-driven interface for managing room data in a database, allowing users to add, retrieve, update, delete rooms, and filter by beds. It loops until the user selects '0' to return, executing SQL queries via a cursor for each operation. | def room_menu(database, cursor):
while True:
print()
print("============================")
print("==========Room Menu=========")
print("============================")
print()
print("1. Add new room")
print("2. Get room details by room no")
print("3. F... |
def add_customer(database, cursor):
room = get_and_print_room_by_no(cursor)
if room is not None:
customer = create_customer(room.room_no)
confirm = input("Complete the operation? (Y/N) ").lower()
if confirm == 'y':
query = "insert into {0}(name, address, phone, room_no, entry... | The code provides a menu-driven interface for managing customer records in a database, allowing users to add, search, view, edit, delete, or check out customers based on various criteria like name, ID, address, phone, room number, or check-in date. It executes SQL queries to interact with the database, displaying resul... | def customer_menu(database, cursor):
while True:
print()
print("==============================")
print("==========Customer Menu=========")
print("==============================")
print()
print("1. New Customer")
print("2. Show Customer Details by name")
... |
def successor(self):
return self.finger[0][1]
def findSuccessor(self, id, mode = 0):
np = self.findPredecessor(id, mode)
return np.successor()
def findPredecessor(self, id, mode = 0):
np = self
path = []
hops = 0
while not self.check(id, np.id, np.successor().id, ... | The method `deleteOthers` updates the finger tables of neighboring nodes when a node is removed from the DHT. It adjusts predecessors and successors by iterating through intervals defined by `Node.m`, identifies target nodes, and triggers updates to ensure correct routing information is maintained across the network. | def deleteOthers(self):
self.successor().predecessor = self.predecessor
for i in range(0, Node.m):
id1 = (self.id - pow(2, i)) % pow(2, Node.m)
nodePre = self.findSuccessor(id1)
if(nodePre.id != id1):
nodePre = self.findPredecessor((self.id - pow(2, i)... |
def squareUnderAttack(self, r, c):
self.whiteToMove = not self.whiteToMove #switch to opponents POV
oppMoves = self.getAllPossibleMoves()
self.whiteToMove = not self.whiteToMove
for move in oppMoves:
if move.endRow == r and move.endCol == c:
return True
... | This function generates valid castling moves for a king in chess. It checks if the current square is under attack, and if not, adds king-side or queen-side castling moves to the provided list based on the game's castling rights and the current player's turn. | def getCastleMoves(self, r, c, moves):
if self.squareUnderAttack(r, c):
return #cant castle in check
if (self.whiteToMove and self.currentCastlingRights.wks) or (not self.whiteToMove and self.currentCastlingRights.bks):
self.getKingSideCastleMoves(r, c, moves)
if (self.wh... |
def getAllPossibleMoves(self):
moves = []
for r in range(len(self.board)): #number of rows
for c in range(len(self.board[r])): #number of cols in given row
turn = self.board[r][c][0]
if (turn == "w" and self.whiteToMove) or (turn == "b" and not self.whiteToMov... | The code generates valid chess moves by first obtaining all possible moves, then validating them by simulating each move to check if the king is in check. It handles castling rights, en passant possibilities, and removes invalid moves. After processing, it determines checkmate or stalemate if no valid moves remain, the... | def getValidMoves(self):
tempEPP = self.enpassantPossible
tempCastleRights = CastleRights(self.currentCastlingRights.wks, self.currentCastlingRights.bks,
self.currentCastlingRights.wqs, self.currentCastlingRights.bqs)
moves = self.getAllPossibleMoves()
... |
def proper_list(cl):
result = []
return proper_list_inner(result,cl)
def int_list(cl):
return [Program.to(x).as_int() for x in Program.to(cl).as_atom_list()]
def de_none_list(l):
return [x if x is not None else [] for x in l] | The main task of the code is to test if a program correctly generates all permutations of a list of size `n`. It creates a random list, computes its expected permutations, runs the program to generate permutations, processes the output, and verifies correctness by comparing the results with the expected permutations us... | def do_test_permutations_of_size_n(n):
try_list = [random.randint(0,100) for x in range(n)]
want_set = list([list(v) for v in sorted(permutations(try_list))])
listed_result = smoke_test_permutations_program.run(Program.to([try_list]))
pl = proper_list(listed_result)
perms_result = sorted([int_list(x... |
def proper_list(cl):
result = []
return proper_list_inner(result,cl)
def int_list(cl):
return [Program.to(x).as_int() for x in Program.to(cl).as_atom_list()]
def de_none_list(l):
return [x if x is not None else [] for x in l] | The code tests if a CLVM program correctly generates all permutations of a 2-element list. It compares the program's output (processed into integers) against expected permutations derived from Python's `permutations` function. The test ensures the program handles both orderings of the input list `[all_a_string, all_b_s... | def test_permutations_2():
n = 2
all_a_string = 0x616161616161
all_b_string = 0x626262626262
for try_list in [[all_a_string,all_b_string], [all_b_string,all_a_string]]:
want_set = list([list(v) for v in sorted(permutations(try_list))])
listed_result = diag_run_clvm(smoke_test_permutation... |
def add_task(tasks):
task_name = input("Enter task name: ")
timestamp = datetime.datetime.now()
tasks.append({"name": task_name, "completed": False, "timestamp": timestamp})
print("Task added successfully!")
def list_tasks(tasks):
if not tasks:
print("No tasks found.")
else:
prin... | The main task of the code is to provide a menu-driven task management system. It allows users to add tasks, list all tasks, mark tasks as completed, or exit while saving tasks upon exit. The loop handles user input, delegates actions to corresponding functions, and maintains task data in a list until the user chooses t... | def main():
tasks = [] # Initialize an empty list to store tasks
while True:
print("\nTask Manager Menu:")
print("1. Add Task")
print("2. List Tasks")
print("3. Mark Task as Completed")
print("4. Exit")
choice = input("Enter your choice (1/2/3/4): ")
... |
def parse_csv(path):
res_lines = []
with open(path) as f1:
reader = csv.DictReader(f1)
for line in reader:
for i in range(1,9):
try:
res_dict = {"worker_id": line["WorkerId"],
"assignment_id": line["AssignmentId"],
... | The main task of the code is to process a CSV file by parsing its contents, calculating accuracy metrics with optional normalization and exclusion filters, and writing filtered results to a new CSV file if specified. The function uses helper functions to parse data, compute accuracy, and filter output based on command-... | def main(args):
parsed_csv_lines = parse_csv(args.csv)
anns_by_acc = get_accuracy(parsed_csv_lines, args.exclude, args.normalize)
if args.produce_csv is not None:
filtered = filter_data(parsed_csv_lines,
anns_by_acc,
args.produce_csv,... |
def _run_cycle(self):
cycle_inputs = (
self.stimulus.pop(self.cycle) if self.cycle in self.stimulus else {}
)
if self.delay == 1:
self._run_cycle_delay_1(cycle_inputs)
else:
self._run_cycle_delay_0(cycle_inputs)
def _circuit_snapshot(self):
ret... | This code simulates a digital circuit, recording its state over time in a CSV file. It runs simulation cycles, captures circuit snapshots, and writes timestamps/states. When the circuit stabilizes, it repeats the last state until the next signal change, ensuring continuous logging. The loop terminates when the simulati... | def run(self):
self.csv_writer.writerow(["Tempo"] + sorted(self.circuit.keys()))
prev_line = None
while True:
self._run_cycle()
line = self._circuit_snapshot()
self.csv_writer.writerow([self.cycle] + line)
if prev_line == line: # circuit is stable
... |
def get_input(lines):
draw = [int(n) for n in lines[0].split(",")]
boards = [] # 3D array containing all boards (2D array)
index = -1 # index of the current board
for row in range(1, len(lines)):
if row % 6 == 1: # the empty row before first number row
boards.append([])
... | The code simulates a bingo game by processing drawn numbers and boards. It finds the first winning board by incrementally checking subsets of drawn numbers. Once a winner is identified, it calculates the product of the last called number and the sum of unmarked numbers on the winning board, then prints the result. | def part1():
draw, boards = get_input(read_file())
i = 5
winner = find_bingo(draw[:i], boards)
while(winner == -1):
i += 1
winner = find_bingo(draw[:i], boards)
last_called = draw[i-1] # the last number called before bingo
unsum = calc_unmarked(draw[:i], boards[winner])
p... |
def get_input(lines):
draw = [int(n) for n in lines[0].split(",")]
boards = [] # 3D array containing all boards (2D array)
index = -1 # index of the current board
for row in range(1, len(lines)):
if row % 6 == 1: # the empty row before first number row
boards.append([])
... | The code simulates a Bingo game, determining the last winning board by iterating through drawn numbers. It identifies winning boards, removes them, and tracks the final winner. It then calculates the sum of unmarked numbers on the last winning board and prints the product of this sum and the last called number. | def part2():
draw, boards = get_input(read_file())
last_winner = None
last_called = -1
for i in range(4, len(draw)):
if len(boards) > 0:
winner = find_bingo(draw[:i], boards)
while winner != -1:
last_winner = boards.pop(winner)
last_called ... |
def move_cards(controller: Controller, cards: List[Card], centre: bool = False, place: str = "") -> Controller:
if controller.moveables:
if controller.pointer != MOVE_INTERVAL:
for moveable in controller.moveables:
card, placement, incrementx, incrementy = moveable
... | The function `game_logic` manages a game loop that processes card movements, player/computer turns, and event handling. It checks game states (e.g., empty cards, moveables) to trigger actions like dealing cards, moving cards between zones, or waiting for user input. It updates the game state based on player interaction... | def game_logic(controller: Controller) -> Controller:
# Only run the logic if not quitted and the game is explicitly running
while not controller.quit and controller.game_running:
if controller.empty and (len(controller.lower_cards) == 0 and len(controller.upper_cards) == 0):
if controller.m... |
def _build():
# Setting up caption
pygame.display.set_caption("Scopa")
# Loading image for the icon
icon = pygame.image.load(ICON_PATH)
# Setting the game icon
pygame.display.set_icon(icon)
def get_board() -> pygame.Surface:
screen = pygame.display.set_mode((WIDTH, HEIGHT))
screen.fill... | The code's main task is to run a game loop that handles game logic, win conditions, and restarts. It initializes the game board, processes controller inputs, checks for quit/restart flags, and recursively restarts the game if needed, maintaining state through the Controller object until the user quits. | def main():
_build()
screen = get_board()
controller = Controller(screen=screen)
while not controller.quit:
controller = game_logic(controller)
if controller.quit:
break
controller = win_logic(controller)
if controller.restart:
main()
r... |
def generate_flags_dict(flags_list):
d = {}
for item in flags_list:
# flagID, points, x, y
d[item[0]] =[item[0], int(item[1]), float(item[2]), float(item[3])]
return d
def get_distance(node_A, node_B):
return ((node_A[2] - node_B[2]) ** 2 + (node_A[3] - node_B[3]) ** 2)... | The main task of the code is to generate an optimized route by selecting flags based on their fitness values (calculated as flag value divided by distance from a fixed point), inserting them in the best position iteratively, and applying a two-opt algorithm for local optimization. The route is constructed until the cum... | def get_route(p, v, flags):
# code here
flags_dict = generate_flags_dict(flags)
flag_lst =[]
for flag in flags:
fitness = float(flag[1]) / get_distance([0,0,0,0], flags_dict[flag[0]])
flag_lst.append([flag[0], fitness])
flag_lst.sort(key= lambda x: -x[1])
route = [flag_lst[0]... |
def _server_Hash(potato:str) -> str:
return sha256(potato.encode()).hexdigest()
def _server_DatabaseWrite(key, val) -> None:
database[key] = val
_server_DatabaseSave()
def _server_GenerateToken() -> str:
# TODO: Implement
return Token() | The main task of the code is to register a user by hashing their password, storing the username and hashed password in a database, and generating a token upon successful registration. It returns the generated token or a registration error, with a success message logged containing the username, password, and hash. | def _server_Register(username, password) -> Token | RegistrationError:
hash = _server_Hash(password)
_server_DatabaseWrite(username, hash)
print("Registered successfully", username, password, hash)
return _server_GenerateToken() |
def HandleHolepunch(b:bytes) -> None:
message = b.decode().split(" ")
print("handling holepunch", message)
match message:
case ["EXPECT", addr, local, port, localport]:
#enetHost.connect(enet.Address(addr, int(port)), channelCount=CHANNELS.MAX)
#print("local", local)
... | This function serves as a network event handler in a peer-to-peer application, processing ENet events like connections, disconnections, and incoming data. It routes received packets to channel-specific handlers (holepunch, control, stats, video), manages the mobile peer connection, and sends appropriate responses using... | def Service() -> None:
"""Main loop"""
global mobile_peer
global video_handled
video_handled = False
schedule.run_pending()
event = enetHost.service(1000)
print("service")
if False:
if event.type == enet.EVENT_TYPE_RECEIVE:
channel = CHANNELS(event.channelID)
... |
def LoadSettings(force_default=False) -> None:
"""Load embedded settings from file, or use default on error"""
global settings
if force_default:
settings = Settings()
return
# Try load from file
try:
with open("4800-settings.json", 'r') as f:
settings = Settings... | The main task of the code is to initialize system settings, schedule updates, register for network hole-punching, and start a background thread for service data pushing. It then enters an infinite loop to continuously handle sensor control, core services, and queue flushing, ensuring real-time processing and data trans... | def main() -> None:
LoadSettings()
UpdateSchedule() # Set initial schedule
RegisterForHolepunch()
Thread(target=ServicePush_Loop).start()
while True:
sensor_control.service()
Service()
flush_queue() |
def client_UserPass() -> tuple:
while not (username := input("Username? ")):
pass
while not (password := input("Password? ")):
pass
return username, password
def client_Register(username, password):
print(f"Your desired username and password are [{username}] [{password}]")
token = s... | The main task of the code is to present a menu-driven interface for user account management, allowing users to register a new account, log in, or quit. It continuously displays options, accepts numeric input, and executes corresponding functions: `client_Register` or `client_Login` for choices 1/2, and `client_Quit` fo... | def main():
options = [
"Register new account",
"Log in to account",
"Quit"
]
while True:
print("What would you like to do?")
for i, o in enumerate(options):
print(f"{i+1}) {o}")
inp = int(input("> "))
match inp:
case ... |
def server_TryLogin(username, password) -> Token | LoginError:
if not _server_DatabaseExist(username):
return InvalidLoginInfoError()
computed_hash = _server_Hash(password)
stored_hash = _server_DatabaseRead(username)
if computed_hash == stored_hash:
return _server_GenerateToken()
... | The code implements a server using the ENet library to handle peer-to-peer communication. It processes incoming messages for user registration, login, connection requests, and notifications. The server authenticates users, manages client connections via dictionaries, and relays data between peers. It sends responses fo... | def enet_main():
print("Entering enet main")
userdict = {} # username -> ip ip port port
hostdict = {} # username -> enet.peer
pending_pushes = []
enetHost = enet.Host(enet.Address(None, HOST_PORT), peerCount=32)
while True:
event = enetHost.service(10000)
match event.type:
... |
def check_course_number(number):
for course in course_list_map.values():
if number == course.get_number():
return course
return -1
def check_course_name(name):
for course in course_list_map.values():
if name == course.get_name():
return True
return False
def updat... | The main task of the code is to update a course's information (name, description, or enrolled students) based on user input. It first validates the course number, then lets the user select an update type. For name changes, it checks for duplicates before updating. For descriptions, it directly updates. For students, it... | def update_course(self, course_number):
if check_course_number(course_number) == -1:
print("The Course Number didn't exist!")
return
course = course_list_map[course_number]
operation_case = input("Please choose your operation, 1 for update course name, 2 for update course... |
def get_data_and_addr_from_sender(self):
"""
It receives tuple (data, address) from sender. Where data is a package.
"""
if self.counter_from_sender == self.amount_of_packages:
try:
data, addr = self.udp_server_socket.recvfrom(self.buffer_size)
... | The main task of the code is to continuously receive data from a sender, parse and process it, update a hash, manage confirmation arrays, write data to a file, and compare hash codes. It handles data reception, confirmation signaling, file writing, and hash verification until completion, ensuring data integrity and pro... | def listener(self):
"""
Main function listens to data from sender. It also writes the file
"""
while not self.isEnd:
data = self.get_data_and_addr_from_sender()
data = self.parse_data(data)
print(self.count)
print("Sender's count: " + str(... |
def loadFiles(FILE_NO1,FILE_NO2,FILE_NO3,FILE_NO4):
admissionFile = pd.read_csv(FILE_NO1)
diagnosesFile = process(pd.read_csv(FILE_NO2),DISEASE_COLUMN)
symptomsFile = process(pd.read_csv(FILE_NO3),SYMPTOM_COLUMN)
symptomsFile = cutColumn(symptomsFile,COLUMN_LIST)
patientsFile = pd.read_csv(FILE_NO4)... | The main task of the code is to load multiple files, merge and clean the data, then split the processed data into categories like 'DISEASES', 'GENDER', and 'INSURANCE', while measuring the execution time. | def main():
# loading all files
sys_time = time.time()
loadedFiles = loadFiles(FILE_NO1, FILE_NO2, FILE_NO3, FILE_NO4)
#result1 = process(loadedFiles[2],SYMPTOM_COLUMN)
#result2 = process(loadedFiles[1],DISEASE_COLUMN)
mergedData = mergeFiles(loadedFiles)
final_Data = cleanData(mergedData)
... |
def loadFiles(FILE_NO1,FILE_NO2,FILE_NO3,FILE_NO4):
admissionFile = pd.read_csv(FILE_NO1)
diagnosesFile = process(pd.read_csv(FILE_NO2),DISEASE_COLUMN)
symptomsFile = process(pd.read_csv(FILE_NO3),SYMPTOM_COLUMN)
symptomsFile = cutColumn(symptomsFile,COLUMN_LIST)
patientsFile = pd.read_csv(FILE_NO4)... | The main task of the code is to load multiple files, merge their data, clean the merged dataset, and split the cleaned data into three categories: 'DISEASES', 'GENDER', and 'INSURANCE'. The code comments out processing steps for specific columns, focusing instead on data integration and categorization. | def main():
# loading all files
loadedFiles = loadFiles(FILE_NO1, FILE_NO2, FILE_NO3, FILE_NO4)
#result1 = process(loadedFiles[2],SYMPTOM_COLUMN)
#result2 = process(loadedFiles[1],DISEASE_COLUMN)
mergedData = mergeFiles(loadedFiles)
final_Data = cleanData(mergedData)
split('DISEASES',final_... |
def query_syno_api_info(self):
return self.request(
"get", "webapi/entry.cgi?api=SYNO.API.Info&version=1&method=query"
).json()
def login(self):
"""Set cookies."""
return self.request(
"get",
f'webapi/entry.cgi?api=SYNO.API.Auth&version=6&method=login&... | The code initializes a session, constructs an endpoint, queries API data to extract audio-related versions, authenticates by logging in, and retrieves a remote player ID for subsequent operations. | def __post_init__(self):
self.endpoint = f"{self.hostname}:{self.port}"
self.session = Session()
response = self.query_syno_api_info()
self.versions = {k: v for k, v in response["data"].items() if "Audio" in k}
self.login()
self.get_remote_player_id() |
def parseCurriculumFiles(fileName):
f = open(fileName, "r")
rulesSet = set()
for name in f.readlines():
rulesSet.add(json_to_rules.parseRules(name.strip()))
f.close()
return rules.AndRules(rulesSet, "Curriculum")
def validateCourses(courseFile, curriculum, courseDatabase):
f = open(cour... | The main task of the code is to validate course requirements against a curriculum by parsing input files, checking for unsatisfied rules, and outputting missing requirements to a specified file. It adjusts working directories for compatibility, verifies argument counts, processes course data, identifies gaps in fulfill... | def main(args):
# if executing from backend, change cwd so paths work
if os.getcwd()[-9:] == 'goBackend':
os.chdir(os.getcwd() + '/../pythonScripts')
print("executing python script")
print('args', args)
print('cwd', os.getcwd())
# fail silently if incorrect number of args :)
# ... |
def stop(self):
log("%s.%s", self.__class__, self.stop.__name__)
if self._btp_worker:
self._btp_worker.close()
self._btp_worker = None
self._btp_socket = None
if self._event_handler:
self._event_handler.clear_listeners()
# Close the Andr... | The code's main task is to restart a Bluetooth-related process by stopping and starting it, then work around Android's notification-based pairing confirmation by opening the Bluetooth settings activity, forcing a popup window instead of parsing an unparsable notification. | def reset(self):
self.stop()
self.start()
# When pairing with newer Android versions the pairing is confirmed
# using a notification instead of a popup window. We are not able to
# parse this notification. To work around it we open Bluetooth
# settings activity. When in t... |
def transliterate_baseline(self, text, lang, translit=None):
if translit is None or lang not in self.settings.languages:
return text
spans = self.rxTextSpans.findall(text)
translitFuncName = 'trans_' + translit + '_baseline'
localNames = globals()
if translitFuncName ... | The function processes a single word from search results, extracting linguistic data like frequency, rank, and grammatical information. It handles both 'word' and 'lemma' search types, transliterating terms and generating HTML table rows for display. The output depends on the search type, rendering either a word or lem... | def process_word(self, w, lang, searchType='word', translit=None):
"""
Process one word taken from response['hits']['hits'].
"""
if '_source' not in w:
return ''
wSource = w['_source']
freq = str(wSource['freq'])
rank = str(wSource['rank'])
nDo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.