dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_reference_line(x, y):
index = range(0, len(x), 3)
x = [x[i] for i in index]
y = [y[i] for i in index]
cubicspline = cubic_spline.Spline2D(x, y)
s = np.arange(0, cubicspline.s[-1], 0.1)
rx, ry, ryaw, rk = [], [], [], []
for i_s in s:
ix, iy = cubicspline.calc_position(i_s)
... | The code implements a cruising mode path planning algorithm using a lattice planner. It initializes an environment with reference lines, boundaries, and obstacles, then iteratively computes feasible paths while updating vehicle state variables (position, velocity, acceleration). The planner visualizes the reference pat... | def main_Crusing():
ENV = env.ENVCrusing()
wx, wy = ENV.ref_line
bx1, by1 = ENV.bound_in
bx2, by2 = ENV.bound_out
C.obs = np.array([[50, 10], [96, 25], [70, 40],
[40, 50], [25, 75]])
obs_x = [x for x, y in C.obs]
obs_y = [y for x, y in C.obs]
rx, ry, ref_path = g... |
def has_o_won(self):
return self.has_won(player='o')
def has_x_won(self):
return self.has_won(player='x')
def available_indices(self):
idx = set()
for i in range(self.dimension):
for j in range(self.dimension):
if self.board[i][j] == '_':
i... | The code checks if the game is a tie by verifying that neither player has won and all moves are exhausted. It returns True when no player has a winning condition and there are no available moves left, indicating a draw. | def tie(self):
return not self.has_o_won() and not self.has_x_won() and len(self.available_indices()) == 0 |
def has_o_won(self):
return self.has_won(player='o')
def has_x_won(self):
return self.has_won(player='x')
def available_indices(self):
idx = set()
for i in range(self.dimension):
for j in range(self.dimension):
if self.board[i][j] == '_':
i... | Your return The function `is_game_complete` checks if a game has ended by verifying if either player O or X has won, or if there are no remaining moves available. It returns `True` if any of these conditions are met, indicating the game is complete (either through a win or a draw). | def is_game_complete(self):
return self.has_o_won() or self.has_x_won() or len(self.available_indices()) == 0 |
def available_indices(self):
idx = set()
for i in range(self.dimension):
for j in range(self.dimension):
if self.board[i][j] == '_':
idx |= {i*self.dimension + j}
return idx
def is_game_complete(self):
return self.has_o_won() or self.has_x_... | This function implements the Minimax algorithm with alpha-beta pruning to determine the optimal move for a game-playing AI. It recursively evaluates game states by simulating moves for both players ('o' as maximizing, 'x' as minimizing), using depth limits and pruning to optimize search efficiency. The evaluation adjus... | def minimax_helper(self, alpha, beta, depth=18, is_maximizing=True, max_depth=18):
avail_indices = list(self.available_indices())
if depth == 0 or self.is_game_complete() or len(avail_indices) == 0:
ev = self.evaluate()
return ev
shuffle(avail_indices)
... |
def is_game_complete(self):
return self.has_o_won() or self.has_x_won() or len(self.available_indices()) == 0
def has_o_won(self):
return self.has_won(player='o')
def has_x_won(self):
return self.has_won(player='x')
def tie(self):
return not self.has_o_won() and not self.has_x_won() and ... | This function determines the best move for player 'X' using the minimax algorithm with alpha-beta pruning. It checks if the game is complete, returns specific codes for win/tie states, calculates an adaptive max search depth based on board size, evaluates all available moves recursively, and selects the move with the m... | def get_best_move_x(self, max_depth=None):
if self.is_game_complete():
if self.has_o_won():
return -2
elif self.has_x_won():
return -3
elif self.tie():
return -4
return -1
alpha = -inf
beta = inf
... |
def init_text(self):
self.select_language_txt = tkinter.StringVar()
self.language_txt = tkinter.StringVar()
self.clutch_shortcut_txt = tkinter.StringVar()
self.upshift_shortcut_txt = tkinter.StringVar()
self.downshift_shortcut_txt = tkinter.StringVar()
self.clutch_txt = t... | The code initializes a GUI application for Forza Horizon 5's auto gear shifting, configuring a tkinter window with layout weights, variables for car settings, and frames for displaying data. It sets up a thread pool, initializes a Forza game interface, starts a keyboard listener, and logs the application's launch. The ... | def __init__(self):
"""init
"""
self.root = tkinter.Tk()
# init text
self.language = helper.get_sys_lang()
self.init_text()
self.text_update(self.language)
# Configure the rows that are in use to have weight #
self.root.grid_rowconfigure(0, mins... |
def read_header(objfile_path: str) -> struct_header:
inferior = gdb.selected_inferior()
patchlib = gdb.lookup_objfile(objfile_path)
if patchlib is None:
return None
try:
header_addr = find_object_static(PATCH_HEADER_VAR_NAME, objfile_path)
except:
return None
buffer = in... | The function reads a specific log entry from a binary file by validating the index, checking the header's magic number and log presence, calculating the correct memory address, reading the data from GDB, and converting it into a structured log entry. | def read_log_entry(index: int) -> struct_log_entry:
global master_lib_path
objfile = gdb.lookup_objfile(master_lib_path)
if objfile is None:
return None
header = read_header(master_lib_path)
#TODO
if header.magic != MAGIC_CONSTANT or header.contains_log == False:
return None
... |
def read_header(objfile_path: str) -> struct_header:
inferior = gdb.selected_inferior()
patchlib = gdb.lookup_objfile(objfile_path)
if patchlib is None:
return None
try:
header_addr = find_object_static(PATCH_HEADER_VAR_NAME, objfile_path)
except:
return None
buffer = in... | This function searches for the first log entry in a shared library's patch log that matches a given function address. It reads the library's header, locates the patch log, iterates through log entries, and returns the first entry whose target function pointer matches the input address. If no match is found, it returns ... | def find_first_patch(func_address: int) -> struct_log_entry:
global master_lib_path
hdr = read_header(master_lib_path)
log_ptr = find_object_dlsym(PATCH_LOG_VAR_NAME, master_lib_path)
buffer = bytearray(gdb.selected_inferior().read_memory(log_ptr, hdr.log_entries_count*LOG_ENTRY_SIZE))
for i in rang... |
def find_object_dlsym(symbol_name: str, objfile_name: str) -> int:
dlsym = find_object("dlsym")
hdr = read_header(objfile_name)
if hdr is None:
return 0
libhandle = hdr.libhandle
symbol_address = int(dlsym(libhandle, c_string(symbol_name)).cast(gdb.lookup_type("uint64_t")))
if symbol_add... | The main task of the code is to copy logging and patch-related data from a source module to a destination module. It updates the destination's header to indicate it contains logs, mirrors log entry counts and pointers from the source, and writes the source's log buffer and backup data into the destination's memory. Fin... | def copy_log(dest: str, src: str):
global master_lib_path
src_log = find_object_dlsym(PATCH_LOG_VAR_NAME, src)
src_backup = find_object_dlsym(PATCH_LOG_DATA_VAR_NAME, src)
dest_log = find_object_dlsym(PATCH_LOG_VAR_NAME, dest)
dest_backup = find_object_dlsym(PATCH_LOG_DATA_VAR_NAME, dest)
src_hd... |
def is_attached() -> bool:
inferior = gdb.selected_inferior()
if inferior.was_attached:
return True
return False
def find_master_lib() -> None:
global master_lib_path
master_lib_path = ""
for objfile in gdb.objfiles():
try:
header = read_header(objfile.filename)
... | The code's main task is to display log entries from a dynamically linked library in GDB. It verifies a process is attached, locates the library's log data, reads memory entries, and prints each log entry's details. It checks for no parameters, ensures a process is attached, retrieves the log buffer, parses entries, and... | def invoke(self, arg, from_tty):
global master_lib_path
argv = gdb.string_to_argv(arg)
if len(argv) != 0:
raise gdb.GdbError("patch-log takes no parameters")
if not is_attached():
raise gdb.GdbError("No process attached.")
print("[0] revert")
fi... |
def read_header(objfile_path: str) -> struct_header:
inferior = gdb.selected_inferior()
patchlib = gdb.lookup_objfile(objfile_path)
if patchlib is None:
return None
try:
header_addr = find_object_static(PATCH_HEADER_VAR_NAME, objfile_path)
except:
return None
buffer = in... | The function allocates a trampoline for a given target function address by locating a free memory page, reserving space within it, and returning the calculated address of the allocated trampoline slot. It checks for existing trampoline pages, allocates a new one if needed, finds the first available index in the page's ... | def alloc_trampoline(target_function_address: int) -> int:
hdr = read_header(master_lib_path)
if hdr.trampoline_page_ptr == 0:
page_base = find_nearest_free_page(target_function_address)
if page_base == 0:
return 0
alloc_trampoline_page(page_base)
hdr.trampoline_page_... |
def read_header(objfile_path: str) -> struct_header:
inferior = gdb.selected_inferior()
patchlib = gdb.lookup_objfile(objfile_path)
if patchlib is None:
return None
try:
header_addr = find_object_static(PATCH_HEADER_VAR_NAME, objfile_path)
except:
return None
buffer = in... | This function adds a log entry and associated backup data to a library file, updating its header and memory. It checks size limits, writes backup data (from path or memory) using GDB, and updates log entry offsets. If size constraints are exceeded, it aborts. | def add_log_entry(log_entry: struct_log_entry, patch_backup: struct_patch_backup) -> None:
global master_lib_path
header = read_header(master_lib_path)
index = header.log_entries_count
patch_backup_ptr = find_object_dlsym(PATCH_LOG_DATA_VAR_NAME, master_lib_path)
log_size = header.log_entries_count*... |
def read_header(objfile_path: str) -> struct_header:
inferior = gdb.selected_inferior()
patchlib = gdb.lookup_objfile(objfile_path)
if patchlib is None:
return None
try:
header_addr = find_object_static(PATCH_HEADER_VAR_NAME, objfile_path)
except:
return None
buffer = in... | This function identifies an active log entry associated with a specified function address, deactivates it by updating its status, and optionally removes a trampoline if the target function uses a jump instruction (0xe9). It reads log entries from memory, checks for a matching active entry, modifies the entry's state, a... | def find_active_entry_and_set_as_inactive(func_address: int) -> struct_log_entry:
global master_lib_path
size = read_header(master_lib_path).log_entries_count
log_ptr = find_object_dlsym(PATCH_LOG_VAR_NAME, master_lib_path)
buffer = bytearray(gdb.selected_inferior().read_memory(log_ptr, size*LOG_ENTRY_S... |
def read_header(objfile_path: str) -> struct_header:
inferior = gdb.selected_inferior()
patchlib = gdb.lookup_objfile(objfile_path)
if patchlib is None:
return None
try:
header_addr = find_object_static(PATCH_HEADER_VAR_NAME, objfile_path)
except:
return None
buffer = in... | The function identifies the last active patch entry associated with a given function address in a dynamic library, deactivates it by updating the log entry, and returns the patch's path. If the target function's instruction starts with a jump (0xe9), it also frees the trampoline. This is used to manage and disable spec... | def find_last_patch_and_set_as_inactive(func_address: int) -> str:
global master_lib_path
hdr = read_header(master_lib_path)
i = hdr.log_entries_count - 1
log_ptr = find_object_dlsym(PATCH_LOG_VAR_NAME, master_lib_path)
buffer = bytearray(gdb.selected_inferior().read_memory(log_ptr, hdr.log_entries_... |
def read_header(objfile_path: str) -> struct_header:
inferior = gdb.selected_inferior()
patchlib = gdb.lookup_objfile(objfile_path)
if patchlib is None:
return None
try:
header_addr = find_object_static(PATCH_HEADER_VAR_NAME, objfile_path)
except:
return None
buffer = in... | This function closes a shared library by updating its header to remove log data, checking if it's the last reference, freeing associated resources like the trampoline page, and invoking `dlclose` on the library handle. It ensures proper cleanup by handling logs from other object files and resetting global state if no f... | def close_lib(lib: str):
global master_lib_path
hdr = read_header(lib)
is_last = False
if hdr.contains_log:
hdr.contains_log = False
is_last = True
write_header(lib, hdr)
for objfile in gdb.objfiles():
try:
header = read_header(objfile.filename... |
def is_attached() -> bool:
inferior = gdb.selected_inferior()
if inferior.was_attached:
return True
return False
def find_object(symbol_name: str) -> gdb.Value:
try:
symbol = gdb.parse_and_eval(symbol_name)
except:
raise gdb.GdbError("Couldn't find " + symbol_name + ".")
... | This code patches shared libraries in a running process using GDB. It validates input parameters, checks process attachment, locates dlopen/dlclose functions, loads patch metadata, and applies patches to target functions using strategy objects. It handles two patch types (own/library) and updates master library headers... | def invoke(self, arg, from_tty):
global master_lib_path
self.type_dict.clear()
argv = gdb.string_to_argv(arg)
if len(argv) != 1:
raise gdb.GdbError("patch takes one parameter")
if not is_attached():
raise gdb.GdbError("No process attached.")
#fin... |
def read_header(objfile_path: str) -> struct_header:
inferior = gdb.selected_inferior()
patchlib = gdb.lookup_objfile(objfile_path)
if patchlib is None:
return None
try:
header_addr = find_object_static(PATCH_HEADER_VAR_NAME, objfile_path)
except:
return None
buffer = in... | The function decreases the reference count of a library's header. If the count reaches zero or below, it closes the library. | def decrease_refcount(lib: str):
hdr = read_header(lib)
hdr.refcount -= 1
write_header(lib, hdr)
if hdr.refcount <= 0:
close_lib(lib) |
def find_last_patch_and_set_as_inactive(func_address: int) -> str:
global master_lib_path
hdr = read_header(master_lib_path)
i = hdr.log_entries_count - 1
log_ptr = find_object_dlsym(PATCH_LOG_VAR_NAME, master_lib_path)
buffer = bytearray(gdb.selected_inferior().read_memory(log_ptr, hdr.log_entries_... | This function adjusts reference counts for libraries. It first identifies the last patched library associated with a function address, decreases its reference count if found, then increments the reference count of the current library by updating its header. The task involves managing library resources by modifying refc... | def steal_refcount(func_address: int, current_lib: str):
lib = find_last_patch_and_set_as_inactive(func_address)
if lib is not None:
pass
#TODO use decrease_refcount instead
decrease_refcount(lib)
current = read_header(current_lib)
current.refcount += 1
write_header(current_... |
def read_header(objfile_path: str) -> struct_header:
inferior = gdb.selected_inferior()
patchlib = gdb.lookup_objfile(objfile_path)
if patchlib is None:
return None
try:
header_addr = find_object_static(PATCH_HEADER_VAR_NAME, objfile_path)
except:
return None
buffer = in... | This function reverts all active patches by restoring original memory contents from backups stored in log entries. It reads patch logs, iterates through entries, and rewrites memory at target locations based on patch type ("O" or "L"), handling jump instructions and GOT entries. It ensures proper memory restoration and... | def revert_all(self):
header = read_header(master_lib_path)
patch_log = find_object_dlsym(PATCH_LOG_VAR_NAME, master_lib_path)
inferior = gdb.selected_inferior()
buffer = bytearray(gdb.selected_inferior().read_memory(patch_log, header.log_entries_count*LOG_ENTRY_SIZE))
for i in r... |
def autocorrelation(values):
acf = fftconvolve(values, values[::-1], mode='full')
return acf[acf.size // 2:]
def _get_power_threshold(self):
if self.threshold_method == 'mc':
return self._mc_threshold()
elif self.threshold_method == 'stat':
return self._stat_thres... | This code initializes a time-series analyzer to detect periodic signals by computing autocorrelation, applying the Lomb-Scargle periodogram for frequency analysis, normalizing power spectra, determining significance thresholds, and validating period hints. It generates sine-wave fits for detected periods and optionally... | def __init__(self, times, values, plotter=None, threshold_method='mc', mc_iterations=40, confidence_level=.9):
# convert absolute times to time differences from start timestamp
self.times = times
self.values = values
self.plotter = plotter
self.acf = self.autocorrelation(values)... |
def test_deterministic(
emitter=None,
sbml_deterministic=None,
total_time=200,
out_dir=None,
):
if not sbml_deterministic:
dirname = os.path.dirname(__file__)
sbml_deterministic = os.path.join(dirname, SBML_FILE_DETERMINISTIC)
output, comp0 = simulate_bioscrape_c... | The main task of the code is to execute various biological simulations (deterministic, stochastic, spatial, etc.) based on command-line arguments, using SBML files. It creates an output directory, processes flags for simulation types, parallel execution, and data emission (database/timeseries), and invokes correspondin... | def main():
out_dir = os.path.join('out', 'bioscrape_cobra')
if not os.path.exists(out_dir):
os.makedirs(out_dir)
parser = argparse.ArgumentParser(description='bioscrape_cobra')
parser.add_argument('-database', '-d', action='store_true', default=False, help='emit to database')
parser.add_ar... |
def getChangedFiles(repo,commit):
changedFiles=[]
c=repo.get_commit(commit)
for f in(c.modified_files):
if f.old_path and f.new_path:
rec={}
rec["old"]=f.old_path
rec["new"]=f.new_path
changedFiles.append(rec)
return changedFiles
def getFilesLang(f... | The function identifies commits that introduced code changes in a specified commit, mapping each line to its originating commit if the introduction date precedes the issue's creation date, returning structured data with commit mappings, filenames, and dates for each affected file. | def identifyIntroCommits(drillerrepo,repo,commitHash,issueCreationDate,lang):
#print(repoDir)
#print("I'm here")
dateFormat = '%Y-%m-%d %H:%M:%S %z'
files=getChangedFiles(drillerrepo,commitHash)
#print(files)
changedLang=getFilesLang(files,lang)
items=[]
#print(changedLang)
for chj i... |
def on_session_started(session_started_request, session):
""" Called when the session starts """
print("on_session_started requestId=" + session_started_request['requestId']
+ ", sessionId=" + session['sessionId'])
return get_welcome_response()
def on_launch(launch_request, session):
""" Called when the user l... | The main task of the code is to route incoming Alexa skill requests (LaunchRequest, IntentRequest, SessionEndedRequest) to appropriate handler functions based on request type, while validating the application ID to ensure secure execution. | def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
print("event.session.application.applicationId=" +
event['session']['application']['applicationId'])
"""
Uncomment this if... |
def get_types() -> Set[str]:
"""Get the set of all types used in CONSO."""
with open(CLASSES_PATH) as file:
reader = csv.reader(file, delimiter='\t')
_ = next(reader) # skip the header
return {
line[0]
for line in _get_types_helper(reader)
}
def get_autho... | The main task of the code is to validate the consistency and correctness of biological data elements, including terms, synonyms, cross-references, and relations. It checks files for synonyms, xrefs, and relations using identifier mappings, verifies specific class relationships (e.g., 'isoform' and 'antibody'), and ensu... | def check():
"""Run the check on the terms, synonyms, and xrefs."""
classes = get_types()
authors = get_authors()
identifier_to_name = get_identifier_to_name(classes=classes, authors=authors)
check_synonyms_file(identifier_to_name=identifier_to_name)
check_xrefs_file(identifier_to_name=identifi... |
def _write_namespace(path, values: Mapping[str, str], namespace_version: Optional[str] = None):
with open(path, 'w') as file:
write_namespace(
namespace_name='Curation of Neurodegeneration Supporting Ontology',
namespace_keyword='CONSO',
namespace_domain=NAMESPACE_DOMAIN_... | (This function exports CONSO data into BELNS format by generating three files: identifiers, names, and a mapping. It uses the provided version to write terms and labels into separate namespace files, then creates a mapping file linking them, facilitating structured representation of biological entities and their relati... | def belns(directory: str, version):
"""Export CONSO as BELNS."""
identifiers_path = os.path.join(directory, 'conso.belns')
names_path = os.path.join(directory, 'conso-names.belns')
mapping_path = os.path.join(directory, 'conso.belns.mapping')
_write_namespace(identifiers_path, _get_terms(), namespa... |
def update_all_templates(substitutions: Dict[str, any]) -> None:
for config in load_template_configs():
_substitutions = {**substitutions, **config.variables}
_update_templates(config.templates, _substitutions)
def update_pipeline_templates(pipeline_names: List[str], substitutions: Dict[str, any]) -... | The main task of the code is to update templates based on command-line arguments. It loads a theme and environment variables, then applies substitutions to templates: updating all templates if no arguments are provided, pipeline templates if 'on' is specified, or specific templates based on the given arguments. | def main():
theme = load_theme()
env = {k: v for k, v in os.environ.items()}
substitutions = {'theme': theme, 'env': env}
argv = sys.argv
argn = len(argv) - 1
if argn == 0:
update_all_templates(substitutions)
elif argv[1] == 'on':
update_pipeline_templates(argv[2:], substi... |
def tellME(_data):
Fi = open(
"./reports/report_Info.txt",
"a",
)
if verbose:
Fi.write(_data)
# Close the file
Fi.close()
def ad(_ac):
return add_dict[_ac]
def index_output_check():
Fi = open("./reports/report_Info.txt", "a")
... | This code performs random token operations (transfer, mint, burn) on a blockchain contract. It selects a 50% chance to transfer a random token between accounts, or 55% to mint a token, else burn one. Each action includes error handling, logging, and interacts with two contracts (demo/testo) using safeTransferFrom, sing... | def trans():
cas = random.randint(0, 100)
if cas < 50:
try:
sup = demo.totalSupply()
sleep(0.05)
rndTok = demo.tokenByIndex(random.randint(0, sup - 1))
sleep(0.05)
own = demo.ownerOf(rndTok)
sl... |
def problem_file(conj, list_of_deps, statements_file, dir_path, format_2=False):
if format_2:
statements = read_statements_2(statements_file)
else:
statements = read_statements(statements_file)
uuid4 = uuid.uuid4().hex
input_filename = os.path.join(dir_path, uuid4 + '.E_input')
with ... | The function `find_proof` attempts to prove a conjecture using an automated theorem prover (E-prover). It generates input/output files based on the conjecture, dependencies, and format, runs E-prover, checks if the output contains a proof marker, logs the result, and returns `True` if proven, `False` otherwise. | def find_proof(conj, deps, statements_file, dir_path, logger, format_2):
assert not conj in set(deps), (conj, deps)
input_filename = problem_file(conj, deps, statements_file, dir_path,
format_2)
output_filename = input_filename.replace('input', 'output')
run_E_prover(in... |
def _source_mask(self, source):
return (source != self.source_vocab.PAD_INDEX).unsqueeze(1)
def _target_mask(self, target):
return self._target_length_mask(target) & self._subsequent_mask(target.size(-1), target.device)
def encode(self, source, source_mask):
return self.encoder(self.source_embed... | The forward method processes input sequences (source) and optionally target sequences (for teacher forcing) using different decoding strategies. It encodes the source, applies masks if needed, and decodes either via teacher forcing (with target and masks), beam search (with beam size and max length), or greedy decoding... | def forward(self, source, target = None, source_mask = None, target_mask = None, type = 'teacher_forcing', max_length = None, beam_size = None):
if (type == 'teacher_forcing'):
if (source_mask is None):
source_mask = self._source_mask(source)
if (target_mask is None):
... |
def find_table_value_from_column_value(self, input, key):
parent_id = input[key]["parent"]
return input[parent_id]["value"]
def normalize_columns_names(self, columns):
normalized_columns = []
for column in columns:
column = self.normalize_column_name(column)
if co... | The main task of the code is to build a structured data representation of database tables from flat input data. It categorizes entries into tables with columns, processes relationships (arrows) to add foreign key references, and normalizes column/table names. The output is a list of tables, each containing normalized n... | def build_table_data(self):
input = self.flat_data
tables = {}
columns = []
for each in input:
if each == "arrows":
continue
if input[each]["parent"] == "1":
tables[each] = {}
tables[each]["name"] = input[each]["valu... |
def readed_in_draw_io_file(self):
filename = f"{self.project_name}.drawio"
tree = ET.parse(filename)
data = base64.b64decode(tree.find("diagram").text)
xml = zlib.decompress(data, wbits=-15)
xml = xml.decode("utf-8")
xml = unquote(xml)
my_dict = xmltodict.parse(xm... | The code initializes a class to process project data by reading Draw.io files, flattening raw data into structured formats, building table structures, identifying tables, and generating tables with column names and types for organized data handling and potential code cleanup. | def __init__(self, project_name):
self.project_name = project_name
self.db_data_raw = self.readed_in_draw_io_file()
self.flat_data = self.build_flatened_data()
self.table_data = self.build_table_data()
self.tables = self.find_tables()
# tables_with_column_name_type is new... |
def _set_text(elems, text, lang):
"""Set text for elems to 'text' for the correct language."""
for i in elems:
if i.attrib["lang"] == lang:
i.text = text
def _set_licence_info(item, distInfo, download=True):
"""Create licenceInfo trees for item and append them to distInfo."""
ns = ME... | The code converts YAML metadata into META-SHARE XML format by parsing templates, populating fields like resource type, identification details, names, descriptions, license info, contact data, and language settings, then outputs the structured XML file. It skips unlisted resources, handles multilingual content, and ensu... | def create_metashare(yaml_path, out=None):
"""Create META-SHARE format from yaml metadata."""
# Read yaml metadata
with open(yaml_path, encoding="utf-8") as f:
yaml_metadata = yaml.load(f, Loader=yaml.FullLoader)
# Skip unlisted resources
if yaml_metadata.get("unlisted") == True:
pr... |
def store_section(section_id):
store_conn = http.client.HTTPConnection(settings.STORE_ADDRPORT[0], settings.STORE_ADDRPORT[1])
data = pickle.dumps((section_id, clean_section(sections[section_id]), FRONT, addrport))
try:
store_conn.request("POST", "/map", data)
response = store_conn.getresp... | This code handles HTTP POST requests for a distributed system, managing player connections, map section retrieval, neighbor updates, and player movement. It processes four endpoints: initializing players, fetching map sections from sources, updating section neighbors, and receiving players from other fronts. Data is se... | def do_POST(self):
protocol_version = "HTTP/1.1"
query = urlparse(self.path)
content_len = int(self.headers.get('Content-Length'))
if content_len > 0:
body = self.rfile.read(content_len)
if query.path == "/player": # Request to initialize a player connection
... |
def try_send(s, packet, addr):
if(random.randint(1, 100) > settings.PACKET_LOSS):
s.sendto(packet, addr)
def player_command(player, cmd):
id = player["id"]
ship = sections[player["section"]]["objects"][id]
# Update player's movement first if their ship is moving
if ship["speed"] > 0:
... | The code implements a network listener handling quorum keepalives, player/store acknowledgments, command processing, and data resends. It maintains state for player RTT, send buffers, and section movements, using thread locks for concurrency. The function processes incoming packets, manages resend queues, and periodica... | def front_listener():
global s, s_lock, resend_queue, store_resend_queue
last_quorum_ping = time.time()
last_move = time.time()
next_timeout = 1
while True:
try:
data, addr = s.recvfrom(1024)
if addr == settings.QUORUM_ADDRPORT:
if data == b"PING": ... |
def process_fines(self, user, book):
val = self.calculate_fines(user, book)
if val != 0:
self.update_solidated_fines(user, val)
def cancel_reservation(self, user, book): # cancel reservation at any time
try:
cursor.execute(
"DELETE FROM Library.Reserve WH... | The function `return_book` processes a user returning a book by first calculating and handling any associated fines, then removing the borrow record from the database. If successful, it checks for a reserved user for the book and, if found, cancels the reservation and automatically lends the book to the reserved user. ... | def return_book(self, user, book): # this function also makes sure that reserveUser borrows the book
try:
self.process_fines(user, book)
cursor.execute("DELETE FROM Library.Borrow WHERE borrowUserID = {} AND bookID = {}".format(user, book))
db.commit()
except:
... |
def _test(self, f=lambda _: True, i: int = 0):
return self.tokens and len(self.tokens) >= i + 1 and f(self.tokens[i])
def _parse_return(self) -> ReturnStmt:
self._consume(lambda x: x.type == TokType.ReturnStmt)
root = ReturnStmt()
root.expr = self._parse_expr()
return root
def _p... | The main task of the code is to parse a statement, determining if it is a return statement or a variable declaration. It checks the current token for a return statement, then checks the second token for an equality sign to identify a variable declaration. If neither is found, it raises a ValueError. | def _parse_statement(self):
# return statement
if self._test(lambda x: x.type == TokType.ReturnStmt):
return self._parse_return()
if self._test(lambda x: x.type == TokType.EQ, i=2):
return self._parse_var_decl()
raise ValueError() |
def _test(self, f=lambda _: True):
return self.q and f(self.q[0])
def _directive(self):
name, sub = self._consume()
self.out.append(Directive(name, sub))
def _label(self):
name = self._consume()[0][:-1]
self.out.append(Label(name))
def _statement(self):
ops = {
... | This method determines the type of a line in a configuration or code by checking if it starts with a dot (returns a directive), ends with a colon (returns a label), or defaults to a statement. It uses conditional checks on the first element of a test result to route processing accordingly. | def _line(self):
if self._test(lambda x: x[0].startswith('.')):
return self._directive()
if self._test(lambda x: x[0].endswith(':')):
return self._label()
return self._statement() |
def _test(self, f=lambda _: True, i: int = 0):
return self.tokens and len(self.tokens) >= i + 1 and f(self.tokens[i])
def _preserving_state(self):
q = deepcopy(self.tokens)
try:
yield
except ValueError:
self.tokens = q
except Exception as e:
pr... | The main task of the code is to parse and construct a Root object by repeatedly appending parsed statements and declarations as its children, using a loop that continues as long as self._test() returns true. The _preserving_state() context managers ensure state consistency during parsing steps, and the resulting Root n... | def _parse_root(self) -> Root:
root = Root()
while self._test():
with self._preserving_state():
root.children.append(self._parse_statement())
with self._preserving_state():
root.children.append(self._parse_declaration())
return root |
def _test(self, f=lambda _: True, i: int = 0):
return self.tokens and len(self.tokens) >= i + 1 and f(self.tokens[i])
def _parse_return(self) -> ReturnStmt:
self._consume(lambda x: x.type == TokType.ReturnStmt)
root = ReturnStmt()
root.expr = self._parse_expr()
return root
def _p... | This function parses a block of code by collecting statements into a list until it encounters a return statement or the end of the block (RBRACE), returning the list of parsed statements. | def _parse_body():
body = []
while self._test(lambda x: x.type != TokType.RBRACE):
if self._test(lambda x: x.type == TokType.ReturnStmt):
body.append(self._parse_return())
break
s = self._parse_statement()
bo... |
def vMultiplyConstant(u, k):
return [k*u[i] for i in range(len(u))]
def vSub(u, v):
return [u[i]-v[i] for i in range(len(u))]
def sigmoid_layer_derivative(X):
return [sigmoid_derivative(X[i]) for i in range(len(X))]
def vMult(u, v):
return [u[i]*v[i] for i in range(len(u))]
def mMult(u,v):
prod = ... | This function performs backpropagation in a neural network to compute gradients for weights and biases of both output and hidden layers. It calculates loss gradients using the difference between predictions (A2) and true labels (Y), applies sigmoid derivatives for non-linear activations, and uses matrix operations to p... | def backPropagation(Z1, A1, Z2, A2, w1, w2, X, Y):
#calculations for the output layer
#stochastic gradient descent, send each input and alter each weight
#calculate the gradient of the loss function across X
#this is equal to(2 * (Prediction - Output))
gradLoss = vMultiplyConstant((vSub(A2, Y)), 2)
... |
def initialize(inputDim, outputDim, hiddenLayerDim):
w1 = [[uniform(-1, 1) for i in range(inputDim)]
for j in range(hiddenLayerDim)]
b1 = [uniform(-1, 1) for j in range(hiddenLayerDim)]
w2 = [[uniform(-1, 1) for j in range(hiddenLayerDim)] for j in range(outputDim)]
b2 = [uniform(-1, 1) for ... | The code trains a single-hidden-layer neural network using gradient descent with backpropagation, then evaluates its performance on test data. It initializes weights/biases, iterates over training data to compute forward passes, updates parameters via backpropagation, and periodically prints loss. After training, it co... | def trainAndTest(inputDim, outputDim, hiddenLayerDim, X_train, X_test, y_train, y_test, name, learningRate, numIterations):
# print("Training and testing of", name,"\n")
# print("The parameters are as follows:")
# print("Number of hidden layers: 1")
# print("Hidden layer(s) dimension:", hiddenLayerDim)
... |
def get_time():
now = datetime.datetime.now(datetime.timezone.utc).astimezone()
return f"{now:{time_format}}"
def add_in_log(string):
log_file = open('log.txt', 'a', encoding='utf-8')
log_file.write(string)
log_file.close()
def serve_client(client_sock, client_address, port):
try:
da... | This code creates a TCP server on a specified port, accepting client connections and logging them. It prompts clients for ONVIF device credentials (IP, port, username, password) and processes commands via the serve_client() function, looping until valid input is received or terminating with an error message. | def run_server(port):
serv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv_sock.bind(("127.0.0.1", port))
serv_sock.listen(5)
while True:
client_sock, client_address = serv_sock.accept()
string = get_time() + ' Connected ' + str(client_address) + '\n'
print(string)
... |
def setParameters(self, rParams, tParams, pParams, thldParam, mtiParam):
""" Set the values of all the parameters according to given ones.
"""
self.rMin.set(rParams[0])
self.rMax.set(rParams[1])
self.rRes.set(rParams[2])
self.tMax.set(tParams[1])
self.tRes.set(tPa... | The main task of the code is to initialize the application loop when the 'Start' button is pressed. It connects to the Walabot device, applies user-defined arena parameters, handles errors, updates UI elements, calibrates if needed, configures display grids, disables UI controls, and triggers the main loop for sensor d... | def initAppLoop(self):
""" Executed when 'Start' button gets pressed.
Connect to the Walabot device, set it's arena parameters according
to one's given by the user, calibrate if needed and start calls
the loop function.
"""
self.ctrlPanel.errorVar.set("")
... |
def __readMode(self):
mode = str(self.program[self.__index]).zfill(5)[:3].zfill(3)
opcode = int(str(self.program[self.__index])[-2:])
return (mode, opcode)
def __opcode1(self, mode):
val1 = self.__readParam(mode, 1)
val2 = self.__readParam(mode, 2)
self.__writeParam(3, va... | This method executes a program by processing opcodes sequentially. It checks if the program is running, validates the instruction index, reads the current opcode and mode, and executes corresponding operations (e.g., arithmetic, input/output, control flow). Execution halts when encountering opcode 99, printing "End of ... | def next(self):
if not self.running:
return False
if self.__index > len(self.program):
self.running = False
return False
mode, opcode = self.__readMode()
if opcode == 1:
self.__opcode1(mode)
elif opcode == 2:
self.__opco... |
def __readMode(self):
mode = str(self.program[self.__index]).zfill(5)[:3].zfill(3)
opcode = int(str(self.program[self.__index])[-2:])
return (mode, opcode)
def __opcode1(self, mode):
val1 = self.__readParam(mode, 1)
val2 = self.__readParam(mode, 2)
self.__writeParam(3, va... | This method executes a program by interpreting opcodes, handling operations like addition, multiplication, input/output, and control flow. It processes the current instruction based on the opcode, updates program state, and halts when reaching opcode 99 or exceeding the program length. | def next(self, givenInput = None):
if self.running:
if self.__index > len(self.program):
self.running = False
mode, opcode = self.__readMode()
if opcode == 1:
self.__opcode1(mode)
elif opcode == 2:
self.__opcode2(mod... |
def parameter_parser(self):
'''
A method for parsing command line parameters
using `python argparse`.
'''
parser = argparse.ArgumentParser(description="Parse command line parameters.")
parser.add_argument("--input-folder", "-i",
dest="input_fo... | The code's main task is to set up an environment for processing files, including parsing parameters, creating directories, retrieving files, disassembling binaries with IDA Pro, and clearing temporary data. It checks for an IPython kernel to conditionally handle parameter parsing, ensuring proper preparation for analys... | def run(self):
if 'ipykernel' not in sys.modules:
self.parameter_parser()
self.mkdir()
self.get_all_files_in_directory()
self.idaPro_disassemble()
self.clear_folder() |
def _checkConnection(self):
if self.conn is None:
print("No connection established. Use obj.connect() to connect to database.")
return False
else:
return True
def writeIPData(self, new_ip_data):
self._writeData(self.ip_address_table_name, self.ip_table_query, ... | The function retrieves the database key associated with a given IP address. If the IP exists, it returns the key; if not, it inserts the IP with a generated key and returns it. The process ensures each IP has a unique key for mapping. | def getIPAddressKey(self, ip_address):
if self._checkConnection():
cur = self.conn.cursor()
#query = sql.SQL("SELECT * FROM {} WHERE key = (SELECT key FROM {} WHERE key = {})").format(sql.Identifier(self.data_table_name), sql.Identifier(self.data_table_name), sql.Identifier(str(ip_addres... |
def get_random_mutants(parent, number_of_new_mutants):
"""
Get from a given parent individual several new mutants.
:param parent: The parents gene combination is copied, before mutations are applied.
:param number_of_new_mutants: The maximum number of new mutants generated by this function.
:return:... | The function generates mutants from each individual in the input population, evaluates their scores (in parallel or sequentially), and constructs a new population containing the original individuals plus only those mutants that show improvement in score relative to their parents. | def mutate_and_keep_improvements(input_population, number_of_new_mutants):
"""
Iterate through the whole population and create several mutants for each. Only the original individuals from
the inputPopulation and mutants with an improved score are transferred into the returned new population.
:param inpu... |
def get_item_list(driver, product):
amazon = ['it', 'de', 'fr', 'es', 'co.uk']
items = []
for dom in amazon:
print('=>Domain: '+dom)
page = 1
go_to_page(driver, dom, product, page)
while not ip_is_banned(driver) and int(len(driver.find_elements(
By.XPATH, "//... | The code's main task is to continuously monitor a list of products by fetching their items, applying discounts, updating data, and restarting the driver periodically. It loops through each product, checks for items, quits and restarts the driver if no items are found, saves updated items, waits for a set duration, and ... | def loop(driver, d, tracking_list, seconds=60*10):
print('----------Loop started--------------')
while True:
for product in tracking_list:
print('----->'+product)
items = get_item_list(driver, product)
if len(items) == 0:
print('Restart...')
... |
def start(is_headless=True):
options = Options()
options.headless = is_headless
options.set_preference("permissions.default.image", 2) # too mutch greedy
return TorBrowserDriver(path_to_tor, options=options)
def go_to_page(driver, dom, product, page):
try:
driver.get('https://www.amazon.'+... | This code scrapes product data (ASIN, price) from Amazon search results for a specified product across multiple pages, handling IP bans and blacklisted items. It collects items into a list, saves them periodically, and returns the final dataset after scraping the specified page range. | def update(amazon_dom, start_page, final_page, product='laptop'):
driver = start()
page = start_page
items = []
jump = (final_page-start_page)//10
driver = go_to_page(driver, amazon_dom, product, page)
while page < final_page:
elements = driver.find_elements(
By.XPATH, "//d... |
def Split_into_HLAs(RawData, HLAs):
HLA_Data_List = {}
CommonInfo = RawData[['Pos','Peptide','ID']].copy() #gather info common to all HLA types into separate dataframe (peptide position, sequence, and mutation info)
#print('Hello, %s'% (type(CommonInfo)))
RawData.drop(['Pos','Peptide','ID', 'core', 'ico... | The code processes HLA-specific data from CSV files, extracts protein sequences, mutation frequencies, and validated epitopes, then integrates them to analyze HLA-related mutations and epitopes using statistical tests and custom functions. It prepares data for identifying HLA-associated peptide variations and their bio... | def ReadFile(FileName):
Raw_data = pd.read_csv(FileName) #Read csv file
preHLAs = list(Raw_data.columns.values) #create list of HLA types from file
HLAs = []
for item in preHLAs:
if item[:3].upper() == 'HLA':
HLAs.append(item)
Raw_data.columns = list(Raw_data.iloc[0])
Raw_dat... |
def compare_seqs(Mut, Ref):
print('THis is Mut and Ref: %s, %s'% (Mut, Ref))
for i in range(len(Mut)):
if Mut[i] != Ref[i]:
if i <= 3:
return '%s'% (i+1)
elif i >= (len(Mut) - 4):
return '%s'% (i - len(Mut))
else:
return... | The code processes HLA-specific mutation data to analyze binding effects, merges mutation tables with reference peptides, calculates mutation rates, and categorizes effects (gain/loss/no effect). It generates Venn diagrams, bar graphs, and exports CSV files to visualize mutation impacts on HLA binding. The function als... | def Print_HLAspecific_Plots(FullTable, RefPeptides, Additional_Data): #, FileName
Processed_HLAs = {}
Concatenated_Full_Frames = pd.DataFrame()
#use separate function to read .txt output from first program (contains list of unique mutations and their mutation rates). Function returns Dictionary with... |
def Import_results_csv(file):
gain_loss = pd.read_csv(file)
print(gain_loss)
return gain_loss.reset_index()
def Effect_on_Binding(Mut, Ref):
if (float(Mut) <= 0.5) and (float(Ref) >= 2.0):
return 'gain'
elif (float(Mut) >= 2.0) and (float(Ref) <= 0.5):
return 'loss'
else:
... | The code aggregates and processes mutation data from multiple HLA-specific CSV files into a unified DataFrame (`Combined_HLAs`). It reformats HLA names, filters relevant columns, calculates the "effect on binding" for each mutation, removes duplicates, and excludes entries with "no effect." Finally, it generates heatma... | def T_test(Results_file):
folder = 'results_ALL_Stringent_Only'
os.makedirs(os.path.dirname('./%s/'% (folder)), exist_ok=True)
Combined_HLAs = pd.DataFrame()
for HLA, value in Results_file.items(): #Iterate through gain/loss results files (in other wors, iterate through HLAs queried).
reform_... |
def preprocess_image(img):
img -= RGB_MEANS
return img
def upsample_predictions(preds):
for i,pred in enumerate(preds):
preds[i] = upsample2xXtimes(pred,UPSAMPLE_SCALES[i])
return preds
def get_box_and_dot_maps(pred, thresh):
# NMS on the multi-scale outputs
nms_out, h = box_NMS(pred, th... | The code processes an input image through a model to predict object detections. It upscales predictions, adjusts tensor formats for NMS compatibility, and extracts box locations and maps using a threshold. The main task is to detect and localize objects in an image using a pre-trained model with post-processing for acc... | def pred_for_one_image(model,image,threshold=0.3):
image = np.expand_dims(image,0).astype(np.float32)
image = preprocess_image(image)
preds = model.predict(image)
s1,s2,s3,s4 = upsample_predictions([*preds])
preds = [s1[0],s2[0],s3[0],s4[0]]
# the nms function i use expects the input to be in
... |
def attack(self, who_attack):
app = App.get_running_app()
myradians = math.atan2(self.pos[1] - who_attack.pos[1], self.pos[0] - who_attack.pos[0])
angle = math.degrees(myradians)
self.BANG = Bang(source=os.path.join('imgs', 'bullet.png'), pos=who_attack.pos,
size... | This code handles unit selection in a game, managing movement, attack actions, and UI updates. It checks game state conditions, adjusts widget positions, determines allowed movement cells based on unit type, highlights valid positions, and triggers attacks or deselects units accordingly. | def select(self):
app = App.get_running_app()
if app.card_in_reserve is not None and not self.my_unit:
app.root.get_screen("gamefield").ids.reserve_cards.ids.rs.children[app.card_in_reserve].pos[1] -= app.root.get_screen("gamefield").ids.reserve_cards.ids.rs.children[app.card_in_reserve].siz... |
def findImbalance(data):
dataNotFraud = data.filter(col("is_attributed") == 0)
dataFraud = data.filter(col("is_attributed") == 1)
countFraud = dataFraud.count()
countNotFraud = dataNotFraud.count()
ratio = int(countNotFraud / countFraud)
print(
"Count Fraud: {}\nCount Not Fraud: {}\nRati... | This function applies various sampling techniques (under-sampling, over-sampling, SMOTE) to an imbalanced dataset, comparing results. It returns a dictionary of sampled data based on specified methods, optionally printing class distribution details. | def diffSampledData(data, isUnderSample=False,isOverSample=False ,isSMOTE=False, ifprint=False):
sampledData={}
print("\n---Comparing data using various Sampling Techniques---")
# print("\n--NO Sampling--")
# sampledData['NO_SAMPLING_APPLIED']=getFeaturesData(data, drop=True)
# Find each class dat... |
def getFeaturesData(
data, inputColumnsList=["ip", "app", "device", "os", "channel"], drop=False
):
va = VectorAssembler(inputCols=inputColumnsList, outputCol="features")
transformedData = va.transform(data)
if drop:
return (
va.transform(data)
.drop(*inputColumnsList)
... | The main task of the code is to evaluate multiple machine learning models (e.g., LightGBM) on different sampled datasets, compute performance metrics (e.g., ROC, accuracy, F1), and compile results into a structured table. It iterates through sampling methods, trains models, tests on a provided dataset, and stores predi... | def getResults(sampledData, test, isLR=False, isRF=False, isLSVC=False, isCatBoost=False, isLightGBM=False,isCV=False):
# Specify the Column Names while initializing the Table
analysisTable = "\n\n\nOutputs\n"
#analysisTable = PrettyTable(["Sampling", "Model", "ROC", "accuracy", "F1", "precision", "recall",... |
def findImbalance(data):
dataNotFraud = data.filter(col("is_attributed") == 0)
dataFraud = data.filter(col("is_attributed") == 1)
countFraud = dataFraud.count()
countNotFraud = dataNotFraud.count()
ratio = int(countNotFraud / countFraud)
print(
"Count Fraud: {}\nCount Not Fraud: {}\nRati... | The code loads and preprocesses a dataset, addresses class imbalance via under-sampling, splits data into training/test sets, applies sampling techniques, and evaluates model performance using LightGBM, returning results and analysis tables for demonstration purposes. | def demoData(path="/content/drive/MyDrive/talkingdata-adtracking-fraud-detection/train_sample.csv"):
dataDownload = spark.read\
.format('org.apache.spark.sql.execution.datasources.csv.CSVFileFormat')\
.option("inferSchema",True)\
.option('header', 'true')\
.load(path).drop("attributed_time",... |
def getCompleteSummary(data, label="is_attributed"):
print("Summary")
print("_________")
data.summary().show()
print("_________")
checkNullPerTable(data)
print("_________")
print("Unique Values for each column in the table")
data.agg(*(countDistinct(col(c)).alias(c) for c in data.columns... | This code loads Parquet data, generates summaries, splits data into training/test sets, applies oversampling to the training data, trains a LightGBM model, evaluates performance on the test set, and returns results with an analysis table. | def RUN6MTEST(path="../Data/Sampled_data.parquet"):
dataDownload=spark.read.parquet(path)
getCompleteSummary(dataDownload)
trainSample,testSample=stratifiedTrainTestSplit(dataDownload, ifprint=False)
sampledData=diffSampledData(trainSample, isUnderSample=False,isOverSample=True, isSMOTE=False, ifprint=F... |
def getCompleteSummary(data, label="is_attributed"):
print("Summary")
print("_________")
data.summary().show()
print("_________")
checkNullPerTable(data)
print("_________")
print("Unique Values for each column in the table")
data.agg(*(countDistinct(col(c)).alias(c) for c in data.columns... | This function processes a Parquet dataset by reading it into Spark, generating summaries, splitting into stratified train/test sets, applying oversampling to the training data, training a LightGBM model, and returning evaluation results along with an analysis table. | def RUN26MTEST(path="../Data/Sampled25M.parquet"):
dataDownload=spark.read.parquet(path)
getCompleteSummary(dataDownload)
trainSample,testSample=stratifiedTrainTestSplit(dataDownload, ifprint=False)
sampledData=diffSampledData(trainSample, isUnderSample=False,isOverSample=True, ifprint=False)
result... |
def __generate_starting_source_comment_url(self, original_article_url):
bbc_article_id = original_article_url.split("-")[-1]
self.BBC_ARTICLE_ID = bbc_article_id
source_comment_url = f"https://push.api.bbci.co.uk/proxy/data/bbc-morph-comments-data/apiKey/ecee5363-c17d-4257-8907-2cd0da83d26b/for... | This code retrieves comments from a BBC article URL by repeatedly fetching paginated comment data via an API, processing each batch, and compiling all comments into a DataFrame. It uses a 'nextToken' for pagination, stopping when no more comments are available. The result is a DataFrame containing all extracted comment... | def extract_comments_from_original_article_url(self, article_url):
url = self.__generate_starting_source_comment_url(article_url)
while True:
data = self.__fetch_comment_data(url)
time.sleep(1)
self.__process_comments(data['comments'])
print(f"{len(self.... |
def _configurePort(self):
if (self._enableEcho() and self._disableFlowControl and self._disableRingAlerts() and self.ping()):
return True
else:
return False
def ping(self):
self._ensureConnectionStatus()
command = "AT"
self.s.write(f"{command}\r".enc... | This code initializes a serial port connection using the provided port ID and baud rate (19200), configures the port, tests connectivity with a ping, and triggers a callback if connected. If configuration or ping fails, it closes the port and raises a custom exception. The 'autoSession' flag enables automatic session m... | def __init__(self, portId, callback):
self.s = None
self.portId = portId
self.callback = callback
self.autoSession = True
# When True, we'll automatically initiate additional sessions if more messages to download
try:
self.s = serial.Serial(self.portId, 192... |
def _ensureConnectionStatus(self):
if (self.s == None or self.s.isOpen() == False):
print("ensureConnectionStatus failed")
raise rockBlockException()
def _attemptConnection(self):
print("482 attempt connnection started")
self._ensureConnectionStatus()
TIME_ATTEMP... | The main task of the code is to check if a connection and session can be established. It ensures the connection status, triggers a "rx started" callback if defined, attempts connection/session, returns True on success, or triggers a "rx failed" callback if either attempt fails. | def messageCheck(self):
self._ensureConnectionStatus()
if (self.callback != None and callable(self.callback.rockBlockRxStarted)):
self.callback.rockBlockRxStarted()
if (self._attemptConnection() and self._attemptSession()):
return True
else:
if (s... |
def _ensureConnectionStatus(self):
if (self.s == None or self.s.isOpen() == False):
print("ensureConnectionStatus failed")
raise rockBlockException()
def _queueMessage(self, msg):
try:
self._ensureConnectionStatus()
if (len(msg) > 340):
pr... | The code's main task is to send a message via a session with retry logic. It ensures connection status, triggers a "tx started" callback, queues the message, and attempts to establish a session up to three times with 1-second delays. If successful, it returns True; otherwise, it triggers a "tx failed" callback and retu... | def sendMessage(self, msg):
self._ensureConnectionStatus()
if (self.callback != None and callable(self.callback.rockBlockTxStarted)):
self.callback.rockBlockTxStarted()
print("179 starting if check on sendMessage")
try:
print("181 before queueMessage and Atte... |
def is_visible(target, base, fov=FOV):
if target == base:
return True
angle = (
math.atan2(target["y"] - base["y"], target["x"] - base["x"]) * 180 / math.pi
- base["theta"]
)
# wrap angle in -180, 180
angle = math.remainder(angle * math.pi / 180, 2 * math.pi) * 180 / math.... | The code generates a natural language description of a scene from a specified agent's perspective, considering visibility, relative motion, distance, and interactions between agents. It processes input data to describe visible entities, their positions, actions (like talking), and mutual gaze, returning a semicolon-sep... | def describe(scene, seen_by=SELF, egocentric=True, normalise_names=True):
global TRANSFORM_NAMES
TRANSFORM_NAMES = normalise_names
agents = scene["scene"]
if seen_by not in agents:
print("%s not in the scene. Can not generate description" % seen_by)
return ""
ref = agents[seen_by... |
def build_sub_tree(root_span, spans):
if root_span[0]==root_span[1]:
return Node(root_span[0])
root = Node(root_span)
left_possibles = filter_by_start(spans, root_span[0])
if len(left_possibles)==0:
root.left = Node(root_span[0])
root.right = build_sub_tree((root_span[0]+1, root_... | This code converts a span set into a tree structure by first building a subtree from the specified span, converting a forest into a tree, and then adding words from a reference to the tree's string representation. The final tree is returned as the result. | def span_set_to_tree(size, span_set, reference):
solution = build_sub_tree([0, size-1], span_set)
solution = forest_to_tree(node2forest(solution))
solution = add_words_to_str_tree(str(Tree(solution)), extract_words_from_str_tree(reference))
return solution |
def check_win_condition(self) -> bool:
"""Check all game win conditions"""
return self.check_rows() or self.check_cols() or self.check_diagonals()
pass
def reset(self):
"""Resets the grid state"""
for i in range(len(self.state)):
self.state[i] = ''
def check_draw_... | The code checks if the game has ended due to a win or draw. If either condition is met, it resets the game state and exits the method. | def check_end_conditions(self):
"""Check all game end conditions"""
if self.check_win_condition():
self.reset()
return
if self.check_draw_condition():
self.reset()
return |
def loadImage(filename):
image = cv2.imread(filename)
if image.shape[1] > 560 or image.shape[0] > 1000:
image = cv2.resize(image, (560, 1000))
return image
def preprocessImage(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 80, 200, apertureSize=3)
threshe... | The code reads a Sudoku image, processes it to detect grid lines and intersection points, and constructs a 2D board representation of the Sudoku puzzle from the processed image, returning the board structure for further analysis or solving. | def readSudoku(filename):
image = loadImage(filename)
edges, threshed = preprocessImage(image)
#Sorted into horizontal and vertical lines to make calculating the grid of intersection points easier
hlines, vlines = getSudokuGridLines(edges, image)
drawLines(hlines + vlines, image)
#a 2D grid o... |
def takeoff(self):
"""
Runs the take off phase of the simulation.
"""
while self.forward_velocity <= self.plane.takeoff_speed:
self.time += self.dt
self.acceleration = (self.plane.thrust - self.calc_air_ressistance()) / self.mass
self.velocity += self.... | The code simulates a plane's entire flight sequence, including takeoff, ascending at a specified angle (ASCEND_ANGLE in radians), cruising, descending, and landing. The main task is to execute these phases in order to model the aircraft's journey from departure to arrival. | def run_sim(self, ASCEND_ANGLE):
"""
Runs the simulation.
Attributes:
ASCEND_ANGLE: float
the ascend angle of the plane in radians.
"""
self.takeoff()
self.ascend(ASCEND_ANGLE)
self.cruising_flight()
self.descend()
self... |
def _get_linenumber():
cf = currentframe()
return cf.f_back.f_lineno
def _debug_log (msg):
debug = True
if debug == True:
fd = open('/tmp/volume_configuration.log', 'a')
fd.write("%s %s\n" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), msg))
fd.close()
def _execute (SYS, cmd, error_return... | The function configures RAID arrays (0,1,5,6) and JBOD/hotspares via MegaCLI, validating disk counts, states, and controller compatibility. It executes commands to create/configure arrays, checks for conflicts, disables JBOD if needed, and updates system state. Returns True if changes were made, False if existing confi... | def _megacli (SYS, request, changed_state):
changed = changed_state
if len(SYS['bays']) < 1:
return changed
RAIDlvl, Disks, VG, LV, GBs, FStype, Mountpoint = request
bays = Disks.split(',')
if not SYS['megacli64'] or Disks == '999':
return changed
if RAIDlvl == '0' or RAIDlvl == '1' or RAIDlvl =... |
def _debug_log (msg):
debug = True
if debug == True:
fd = open('/tmp/volume_configuration.log', 'a')
fd.write("%s %s\n" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), msg))
fd.close()
def _get_linenumber():
cf = currentframe()
return cf.f_back.f_lineno
def _execute (SYS, cmd, error_return... | The main task of the code is to create a filesystem or swap space on specified devices based on the request parameters, including ZFS pool configuration, label generation, device handling, and updating system configuration files like /etc/fstab. It checks for existing filesystems, ensures correct types, creates necessa... | def _mkfs (SYS, request, changed_state):
_debug_log("Running _mkfs, request= %s" % request)
RAIDlvl, Disks, VG, LV, GBs, FStype, Mountpoint = request
changed = changed_state
bays = Disks.split(',')
# Ignore anything without a mountpoint. Otherwise, determine the label, device, and mount (eg: LABEL=, /dev/sdX... |
def _get_linenumber():
cf = currentframe()
return cf.f_back.f_lineno
def _device_type_and_path(SYS, device):
_debug_log("Device: %s" % device)
_debug_log("Device type: %s ; Should be string." % type(device))
try:
dv_array = device.split('/')
except AttributeError:
if "list" in str(type(device)):... | This function destroys non-root storage configurations by removing fstab entries, unmounting non-root volumes, deleting LVM PVs/LVs, and wiping/unconfiguring non-root disks in bays/HDDs, ensuring only the root volume remains. | def _destroy_configuration (SYS):
if '/' not in SYS['dftab']:
ansible_module.fail_json(msg='volume_configuration(_destroy_configuration,%s): Cannot determine the root filesystem.' % _get_linenumber())
# Loop through the fstab and removing entries for everything except the root volume.
for dv in SYS['fsta... |
def _get_n_procs(
CIR_params: Union[CIRParams, tuple[CIRParams, ...]], n_procs: Optional[int]
) -> int:
"""
Define the number of processes, if CIR_params is a tuple the
number of processes is the lenght of the tuple. If it is not a tuple
then it is the "n_procs" supplied as argument,
if it is No... | The function simulates multiple correlated Cox-Ingersoll-Ross (CIR) processes over a time horizon `T`. It accepts either a single set of CIR parameters (for identical processes) or a tuple of parameter sets (for distinct processes). Correlation between processes is controlled by `rho`, and reproducibility is ensured vi... | def get_corr_CIR_procs(
T: int,
CIR_params: Union[CIRParams, tuple[CIRParams, ...]],
n_procs: Optional[int] = None,
rho: Optional[float] = None,
random_state: Optional[int] = None,
) -> np.ndarray:
"""
Simulate correlated CIR processes, correlation (rho) can be 0 or None.
- T is the samp... |
def get_plugin(self, name: str) -> Optional[Any]:
"""Return the plugin registered under the given name, if any."""
return self._name2plugin.get(name)
def is_blocked(self, name: str) -> bool:
"""Return whether the given plugin name is blocked."""
return name in self._name2plugin and self.... | This method loads plugins from the specified setuptools entry point group, optionally filtering by name, by iterating through distributions and their entry points. It skips already registered or blocked plugins, loads valid ones, registers them, and returns the count of successfully loaded plugins. | def load_setuptools_entrypoints(
self, group: str, name: Optional[str] = None
) -> int:
"""Load modules from querying the specified setuptools ``group``.
:param str group: Entry point group to load plugins.
:param str name: If given, loads only plugins with the given ``name``.
... |
def pick_variant(template):
import re
if template is None:
return None
out = template
variants = re.findall(r'\{[^{}]*?}', out)
for v in variants:
opts = v.strip("{}").split('|')
out = out.replace(v, random.choice(opts))
combinations = re.findall(r'\[[^\[\]]*?]', out)... | This function generates and saves images in batches based on provided prompts, handling initial images, dynamic prompts, and output settings. It creates directories, processes batches with specified parameters, generates images using a model, and saves results as files or grids, with options for displaying, saving, or ... | def render_image_batch(device, args, prompts, model):
args.prompts = {k: f"{v:05d}" for v, k in enumerate(prompts)}
# create output folder for the batch
os.makedirs(args.outdir, exist_ok=True)
if args.save_settings or args.save_samples:
print(f"Saving to {os.path.join(args.outdir, args.time... |
def sample_from_cv2(sample: np.ndarray) -> torch.Tensor:
sample = ((sample.astype(float) / 255.0) * 2) - 1
sample = sample[None].transpose(0, 3, 1, 2).astype(np.float16)
sample = torch.from_numpy(sample)
return sample
def sample_to_cv2(sample: torch.Tensor, type=np.uint8) -> np.ndarray:
sample_f32 =... | The main task of the code is to generate an animation by rendering frames using a diffusion model, handling keyframe prompts, resuming from previous outputs, and saving results. It manages 2D/3D transformations, depth maps, color coherence, and frame interpolation for smooth output, while supporting video input and res... | def render_animation(device, args, half_precision, model, anim_args, models_path, animation_prompts):
# animations use key framed prompts
args.prompts = animation_prompts
# expand key frame strings to values
keys = DeformAnimKeys(anim_args)
# resume animation
start_frame = 0
if anim_args.r... |
def Get_City_List(filename) -> None:
global cityList
read = False
with open(filename, 'r') as inputFile:
for line in inputFile:
if read == True:
lineContent = line.split(' ')
cityList.append(City(int(lineContent[0]), float(lineContent[1]), float(lineConten... | The code implements a genetic algorithm to solve the Traveling Salesman Problem (TSP). It loads city data, initializes a population of paths, and iteratively evolves them through crossover, mutation, and selection. The algorithm tracks the best path's score, terminating when reaching 1000 generations or finding a suffi... | def main():
global cityList
Get_City_List("Random100.tsp")
initialPopulation = Generate_Population(1000, cityList)
population = sorted(initialPopulation, key=lambda x: x.score)
print("Best Initial Score: ")
print(population[0].score)
continueValue = True
generation = 0
bestGenerati... |
def list_experiments():
settings_path = pkg_resources.resource_filename(__name__, f"settings/")
experiment_paths = glob.glob(f"{settings_path}/*")
experiment_paths.sort()
for experiment in experiment_paths:
print(experiment)
def read_yml(yml_path):
with open(yml_path) as f:
docs = y... | The code automates FESOM2 experiment testing by parsing command-line arguments, loading configuration files, executing test workflows (clone, build, run, submit), monitoring job status, and saving results as JSON. It supports specifying experiments, output paths, branches, and listing available tests. | def ftest():
parser = argparse.ArgumentParser(prog="ftest", description="run FESOM2 tests.")
parser.add_argument(
"ename", help="Name of the experiment", default="ollie_sanity", nargs="*"
)
parser.add_argument(
"--opath", "-o", type=str, default="./odata/", help="Output directory",
... |
def get_ip_version(raw_input):
"""
Returns the version of the input IP address.
Options are 'IPV4', 'IPV6', or 'None'
"""
output = None
if is_ipv4(raw_input):
output = "IPV4"
elif is_ipv6(raw_input):
output = "IPV6"
return output
def is_valid_subnet_mask_ipv4(raw_input)... | This function validates an IP address and its corresponding subnet mask by determining the IP version (IPv4/IPv6) and checking if the subnet mask is valid for that version. It returns True if both the IP and subnet mask are valid, otherwise False. | def ip_and_subnet_are_valid(query):
""" Returns True if query is valid """
output = True
ip_address = query[0]
subnet_mask = query[1]
ip_version = get_ip_version(ip_address)
if ip_version is None:
output = False
else:
if ip_version == "IPV4":
output = is_valid_s... |
def get_ip_version(raw_input):
"""
Returns the version of the input IP address.
Options are 'IPV4', 'IPV6', or 'None'
"""
output = None
if is_ipv4(raw_input):
output = "IPV4"
elif is_ipv6(raw_input):
output = "IPV6"
return output
def calculate_subnet_ipv4(ip_address, su... | The function `get_network_address` calculates and returns the network address for a given IP address and subnet mask, determining the IP version (IPv4/IPv6) and delegating to the appropriate subnet calculation function. | def get_network_address(query):
""" Returns network address for valid query """
ip_address = query[0]
subnet_mask = query[1]
ip_version = get_ip_version(ip_address)
output = ""
if ip_version == "IPV4":
output = calculate_subnet_ipv4(ip_address, subnet_mask)
elif ip_version == "IPV6... |
def _get_criterion(
name: str, d_out: List[int], alpha: float = 1, **kwargs
) -> nn.Module:
if name == "L1":
return nn.L1Loss(**kwargs)
elif name in ["MSE", "L2"]:
return nn.MSELoss(**kwargs)
elif name == "crossentropy":
return nn.CrossEntropyLoss(**kwargs)
elif name == "MSE+... | (The code trains a compositional neural network model with configurable architecture, using wandb for logging. It initializes data generators, builds model components (monolithic or modular), loads checkpoints, trains with optimizer/scheduler, evaluates periodically, saves best models based on metrics, and visualizes r... | def run(**cfg):
now_str = f"{datetime.datetime.now():%Y%m%d-%H%M%S}"
save_dir = Path(cfg["save_dir"]) / (cfg["save_name"] + "_" + now_str)
save_dir.mkdir(parents=True, exist_ok=False)
cfg["save_dir"] = save_dir
wandb.init(project="CGFP", config=cfg)
# NOTE only set this if input/output has con... |
def display_grid(grid: np.ndarray) -> None:
for i in range(WIDTH // CELL_SIZE):
for j in range(HEIGHT // CELL_SIZE):
colour = grid[j*(WIDTH // CELL_SIZE) + i]
if colour < 0: colour = 0
if colour > 1: colour = 1
colour = (colour*255, c... | The main task of the code is to simulate and visualize a dynamic grid-based system using Pygame and NumPy. It initializes a grid of random values, toggles simulation state via the spacebar, and iteratively updates the grid by computing deltas, applying a restriction function, and redisplaying changes. The loop runs at ... | def main_pg():
# initialise pygame
pg.init()
screen = pg.display.set_mode((WIDTH, HEIGHT))
grid = np.random.rand(HEIGHT // CELL_SIZE, WIDTH // CELL_SIZE)
nextGrid = np.zeros((HEIGHT // CELL_SIZE, WIDTH // CELL_SIZE))
screen.fill((30, 30, 30))
pg.display.flip()
display_grid(screen,... |
def _prep_qkv(self, qk: Tensor, v: Tensor, masks: Tensor):
q, k = qk, qk
q, _ = self._reshape(q, overlapping_patches=False)
k, attn_mask = self._reshape(k, overlapping_patches=True, masks=masks)
if exists(v):
v, _ = self._reshape(v, overlapping_patches=True)
else:
... | This code processes input tensors through an attention mechanism. It prepares query, key, and value vectors, computes windowed attention, reshapes the output, and applies masks if provided. The main task is to perform masked multi-head attention with reshaping, returning the transformed output tensor. | def forward(self, qk: Tensor, v: Tensor = None, masks: Tensor = None):
batch_size, _, seq_len = qk.shape
q, k, v, att_mask = self._prep_qkv(qk=qk, v=v, masks=masks)
windowed_attn = self.attn(query=q, key=k, value=v, att_mask=att_mask)
out = self._undo_reshape(windowed_attn, batch_size, s... |
def _prep_qkv(self, qk: Tensor, v: Tensor, masks: Tensor):
q, k = qk, qk
q, _ = self._reshape(q)
k, attn_mask = self._reshape(k, masks=masks)
if exists(v):
v, _ = self._reshape(v)
else:
v = k
return q, k, v, attn_mask
def _undo_reshape(self, lt_pa... | This function computes attention using the provided query-key-value tensors, applies an attention mask if provided, and returns the masked output after reshaping. The core task involves performing attention operations, handling tensor reshaping, and applying optional masks to the output. | def forward(self, qk: Tensor, v: Tensor = None, masks: Tensor = None):
batch_size, _, seq_len = qk.shape
q, k, v, att_mask = self._prep_qkv(qk=qk, v=v, masks=masks)
lt_attn = self.attn(query=q, key=k, value=v, att_mask=att_mask)
out = self._undo_reshape(lt_attn, batch_size, seq_len)
... |
def connected(self, x, y):
return self.find(x) == self.find(y)
def union(self, x, y):
rootX = self.find(x)
rootY = self.find(y)
if rootX != rootY:
self.root[rootY] = rootX
def find(self, x):
if x != self.root[x]:
self.root[x] = self.find(self.root[x])
... | The code determines the number of connected components in a graph represented by an adjacency matrix using Union-Find. It initializes a Union-Find structure, processes each pair of connected nodes to merge sets, and finally counts the distinct root nodes to find the number of separate friend circles. | def findCircleNum(self, isConnected: List[List[int]]) -> int:
self.size = len(isConnected)
self.root = [i for i in range(self.size)]
self.dups = []
self.count = 0
for i in range(self.size):
for j in range(self.size):
if isConnected[i][j] == 1 and i !=... |
def connected(self, x, y):
return self.find(x) == self.find(y)
def union(self, x, y):
rootX = self.find(x)
rootY = self.find(y)
if rootX != rootY:
self.root[rootY] = rootX
def find(self, x):
if x != self.root[x]:
self.root[x] = self.find(self.root[x])
... | The code checks if a given graph with `n` nodes and `edges` forms a valid tree by using Union-Find. It ensures no cycles exist during edge processing and verifies all nodes are connected to a single root. If both conditions are met, it returns True; otherwise, False. | def validTree(self, n: int, edges: List[List[int]]) -> bool:
self.size = n
self.root = [i for i in range(self.size)]
for i in range(len(edges)):
if self.connected(edges[i][0], edges[i][1]):
return False
else:
self.union(edges[i][0], edges[... |
def SABR_imp_var(alpha,rho,nu,F,K,t):
"""SABR formula. alpha is vol level, rho is
correlation and nu is vol of vol. F is the forward rate, K the strike and t
the maturity"""
A = 1 + (0.25 * alpha * nu * rho + (2 - 3 * (rho**2)) * (nu**2) / 24.) * t
if K <= 0:
sabr_vol = -1
elif F == K: #... | The main task of the code is to calibrate the SABR model to implied volatility data, compute risk reversal (25RR) and fly (25Fly) measures, and compare SABR and SSVI volatility surfaces through numerical integration and plotting. It calculates key strike prices (dnk, ck, pk), their volatilities, and evaluates model imp... | def main():
alpha =0.11
nu=0.8
rho=-0.2
f=1
s=1
t=1
dnk=optimize.brentq(lambda k : log(k/f) - 0.5 * SABR_imp_var(alpha,rho,nu,f,k,t),
0.001,10)
dnvol=math.sqrt(SABR_imp_var(alpha,rho,nu,f,dnk,t) / t)
ck=optimize.brentq(lambda k : (log(... |
def SSVI1_w(y,theta,eta,rho, gamma):
return SSVI1_imp_var(y,theta,eta,rho, gamma)
def SSVI1_wp(y,theta,eta,rho, gamma):
pht=SSVI_pf(theta,eta,gamma)
wp = (theta / 2) * (rho * pht + ((pht * y + rho)**2 + (1 - rho**2))**(-0.5) *
(pht * y + rho) * pht)
return wp
def SSVI1_wpp(y,th... | The function `pdf_SSVI1` computes the probability density function (pdf) for a smile using the SSVI model. It calculates the parameters `w`, `wp`, and `wpp` via helper functions `SSVI1_w`, `SSVI1_wp`, and `SSVI1_wpp`, then passes these to `pdf_smile` to generate the final pdf. The input `y` represents the variable for ... | def pdf_SSVI1(y,params):
w=SSVI1_w(y,params[0],params[1],params[2], params[3])
wp=SSVI1_wp(y,params[0],params[1],params[2], params[3])
wpp=SSVI1_wpp(y,params[0],params[1],params[2], params[3])
pdf=pdf_smile(y,w,wp,wpp)
return pdf |
def SSVI1_w(y,theta,eta,rho, gamma):
return SSVI1_imp_var(y,theta,eta,rho, gamma)
def SSVI1_wp(y,theta,eta,rho, gamma):
pht=SSVI_pf(theta,eta,gamma)
wp = (theta / 2) * (rho * pht + ((pht * y + rho)**2 + (1 - rho**2))**(-0.5) *
(pht * y + rho) * pht)
return wp
def SSVI1_wpp(y,th... | The function computes the probability density function (PDF) of a stochastic volatility model using the SSVI (Stochastic Skew Volatility) framework. It calculates the first, second, and third derivatives of the SSVI function with given parameters and inputs, then passes these along with the input variable to a helper f... | def pdf_SSVI1(y,params):
w=SSVI1_w(y,params[0],params[1],params[2], params[3])
wp=SSVI1_wp(y,params[0],params[1],params[2], params[3])
wpp=SSVI1_wpp(y,params[0],params[1],params[2], params[3])
pdf=pdf_smile(y,w,wp,wpp)
return pdf |
def calibrate_SSVI1(vols,strikes,F,t,initial_guess):
bnds=((0.00001,None),(None,None),(-0.99999,0.99999),(0.00001,0.5))
cons=({'type':'ineq','fun':SSVI1_constraint})
result=minimize(SSVI1_Objective,initial_guess,(vols,strikes,F,t),
method='SLSQP',bounds=bnds,constraints=cons)
SSVI1_p... | The code calibrates SSVI volatility models for FX currency pairs using market data, then applies copula models to analyze cross-currency smile surfaces. It computes option prices, variances, and volatilities for varying correlations, compares results with market data, and visualizes the outcomes. Key steps include data... | def main():
today=date.today()
qlDate = ql.Date(today.day,today.month,today.year)
qlCalendar = ql.UnitedStates()
qlDayCounter = ql.ActualActual()
"""Load in vol data and populate MktSmileData dictionary"""
MktSmileData={}
ccy_pairs=("EURUSD","GBPUSD","EURGBP")
for ccypair in c... |
def identify_servers():
# Identify any potential servers (top-level subdirectories) in current directory
for subdir, _, filenames in walklevel(os.getcwd()):
if "server.jar" in filenames: # Only parse through folders containing the server.jar exe
if os.path.basename(os.path.normpath(subdir))... | This function sets up a new server by creating a directory, downloading server files, generating necessary configurations, and handling EULA acceptance. It uses debug parameters to bypass user input and direct file paths for testing. | def __setup(debug_dir=None, debug_name=None, debug=False):
new_server_name = Prompt.ask("[bold yellow]Input new server name[/bold yellow]") if not debug else debug_name
new_server_dir = os.path.join(os.getcwd(), new_server_name) if not debug else os.path.join(debug_dir,
... |
def create_client(region: str = 'ap-southeast-2'):
config = Config(
region_name = region,
signature_version = 'v4',
retries = {
'max_attempts': 10,
'mode': 'standard'
}
)
return boto3.client('ssm', config=config)
def status(code, body):
return {
... | This code handles an event by creating AWS parameters using a generated UUID and group name. It extracts credentials from the input, generates unique parameter names, creates an OTP parameter, and stores other parameters. The response includes the UUID, OTP value, and list of parameter names for tracking or verificatio... | def handler(event, context):
data = json.loads(event.get('body', None))
client = create_client(data.get('region', 'ap-southeast-2'))
prefix = data.get('prefix', '')
group_name = data.get('group_name', None)
if not group_name:
return status(400, '')
parameter_uuid = str(uuid.uuid4())
... |
def clear(self) -> None:
"""Substitute to the UserDict clear which clears the dict and resets _exceeded_errors
"""
super().clear()
self._exceeded_errors = False
return
def _check_label_uniqueness(self, issue_type_category: str, _document_collected_issues: bool = False):
... | The main task of the code is to validate an object (e.g., MzQcFile) by checking structural and semantic rules, such as label uniqueness, ontology term validity, metric usage, and input file consistency. It organizes detected issues into predefined categories, respects error limits, and optionally documents all possible... | def validate(self, max_errors: int = 0, load_local: bool = False, keep_issues: bool = False, _document_collected_issues: bool = False):
"""Validates the object given during class initialisation, considers a number of parameters
Note before adding new checks: create functions to check specific types of ... |
def distance(city1, city2):
return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)
def calculate_score(tour, dist, N):
score = 0
#insert dummy
tour.append(tour[0])
for i in range(N):
score += dist[tour[i]][tour[i+1]]
tour.pop()
return score
def solve_by_2opt(tour, ... | The code improves a Traveling Salesman Problem (TSP) solution using local search. It initializes a tour from a given output, applies random swaps, and iteratively refines it via 2-opt and 3-opt heuristics to minimize the total distance. After 10 iterations, it returns the best tour and its score, aiming to find a near-... | def solve(cities, output):
N = len(cities)
dist = [[0] * N for _ in range(N)]
for i in range(N):
for j in range(i, N):
dist[i][j] = dist[j][i] = distance(cities[i], cities[j])
best_tour = read_output(output)
best_score = calculate_score(best_tour, dist, N)
print("score0... |
def preprocess_input(img, w, h):
ih, iw, _ = img.shape
scale = min(w/iw, h/ih)
nw = int(iw*scale)
nh = int(ih*scale)
image_data = cv2.resize(img, (nw,nh))
new_image = np.full((h,w,3), (128,128,128), dtype='uint8')
new_image[(h-nh)//2 : (h+nh)//2, (w-nw)//2:(w+nw)//2] = image_data
image_data = new_image... | The function processes a batch of images through a YOLO model, preprocesses them, runs predictions, decodes outputs into bounding boxes using anchors, adjusts box sizes to original dimensions, applies non-max suppression, and returns detected boxes for each image. | def get_yolo_boxes(model, images, net_h, net_w, anchors, obj_thresh, nms_thresh):
image_h, image_w, _ = images[0].shape
nb_images = len(images)
batch_input = np.zeros((nb_images, net_h, net_w, 3))
# preprocess the input
for i in range(nb_images):
batch_input[i] = preproces... |
def baseline_tag_sentence(sentence, perWordTagCounts, allTagCounts):
"""Returns a list of pairs (w,t) where each w corresponds to a word
(same index) in the input sentence. Each word is tagged by the tag most
frequently associated with it. OOV words are tagged by sampling from the
distribution of all ta... | The function `tag_sentence` tags each word in the input sentence using a specified model (baseline, HMM, BiLSTM, or BiLSTM+case). It returns a list of (word, tag) pairs, where each pair corresponds to a word in the input. The model parameters dictate the tagging method: baseline uses word/tag counts, HMM uses transitio... | def tag_sentence(sentence, model):
"""Returns a list of pairs (w,t) where pair corresponds to a word (same index) in
the input sentence. Tagging is done with the specified model.
Args:
sentence (list): a list of tokens (the sentence to tag)
model (dict): a dictionary where key is the model ... |
def get_batch(source, i):
"""
Transforms input data into predictor and target variables
"""
seq_len = min(args.batch_size, len(source) - 1 - i)
if args.model == "FNN":
# Generate batches based on sliding window
data = source[i:i+seq_len]
target = data[:, -1]
data = da... | The code trains a neural network model (RNN, Transformer, or FNN) for language modeling using specified optimizers (Adam, SGD, RMSprop). It processes training data in batches, computes loss with NLLLoss, performs backpropagation with gradient clipping, and evaluates validation perplexity each epoch. The best model is s... | def train(args, model, train_data, val_data):
import sys
result_df = pd.DataFrame()
loss_function = nn.NLLLoss()
if args.optim == 'adam':
optimizer = optim.Adam(model.parameters(), lr=args.lr)
elif args.optim == "sgd":
optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=... |
def clean(directories):
log("INFO", "Cleaning last build...")
for directory in directories:
try:
shutil.rmtree(directory)
except FileNotFoundError:
log("INFO", "No previous build found, skipping clean")
except OSError:
log("ERROR", "Could not clean bu... | The code packages a project by formatting variables, cleaning specified directories, creating new directories, and copying resources using variable substitutions. It processes input arguments, updates directory paths, executes cleanup, directory creation, and resource duplication tasks based on formatted values. | def build(input_arguments, clean_directories, new_directories, resources, variables):
variable_map = input_arguments
for k, v in variables:
formatted = v.format(**variable_map)
variable_map[k] = formatted
print_full_header('Packaging {project_name}'.format(**variable_map))
clean_direct... |
def add_sprites(self):
self.surfaces.add(self.background)
self.add_player()
def create_walls(self):
centerx = WALL_WIDTH/2 + WALL_WIDTH * 4 #wall offset
number_of_walls = 13
flag = 0
for i in range(number_of_walls):
self.add_walls(centerx)
centerx... | The main task of the code is to initialize a game environment by adding sprites, creating walls, reading high scores, and generating text elements. It sets up essential game components like visual objects (sprites/walls), score tracking, and UI text, likely preparing the game state before starting gameplay. | def start(self):
self.add_sprites()
self.create_walls()
self.read_high_score()
self.text.create_text() |
def draw_surfaces(self):
for s in self.surfaces:
self.win.blit(s.surf1, s.rect)
def update_genome(self):
for i in range(len(self.players)):
collision_top = 0
collision_bottom = 0
player_top = self.players[i].get_center_y() - 30
player_bottom = ... | This method updates the game state by clearing the screen, rendering surfaces, updating text and sprites, checking collisions, managing game elements like genome and walls, adding points, and maintaining frame rate using Pygame. | def update(self):
self.win.fill(self.win_rgb)
self.draw_surfaces()
self.text.update_text(self.game_status)
self.update_genome()
self.update_sprite_pos()
self.wall_out_bounds()
self.add_point()
self.check_for_collisions()
self.update_closest_wall()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.