dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def AlphaGammaDescent_algorithm(self, thetas, weights_init):
self.eta_n = self.eta_n0
weights, llh, renyi_bound = self._weights_update(weights_init, thetas)
renyi_bound_lst = [renyi_bound]
llh_lst = [llh]
n_iter = 1
weights_sum = self.eta_n * weights.copy()
whi... | This function performs an iterative optimization algorithm by updating parameters (thetas) and hyperparameters (J_t, h_t) through stochastic perturbations and Alpha-Gamma descent. It evaluates model performance at specified intervals, tracks log-likelihoods, Renyi bounds, and evaluation metrics, returning final paramet... | def _full_algorithm(self):
evaluation_lst = []
thetas = self.thetas_init.copy()
# Init with np.array([1 / self.J_t] * self.J_t)
weights, llh, renyi_bound = self.AlphaGammaDescent_algorithm(thetas, np.array([1 / self.J_t] * self.J_t))
renyi_bound_lst = renyi_bound
llh_ls... |
def game_init(self):
"""Creates the BlackBoxGame object with 4 random atom locations. Returns the object.
"""
atom_list = []
#Generate 4 random coordinates
for i in range(4):
row = random.randint(1,8)
col = random.randint(1,8)
while (row, col)... | The main task of the code is to run a game loop that handles user inputs (mouse clicks), updates the game state (shooting rays, guessing atoms), checks win/loss conditions, and renders visual feedback (circles, Xs, messages) on a Pygame display. It manages game interactions, score tracking, and UI updates based on play... | def play_game(self):
"""Runs the game
"""
playing = True #Used for our loop. Game will end when playing == False
game_status = 'ACTIVE' #When game_status != 'Active' only the new game and quit buttons will do anything.
while playing:
for ev... |
def decompression_benchmark(trials, images, paths, cache_destination, cache_source):
prefix = 'Benchmarks/Decompression'
suffix = 'decompression-benchmark'
baseline, swift = build_benchmarks(prefix, suffix)
colors = assign_colors(images)
if cache_source is None:
series ... | The code benchmarks decompression and compression performance for given image sets, generating speed/size metrics, SVG plots, and structured results. It uses cached data if enabled, calculates ratios as percentages, and returns a dictionary with image counts, plots, and benchmark statistics for analysis. | def benchmark(trials, images, save, load, prefix):
paths = tuple('Tests/Baselines/{0}.png'.format(image) for image in images)
plot, median_ratio, rgb8_ratio = decompression_benchmark(trials[0], images, paths,
cache_destination = '{0}/decompression.data'.format(prefix) if save else None,
cach... |
def find_image_without_error(image_location, image, confidence):
try:
return pyautogui.locate(image_location, image, confidence=confidence)
except pyautogui.ImageNotFoundException:
return None
def print_formatted_board():
for i, row in enumerate(board_strings):
print(" " * abs(i-4), ... | The code identifies game board cells by analyzing screenshots, assigns 'X' or 'O' based on detected images, updates the board state, and visualizes potential moves by drawing red rectangles on clickable cells in a GUI. It processes board logic, propagates changes, and displays the updated board with marked interactions... | def solve_board():
global board_strings, click_list
board_strings = [
[None] * 5,
[None] * 6,
[None] * 7,
[None] * 8,
[None] * 9,
[None] * 8,
[None] * 7,
[None] * 6,
[None] * 5
]
click_list = [
[False] * 5,
[False] ... |
def get_args():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
# Input Directories and Files
parser.add_argument('--top-dir', dest='top_dir',
default='./dataset/mars/',
help='Top Directory with subdirectories containing MARS.')
# Output Directories
... | (The code processes tracking data from a directory structure, extracting training, query, and gallery sets from .mat files and text lists. It organizes data into subsets, then converts them into H5 format for storage, using parallel processing if enabled. The main task is to prepare structured datasets for evaluation i... | def main():
args = get_args()
if not os.path.isdir(args.output_dir):
os.makedirs(args.output_dir)
ids = os.listdir(args.top_dir)
ids = [d for d in ids if not d.startswith('.') and os.path.isdir(d)]
# Retrieve data from info directory
# From: https://github.com/liangzheng06/MARS-evaluation/tree/master... |
def type_of_target(y):
"""Determine the type of data indicated by target `y`
Parameters
----------
y : array-like
Returns
-------
target_type : string
One of:
* 'continuous': `y` is an array-like of floats that are not all
integers, and is 1d or a column vector.
... | This function computes and averages a binary classification metric across multiple classes in a multilabel setting. It applies the provided binary_metric to each class, then aggregates results using the specified average method ('micro', 'macro', 'weighted', or 'samples'), handling sample weights and reshaping inputs a... | def _average_binary_score(binary_metric, y_true, y_score, average,
sample_weight=None):
"""Average a binary metric for multilabel classification
Parameters
----------
y_true : array, shape = [n_samples] or [n_samples, n_classes]
True binary labels in binary label indic... |
def calculate_quartiles(data):
filtred_weight = remove_obvious_outliers(data)
mean_weight = mean(filtred_weight);
first_half = list(filter(lambda x: x < mean_weight, filtred_weight))
last_half = list(filter(lambda x: x >= mean_weight, filtred_weight))
mean_fh = mean(first_half)
mean_lh = mean(last_half)
Q... | The code calculates a standard score (z-score) by first determining valid data points using quartiles, then computing the mean and standard deviation of these values. It applies the formula: mean + (z * standard deviation), returning the resulting score. | def calculate_weight(data, z):
valid_weight = calculate_quartiles(data)
mean_weight = mean(valid_weight)
standard_deviation = stddev(valid_weight)
standard_score = mean_weight + z * standard_deviation;
return standard_score |
def _set_torque_driver(self, min_t, max_t):
for i in range(0, 5):
self.safety.safety_rx_hook(self._torque_driver_msg(min_t))
self.safety.safety_rx_hook(self._torque_driver_msg(max_t))
def _set_prev_torque(self, t):
self.safety.set_subaru_desired_torque_last(t)
self.safety.set_subaru_rt_torque_last... | This test verifies that the safety system enforces torque rate limits in non-realtime scenarios. It checks if the safety_tx_hook allows valid torque values (±MAX_RATE_UP) but blocks values exceeding these limits (±MAX_RATE_UP ±1). The test ensures the system correctly permits allowed torque inputs while rejecting out-o... | def test_non_realtime_limit_up(self):
self._set_torque_driver(0, 0)
self.safety.set_controls_allowed(True)
self._set_prev_torque(0)
self.assertTrue(self.safety.safety_tx_hook(self._torque_msg(MAX_RATE_UP)))
self._set_prev_torque(0)
self.assertTrue(self.safety.safety_tx_hook(self._torque_msg(-MA... |
def _set_torque_driver(self, min_t, max_t):
for i in range(0, 5):
self.safety.safety_rx_hook(self._torque_driver_msg(min_t))
self.safety.safety_rx_hook(self._torque_driver_msg(max_t))
def _set_prev_torque(self, t):
self.safety.set_subaru_desired_torque_last(t)
self.safety.set_subaru_rt_torque_last... | This test function validates safety checks for torque values against driver limits. It verifies that the safety_tx_hook correctly allows valid torque ranges and blocks excessive values, testing both positive/negative directions, boundary conditions, and specific scenarios like max steer, delta changes, and arbitrary hi... | def test_against_torque_driver(self):
self.safety.set_controls_allowed(True)
for sign in [-1, 1]:
for t in np.arange(0, DRIVER_TORQUE_ALLOWANCE + 1, 1):
t *= -sign
self._set_torque_driver(t, t)
self._set_prev_torque(MAX_STEER * sign)
self.assertTrue(self.safety.safety_tx_h... |
def _set_prev_torque(self, t):
self.safety.set_subaru_desired_torque_last(t)
self.safety.set_subaru_rt_torque_last(t)
def _set_torque_driver(self, min_t, max_t):
for i in range(0, 5):
self.safety.safety_rx_hook(self._torque_driver_msg(min_t))
self.safety.safety_rx_hook(self._torque_driver_msg(max_... | This test verifies that the safety system enforces real-time torque limits by checking if the safety_tx_hook method correctly allows valid torque values within MAX_RT_DELTA thresholds and blocks excessive values. It tests both positive and negative scenarios, simulates timer updates, and ensures the system adheres to s... | def test_realtime_limits(self):
self.safety.set_controls_allowed(True)
for sign in [-1, 1]:
self.safety.init_tests_subaru()
self._set_prev_torque(0)
self._set_torque_driver(0, 0)
for t in np.arange(0, MAX_RT_DELTA, 1):
t *= sign
self.assertTrue(self.safety.safety_tx_hook... |
def _angle_meas_msg_array(self, angle):
for i in range(6):
self.safety.safety_rx_hook(self._angle_meas_msg(angle))
def _speed_msg(self, speed):
to_send = make_msg(0, 0x29a)
speed = int(speed / 0.00555 * 3.6)
to_send[0].RDLR = ((speed & 0xFF) << 24) | ((speed & 0xFF00) << 8)
return to_send
def... | This test verifies that angle command rate limits are enforced when controls are enabled. It checks if valid commands within limits are allowed, while exceeding limits triggers control disablement. It also ensures that when controls are disabled, the desired steer matches the actual steer angle, validating safety syste... | def test_angle_cmd_when_enabled(self):
# when controls are allowed, angle cmd rate limit is enforced
# test 1: no limitations if we stay within limits
speeds = [0., 1., 5., 10., 15., 100.]
angles = [-300, -100, -10, 0, 10, 100, 300]
for a in angles:
for s in speeds:
max_delta_up = np.... |
def action_sample(self, input_ids):
'''
Usage:
sample the actions(insert,substitution,remove) for the given input sequence x.
Input:
None
Output:
action: the action to be taken. Notice: 0 for insertion, 1 for substitution, 2 for removal.
... | The function proposes a new state by inserting, substituting, or removing a token based on the old state, calculating the proposal probability (q(x(t+1)|x(t))) and reverse probability. It returns the new state along with these probabilities for Metropolis-Hastings sampling in Markov Chain Monte Carlo methods. | def propose_state(self,old_state):
'''
Usage:
Propose a new state( {e,l,o} in the paper), and calculate the probability of the proposed state. q(x(t+1)|x(t)) in the paper.
Input:
old_state: the old state of the sentence.
Output:
new_state: the new stat... |
def sendGetEui64(ser):
msg = bytearray(b'\x1c')
resp = sendMessage(ser, msg, 1)
if resp is not None and len(resp) == 9 and resp[0] == 0x3A:
return resp[1:]
else:
return None
def sendMassErase(ser):
msg = bytearray(b'\x15')
resp = sendMessage(ser, msg, 1)
if resp == b'\x3B\x00... | The main task of the code is to flash a binary file to a hardware board via a serial port, optionally setting a new EUI-64 address. It parses command-line arguments, validates input, communicates with the device to erase flash memory, write firmware blocks, verify CRC integrity, and reset the board. Error handling and ... | def main():
parser = argparse.ArgumentParser(description=f"Nol.ja flasher for boards supported by Nol.A version {VersionInfo('nola_tools').release_string()}")
parser.add_argument('serial', nargs='?', help='A serial port connected with the board to be flashed (e.g., /dev/ttyUSB0, COM3, ...)')
parser.add_argu... |
def replace_bv_type(ast):
if type(ast) is not list:
return ast
if is_bv_type(ast):
return 'Int'
return [replace_bv_type(e) for e in ast]
def is_bv_type(ast):
return (type(ast) is list and
len(ast) == 3 and
ast[0] == '_' and
ast[1] == 'BitVec')
def infe... | The function `replace_bv_expr` processes an Abstract Syntax Tree (AST) to replace BitVec-related expressions with their corresponding representations. It recursively traverses the AST, modifying nodes like `declare-fun`, `define-fun`, `forall`, `exists`, and `let` to handle BitVec types. It updates symbol tables, infer... | def replace_bv_expr(ast, stacked_symbol_table):
if type(ast) is not list:
return ast
if ast[0] == 'declare-fun':
ast[2] = replace_bv_type(ast[2])
return ast
if ast[0] == 'define-fun':
stacked_symbol_table.insert(0, dict())
for arg in ast[2]:
stacked_symb... |
def extract_bv_widths(ast):
bv_widths = set()
def helper(ast):
if type(ast) is not list:
return
if ast[0] == '_' and ast[1] == 'BitVec':
bv_widths.add(int(ast[2]))
for e in ast:
helper(e)
helper(ast)
return bv_widths
def serialize(statement):
... | The code parses SMT-LIB syntax, extracts bit-vector widths, modifies AST nodes to replace expressions, inserts 'set-logic HORN' if missing, and prepends generated bit-vector functions. It processes input files, handles quoted strings, ignores comments, and outputs transformed statements with logic declarations and BV f... | def main(args):
i_expr = pp.QuotedString(quoteChar='"') | pp.QuotedString(quoteChar='|', unquoteResults=False)
s_expr = pp.nestedExpr(opener='(', closer=')', ignoreExpr=i_expr)
s_expr.ignore(';' + pp.restOfLine)
parser = pp.ZeroOrMore(s_expr)
ast = parser.parseFile(args.input_file, parseAll=True).a... |
def tree_to_str(self):
leaves = self.dfs(CATALOG_ROOT)
res = ''
for l in leaves:
res += self.get_path(l)
if l.is_dir:
res += '/'
else:
res += SEPARATOR + l.info
res += '\n'
return res
def make_req(self, *args):
fields = list(args)
res = ''
for f in fields:
res += f + SEPARATOR
res... | The code synchronizes files across multiple storages by comparing a file tree with stored files. It identifies missing files in each storage and extra, unlisted files. It then sends commands to remove extra files and fetch missing ones from other storages, ensuring consistency across all storage nodes. | def sync(self):
files = [f for f in self.tree_to_str().split('\n') if f != '']
files = [f.split(SEPARATOR)[0] for f in files if f[-1] != '/']
# print(self.storage_catalogs)
# print(files)
contained = self.storage_catalogs
missing = {}
extra = {}
for s in self.storages:
#check if storage is missing ... |
def parse_and_exec(self, message):
#dictionary with all possible functions
types ={'init':self.init,
'inf':self.info,
'crf':self.create,
'cpf':self.copy,
'mvf':self.move,
'rmf':self.delete,
'rmdir':self.deldir,
'mkdir':self.mkdir,
'opdir':self.opendir,
'rddir':self.readdir,
'... | The main task of the code is to handle client communication by receiving and processing messages, generating responses, and maintaining the connection until it is closed. It decodes incoming data, parses and executes commands, sends back structured responses, and continuously listens for new messages. Upon disconnectio... | def run(self):
mess = self.client_sock.recv(BUFFER_SIZE).decode('utf-8')
rtype, lenght, res = self.parse_and_exec(mess)
connected = True
while connected:
try:
resp = self.make_resp(rtype, str(lenght), res)
print(resp)
self.client_sock.send(resp)
mess = self.client_sock.recv(BUFFER_SIZE).decod... |
def discover(self):
self.storages = []
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(b'discovery', ('<broadcast>', DISCOVER_PORT))
def get_storage_catalogs(self):
self.... | The code initializes a daemon thread to listen for events, discovers storage devices, retrieves their catalogs, and enters a loop to periodically rediscover, update catalogs, and synchronize storage data, ensuring continuous monitoring and synchronization of storage information. | def explorer(self):
listener = Thread(target = self.listen, daemon=True)
listener.start()
self.discover()
time.sleep(1)
self.get_storage_catalogs()
while True:
time.sleep(1)
self.discover()
time.sleep(1)
print(self.storages)
self.get_storage_catalogs()
self.sync() |
def _write_nibble(self, nibble: int):
"""
Write a 4-bit nibble to the LCD.
param nibble: The 4-bit nibble to write.
"""
payload = HD447804BitPayload(e=1, rs=0, rw=0, data=nibble)
self.driver.write(payload)
payload = HD447804BitPayload(e=0, rs=0, rw=0, data=nibble... | This method initializes an HD44780 LCD in 4-bit mode by executing a standardized sequence: switching to 8-bit mode, sending repeated function set commands with timed delays, transitioning to 4-bit mode, configuring display settings (lines, font), clearing the display, and setting cursor movement direction. Delays ensur... | def _initialize(self):
"""
Initialize the LCD in 4-bit mode and clear the display.
This method performs the initialization sequence for the HD44780 driver
in 4-bit mode according to the datasheet. The sequence involves switching
to 8-bit mode first, repeating the 8-bit function ... |
def extract_json_from_folder(folder_path):
newest_json_file = None
newest_creation_time = 0
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.json'):
json_file_path = os.path.join(root, file)
creation_time = os.path.getc... | The main task of the code is to analyze JSON files from a specified folder by extracting text data, categorizing it, applying color coding to the results, and rendering them in an HTML template. If no JSON files are found, it returns an error message. | def analyse():
# Define the path to the folder containing JSON files
folder_path = 'policies'
# Extract JSON data from the folder
extracted_json = extract_json_from_folder(folder_path)
if extracted_json:
# Assuming your JSON data is stored in a dictionary under the key "text"
text ... |
def n(self, t):
'''
The baryon density as a function of unitless parameter t.
'''
term1 = (np.sinh(t/4))**3
term2 = (3*(np.pi**2)*((hbar_c/(m_n))**3))
nvalue = term1/term2
return nvalue
def pressure(self, n, i):
'''
outputs the pressure given the ... | The code implements a 4th-order Runge-Kutta method to numerically solve differential equations governing neutron star structure. It iteratively increases the radius (R) by step size h, calculating mass (u) and baryon density (t) until the baryon density (n) and pressure (p) become non-negative. The method uses an equat... | def runga(self, h, R0, t0, u0, i):
'''
performs the 4th order Runga Kutta, increasing the radius by h
until the baryon density and pressure greater than and equal
to 0. Returns the mass and radius of the neutron star for a particular
baryon density.
Parameters:
... |
def get_other_player(self, player):
if player == self.player1:
return self.player2
elif player == self.player2:
return self.player1
else:
raise ValueError("Invalid player name.")
def update_percentages(self,player):
otherPlayer = self.get_other_player(... | This function handles server faults during a tennis match. It checks if the player is the correct server, tracks first/second serve attempts, increments fault counters, and updates statistics. On a first fault, it records the fault and prepares for a second serve. On a second fault (double fault), it awards the point t... | def serve_fault(self, player:str):
"""
function to handle when a server misses a serve. If a point is lost because of a double fault, call the serve_fault() func 2 times to handle the point win/loss instead of the win_point() func
Parameters:
player (str): a string, the player who m... |
def get_other_player(self, player):
if player == self.player1:
return self.player2
elif player == self.player2:
return self.player1
else:
raise ValueError("Invalid player name.")
def update_percentages(self,player):
otherPlayer = self.get_other_player(... | The main task of the code is to update tennis match statistics when a player wins a point, tracking serves (first/second), aces, double faults, and shot types. It updates game/set scores, handles tiebreak logic, alternates serves, checks for game/set/match wins, and ensures no points are scored after a match concludes. | def win_point(self, player:str, how_won=[]):
"""
function to handle a player winning a point
Parameters:
player (str): name of the player who won the point.
how_won (list): an list of values on how the point was won, defaults to []. possible values include Ace, ... |
def get_other_player(self, player):
if player == self.player1:
return self.player2
elif player == self.player2:
return self.player1
else:
raise ValueError("Invalid player name.")
def update_percentages(self,player):
otherPlayer = self.get_other_player(... | This function handles a server's missed serve, tracking faults and determining point outcomes. It checks if the serving player is correct, increments fault counters, and updates statistics. On the first fault, it marks a second serve attempt. On the second fault (double fault), it awards the point to the opponent with ... | def serve_fault(self, player:str):
"""
function to handle when a server misses a serve. If a point is lost because of a double fault, call the serve_fault() func 2 times to handle the point win/loss instead of the win_point() func
Parameters:
player (str): a string, the player who m... |
def add_number_to_filename(file_name, number):
path = Path(file_name)
return Path.joinpath(
path.parent, f'{number}_{path.name}')
def csv_dict_reader(file_name: str, key_field):
result_table = {}
with open(file_name) as file_obj:
reader = csv.DictReader(file_obj, delimiter=',')
f... | This function parses CSV data from an uploaded sheet, checks if rows already exist in a parsed file, and updates or adds entries with parsed information (like watchers count and date) from URLs. It avoids reprocessing existing data unless necessary, splits tasks into parts using part_number, and writes results incremen... | def csv_parser(uploaded_sheet_file=UPLOADED_GSHEET_FILE,
parsed_file_name=PARSED_DATA_SET_FILE,
part_number=PARTS_NUMBER):
parsed_parted_file_name = add_number_to_filename(
parsed_file_name, part_number)
uploaded_sheet_file = add_number_to_filename(
uploaded_sheet_... |
def _get_evm_parameters(order, order_instrument, signer):
abi_types = []
evm_parameters = []
# account
abi_types.append('address')
evm_parameters.append(to_checksum_address(order['accountId']))
# originatorTimestamp
abi_types.append('uint64')
evm_parameters.append(to_int(order['timesta... | The code generates a digital signature for an order using Ethereum Virtual Machine (EVM) parameters. It retrieves ABI types and EVM parameters, computes a Keccak hash of the packed data, and signs the hash with the provided signer's key, returning the resulting signature for blockchain transaction validation or authent... | def sign_order(order, order_instrument, signer):
(abi_types, evm_parameters) = _get_evm_parameters(
order, order_instrument, signer)
# solidity pack into bytes
keccak_hash = _get_hash(abi_types, evm_parameters)
signature = sign(keccak_hash, signer)
return signature |
def one_by_one_with_splitting(lst, maxsum):
result = []
half_list = []
for i in set(lst):
cnt = lst.count(i)
half_list += ([i] * math.floor(cnt / 2))
solution = one_by_one_solution(half_list, maxsum)
rest_of_list = lst.copy()
for i in solution:
result.append(i.copy())
... | This function selects and executes an appropriate algorithm to process a list (`lst`) with a maximum sum constraint (`maxsum`), based on whether splitting is enabled (`splitting`) and the chosen algorithm type (`alg_type`, either "fast" or "best"). It routes to different implementations: `one_by_one_with_splitting`/`be... | def one_by_one_final(lst, maxsum, splitting, alg_type):
if splitting:
if alg_type == "fast":
return one_by_one_with_splitting(lst, maxsum)
elif alg_type == "best":
return best_one_by_one_with_splitting(lst, maxsum)
else:
if alg_type == "fast":
return o... |
def _validate_img(self, url, name):
self.img = self._decode(self.url)
#self.img = self._preprocess_img(img)
self.d = self._run_OCR(self.img)
result = self._scan(self.d)
if result[0] != -1:
self.status_code = 200 # OK- OCR detected income
self._income_idx... | The code validates user data by checking an image URL, verifying user attributes (age, CPF, income), determining renewability, and setting highlights. It handles exceptions, setting a 500 error status and capturing errors if validation fails. | def validate(self, url, name, income, age, cpf):
try:
self.name = name
self.url = url
self._validate_img(self.url, self.name)
if status_code != 400:
self.verified = self._check_verified(age, cpf, income)
self.renewable = self._check... |
def print_out(data, end='\n'):
datetimestr = str(datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S'))
print(Style.NORMAL + "[" + datetimestr + "] " + re.sub(' +', ' ', data) + Style.RESET_ALL,' ', end=end)
def update():
print_out(Fore.CYAN + "Just checking for updates, please wait...")
print... | This code initializes by validating a target domain, fetching its IP address, and checking if it belongs to the Cloudflare network. If the target is invalid or not on Cloudflare, it exits. It also ensures an "ipout" data file exists, creating it if necessary. | def init(target):
if args.target:
print_out(Fore.CYAN + "Fetching initial information from: " + args.target + "...")
else:
print_out(Fore.RED + "No target set, exiting")
sys.exit(1)
if not os.path.isfile("data/ipout"):
print_out(Fore.CYAN + "No ipout file found, fetching... |
def check_for_wildcard(target):
resolver = dns.resolver.Resolver(configure=False)
resolver.nameservers = ['1.1.1.1', '1.0.0.1']
#Unsure how exactly I should test, for now simple appending to target. Don't know how to extract only domain to append *. for wildcard test
try:
#Throws exception if no... | The main task of the code is to scan subdomains of a target domain by checking each potential subdomain's HTTP response and IP address. It reads a list of subdomains from a file, tests each by making HTTP requests, resolves IPs, and filters out Cloudflare network IPs. It reports found subdomains with their IPs and HTTP... | def subdomain_scan(target, subdomains):
i = 0
c = 0
if check_for_wildcard(target):
#If has wildcard or input N, return
print_out(Fore.CYAN + "Scanning finished...")
return
if subdomains:
subdomainsList = subdomains
else:
subdomainsList = "subdomains.txt"
... |
def b64decode(v):
return base64.b64decode(v.encode('utf-8')).decode('utf-8')
def api_zipget(hash, subname):
global ITEMS, ZIPVIEWS
view = get_zip_view(hash)
data = view.read(subname)
return data
def get_mimetype_from_name(name):
mimetype = mimetypes.guess_type(name)[0]
if mimetype == 'audio/... | The function `zipget` decodes a base64-encoded filename, retrieves data via `api_zipget` using a hash and decoded name, determines the MIME type from the filename, and returns the data as an HTTP response with appropriate content type and status code. | def zipget(hash, b64name):
subname = b64decode(b64name)
data = api_zipget(hash, subname)
mimetype = get_mimetype_from_name(subname)
resp = Response(data, 200, mimetype=mimetype, content_type=mimetype, direct_passthrough=True)
return resp |
def log(string: str):
print(f'{time.time()}: {string}')
def update_clients():
set_state(get_state())
def set_state(state: str):
log(f'Setting state to {state}')
for i in ids:
client.publish(f'shellies/shelly1-{i}/relay/0/command', state) | This function handles changes to the automatic temperature control system's active status. It updates a global 'active' state based on the received message payload, logs the status change, and triggers either client updates (if active) or a state transition to 'off' (if inactive). | def handle_active_change(message):
global active
active = message.payload == b'true'
log(f'Automatic temperature control is {"active" if active else "disabled"}')
if active:
update_clients()
else:
set_state('off') |
def handle_set(message):
global desired_temp
try:
desired_temp = float(message.payload)
log(f'Got desired temperature: {desired_temp}')
update_clients()
except Error as e:
log(e)
def handle_temperature_change(message):
global temperature
try:
temperature = flo... | This function processes incoming MQTT messages by routing them to specific handlers based on their topic. It directs temperature set commands, temperature changes, auto-mode adjustments, auto-time settings, and heater state updates to respective functions, while logging unhandled topics for debugging. | def on_message(client, userdata, message):
if message.topic == 'temperature/set':
handle_set(message)
elif message.topic == 'temperature/inside':
handle_temperature_change(message)
elif message.topic == 'temperature/auto':
handle_active_change(message)
elif message.topic == 'temp... |
def irt(train_data, val_data, lr, iterations, num_subjects, version):
""" Train IRT model.
:param train_data: A dictionary {user_id: list, question_id: list,
is_correct: list, subject_ids: list[list[int]]}
:param val_data: Same as train_data but for validation set.
:param lr: float
:param i... | The code trains an Item Response Theory (IRT) model using provided datasets (train, validation, test) and question metadata. It processes subject IDs from questions, updates datasets with these IDs, and trains the IRT model with specified learning rate and iterations. Depending on the version (1, 2, or 3), it uses diff... | def train(train_data, val_data, test_data, question_meta, lr, iterations, version):
all_subject_ids = []
question_id_to_subject_ids = {}
for question_id, subject_ids in question_meta:
question_id = int(question_id)
subject_ids = subject_ids.strip('][').split(', ')
subject_ids = [int(... |
def load_question_meta(path):
with open(path, 'r') as f:
reader = csv.reader(f)
next(reader)
question_meta = []
for line in reader:
question_meta.append(line)
return question_meta
def train(train_data, val_data, test_data, question_meta, lr, iterations, version):
... | The main task of the code is to experiment with different learning rates and training iterations for four model versions (v0-v3) on a question-answering dataset. It loads training/validation/test data, trains each model variant, records accuracy and negative log-likelihood metrics, and generates comparison plots showin... | def main():
os.makedirs('./part_b_images', exist_ok=True)
# TODO: Change .. to .
train_data = load_train_csv("./data")
val_data = load_valid_csv("./data")
test_data = load_public_test_csv("./data")
question_meta = load_question_meta("./data/question_meta.csv") # list of length # questions
... |
def build_r_graph(N, p_i, p_o, gs):
np.random.seed()
random.seed(7) # 5 6 7
#98
matr = [[0 for i in range(N)] for j in range(N)]
sz = N//gs
for i in range(N):
for j in range(N):
if i == j:
pass
else:
ran = random.r... | The main task of the code is to analyze a graph's structure by computing its Laplacian eigenvalues and eigenvectors, identifying the second smallest eigenvalue, reordering the graph based on the corresponding eigenvector, and evaluating the graph's quality. It also measures execution times for key steps and optionally ... | def run_part(N, plot = False):
G = build_r_graph(N, .5, .1, 4)
lapl = m_laplacian(G)
st = time.time()
w, v = np.linalg.eigh(lapl)
ei_v = np.argsort(w)
tim_e = time.time() - st
w_sort = w[ei_v]
uniq = set(abs(w))
uniq.remove(min(uniq))
neg = np.where(w == min(uniq))[0]
pos ... |
def str_to_date(strdate: Union[str, any], dateformat: str = DATEFORMAT) -> any:
"""
String to date.
Args:
strdate (Union[str, any]): The string date encoded by the dateformat.
dateformat (str, optional): The format of the date. Defaults to DATEFORMAT.
Returns:
any: Datetime obj... | The function `year_month_day_lists` generates structured date ranges (as nested lists) for the CDS API, breaking input start/end dates into yearly/monthly segments with day lists. It handles multi-year and multi-month spans by recursively splitting ranges, ensuring inclusive counting of days, and formatting dates as st... | def year_month_day_lists(
startdate: Union[np.datetime64, str], enddate: Union[np.datetime64, str]
) -> List[Union[str, List[str]]]:
"""
Month Day lists for running cds api.
!Inclusive counting!
If str formatted as '%Y-%m-%d'
Args:
startdate (np.datetime64): Start date.
enddat... |
def create_X_tensor_elo(play_track_df, prob_tackle):
'''
Creates X input tensor for elo model.
Acknowledgement: This function as adapted from code written by Gordeev and Singer for their model.
https://www.kaggle.com/jccampos/nfl-2020-winner-solution-the-zoo
Inputs:
play_tr... | The function `get_input_data_elo` prepares training and test tensors for machine learning models using play-tracking data. It generates input features (`X_tensor`) and target labels (`y_tensor`) for either kickoffs or punts, splits them using preloaded indices, and saves tensors if specified. Key steps include creating... | def get_input_data_elo(play_track_df, output_tag, min_idx_y, max_idx_y, prob_tackle, test_size=0.1, save_tensors=True):
'''
Create the X and y train and test tensors for either kickoffs or punts
Inputs:
play_track_df: dataframe with all data needed for the model. Each row in the df
... |
def process_play_data(df_plays):
'''
Get the necessary columns from the plays dataframe and select only the rows that are for kickoffs where there
was actually a return on the play
'''
kick_plays_df = df_plays[((df_plays["specialTeamsPlayType"] == "Kickoff") | (df_plays["specialTeamsPlayType"] == ... | The function calculates Elo ratings for returners and tacklers using combined tracking, play, and PFF data, merges player matchups, applies weighted Elo scoring, and compiles results into a DataFrame (`all_elos_df`) storing tackle ratings for export. | def calculate_and_save_elos():
'''
Calculate elo rating for returners and tacklers. Save to csv
Return:
all_elos_df: dataframe which shows the tackle ratings
'''
df_tracking = pd.concat([df_track_2018, df_track_2019, df_track_2020])
kick_plays_df = process_play_data(df_plays)
pff_ta... |
def parse_socket_object(self, connection: socket, parsed_format: str) -> str:
"""
Parse a given socket object to a custom format.
Mainly for logging and printing purposes.
:param connection: For the socket to parse.
:param parsed_format: For the format to parse to.
:retur... | The main task of the code is to process a client's registration request by receiving and unpacking the request packet, extracting the client's username, updating RAM templates with the username, logging the process, and invoking further registration logic. It handles errors by logging exceptions and appending error mes... | def process_register_request(self, connection: socket, client_template: dict,
files_template: dict, summery: list) -> None:
"""
Processing registration request with a given client.
:param connection: For the client connection.
:param client_template: For ... |
def receive_packet(self, connection: socket) -> bytes:
"""
Main receive method, receives client packet and return it for unpacking purposes.
:param connection: For the clients connection to receive from.
:return: The received packet.
"""
receive_message = self.parse_socke... | This function handles CRC validation for client file uploads by receiving and verifying CRC values. It updates server databases and RAM templates upon successful validation, logs results, and either accepts the file or removes it if CRC fails repeatedly. The loop allows multiple attempts, with specific actions for vali... | def handle_crc_request_logic(self, connection: socket, username: str, file_name: str, file_path: str,
file_crc: str, client_template: dict, files_template: dict, summery: list) -> None:
"""
Auxiliary method to handle all CRC request protocol logic.
:param connect... |
def findGears():
gears = []
for i in range(0, len(data)):
for j in range(0, len(data[0])):
if grid[i][j] == '*':
gears.append(point(i,j))
return gears
def findNeighbourNumbers(i,j):
neighbours = []
foundUp = False
foundDown = False
# Check up
neighbour... | The code calculates gear ratios by finding neighboring numbers for each gear. It checks if exactly two valid neighbors exist, multiplies their values, and collects these products in a list. If a gear has fewer or more than two neighbors, it's skipped. The function returns the list of valid gear ratios. | def getGearRatios():
ratios = []
gears = findGears()
for gear in gears:
ratio = 1
neighbours = findNeighbourNumbers(gear.i, gear.j)
count = 0
for n in neighbours:
if n is not None:
count += 1
if count != 2:
continue
... |
def hex_to_bytes(val):
if not val:
return []
val = val.strip()
if val.startswith('0x'):
val = val[2:]
num_bytes = len(val) // 2
bytes_ = []
for i in range(num_bytes):
bytes_.append(int(val[i*2:i*2+2], 16))
return bytes_
def parse_positional_data(buffer):
flags = ... | The function `parse_sigfox` decodes Sigfox data packets by converting hex input to bytes, extracting a record type from the first byte, and routing the data to specialized parsers for positional data, downlink acknowledgments, device statistics, or extended positional data based on the record type. It returns parsed re... | def parse_sigfox(data):
buffer = hex_to_bytes(data)
if not buffer:
return None
record_type = buffer[0] & 0x0f
if record_type == 0: #positional data
return parse_positional_data(buffer)
elif record_type == 1: #downlink ACK
return parse_downlink_ack(buffer)
elif record_t... |
def connect():
"""
Explanations: Connect to socket.
Returns: client_socket (socket object).
"""
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((SERVER_IP, SERVER_PORT))
return client_socket
def login(socket_connection):
"""
Explanations: Logi... | The main task of the code is to implement a client-side application that connects to a server, authenticates the user, and provides a menu-driven interface for interacting with the server. The client can play questions, retrieve personal scores, view high scores, check logged users, and logout, all through a loop that ... | def main():
client_socket = connect()
print("[CLIENT] Server is Up and Running ...")
login(client_socket)
while True:
print("==============================")
print("P | Play Question ")
print("S | Get My Score ")
print("H | Get High Sco... |
def load_questions_from_web():
"""
Explanations: Get questions from Web Page.
Example :
questions = {
2313 : {"question": "How much is 2 + 2" , "answers": ["3", "4", "2", "1"] , "correct": 2},
4122 : {"question": "What is the capital of France ?", "answers": ["Lion", "... | The code implements a trivia server that manages client connections, processes incoming messages, handles user interactions, and broadcasts responses using a multi-socket communication model with select() for asynchronous handling. It initializes user data and questions, accepts client connections, processes commands, ... | def main():
# Initializes global users and questions dictionaries using load functions, will be used later #
global users
global questions
global messages_to_send
print("Welcome to Trivia Server !")
questions = load_questions_from_web()
users = load_user_database()
server_socket = setup_sock... |
def updateHWND(self,hwnd):
rect = win32gui.GetWindowRect(hwnd)
x, y, right, bottom = rect
# width = right - x
# height = bottom - y
self.hwndX = rect[0] + 8
self.hwndY = rect[1] + 30 + 1
def clickOrigin(self):
pydirectinput.moveTo(self.hwndX,self.hwndY)... | The code automates game interactions by continuously updating window positions, activating the game window, detecting chat toggles, and controlling player movements to harvest items from chests. It handles left/right chest interactions, triggers movement, navigates GUI elements, and exits chest interfaces, looping unti... | def run(self):
sleep(1)
# TODO: you can write your own time/iterations calculation to determine how fast this is
while not self.stopped:
#Update Hwnd position
self.updateHWND(self.hwnd)
#Activate window
self.clickOrigin()
... |
def generate_keypair(self, hash_type, key_size_curve, admin):
try:
with open('./config.yaml') as f:
config = yaml.load(f, Loader=yaml.FullLoader)
except FileNotFoundError:
print('ERROR in reading config file: ')
traceback.print_exc()
os.makedi... | The code initializes a blockchain node by setting up key pairs, generating a unique node ID, creating a genesis block, and initializing structures for transactions, applications, and the blockchain. It configures the node's address, submits an initial transaction, and prepares the digital signature system for subsequen... | def __init__(self, argms):
self.args = argms
self.transactions = []
self.applications = []
self.chain = []
self.nodes = set()
# Generate random number to be used as node_id
self.node_id = str(uuid4()).replace('-', '')
# Create genesis block
self.p... |
def _check_oma_output_path(self):
"""
This method analysis how the standalone_path argument is used:
1. OmaStandalone run, and standalone_path points to base folder
2. OmaStandalone run, but standalone_path points to output folder
3. Marker gene export, standalone_path poin... | The code initializes the OMAOutputParser class by configuring parameters, checking output paths, estimating species numbers, handling ignored species, and loading OGS data for processing. It sets up attributes like `args`, `mode`, `oma_output_path`, and `ogs`, while determining `min_species` and managing species exclus... | def __init__(self, args):
'''
Initialise the OMAOutputParser
'''
self.args = args
self.mode = ''
self.oma_output_path = self._check_oma_output_path()
self.num_selected_ogs = 0
self.num_species = 0
self.min_species = self._estimate_best_number_spec... |
def render_compositing(self, view_matrix: np.ndarray, volume: Volume, image_size: int, image: np.ndarray,
step=1):
# Clear the image
self.clear_image()
u_vector = view_matrix[0:3].reshape(-1, 1)
v_vector = view_matrix[4:7].reshape(-1, 1)
view_vector = ... | This function renders volumetric data of a mouse brain using compositing techniques. It selects between three modes: rendering a specified region (option 0), whole-brain energy data (option 1), or region-specific energy data (option 2). The function initializes gradient magnitude values, processes input volumes, and ap... | def render_mouse_brain(self, view_matrix: np.ndarray, annotation_volume: Volume, energy_volumes: dict,
image_size: int, image: np.ndarray):
self.tfunc.init(0, math.ceil(self.annotation_gradient_volume.get_max_gradient_magnitude()))
magnitudeVolume = Volume(self.annotation_gra... |
def getGaussExpected(nparr, x, y):
maxloc = np.argmax(y)
maxlocx = x[maxloc]
ymax = np.max(y)
return [maxlocx,20,ymax]
def least_squares(params, x, y):
l = 0
for xcord, ycord in zip(x, y):
if (len(params) == 3):
l += (gauss(xcord, params[0], params[1], params[2]) - ycord) ** ... | This function fits a Gaussian distribution to data in a specified column of a table using least squares optimization, plots the histogram and fitted curve, and returns the optimized parameters along with their standard deviations. It calculates initial expected parameters if not provided, performs curve fitting, comput... | def gaussGraph(col, table, expected=None):
nparr = np.asarray(table[col].tolist())
y,x,_=hist(nparr,100,alpha=.3,label='data')
x=(x[1:]+x[:-1])/2
if expected is None:
expected = getGaussExpected(nparr, x, y)
print(expected)
params,cov=curve_fit(gauss,x,y,expected)
sigma=sqrt(diag(cov... |
def getBimodalExpected(nparr, x, y):
'''Get's an exected bimodal tuple from the data to be passed into scipy's curve fit fn.
Procedure:
1. Find the peak of zeros (largest peak within the first half of data)
2. Find the min in the first half (end of first normal, start of second)
3. Find... | This function generates a bimodal histogram of a column from a table using 100 bins, fits two Gaussian curves to the data via least squares optimization, and returns the fitted parameters (means, standard deviations, amplitudes) along with their uncertainties. It uses expected initial parameters if provided, otherwise ... | def bimodalGraph(col, table, expected=None): #change bins?
'''Bimodal Graph for histogram of col from table with 100 bins.
Based upon: https://stackoverflow.com/questions/35990467/fit-two-gaussians-to-a-histogram-from-one-set-of-data-python
'''
nparr = np.asarray(table[col].tolist())
y,x,_=hist(npar... |
def render_button(self):
"""Render a push button using the properties of this renderer"""
return f""""""
def render_checkbox(self):
"""Render a checkbox using the properties of this renderer"""
return f"""<input type='checkbox' {self.render_basic_attrs()} {self.render_value_checked_if()}... | This code renders HTML form elements based on the `self.type` attribute by calling specific rendering methods for each known input type (e.g., button, checkbox, text). If the type is unrecognized, it raises a ValueError. The main task is to dynamically generate appropriate UI components according to the specified input... | def render(self):
if self.type == 'button':
return self.render_button()
if self.type == 'checkbox':
return self.render_checkbox()
if self.type == 'file':
return self.render_file()
if self.type == 'password':
return self.render_password()
... |
def _green(str):
print(colors.GREEN + str + colors.ENDC)
def filter_large_gradle():
_yellow("==start==")
replace(LARGE_GRADLE_FILE,REPLACEMENT_DICT_1)
## now that jcenter is gone, remove it
_yellow("==end==")
def filter_gradle_wrapper():
_yellow("==start==")
replace(GRADLE_WRAPPER_FILES,REPL... | The code processes multiple Gradle-related files in a project. It checks for the existence of a large `build.gradle` file, the `gradle-wrapper.properties` file, and the `app/build.gradle` file. If found, it applies specific processing functions (`filter_large_gradle`, `filter_gradle_wrapper`, `filter_app_build_gradle`)... | def main():
## 1. process large build.gradle file
if(os.path.exists(LARGE_GRADLE_FILE)):
_green ('start processing File {0} {1}'.format(LARGE_GRADLE_FILE,"===="))
filter_large_gradle()
else:
_green ('File {0} {1}'.format(LARGE_GRADLE_FILE,"not exists"))
### 2. process gradle-war... |
def _load_spreadsheet(self, modality, na=None, fix_anon=True):
title = defaults.spreadsheets[modality]['spreadsheet']
key = defaults.spreadsheets[modality]['key']
accept_spreadsheet = False
info = ()
for attempt in range(max(0, defaults.retry_attempts)):
info = self._... | This function processes MDS-UPDRS data by loading and cleaning spreadsheet data, mapping session IDs, converting relevant columns to numeric values, calculating scores for three parts (I, II, III) with missingness indicators, filtering invalid rows, and optionally returning a concise version with only key session IDs, ... | def import_mds_updrs(self, concise=True):
data = self._load_spreadsheet(modality='mds_updrs',
na=['na', 'NA', 'NA1', 'NA2', 'NA3', 'NA4', 'NA5', 'NA6', 'UR', '', 'None', None])
data = self._map_to_universal_session_id(data)
for col in data.columns[data.col... |
def _load_spreadsheet(self, modality, na=None, fix_anon=True):
title = defaults.spreadsheets[modality]['spreadsheet']
key = defaults.spreadsheets[modality]['key']
accept_spreadsheet = False
info = ()
for attempt in range(max(0, defaults.retry_attempts)):
info = self._... | This function imports and processes HADS (Hospital Anxiety and Depression Scale) data by loading a spreadsheet, cleaning NA values, dropping precomputed totals, mapping session IDs, calculating anxiety and depression scores from individual questions, renaming columns, and optionally returning a concise version with onl... | def import_hads(self, concise=True):
data = self._load_spreadsheet('hads', na=['NA', 'NA1', 'NA2', 'NA3', 'NA4', 'NA5', 'NA6', '', None])
data = data.drop(columns=['anxiety_total', 'depression_total'])
data = self._map_to_universal_session_id(data)
data = data.assign(HADS_anxiety=data[[... |
def _load_spreadsheet(self, modality, na=None, fix_anon=True):
title = defaults.spreadsheets[modality]['spreadsheet']
key = defaults.spreadsheets[modality]['key']
accept_spreadsheet = False
info = ()
for attempt in range(max(0, defaults.retry_attempts)):
info = self._... | This function imports and processes session data by loading spreadsheet information, transforming date and scan number fields, filtering sessions based on exclusion criteria, merging with participant birth dates to calculate age, and returning a structured DataFrame sorted by subject and session date. | def import_sessions(self, from_study=None, exclude=True):
data = self._load_spreadsheet(modality='sessions', na=('', 'None', None))
data = data.astype({'date': 'datetime64', 'mri_scan_no': 'UInt64'}).astype({'mri_scan_no': str})
data['mri_scan_no'] = data.apply(lambda x: '' if x.mri_scan_no == ... |
def getArtistId(self, artistName:str) -> int:
printInfo("Searching for: " + artistName)
self.handleRateLimit()
response = requests.get('https://itunes.apple.com/search?term=' + artistName + '&entity=allArtist&attribute=allArtistTerm&country=' + self.country)
if response.ok:
o... | The main task of the code is to process music files in specified folders by retrieving artist and album information, tagging songs accordingly, and reporting results. It validates the artist's existence, checks for associated albums, iterates through folders (either a single specified folder or all subfolders), and log... | def main(self) -> bool:
artistID = self.getArtistId(self.folder.split("/")[-1])
if artistID == -1:
printError("Artist not found.")
return False
albums = self.getAllAlbumsByArtist(artistID)
if len(albums) == 0:
printError("Albums not found")
... |
def printHelp(self):
print("USAGE: explicit.py <Path to Artist Folder> [-m] [-co COUNTRYCODE]")
print("-m (Optional): Try to suggest options for unknown albums/songs")
print("-co [COUNTRYCODE] (Optional): Search in the store of the selected country. Default: us")
print("-a (Optional): Ap... | The code initializes a class to process music files by parsing command-line arguments for folder paths, country codes, search modes, and renaming options. It sets up data structures to track tagged songs and errors, checks for required inputs, and triggers the main processing logic. | def __init__(self):
initPrint()
self.taggedSongs = []
self.errorSongs = []
self.folder = ""
self.country = "us"
if len(sys.argv) == 1:
self.printHelp()
return
self.requestCount = []
self.checkMode = False
self.exactSearch = ... |
def milk_window(df, n_splits=24, n_before=1, n_after=2):
"""
Gets time windows for morning and evening for one group.
Parameters
----------
df : pd.dataframe
should be from only one group.
n_splits : integer, optional
number of splits to split day in. The default is 48.
n_be... | The function processes a dataframe to analyze morning and evening activity periods, validating entry/exit points against geographic areas. It filters valid entries, calculates positions, and aggregates results into a structured DataFrame containing entry/exit times and positions for both periods, indexed by tag IDs. | def summary_dataframe(df, area_dict):
morning, evening = milk_window(df, n_before=2, n_after=3)
entry_morning, exit_morning = entry_exit(morning)
morning_valid = False
while morning_valid is not True:
first_key, first_time = next(iter(entry_morning.items()))
if vali... |
def _fetch_test_descriptions(description_files_root_path, pattern=None):
description_files = _get_description_files(description_files_root_path, pattern)
descriptions = {}
for description_file in description_files:
test_short_name = description_file.split('/')[-2]
description = None
... | The main task of the code is to generate a report using a provided processing engine. It fetches test case descriptions, optionally filters tests, runs the processing engine if no pre-defined results are given, and renders the report in the specified format (e.g., PDF, MD) to the designated output folder. The function ... | def make(processing_engine, description_files_root_path=DATASET_PATH,
output_folder='.', report_name='report.pdf', results=None,
runby='zbrrt@example.com', tests=[], pattern=None):
"""
Make a report using the provided processing engine
:params processing_engine: a method that acce... |
def register_agent(self):
"""Register BlueHandler as the default agent"""
manager = dbus.Interface(
self.bus.get_object(SERVICE_NAME, "/org/bluez"), "org.bluez.AgentManager1"
)
manager.RegisterAgent(BlueHandler.AGENT_PATH, self.capability)
manager.RequestDefaultAgent(... | This code initializes a Bluetooth agent to monitor and manage media players via D-Bus. It sets up signal handlers for property changes, discovers devices, and connects to them asynchronously. The main tasks include registering the agent, detecting available players, and handling device interactions through D-Bus commun... | def __init__(
self,
bus,
loop,
updatePlayer,
capability="NoInputNoOutput",
discoverTimeout="180",
):
"""Initialize gobject and find any current media players"""
self.capability = capability
self.update_player = updatePlayer
self.bus = b... |
def has_changed(self):
return any([item.changed() for item in self.menu])
def update_settings(self) -> None:
for item in self.menu:
if item.key in settings:
update_setting(item.key, item.value)
save_settings()
def get_settings_menu():
settings_menu = [
Set... | This code processes user input events in a menu system. It navigates menu options with arrow keys, triggers saving settings when "Save" is selected, displays an escape dialog on ESC if changes exist, and reverts to the last state if no changes. It delegates input to the escape dialog if visible, otherwise handles key p... | def handle_input(self, events):
for event in events:
if self.escdialog.visible:
self.escdialog.handle_input(events)
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
self.selected = (self.selected + 1) % len(self.menu)
... |
def __log(self, message):
if self.silent:
return
print("CCC: {}".format(message))
def hb(self) -> Optional[Tuple[str, str]]:
try:
answer = self.sender.query(client_to_serv["HB"], "TXT", source_port=self.source_port)
if len(answer.response.answer[0]) > 1:
... | This method handles heartbeat (HB) responses by invoking `self.hb()`, checking the result, and reacting to specific signals. If no response is received, it logs an error. For "NOP" (no operation), it logs and exits. For "SD" (shutdown), it logs and stops the process. Otherwise, it executes the command using `carry_out_... | def do_send_hb(self):
self.__log("HB")
res = self.hb()
if res is None:
self.__log("No HB response!")
return
answer, arg = res
if answer == serv_to_client["NOP"]:
self.__log("NOP")
return
elif answer == serv_to_client["SD... |
def server_registration(self):
"""
Initializes communication with the server.
"""
ret = self.hb()
if ret is None:
return False
answer, arg = ret
return answer == serv_to_client["ACK"]
def __log(self, message):
if self.silent:
retur... | The main task of the code is to run a loop that maintains a connection to a server by registering initially, then continuously sending heartbeats or data while the process is active. It checks for running status, handles registration failure, and alternates between sending heartbeat signals and data payloads in a recur... | def run(self):
if self.running:
return
self.running = True
# Register with the server:
if not self.server_registration():
self.__log("We got an invalid response for our initial heartbeat! Shutting down...")
self.stop()
return
# In... |
def removespaces(input):
nospaces = input.strip() #Gets rid of the spaces before and after the string
return nospaces
def checkparentheses(input):
count = 0
for token in input:
if(token == ')' or token == '('):
count = count + 1
#If the parenthesis count is even, that means ... | This program allows users to convert infix arithmetic expressions to postfix notation or evaluate infix expressions. It checks for balanced parentheses and repeatedly presents a menu until the user chooses to quit. | def main():
#Introduction:
print("\nThis program converts infix arithmatic expressions to postfix expressions.")
print("It also evaluates infix expressions.")
#Menu:
print("\nPlease choose the operation: ")
print("1. Convert an infix expression to its equivalent postfix expression form")
... |
def create_config(username, password):
user_data = {
"username": username,
"password": password
}
with open('config.json', 'w') as f:
f.write(json.dumps(user_data, indent=4))
return user_data
def login():
print("=" * 100)
zmethod = "login"
print(zmethod.center(70))
... | The code's main task is to parse command-line arguments, handle login authentication by creating or reading a configuration, initialize a session with a ZedControl API, and execute user or enterprise-related operations based on provided arguments. It uses global session management, handles login errors, and conditional... | def main():
global zsession
try:
args = docopt(usage)
except Exception as e:
print(e)
base_url = "https://zedcontrol.hummingbird.zededa.net"
if args['login']:
user_config = create_config(args['--username'], args['--password'])
zsession = zapi(base_url, user_config)
... |
def convertToDeployment(**kwargs):
"""
Method convert docker compose to kubernetes pod definition
"""
compose_file = kwargs['<docker-compose-resource.yaml>']
cmd = f"kompose --file {compose_file} convert"
with subprocess.Popen(cmd.split(" "), stdout=subprocess.PIPE) as proc:
output, erro... | The main task of the code is to handle command-line arguments for converting Kubernetes definitions to deployment or application configurations. It uses `docopt` to parse inputs, processes YAML files for pod, service, and configmap definitions, and invokes `convertToDeployment` or `convertToApp` accordingly. If convers... | def main():
"""
Main Method
"""
try:
args = docopt(usage)
except Exception as docopt_error:
print(docopt_error)
if args['convert']:
status = convertToDeployment(**args)
if status != 0:
print("Conversion failed")
sys.exit(1)
elif args['... |
def parse_args():
parser = argparse.ArgumentParser(description='Testing')
parser.add_argument(
'--driver_model_path',
default="./checkpoint/snapshot/checkpoint.pth.tar",
type=str)
parser.add_argument(
'--road_side_input_video_path',
type=str,
required=True)
... | The code processes driver and road inputs, updates driver states, evaluates stop sign compliance using a strategy, and calculates accuracy against labeled data if specified. It outputs final states, safety status, and evaluation metrics like stop sign detection and gaze directions. | def main(args):
args = parse_args()
driver_state = DriverState()
process_driver_view_input(args, driver_state)
process_road_view_input(args, driver_state)
process_speed(args, driver_state)
print("============ Final driver states ===============")
for s in driver_state.states:
print... |
def search_prime(index):
step = len(primes)
number = primes[-1]
while step != index:
number += 1
prime = True
for s in range(1, len(primes) - 1):
if (number % search_prime(s)) == 0:
prime = False
break
if prime:
step +... | The main task of the code is to generate RSA public and private key pairs. It selects two primes based on random bases, computes their product as the modulus, generates exponents for public and private keys, and verifies cryptographic properties like coprimality and modular inverses. The function returns validated key ... | def keygen(base1=random.randint(3, 20), base2=random.randint(5, 20)):
import fractions
p = search_prime(base1)
q = search_prime(base2)
product = p * q
publick = public_key(product)
privatek = private_key(publick)
t = phi(product)
assert fractions.gcd(publick[0], t) == 1
assert pu... |
def getHitmask(image):
mask = []
for x in xrange(image.get_width()):
mask.append([])
for y in xrange(image.get_height()):
mask[x].append(bool(image.get_at((x, y))[3]))
return mask
def showWelcomeAnimation():
playerIndex = 0
playerIndexGen = cycle([0, 1, 2, 1])
loopIte... | The main task of the code is to initialize and run a Flappy Bird game using Pygame. It sets up the game window, loads assets (backgrounds, player, pipes, numbers), generates random visual elements, creates collision masks, and executes the game loop by calling functions for the welcome animation, main gameplay, and gam... | def main():
global SCREEN, FPSCLOCK
pygame.init()
FPSCLOCK = pygame.time.Clock()
SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))
pygame.display.set_caption('Flappy Bird')
IMAGES['numbers'] = (
pygame.image.load('assets/sprites/0.png').convert_alpha(),
pygame.image.... |
def getHitmask(image):
mask = []
for x in xrange(image.get_width()):
mask.append([])
for y in xrange(image.get_height()):
mask[x].append(bool(image.get_at((x, y))[3]))
return mask
def showWelcomeAnimation():
playery = int((SCREENHEIGHT - IMAGES['player'][0].get_height()) / 2)... | This code initializes a Flappy Bird game by setting up Pygame, loading assets (images, hitmasks), and running the game loop. It randomly selects backgrounds, player sprites, and pipes, then executes the welcome animation, main game logic, and game-over screen to manage gameplay flow and collision detection. | def main():
global SCREEN, FPSCLOCK
pygame.init()
FPSCLOCK = pygame.time.Clock()
SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))
pygame.display.set_caption('Flappy Bird')
IMAGES['numbers'] = (
pygame.image.load('assets/sprites/0.png').convert_alpha(),
pygame.image.... |
def _create_clusters(self, centroids, k):
"""
Assign the samples to the closest centroids to create clusters
Input: centroids values of all features, no of k
Output: indices of all samples per each centroid/k
"""
clusters = [[] for _ in range(k)]
for ... | The code performs KMeans clustering on input data to determine optimal cluster numbers using the elbow method. It iterates over k=1 to 7, running multiple KMeans iterations for each k to find centroids minimizing the J metric (inertia). When consecutive k's J improvement falls below a threshold, it plots clusters for s... | def predict(self, X):
"""
Initialize KMeans class that will run the clustering algorithm
Input: Input data
Output: result data shown in label, no of clusters
"""
self.X = X
self.n_samples, self.n_features = X.shape
# Elbow method:
j_dif... |
def all_valid_moves(en_passant, piece_type,piece_color,row,col,board):
"""
Returns a list of valid moves for a given chess piece at a given position on the board.
piece_type: the type of piece ("king", "queen", "rook", "bishop", "knight", or "pawn")
piece_color: the color of the piece ("white" or "black... | The function highlights valid moves for a chess piece on a board using Pygame, including special castling moves for the king. It checks conditions like king/rook movement history, clear paths, and safety from enemy attacks. Valid moves are drawn as green rectangles, with castling moves highlighted in blue if applicable... | def highlight_valid_moves(piece_type, piece_color, row, col, board):
"""
Highlights all valid moves for a given chess piece at a given position on the board.
piece_type: the type of piece ("king", "queen", "rook", "bishop", "knight", or "pawn")
piece_color: the color of the piece ("white" or "black")
... |
def stalemate(board):
"""
determines if the game is a stalemate, if the king is not in check,
and no moves can be made returns True
"""
no_moves = True
valid_moves = []
in_check, rows, cols, king_color = check(board)
if not in_check:
for row in range(8):
for col in r... | The function `game_over` determines if a game has ended by checking for stalemate, checkmate, or a draw conditions on the given board, returning `True` if any of these end-game scenarios are met, otherwise `False`.) | def game_over(board):
"""
if the game ends by stalemate,chckmate of draw, returns true otherwise false
"""
if stalemate(board) or checkmate(board)[0] or draw(board):
return True
return False |
def blue(text):
return '\N{ESC}[34m' + text + '\N{ESC}[0m'
def bold(text):
return '\N{ESC}[1m' + text + '\N{ESC}[0m'
def take_time(min_days : int, max_days: int):
global days_from_start
global lbs_of_food
global player_health
days_passed =0
days_to_pass = random.randrange(min_days, max_... | The function `travel()` simulates a journey where the traveler's progress is affected by random events. If specific conditions are met (November, 1500+ miles traveled, and a 20% chance), a blizzard halves the distance traveled, adding 15-30 miles. Otherwise, 30-60 miles are added. It updates total miles, prints progres... | def travel():
global miles_traveled
if (
month_cal[days_from_start] >= 11 and
miles_traveled >= 1500 and
random.randrange(1, 11) <= 2
):
print(blue("You got caught in a blizzard in the Sierra Nevadas... 🥶 The distance you traveled is halfed."))
# add between ... |
def take_time(min_days : int, max_days: int):
global days_from_start
global lbs_of_food
global player_health
days_passed =0
days_to_pass = random.randrange(min_days, max_days + 1)
while days_passed < days_to_pass:
days_from_start = days_from_start + 1
days_passed = days_pass... | The code simulates resting by increasing player health by 1 (unless already at max 5) over a random 2-5 day period, while consuming food. It updates and displays health status after resting. | def rest():
global player_health
days_this_rest = take_time(2, 5)
eat_food(days_this_rest, 3)
if player_health == 5:
print("Your health stayed at " + bold(str(player_health)) + " health while resting for " + bold(str(days_this_rest)) + " days.")
else:
player_health = player... |
def travel():
global miles_traveled
if (
month_cal[days_from_start] >= 11 and
miles_traveled >= 1500 and
random.randrange(1, 11) <= 2
):
print(blue("You got caught in a blizzard in the Sierra Nevadas... 🥶 The distance you traveled is halfed."))
# add between ... | The code defines a function `take_action` that processes user input to execute game actions like traveling, hunting, resting, checking status, or quitting. It calls specific functions for each action, displays player stats for "status," and validates inputs, prompting valid options if unrecognized. | def take_action(action):
if action == "travel":
travel()
elif action == "hunt":
hunt()
elif action == "rest":
rest()
elif action == "status":
print ("You have traveled " + bold(str(miles_traveled)) + " miles for " + bold(str(days_from_start)) + " days.")
print ("Y... |
def setTrainingData(self,X,T):
"""
set training data
:param X: data matrix (one data vector per row) of size NxD
:param T: target vector of class labels (should be coded as integers) (one target vector per row; should be "one-hot" 1-of-K coding of size NxK
"""
# (i) set... | The code trains a classifier using input data `X` and class labels `T` by iteratively optimizing synaptic weights through multiple learning trials. It initializes weights randomly if specified, runs trials to minimize an error function, and retains the weight configuration yielding the lowest error. The classifier's fi... | def fit(self,X,T, flagInitWeights=1):
"""
Train classifier by training data X, T
:param X: Data matrix, contains in each row a data vector
:param T: Vector of class labels, must have same length as X, each label should be integer in 0,1,...,C-1
:returns: -
"""
#... |
def get_teams_info():
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('team_info')
response = table.scan(
)
return {int(info['teamId']): covert_info(info) for info in response['Items']}
def convertMatch(match):
return {
"matchId": match['matchId'],
"round": int(match["roun... | The main task of the code is to retrieve and enrich soccer match data for a specific season from a DynamoDB table. It fetches matches, sorts them by round, appends next-round matches if available, and enhances each match with team details (names, crests, stars, user info) from a team information dictionary. The final o... | def get_matches(season):
dynamodb = boto3.resource('dynamodb')
basic_info_by_team_id = get_teams_info()
table = dynamodb.Table('SoccerMatches')
matches = table.scan(
FilterExpression=Attr("season").eq(season)
)['Items']
results = [convertMatch(match) for match in matches]
results.sor... |
def get_matches(season):
dynamodb = boto3.resource('dynamodb')
basic_info_by_team_id = get_teams_info()
table = dynamodb.Table('SoccerMatches')
matches = table.scan(
FilterExpression=Attr("season").eq(season)
)['Items']
results = [convertMatch(match) for match in matches]
results.sor... | The code simulates the next round of a soccer season by fetching upcoming matches, determining winners based on team "stars" data, and storing results in a DynamoDB table. It raises an exception if no matches remain. The function returns the list of simulated matches with updated results and round information. | def simulate_next_round(season):
all_matches = get_matches(season)
next_round = int(all_matches[0]['round']) if all_matches else 0
next_matches = get_next_matches(season, next_round)
if next_matches == None:
raise Exception("Season is over")
basic_info_by_team_id = get_teams_info()
dynam... |
def query_standing(season):
dynamodb = boto3.resource('dynamodb')
basic_info_by_team_id = get_teams_info()
table = dynamodb.Table('SoccerMatches')
response = table.scan(
FilterExpression=Attr("season").eq(season)
)['Items']
for item in basic_info_by_team_id.values():
... | The code defines a Lambda handler function that processes events to perform specific operations on sports data. It retrieves the operation type (`op`) from the event and executes corresponding actions like querying standings, retrieving matches, simulating the next round, or clearing matches. The `season` parameter det... | def handler(event, context):
'''Provide an event that contains the following keys:
- operation: one of the operations in the operations dict below
- tableName: required for operations that interact with DynamoDB
- payload: a parameter to pass to the operation being performed
'''
# print("... |
def name(self, name: str) -> None:
"""Set name."""
self._name = name
self._update()
def read_io(
self,
io: Union[SupportRead, Response],
size: Optional[float] = None,
action: str = "Read",
) -> bytes:
"""Read from a stream."""
self.progressbar.... | This function downloads a file from a given URL, caches it using an MD5 hash of the URL for unique naming, and returns the file's byte data. It checks if the file already exists in the cache; if not, it downloads the file via HTTP, verifies its size, and stores it locally before returning the content. | def download_file(self, url: str) -> bytes:
name = url.rsplit("/", 1)[-1]
self.name(name)
path = CACHE_DOWNLOAD_PATH / md5(url.encode("utf8")).hexdigest()
path.parent.mkdir(parents=True, exist_ok=True)
try:
total_size_in_bytes = path.stat().st_size
with pa... |
def _list_node_signatures(self, _list):
signatures = []
for j in _list:
if type(j) == dict:
signature = self._object_node_signature(j)
if signature not in signatures:
signatures.append(signature)
return signatures
def _elaborate_dis... | This function generates an ASCII tree representation of a root node, handling list nodes with different modes ('first', 'distinct', 'union') to elaborate their structure. It formats the processed node into a JSON-compatible structure, transforms it, and returns the ASCII tree visualization. | def tree(self, root_node, mode=None):
root_node_type = type(root_node)
if root_node_type == list:
signatures = self._list_node_signatures(root_node)
if mode == 'first' or len(signatures) == 1:
elaborated_root_node = root_node[0]
elif mode == 'distinct'... |
def _get_one_of_values(self) -> List[List["FieldToRender"]]:
"""An object field can have multiple kind of values if it's a oneOf.
This functions returns all the possible one of values the field can take.
Returns:
[list]: List of oneof values.
"""
if not self.oneOf:
... | The code initializes a `FieldToRender` instance by setting properties like `name`, `required`, and `field_metadata`, then processes metadata to determine attributes such as `one_of_values`, `object_properties`, `array_items`, and a composite `comment` from multiple methods. It also retrieves a `default` value, preparin... | def __init__(self, name: str, required: bool, field_metadata: dict) -> None:
"""Initialize a FieldToRender instance
Args:
name (str): name of the field
required (bool): whether it's a required field or not
field_metadata (dict): metadata associated with the field
... |
def GetData():
global Data,NextAgent,SortedAgentList,FullAgentNames
SortedAgentList = []
NextAgent = 0
#
# All data retrieved from other sources is stored in the DDB table with
# the primary partition key of "Data" and a primary sort key of the name
# of the value that has been s... | This code handles HTTP requests to retrieve and render real-time wallboard data. It checks for required query parameters, validates the wallboard name, fetches configuration/data, and returns either HTML or JSON output based on the 'json' parameter, with error handling for missing inputs or invalid configurations. | def lambda_handler(event, context):
GetData()
Response = {}
Response['statusCode'] = 200
Response['headers'] = {'Access-Control-Allow-Origin': '*'}
if str(type(event['queryStringParameters'])).find('dict') == -1 or 'Wallboard' not in event['queryStringParameters']:
Response['body'] = '<... |
def __get_excluded_products_pseudorandomly(self, products, how_many_ratio, random_seed):
dummy_list_of_potentially_excluded_products = products
dummy_list_of_potentially_excluded_products = list(
dummy_list_of_potentially_excluded_products)
dummy_list_of_potentially_excluded_product... | The main task of the code is to optimize product exclusion for the next day by pseudorandomly selecting products to exclude, intersecting them with today's products, updating tracking variables, calculating indicators, and storing results in a structured format for analysis and future reference. | def optimize_day(self, today_df: pd.DataFrame):
products_to_exclude_tomorrow = []
products_to_exclude_tomorrow = self.__get_excluded_products_pseudorandomly(
self.products_seen_so_far, 3.1, 12)
products_to_exclude_tomorrow_as_set = set(products_to_exclude_tomorrow)
todays_... |
def convert_rgb2gray(in_pixels, out_pixels):
'''
Convert color image to grayscale image.
in_pixels : numpy.ndarray with shape=(h, w, 3)
h, w is height, width of image
3 is colors with BGR (blue, green, red) order
Input RGB image
out_pixels : numpy.ndarray w... | The code performs object detection on an input image using a specified model. It converts the image to grayscale, computes Summed Area Tables (SAT) for efficient region analysis, detects objects at multiple scales, groups candidate bounding boxes, and draws final detections on the output image. The process includes tim... | def run(model, in_img, out_img,
scale_factor=1.1, min_neighbors=3, eps=0.2):
'''
Implement object detection workflow.
'''
height, width = in_img.shape[:2]
print(f'Image size (width x height): {width} x {height}\n')
start = timer()
# Convert image to grayscale
gray_img = np.emp... |
def log_info(step, description, line_feed, log_file):
localtime = ' [20' + strftime("%x").rsplit('/', 1)[1] + '/' + strftime("%x").rsplit('/', 1)[0] + ' ' + strftime("%X") + '] '
print(step + localtime + description, end=line_feed, file=log_file, flush=True)
def determine_file_format(filename):
"""
Dete... | The main task of this code is to process contig and query sequences to identify and extend contigs based on overlaps and paired-end read mappings. It categorizes results into self-circular, extended circular, extended partial, failed, and orphan contigs, while generating detailed logs, summary files, and modified FASTA... | def main():
##
# get information from the input files and parameters and save information
# get the name of the query fasta file
if '/' in args.query:
query_name = '{0}'.format(args.query).rsplit('/', 1)[1]
else:
query_name = '{0}'.format(args.query)
# get the name of the whole ... |
def get_data_path():
data_path = os.path.join(os.path.dirname(os.path.realpath("__file__")), "Avv", "test_data", "regs_random")
file_name = "regs_info"
file_ext = ".csv"
file_path = os.path.join(data_path, file_name + file_ext)
slash.logger.info("regs file path: {}".format(file_path))
return dat... | The code performs a series of automated tests to validate random register configurations in a hardware or simulation environment. It iterates multiple times (default: 100, reduced to 10 in debug mode), generating random register setups based on constraints and definitions from files. Each iteration checks for generatio... | def random_registers(iterations=1):
debug = False
if debug:
slash.logger.warning("Running in DEBUG mode")
slash.logger.warning("Running in DEBUG mode")
slash.logger.warning("Running in DEBUG mode")
slash.logger.warning("Running in DEBUG mode")
slash.logger.warning("Runnin... |
def get_counter():
conn =cn()
query = "select counter from other;"
for i in conn.execute(query): return i[0]
def fill_row(id,type,name,pg,no=None,img=None,txt=None,aud=None,summary=None,summaryaudio=None):
conn = cn()
query = "insert into book(id,file_type,file_name,total_pgs,page_no,img_path,text_p... | The function converts a PDF into images, extracts text from each image using OCR, saves the text to individual text files, combines all text into a single file, generates an audio version of the full text, and logs processing details. It handles errors during audio generation and updates a counter for tracking progress... | def pdf2img2txt2aud(pdf_path): # Dont change the name of path as function are
pdf_name = pdf_path[21:-4] # made according to len of path as here [21:-4]
full_text = ""
images = convert_from_path(pdf_path, poppler_path = path_poppler)
pytesseract.pytesseract.tesseract_cmd = path_... |
def get_counter():
conn =cn()
query = "select counter from other;"
for i in conn.execute(query): return i[0]
def fill_row(id,type,name,pg,no=None,img=None,txt=None,aud=None,summary=None,summaryaudio=None):
conn = cn()
query = "insert into book(id,file_type,file_name,total_pgs,page_no,img_path,text_p... | The main task of the code is to convert a PDF document into text by extracting text from both text-based and image-based pages, saving the extracted text to individual and combined text files, and generating an audio version of the full text. It identifies pages with images, converts them to images, performs OCR using ... | def pdf2img2txt2aud_optimised(pdf_path):
list_no_of_pg_having_img = []
# Open the PDF file
pdf_file = open(pdf_path, 'rb')
# Create a PDF reader object
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
#Total no of pages
total_pg = pdf_reader.numPages
# Loop through each page in the PDF file
... |
def get_counter():
conn =cn()
query = "select counter from other;"
for i in conn.execute(query): return i[0]
def fill_row(id,type,name,pg,no=None,img=None,txt=None,aud=None,summary=None,summaryaudio=None):
conn = cn()
query = "insert into book(id,file_type,file_name,total_pgs,page_no,img_path,text_p... | The function converts a PDF document into images, extracts text from each image using OCR, and saves both individual page texts and a consolidated text file. It processes each page by converting it to an image, saving it, performing OCR to extract text, and storing the result in a text file. The full extracted text is ... | def pdf2img2txt(pdf_path):
# Dont change the name of path as function are
# made according to len of path as here [21:-4]
pdf_name = pdf_path[21:-4]
full_text = ""
images = convert_from_path(pdf_path, poppler_path = path_poppler)
pytesseract.pytesseract.tesseract... |
def get_counter():
conn =cn()
query = "select counter from other;"
for i in conn.execute(query): return i[0]
def fill_row(id,type,name,pg,no=None,img=None,txt=None,aud=None,summary=None,summaryaudio=None):
conn = cn()
query = "insert into book(id,file_type,file_name,total_pgs,page_no,img_path,text_p... | This function processes a PDF by extracting text from both image-containing and non-image pages. It identifies pages with images, converts them to images, applies OCR (Tesseract) to extract text, and saves results. Non-image pages use PyPDF2 for direct text extraction. All extracted text is compiled into a full text fi... | def pdf2img2txt_optimised(pdf_path):
list_no_of_pg_having_img = []
# Open the PDF file
pdf_file = open(pdf_path, 'rb')
# Create a PDF reader object
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
#Total no of pages
total_pg = pdf_reader.numPages
# Loop through each page in the PDF file
... |
def get_counter():
conn =cn()
query = "select counter from other;"
for i in conn.execute(query): return i[0]
def fill_row(id,type,name,pg,no=None,img=None,txt=None,aud=None,summary=None,summaryaudio=None):
conn = cn()
query = "insert into book(id,file_type,file_name,total_pgs,page_no,img_path,text_p... | The code converts a PDF document into individual images (JPEG format), saves them with a specific naming convention, and logs each image's details (PDF name, page number, path) using a counter. It extracts a filename from the input path, processes each page, and stores images in a designated directory while updating a ... | def pdf2img(pdf_path):
# Dont change the name of path as function are
# made according to len of path as here [21:-4]
pdf_name = pdf_path[21:-4]
full_text = ""
images = convert_from_path(pdf_path, poppler_path = path_poppler)
no_img = len(images)
for i in ra... |
def get_counter():
conn =cn()
query = "select counter from other;"
for i in conn.execute(query): return i[0]
def fill_row(id,type,name,pg,no=None,img=None,txt=None,aud=None,summary=None,summaryaudio=None):
conn = cn()
query = "insert into book(id,file_type,file_name,total_pgs,page_no,img_path,text_p... | The function converts a PDF document into images, extracts text from each image using OCR, saves individual page texts and a combined full text file, generates a summary of the full text, and stores all outputs with structured file paths while tracking progress via a counter. | def pdf2img2txt2summary(pdf_path):
pdf_name = pdf_path[21:-4]
full_text = ""
images = convert_from_path(pdf_path, poppler_path = path_poppler)
pytesseract.pytesseract.tesseract_cmd = path_tesseract
no_img = len(images)
for i in range(no_img):
counter = get_counter()
#... |
def get_counter():
conn =cn()
query = "select counter from other;"
for i in conn.execute(query): return i[0]
def fill_row(id,type,name,pg,no=None,img=None,txt=None,aud=None,summary=None,summaryaudio=None):
conn = cn()
query = "insert into book(id,file_type,file_name,total_pgs,page_no,img_path,text_p... | This function converts a PDF into text by detecting images on pages, using OCR for pages with images and direct extraction for others. It saves extracted text, images, and generates a summary. It also logs processing details with a counter. | def pdf2img2txt2summary_optimised(pdf_path):
list_no_of_pg_having_img = []
# Open the PDF file
pdf_file = open(pdf_path, 'rb')
# Create a PDF reader object
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
#Total no of pages
total_pg = pdf_reader.numPages
# Loop through each page in the PDF f... |
def get_counter():
conn =cn()
query = "select counter from other;"
for i in conn.execute(query): return i[0]
def fill_row(id,type,name,pg,no=None,img=None,txt=None,aud=None,summary=None,summaryaudio=None):
conn = cn()
query = "insert into book(id,file_type,file_name,total_pgs,page_no,img_path,text_p... | This function converts a PDF to images, extracts text using OCR, generates a summary, and creates an audio version of the summary. It saves intermediate results (images, text, summary) and logs metadata. | def pdf2img2txt2summary2aud(pdf_path):
pdf_name = pdf_path[21:-4]
full_text = ""
images = convert_from_path(pdf_path, poppler_path = path_poppler)
pytesseract.pytesseract.tesseract_cmd = path_tesseract
no_img = len(images)
for i in range(no_img):
counter = get_counter()
... |
def get_counter():
conn =cn()
query = "select counter from other;"
for i in conn.execute(query): return i[0]
def fill_row(id,type,name,pg,no=None,img=None,txt=None,aud=None,summary=None,summaryaudio=None):
conn = cn()
query = "insert into book(id,file_type,file_name,total_pgs,page_no,img_path,text_p... | The main task of the code is to convert a PDF document into text by processing pages with images via OCR and extracting text from non-image pages, then generating a summary and audio version of the summary, while saving intermediate results in designated directories. | def pdf2img2txt2summary2aud_optimised(pdf_path):
list_no_of_pg_having_img = []
# Open the PDF file
pdf_file = open(pdf_path, 'rb')
# Create a PDF reader object
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
#Total no of pages
total_pg = pdf_reader.numPages
# Loop through each page in the P... |
def fvalue(self, p):
return self.costDict[p] + self.weight * self.heuristic(
p, self.dataMap.GPoint)
def ImprovePath(self):
while not self.openList.empty() and self.fvalue(
self.dataMap.GPoint) > self.minfvalueOpen():
s = self.openList.remove()
if s no... | This code implements an iterative path optimization algorithm, primarily adjusting weights and updating node priorities in an open list to find the optimal path. It initializes costs for start/goal points, iteratively improves the path using f-value calculations, and dynamically adjusts the weight parameter (towards A*... | def Solve(self):
timeStart = time.time()
self.costDict[self.dataMap.GPoint] = math.inf
self.costDict[self.dataMap.SPoint] = 0
self.openList.add(
self.fvalue(self.dataMap.SPoint), self.dataMap.SPoint)
self.ImprovePath()
self.minWeight()
# self.weight... |
def Solve(self):
timeStart = time.time()
self.costDict[self.dataMap.GPoint] = math.inf
self.costDict[self.dataMap.SPoint] = 0
self.openList.add(
self.fvalue(self.dataMap.SPoint), self.dataMap.SPoint)
self.ImprovePath()
self.minWeight()
# self.weight... | The function writes a solution to a file after solving a problem. If no solution exists for the given GPoint, it writes a 'no solution' flag. Otherwise, it retrieves the solution path and cost from dictionaries, then writes them to the specified output file along with the data map. | def writeSolution(self, name_out):
self.Solve()
# khong co solution
if self.dataMap.GPoint not in self.previousDict:
writeSolutionToFile(name_out, None, None, None, noSolution=True)
return
# co solution
path = getSolutionPath(self.dataMap.GPoint, self.pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.