dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_is_debug():
is_debug = False
query_params = st.query_params
if query_params:
debug_query_param_value = query_params["debug"][0]
if debug_query_param_value:
is_debug = debug_query_param_value.lower() == "true"
return is_debug
def task_by_date_component(task_list: TaskL... | The main task of the code is to create a Streamlit dashboard titled "Hardik's PTM Dashboard" that visualizes task data from Workflowy. It fetches tasks and historical task data, provides a button to save Workflowy snapshots, and displays task statistics, story points, calendar views, goals, and comparative analytics us... | def main():
st.set_page_config(page_title="Hardik's PTM Dashboard")
st.title("Hardik's PTM Dashboard")
is_debug = get_is_debug()
workflowy_service = WorkflowyService(read_cache=is_debug)
workflowy_history_manager = WorkflowyHistoryManager(workflowy_service)
task_store = TaskStore(workflowy_serv... |
def load_config_file(self, config):
""" Read in the contents of JSON file (config.txt) """
with open(config) as file:
self.config = json.load(file)
def load_local_version_number(self, path):
""" Loads the version file from the local copy of the module and returns its values as a dict... | This function ensures the client application is downloaded and up to date by cloning a Git repository, installing dependencies, updating configuration files, and checking for version upgrades. It handles both initial setup (when no config exists) and updates (when config exists), returning True on success or False if a... | def download_client_app(self):
""" Ensures that a running copy of the app has been downloaded. ToDo: Roll back any failed version. """
if self.config is None:
config_path = "/interface/config.txt"
config = self.client_app_repo_name + config_path
if not os.path.isfile(... |
def activate_venv(self):
""" Activates the virtual environment. This function restarts the app and switches over to using the venv interpreter. """
# Check to see if the launcher is running with the default Python interpreter or the virtual environment interpreter
if sys.executable != self.venv_... | The main task of the code is to execute a launcher process by activating a virtual environment, checking for updates, downloading and launching a client application (while removing previous versions), evaluating action requests from the app, and saving configuration files, ensuring proper setup and execution of the app... | def run_launcher(self):
''' Main entry-point for launcher execution '''
self.activate_venv() # Ensures virtual environment is installed and switches over to it.
self.check_for_launcher_update()
if self.download_client_app(): # Ensures a version of the app has been downloaded and conf... |
def load_config_file(self, config):
""" Read in the contents of JSON file (config.txt) """
with open(config) as file:
self.config = json.load(file)
def setup_logging(self, console=logging.INFO, file=logging.WARNING):
""" Set logger to capture different levels of information. Data log... | This code initializes a launcher for a client application by configuring repository URLs, setting up a virtual environment, loading configuration settings from a file, installing required dependencies, and launching the application. It handles both default and user-specified repository branches and names, ensuring the ... | def __init__(self):
self.config = None # A dictionary representation of JSON data describing the app
self.application = None # Holds an instance of the entry_point class for the application loaded from the github repository linked below
self.clock = int(time.time()) # Unix timestamp u... |
def generate_board(model):
"""
Generates random valid player boards and spymaster boards and returns them
Input:
- model is a word2vec model that is checked to see
if the words chosen exist in the model
Output:
- gamewords is a list of strings which represents the board of words
- spymaster_board is... | The code implements a two-player word guessing game where teams take turns using clues generated by a model to identify their assigned words on a board, aiming to complete their set before the opponent while avoiding the assassin card. | def play_game_as_player(m):
"""
Starts up a game with a given model to guess words
"""
gamewords, spymaster_board, current_board, first, second = generate_board(m)
red_words = []
blue_words = []
neutral_words = []
assassin_word = ""
# Separate the board into their respective lists
for combo in sp... |
def print(
self, string: str = "", colors: bool = False, add_to_history: bool = False, **print_args
) -> None:
"""Print text using custom options.
Parameters
----------
string : str
colors : bool
If False, ANSI colors will be turned off.
add_to_hi... | The function compares two lists, checking if their contents are identical (with optional order sensitivity), and returns counts of unique items in each list and shared items. If contents match, it returns (0, 0, len(list_a)); otherwise, it calculates and displays differences via side-by-side comparisons, returning (lef... | def lists_diff(
self,
list_a: list,
list_b: list,
ignore_order: bool = True,
) -> tuple[int, int, int]:
"""Compare two lists and state whether there are differences."""
set_a, set_b = set(list_a), set(list_b)
s_union = set_a.union(set_b)
# Are these ... |
def _get_dims(nc_filepath: Union[str, Path]) -> list:
def __get_dim_list(decode_times=True):
with xr.open_dataset(nc_filepath, decode_times=decode_times) as dataset:
return list(dataset.dims.items())
try:
dims_list = __get_dim_list()
except ValueError as err:
if "decode_... | The function compares two NetCDF files by analyzing structural elements (dimensions, groups, variables) and data values. It checks differences in root-level dimensions and groups, then evaluates variables within a specified group. If a variable is provided, it prints sample values and compares random entries between fi... | def run_through_comparisons(
out: Outputter,
nc_a: Union[str, Path],
nc_b: Union[str, Path],
comparison_var_group: Optional[str],
comparison_var_name: Optional[str],
show_chunks: bool,
show_attributes: bool,
) -> None:
"""Execute a series of comparisons between two NetCDF files.
Par... |
def choose_actions(self):
"""Choose the best candidates for actions and enqueue them."""
for action in sorted(self.actions.values(), key=lambda x: x.source):
self.consider_action(action)
def execute_actions(self):
"""Execute the queued actions grouped by the target directory."""
... | The code's main task is to orchestrate a sequence of operations: selecting appropriate actions, executing them, and then cleaning up any resources or states afterward, ensuring a structured and completed workflow. | def run(self):
self.choose_actions()
self.execute_actions()
self.cleanup_actions() |
def run_make(targets, container, args, variables={}, jobs=1):
mvars = map(lambda kv: kv[0] + "=" + kv[1], variables.items())
jobs_str = "-j{0}".format(jobs)
return run_cmd(container=container,
command=["make"] + list(mvars) + [jobs_str] + targets,
args=args)
def find_s... | The main task of the code is to execute sanitizer tests within a container. It first builds test targets, then iterates through identified sanitizers to build each, and finally runs a dedicated script to execute sanitizer checks, passing additional command-line arguments. The process halts immediately if any build or e... | def do_sanitizers(container, args):
"""Run sanitizers"""
if not run_make(["tests"], container, args,
variables={"TARGET_ARCH": "tests"},
jobs=args.jobs):
return
for t in find_sanitizers(args):
if not run_make(["tests"], container, args,
... |
def is_greenhouse_too_hot():
latest_reading = get_latest_reading()
temptrigger = float(os.environ.get('TEMPERATURE_HIGH_TRIGGER', 100.0))
if "temperature" in latest_reading:
try:
return float(latest_reading["temperature"]) > temptrigger
except ValueError:
print("Could... | The code monitors greenhouse temperature, triggers fans if too hot, stops them if cool enough, and logs the check timestamp. | def check_greenhouse_temp():
# Figure out whether the temp is greater than the threshold
# If it is, trigger the greenhouse fans
if is_greenhouse_too_hot():
start_greenhouse_fans()
if is_greenhouse_cool_enough():
stop_greenhouse_fans()
current_time = datetime.now().str... |
def get_div_problem(r, alpha, a1, a2, D):
A_offset = 1
b1 = 0.0
pow_r1 = (1 - alpha*a1)**r
pow_r2 = (1 - alpha*a2)**r
pow_2r1 = (1 - alpha*a1)**(2*r)
pow_2r2 = (1 - alpha*a2)**(2*r)
b2 = np.sqrt(D*2)*2/np.abs((a1*pow_2r1 + a2*pow_2r2)*pow_r2/(a1*pow_r1 + a2*pow_r2) - pow_2r2)
A = np.a... | The code simulates and visualizes two mathematical tasks (T¹ and T²) and their optimization dynamics. It generates plots of task functions, compares FOM/UFOM optimization results via loss curves, and visualizes gradient magnitudes over iterations. Parameters define problem settings, while simulations evaluate convergen... | def simulate_fo_div():
r = 10
alpha = 0.1
a1 = 0.5
a2 = 1.5
D = 0.06
b1, b2, A = get_div_problem(r, alpha, a1, a2, D)
print(b1, b2, A)
x0_min = -10
x0_max = 30
draw_points_count = 1000
samples_count = 5
as_ = np.array([a1, a2])
bs = np.array([b1, b2])
task_d... |
def events(self):
#game loop - events
for event in pg.event.get():
if event.type == pg.QUIT:
if self.playing:
self.playing = False
self.running = False
''''if event.type == pg.KEYDOWN and event.key == pg.K_c:
... | The code's main task is to execute a game loop that maintains the game's frame rate, processes events, updates game logic, renders graphics, and displays an escape screen, ensuring continuous gameplay until the loop terminates. | def run(self):
self.playing = True
print("method called")
while self.playing:
self.clock.tick(settings.FPS)
self.events()
self.update()
self.draw()
self.show_escape_screen() |
def deleteUploadFileHelper(job_status, job_info, WEBHOOK):
"""
Helper to delete the upload file
:param job_status: event_message TranscriptionJobStatus
:param job_info: get_transcription_job TranscriptionJob
:param WEBHOOK: webhook for teams notification
"""
if job_status == "COMPLETED":
... | The Lambda function processes SQS messages triggering transcription job handling. It checks job status, retrieves transcripts, generates DOCX files (if duration limits are met), uploads to S3, and notifies Teams of success/failure. Failed jobs or exceeding duration limits trigger alerts, while valid outputs are stored ... | def lambda_handler(event, context):
"""
Entrypoint for the Lambda function. Pulls batch of messages from SQS standard queue.
"""
print(f"audio_to_transcribe.lambda_handler started")
# Get environment variables
TIMEOUT = int(os.environ['TIMEOUT']) # Timeout for docx generation in millisec... |
def load_transcribe_job_status(cli_args):
"""
Loads in the job status for the job named in cli_args.inputJob. This will try both the standard Transcribe API
as well as the Analytics API, as the customer may not know which one their job relates to
:param cli_args: CLI arguments used for this processing... | The main task of the code is to convert Amazon Transcribe JSON output into an MS Word document via a CLI tool. It accepts either a JSON file or a Transcribe job ID, validates job status, downloads transcripts if needed, processes speaker/channel data from the JSON, and generates a `.docx` file with optional confidence ... | def generate_document():
"""
Entrypoint for the command-line interface.
"""
# Parameter extraction
cli_parser = argparse.ArgumentParser(prog='transcribe_to_docx',
description='Turn an Amazon Transcribe job output into an MS Word document')
source_group = ... |
def process_ibd_hbd(ibd, hbd, endMarkers, bins, num_haps):
#read ibd.gz and hbd.gz file
#return effective sample size for each bin and mean number of IBD segments in each bin
hapPair2Index = {}
n_pairs = int(num_haps*(num_haps-1)/2)
IBD_matrix = np.zeros((n_pairs, len(bins)))
IBD_count_censored... | The code processes IBD/HBD data to estimate effective population size (Ne) trajectories via maximum likelihood. It parses input files, computes statistics (effective sample size, IBD counts), evaluates objective functions against reference Ne data if provided, and fits an MLE-based Ne trajectory. The output includes th... | def main():
parser = argparse.ArgumentParser()
parser.add_argument('--ibd', action="store", dest="ibd", type=str, required=True)
parser.add_argument('--hbd', action="store", dest="hbd", type=str, required=True)
parser.add_argument('-e', action='store', dest='end', type=str, required=True, help="path to ... |
def plot_1d(cube, plot_method, gridlines):
"""
Produces a plot object for 1D cubes using the quickplot.plot() method or
the matplotlib.pyplot.plot() method.
Args:
* cube
The 1D cube to be plotted.
* plot_method
String holding the users choice of plotting using either quickplot... | The function updates a visualization by generating a sub_cube from the input cube based on current interface settings, then plots it using specified parameters. It returns the plotted sub_cube and a flag indicating if the set_global method was needed to adjust the plot's extent. | def update(status):
"""
Called whenever the update button is pressed.
This function takes the status of the interface of its argument, and
returns the sub_cube that has been plotted, and whether or not the set
global method has been used.
Args:
* status
A dictionary representing t... |
def get_branding(url: str, on_prem_source: bool):
dracoon_url = 'https://dracoon.team'
# remove trailing / if present
if url[-1] == '/':
url = url[:-1]
headers = {
"accept": "application/json"
}
if on_prem_source:
api_url = dracoon_url + '/branding/api/v1/public/bra... | The code extracts branding data from a source URL, processes color details, generates a JSON file, and packages it with specific images into a ZIP archive. It filters only 'normal' color types, writes parsed branding data to 'branding.json', zips it with large-format images, then deletes temporary files. The task is to... | def zip_branding(source_url: str, zip_name: str, on_prem_source: bool):
branding_json = get_branding(source_url, on_prem_source)
download_images(branding_json)
parsed_colors = []
# parse colors (only normal color required)
for color in branding_json['colors']:
for details in color['colorD... |
def upload_images(url: str, auth_header):
# remove trailing / if present
if url[-1] == '/':
url = url[:-1]
# public branding API endpoint
api_url = url + '/branding/api/v1/branding/files'
images = ['webLogo' ,'webSplashImage', 'squaredLogo', 'appSplashImage', 'appLogo']
image_ids = []... | The main task of the code is to load branding assets from a ZIP file, validate required files, upload images, parse and modify branding JSON data, and apply the updated branding configuration to a server via an API call. It ensures all necessary files are present, extracts them, processes color data, and handles cleanu... | def load_from_zip(zip_file: str, url: str, auth_header):
with zipfile.ZipFile('branding.zip', 'r') as branding_zip:
branding_files = branding_zip.namelist()
required_files = ['branding.json', 'webLogo_large.png', 'webSplashImage_large.png',
'squaredLogo_large.png', 'appSplashImage_large.pn... |
def loglikelihood(x,data):
betap = x[0]#[0]
gammap = x[1]#0.95
psip = 0.2#x[2]
tend2 = np.max(data)
get = quad(phi_integrand, 0, tend2,args=(betap,gammap,psip))[0]
for i in np.diagonal(data):
st = tend2 - i
res, err = quad(phi_integrand, 0, st, args=(betap,gammap,psip))
... | The code implements the Metropolis-Hastings algorithm to generate samples from a posterior distribution. It starts with an initial parameter value, iteratively proposes new samples via a symmetric transition model, evaluates their likelihood and prior probabilities, and accepts/rejects them based on an acceptance rule.... | def metropolis_hastings(param_init,iterations,data):
# likelihood_computer(x,data): returns the likelihood that these parameters generated the data
# transition_model(x): a function that draws a sample from a symmetric distribution and returns it
# param_init: a starting sample
# iterations: number of a... |
def print_infos(file_name, file_path):
print(get_color("A simplified-securify2 for reentrancy detection", "BLUE"))
print("")
print(get_color("Contracts Analyzed!", "BLUE"))
print_format("FileName:", file_name, "BLUE")
print_format("FilePath:", file_path, "BLUE")
def get_color(code, color):
color... | This function prints reentrancy violations in a formatted way, highlighting affected code lines with visual markers and color coding. It processes violation details, calculates code positions, and displays numbered violations with contract names, line numbers, and annotated source code. If no violations exist, it outpu... | def print_violations(violations, contract, file_name, file_path):
print_infos(file_name, file_path)
if violations:
for violation in violations:
num = violation.getId()
line = violation.getLine()
loc = violation.getLoc()
contract_name = violation.getC... |
def _generate_population(self):
population = {}
for b_name in self.b_names:
actions = []
state = np.full(self.pop - 1, self.current_SoC[b_name])
for _ in range(self.horizon):
action = np.random.uniform(np.maximum(-1 * state, self.low_bound),
... | This code performs evolutionary optimization to minimize an objective function over multiple generations. It initializes a population of actions, evaluates their fitness, and iteratively generates new actions. If new actions yield lower objective values, they replace the old ones. The process stops when convergence (st... | def optimize(self, generations: int, tol: float = 0.01,
future_states: dict = None,
future_electricity=None, future_carbon=None
):
# initialize
actions = self._generate_population()
obj = self.objective_function(actions, future_states, future_el... |
def _assert_is_bool_numpy_array(name, array):
_assert_is_numpy_array(name, array)
if array.dtype != bool:
raise ValueError(
"The argument {!r} should be a numpy array of type bool, "
"not {}".format(name, array.dtype))
def _check_2d_numpy_array(name, array):
_check_nd_numpy_a... | This function computes the closest distances between surface elements (contours in 2D, surfels in 3D) of two binary masks (ground truth and prediction) using voxel spacing. It calculates distances from all surface points of one mask to the other, along with their lengths/areas in mm, returning sorted distance lists and... | def compute_surface_distances(mask_gt, mask_pred, spacing_mm):
"""Computes closest distances from all surface points to the other surface.
This function can be applied to 2D or 3D tensors. For 2D, both masks must be
2D and `spacing_mm` must be a 2-element list. For 3D, both masks must be 3D
and `spacing_mm` ... |
def make_mask(rle, shape, resize_fraction):
if resize_fraction < 0.0 or resize_fraction > 1.0:
raise ValueError("`resize_fraction` must be between 0.0 and 1.0, inclusive.")
mask = rle_decode(rle, shape)
if resize_fraction < 1.0:
new_shape = int(shape[0] * resize_fraction), int(shape[1] * re... | The function calculates the **Mean Surface Dice** score to evaluate the similarity between predicted (submission) and ground-truth (solution) 2D/3D masks encoded in run-length format (RLE). It decodes RLE masks, computes surface distances between predicted and true masks with a given tolerance, and averages the Surface... | def score(
solution: pd.DataFrame,
submission: pd.DataFrame,
row_id_column_name: str,
rle_column_name: str,
tolerance: float = 1.0,
image_id_column_name: Optional[str] = None,
slice_id_column_name: Optional[str] = None,
resize_fraction: float = 1.0,
) -> float:
"""Mean Surface Dice o... |
def read_csv() -> List[List[float]]:
"""Read all members of csv."""
reader = csv.reader(open('weights.csv', 'r', newline=''), quoting=csv.QUOTE_NONNUMERIC)
weights = []
for row in reader:
weights.append(row)
return weights
def initiate(size: int = SIZE) -> List[List[float]]:
"""Make an i... | (The code evolves a population of game strategies by either initializing new members or using previous weights, then selects the best-performing individuals through pairwise comparison to generate a new generation, which is saved for future iterations.) | def run(size: int = SIZE) -> None:
"""Create an initial population if none available and test members of the population against
one another to try and select for traits that provide the best chance to win in a 1v1 game.
Preconditions:
- size >= 2"""
# read weights.csv for previous weights
prev_... |
def prepare_data(self):
if os.path.exists('train_data.npy'):
train_data = np.load('train_data.npy', allow_pickle=True)
else:
train_data = self.create_train_data()
if os.path.exists('test_data.npy'):
test_data = np.load('test_data.npy', allow_pickle=True)
... | The code initializes a class by setting up data attributes (X_train, y_train, X_test, y_test) and a model. It calls methods to prepare data, define the model architecture, and retrieve the model, preparing the system for training and evaluation. | def __init__(self):
self.model = None
self.X_test = None
self.y_test = None
self.X_train = None
self.y_train = None
self.prepare_data()
self.model_arch()
self.get_model() |
def generate_keys(n_bits):
N = 1
p = q = 1
while N.bit_length() != n_bits:
prime_size = n_bits // 2
p = generate_prime(prime_size)
q = generate_prime(n_bits - prime_size)
N = p * q
phi_N = (p - 1) * (q - 1)
e = random.randrange(3, phi_N)
while True:
... | The main task of the code is to perform RSA encryption/decryption using pre-generated or provided keys. It reads public and secret keys from files, then encrypts plaintext or decrypts ciphertext based on command-line arguments. The function either generates new keys, loads existing ones, and applies encryption/decrypti... | def Textbook_RSA():
if args.generate_keys:
generate_keys(args.n_bits)
return
else:
public_key = []
secret_key = []
with open('./key/RSA_Public_Key.txt', 'r') as file:
lines = file.readlines()
for line in lines:
public_key.append(in... |
def _get_extractor_list(to_include: list, to_exclude: list) -> list:
""" Helper function to get a list of extractors given lists of extractors to include/exclude
Args:
to_include ([str]): Predefined list of extractors to run. Only these will be used.
Mutually exclusive with `exclude_extract... | This function processes all files in a specified directory using configured extractors and adapters. It applies context parameters, filters extractors (via inclusion/exclusion lists), maps extractors to adapters, and yields results as (file group, extractor name, metadata) tuples. Adapters transform metadata if defined... | def run_all_extractors_on_directory(directory: str, global_context=None,
adapter_context: Union[None, dict] = None,
extractor_context: Union[None, dict] = None,
include_extractors: Union[None, List[str]] = None,
... |
def _get_extractor_list(to_include: list, to_exclude: list) -> list:
""" Helper function to get a list of extractors given lists of extractors to include/exclude
Args:
to_include ([str]): Predefined list of extractors to run. Only these will be used.
Mutually exclusive with `exclude_extract... | The function `run_all_extractors_on_group` processes a group of files to extract metadata using specified extractors and adapters. It applies user-defined context and adapter mappings, allowing customization of extraction behavior. The function iterates over each extractor, determines the appropriate adapter, and yield... | def run_all_extractors_on_group(group,
adapter_map=None,
global_context=None,
adapter_context: Union[None, dict] = None,
extractor_context: Union[None, dict] = None,
... |
def predict_batch(model, x_batch, mask_batch):
pred = model.forward(x_batch)
pred = torch.sigmoid(pred)
D_ = cons_min[0] + pred[:,0,:,:,:].flatten(1)[mask_batch] * (cons_max[0] - cons_min[0])
f_ = cons_min[1] + pred[:,1,:,:,:].flatten(1)[mask_batch] * (cons_max[1] - cons_min[1])
Dp_ = cons_min[2] +... | The code trains a neural network model using a training and validation dataloader, performing forward passes, computing physics-informed losses (D, f, Dp), backpropagation, and early stopping based on validation loss. It tracks epoch-wise losses, saves the best model state, and returns the model path upon convergence. | def train(model, train_dataloader, valid_dataloader, optimizer, patience=10):
timestamp = datetime.now()
model.train()
epoch_n = 0
n_bad_epochs = 0
best_loss = np.inf
while n_bad_epochs < patience:
epoch_n +=1
epoch_loss = np.zeros(4) #losses per epoch: [total, D , f, Dp]
... |
def get_taxis(city=''):
if city:
url = TAXI_ENDPOINT + '/' + city.lower()
else:
url = TAXI_ENDPOINT
taxis = utilities.api_call(url)
return taxis["data"]
def get_taxi_info(city, taxi_id):
url = TAXI_ENDPOINT + '/' + city + "/" + taxi_id
taxi_info = utilities.api_call(url)
retu... | This code handles user commands for a taxi service bot, updating global variables like city, address, and coordinates. It processes commands to retrieve taxi listings, set user locations, fetch taxi details, and book rides, then sends formatted responses via Slack. | def handle_command(command, channel):
"""
Executes bot command if the command is known
"""
# Default response is help text for the user
default_response = "Sorry I did not understand you command. Try: "
for example in EXAMPLE_COMMAND:
default_response+= "\n - " + example
# Finds ... |
def read_matches() -> pd.DataFrame:
M1 = pd.read_csv("matches_10_15.csv",dtype=matches_dtypes,parse_dates=["date"], encoding = "ISO-8859-1")
M2 = pd.read_csv("matches_16_end.csv",dtype=matches_dtypes,parse_dates=["date"], encoding = "ISO-8859-1")
M = pd.concat([M1,M2]).reset_index(drop=True)
M["match_id... | The function creates a master DataFrame by merging matches, tournaments, cities, and elo data, adding tournament year, and optionally including previous match details (surface, scores, Elo values) and Elo-based win probabilities for winners and losers, with configurable inclusion of city data and historical columns. | def create_master_table(previous_columns_bool: bool = False, cities_bool: bool = False, matches_table: pd.DataFrame = read_matches(), tournaments_table: pd.DataFrame = read_tournaments(), cities_table: pd.DataFrame = read_cities()) -> pd.DataFrame:
"""
Args:
M (pandas dataframe): corresponds to mat... |
def read_matches() -> pd.DataFrame:
M1 = pd.read_csv("matches_10_15.csv",dtype=matches_dtypes,parse_dates=["date"], encoding = "ISO-8859-1")
M2 = pd.read_csv("matches_16_end.csv",dtype=matches_dtypes,parse_dates=["date"], encoding = "ISO-8859-1")
M = pd.concat([M1,M2]).reset_index(drop=True)
M["match_id... | The code downloads tennis match, player, and tournament data from GitHub for a specified year, processes the data by cleaning and merging with existing databases, and returns new entries for matches, tournaments, and players not already present in the provided tables. | def download_from_github(year: int = datetime.now().year, matches_table: pd.DataFrame = read_matches(), players_table: pd.DataFrame = read_players(), tournaments_table: pd.DataFrame = read_tournaments()):
matches_github_columns = ["tourney_id","tourney_name","surface","tourney_date","score","best_of","round","... |
def record_moves(moves:list):
x = 0
y = 0
xs = [x]
ys = [y]
lines = []
for move in moves:
old_x = x
old_y = y
x,y = do_move(x,y,move)
xs.append(x)
ys.append(y)
if x==old_x:
LineClass = VerticalLine
else:
LineCla... | The code calculates the smallest Manhattan distance between intersection points of two sets of lines generated from input move strings. It splits the input strings into move sequences, converts them into line paths, identifies their intersections, and determines the closest intersection using Manhattan distance.
You... | def run(moves1_str:str, moves2_str:str):
moves1 = moves1_str.split(',')
moves2 = moves2_str.split(',')
lines1 = record_moves(moves=moves1)
lines2 = record_moves(moves=moves2)
xs,ys = get_intersections(lines1=lines1, lines2=lines2)
smallest_distance = None
for x,y in zip(xs,ys):
di... |
def get_epoch_snapshot(self, epoch):
return OrderedDict()
def collect_data(self, task_z, num_samples):
'''
get trajectories from current env in batch mode with given policy
collect complete trajectories until the number of collected transitions >= num_samples
'''
num_tran... | This code implements a meta-training loop for a meta-learning algorithm. It pretrains the model, iteratively samples tasks, collects data, performs gradient updates on parameters using sampled tasks, and evaluates the model periodically. The core task involves meta-updating parameters across multiple tasks per iteratio... | def train(self):
'''
meta-training loop
'''
self.pretrain()
params = self.get_epoch_snapshot(-1)
logger.save_itr_params(-1, params)
gt.reset()
gt.set_def_unique(False)
# at each iteration, we first collect data from tasks, perform meta-updates, th... |
def getOneWinning(self):
winning = []
emptyPoints = self.board.get_empty_points()
moves = []
for p in emptyPoints:
if self.board.is_legal(p, self.color):
moves.append(p)
for move in moves:
board = self.board.copy()
board.play_m... | The code determines the optimal move strategy in a game by prioritizing: 1) Winning moves, 2) Blocking opponent's win, 3) Creating open four, 4) Blocking open four, and 5) Random moves if no priority moves exist. It returns the move type and list of valid moves based on this hierarchy, ensuring strategic decision-makin... | def getMoves(self):
moveType = None
moveList = []
if not self.random:
moveType = "Win"
moveList = self.getOneWinning()
if len(moveList) == 0:
moveType = "BlockWin"
moveList = self.getBlockWin()
if len(moveList) =... |
def create_widgets(self):
for j, col_hint in enumerate(self.board.col_hints):
hint_str = "-".join(map(str, col_hint))
label = tk.Label(self, text=hint_str, padx=10, pady=10)
label.grid(row=0, column=j + 1, sticky=tk.W + tk.E)
for i in range(self.number_of_rows):
... | This code initializes a GUI component for a board puzzle, copying the board, attempting to solve it, and setting up UI elements like buttons and solution controls. It stores the solved state if successful, handles errors, and prepares the interface for interaction. | def __init__(self, parent, board):
super().__init__(parent)
self.parent = parent
self.board = board
self.original_board = copy.deepcopy(board)
self.pack(fill=tk.BOTH, expand=True)
# Try to solve a copy of the board and store the solution
try:
self.sol... |
def get_images_list(dir_name: str) -> list:
path = f'data/labelIds/{dir_name}/'
img_list = [file for file in os.listdir(path)]
return img_list
def crop_image_by_coordinates(dir_name: str, origin_img: Image, coordinates: np.array, label: int):
x_coordinates, y_coordinates = coordinates
x = x_coordin... | The code processes images to extract traffic light (TFL) regions and non-TFL regions. It loads label images, identifies TFL coordinates (value 19), crops original images using these coordinates (labeled 1), and also crops non-TFL areas (labeled 0) for dataset preparation, likely for segmentation or classification tasks... | def prepare_dataset(dir_name: str) -> None:
img_list = get_images_list(dir_name)
for img_name in img_list:
image = Image.open(f'data/labelIds/{img_name}')
tfl_coordinates = np.where(np.array(image) == 19)
if tfl_coordinates[0].any():
origin_img = Image.open(f'data/leftImg8b... |
def process_t1(sub):
"""
Processes T1-weighted MRI images by converting DICOM to NIfTI format if necessary.
"""
# Iterate through specific T1-weighted image types: UNI, INV1, INV2.
for mp_file in ['UNI', 'INV1', 'INV2']:
# Check if NIfTI files for the T1 image type exist.
if not glob... | The main task of the code is to process MRI images across multiple subject directories by copying T2star files, executing image processing pipelines (e.g., T1, neuromelanin, BET), handling errors for missing data, and generating statistical analyses. It iterates through subjects, applies specific processing steps, and ... | def main():
"""
Main function to orchestrate the processing of MRI images, including directory setup, image processing, and statistical analysis.
"""
for subjects_dir in subjects_dirs:
# Perform operations with each directory
print(f"Processing directory: {subjects_dir}")
for i, su... |
def is_pseudo_element(self):
return self.atom_type == "PseudoElementAtom"
def is_anon_box(self):
if self.is_tree_pseudo_element():
return False
return self.is_non_inheriting_anon_box() or self.is_inheriting_anon_box()
def is_tree_pseudo_element(self):
return self.value.starts... | This code initializes an object representing a specialized atom type (e.g., for Gecko's nsStaticAtom), setting attributes like identifier, value, hash, and type. It processes pseudo-elements/anon-boxes by extracting sub-identifiers and validates anon-box categorization through assertions. | def __init__(self, ident, value, hash, ty, atom_type):
self.ident = "nsGkAtoms_{}".format(ident)
self.original_ident = ident
self.value = value
self.hash = hash
# The Gecko type: "nsStaticAtom", "nsCSSPseudoElementStaticAtom", or
# "nsAnonBoxPseudoStaticAtom".
sel... |
def select_parents(population, k=2):
parents = []
fitnesses = {}
# Calculate fitness for all individuals
for individual in population:
fitnesses[str(individual)] = fitness(individual, model, train_loader, test_loader, criterion)
# Select the k individuals with highest fitness
f... | The function `evolve` generates a new population of neural networks through genetic operations. It repeatedly selects parent networks, applies crossover to create offspring, and introduces mutations. This process continues until the new population reaches the specified size (`popSize`), using parameters like `k` for se... | def evolve(population, model, train_loader, test_loader, criterion, popSize=10, k=2, mutation_rate=0.1):
new_population = []
# Select two parents and generate two offspring until population is filled
while len(new_population) < popSize:
parents = select_parents(population, k=k)
offsprin... |
def _create_cells(self):
for i in range(self._num_rows):
row = []
for j in range(self._num_cols):
row.append(Cell(self._win))
self._cells.append(row)
if self._win is not None:
for i in range(self._num_rows):
for j in rang... | This code initializes a maze structure by setting up grid dimensions, cell sizes, and a window. It creates cells, breaks walls recursively using a randomized algorithm, and prepares the maze for solving by resetting visited states. | def __init__(self, x1, y1, num_rows, num_cols, cell_size_x, cell_size_y, win=None, seed=None):
self._x1 = x1
self._y1 = y1
self._num_rows = num_rows
self._num_cols = num_cols
self._cell_size_x = cell_size_x
self._cell_size_y = cell_size_y
self._win = win
... |
def logger(mensaje):
now = datetime.now()
dt_string = now.strftime("%Y-%m-%d_%H:%M:%S")
print(dt_string + " " + mensaje)
def contar():
csv = open(INPUT_PATH+'/'+today+'_rdy_to_load.csv')
numline = len(csv.readlines())
logger("Se insertaran " +str(numline-1)+ " registros del documento descargad... | The code defines a function `job()` that orchestrates a workflow: it redirects console output to a log file, logs process steps, downloads a CSV file using an external script, counts data, loads it into a database via SQL execution, moves input files to an output directory, and logs completion. The main task is to auto... | def job():
sys.stdout = open(logFile, "w")
logger("Inicia el proceso Orquestador.")
logger("Inicia el proceso de descarga del documento CSV.")
os.system(ACTUAL_PATH+"/csv_downloader.py")
logger("Descarga finalizada.")
contar()
logger("Inicia el proceso de carga a la BD.")
ejecutarSQL()
... |
def move(self,no):
if not self.started:
x,y = map(int,self.position(0))
i,j = map(int,self.position(no))
if((i==x-1 and j==y) or (i==x+1 and j==y) or (i==x and j==y-1) or (i==x and j==y+1) ):
self.board[i][j],self.board[x][y]=self.board[x][y],self.board[i][j]
self.display()
def start(self):
self.sta... | This code initializes a GUI for an 8-puzzle game using Tkinter. It sets up a 3x3 grid board with numbered buttons representing tiles, configures layout settings, and creates controls like a "Start" button to initiate gameplay. The board excludes the (0,0) position, and buttons are linked to movement logic. The interfac... | def __init__(self):
self.started = False
self.homePage = False
self.mainFrame = Tk()
self.mainFrame.title("8 Puzzle")
Grid.rowconfigure(self.mainFrame, 0, weight=1)
Grid.columnconfigure(self.mainFrame, 0, weight=1)
self.boardFrame = Frame(self.mainFrame,bg = "white")
self.board = [[0,1,2],[3,4,5],[6,7,... |
def get_binary_systems(zpe_structures):
sections = [list(), list(), list()]
systems = [list(), list(), list()]
structures = deepcopy(zpe_structures)
for structure in structures:
if len(structure['composition reduced']) == 3:
if structure['composition reduced'][0] == 0:
... | This function computes convex hulls for thermodynamic stability analysis across temperature ranges. It processes binary systems, updates structures with temperature-dependent fitness values using ExtendedConvexHull, saves results, and generates plots. Antiseeds are tracked to avoid redundant calculations. The output is... | def get_convex_hulls(zpe_structures, system, zpe_path, temp, plot, press):
press = int(press / 10)
antiseeds = dict()
sections = list()
new_temp = np.arange(0, 2010, 10)
for _t in new_temp:
antiseeds[f'{str(_t)}'] = list()
if len(system) == 3:
sections, systems = get_binary_syste... |
def get_simplex(point, points, formula):
points = np.asarray(points)
x, y = point
_hull = ConvexHull(points)
result = np.zeros((3, 3))
n = 6
f = False
while result.any() == 0 and n > 0:
for triangle in points[_hull.simplices]:
if round(get_normal(triangle)[-1], 3) != 0:
... | The function computes new fitness values for structures in `self.zpe_structures` based on their convex hull positions, using 2D/3D simplex distance calculations. It updates fitness values for both ZPE and temperature-dependent cases, identifies stable structures (fitness ≤ 0), and records them in `self.old_stable` and ... | def get_new_fitness(self, sections=list(), print=True):
section_id = list()
section_old_fitness = list()
section_fitness = list()
for section in sections:
if len(section) > 2:
for structure in section:
if structure['id'] not in section_id:
... |
def init():
global _cd, _home, _dFiles, _tmp
_cd = os.getcwd()
_home = os.getenv('USERPROFILE')
_dFiles = []
_tmp = os.path.join(_home,".temp")
cleanup
createDir(_tmp)
def disableUpdate(loop=False):
# download windows update disable script
if os.path.isfile(os.path.join(_tmp, "dsu.p... | The main task of the code is to automate the installation and configuration of applications (e.g., Chrome, Bandizip, PyShell) while disabling update services. It uses multithreading to download and install software, applies registry settings for Bandizip, and deploys an anti-update service to prevent future updates. Th... | def main():
# init
print('Welcome to Sajibang QUICK Configurator! (' + _appVer + ')\n\n')
print('Initializing...')
init()
print('\nDisabling Update Services...')
_winScript = False
disableUpdate()
print('\nInstalling Applications:')
_urlList = [
'https://dl.google.com/tag/... |
def get_initial_centroids_strategy_2(n, data):
# randomly initialize first centroid indices
initial_centroid_indices = random.sample(range(0, len(data)), 1)
# get co-ordinates from the data for the centroid
centroids = get_coordinates_from_indices(initial_centroid_indices, data)
# get other centroid... | The code implements K-means clustering with Strategy 2 for centroid initialization, iterating k from 2 to 10. For each k, it initializes centroids, performs 20 iterations of assigning data points to clusters and updating centroids, then records the final distance sum. It returns objective function values across all k-v... | def implement_k_means_strategy_2(samples):
final_distance = []
for j in range(2, 11):
#get initial centroids using strategy 2
centroids_data = get_initial_centroids_strategy_2(j, samples)
centroids_data = np.array(centroids_data)
samples_array = np.array(samples)
print("I... |
def generate_pawn_moves(board, coordinate):
moves = []
color = board.get_piece(coordinate).get_color()
dir = -1 if color else 1
start_row = 6 if color else 1
next_to_last_row = 1 if color else 6
promotion = True if next_to_last_row == coordinate[1] else False
piece_one_square_ahead = board.... | The function `naive_move_generation` generates all valid moves for a specified player's pieces on a chessboard. It iterates through each cell, checks if the piece's type and color match the input, and appends moves generated by specialized functions for each piece type (pawn, knight, etc.). The collected moves are retu... | def naive_move_generation(board, color):
moves = []
for i in range(8):
for j in range(8):
piece = board.get_piece((i, j))
type = piece.get_type()
piece_color = piece.get_color()
if type == 'Pawn' and color == piece_color:
moves += generate_... |
def naive_move_generation(board, color):
moves = []
for i in range(8):
for j in range(8):
piece = board.get_piece((i, j))
type = piece.get_type()
piece_color = piece.get_color()
if type == 'Pawn' and color == piece_color:
moves += generate_... | The code generates all valid, unambiguous moves for a given player on a board. It first creates naive moves, filters out illegal ones, and resolves ambiguities to return a list of clear, executable moves. | def generate_moves(board, color):
naive_moves = naive_move_generation(board, color)
legal_moves = remove_illegal_moves(board, naive_moves, not color)
unambiguous_moves = remove_ambiguity_from_moves(legal_moves)
return unambiguous_moves |
def create_new_booking(booking_lst):
form = {
'guest_name': '',
'guest_checkin': '',
'guest_checkout': ''
} # Create a form template
validate_form(form) # Validate guess infos
booking_lst.append(form) # Add a new booking to booking database
print('Booking added successful... | This code manages hotel room bookings by allowing users to create, view, and calculate minimum required rooms based on existing bookings. It provides a menu-driven interface for adding bookings, displaying them, and determining room needs, ensuring at least two bookings are present for the calculation. | def hotel_room_booking_management():
# Initialize vars
booking_lst = []
# Welcome message
print('''
========================================
WELCOME TO HOTEL ROOM BOOKING MANAGEMENT
========================================
1. Create Booking
2. View Booking
3. Minimum Room Required Calculator
... |
def load_data(filename):
return np.genfromtxt(filename, delimiter=',')
def lsh_setup(A, k = 24, L = 10):
functions = create_functions(k = k, L = L)
hashed_A = hash_data(functions, A)
return (functions, hashed_A)
def lsh_search(A, hashed_A, functions, query_index, num_neighbors = 3):
hashed_point = h... | The code's main task is to analyze and compare the performance of Locality-Sensitive Hashing (LSH) and linear search methods. It measures average search times for both techniques when `problem="time"`, evaluates error rates for varying LSH parameters (`L` and `k`) when `problem="error"`, and retrieves top-10 nearest ne... | def main(problem):
A = load_data("data/patches.csv")
##### AVERAGE TIME #####
if problem == "time":
LSH_time = []
lin_time = []
f, hashed = lsh_setup(A)
for i in range(99, 1000, 100):
start_time = time.time()
lsh_search(A, hashed, f, i, 3)
... |
def loadData(datafile, dataset_type):
'''
Load data from datafile, selecting portion appropriate to dataset_type
'''
data = np.loadtxt(datafile)
if dataset_type == 'high_accuracy_spot':
data = data[:N_HIGH_ACCURACY,:] # Select only the high accuracy points
elif dataset_type == 'all_spot'... | The main task of the code is to compute spherical harmonic coefficients and the inverse covariance matrix (Sigma) for a Gaussian Process (GP) using observed topography data and hyperparameters. It loads data, constructs a Matern-based covariance matrix with noise, solves a linear system to obtain coefficients, and save... | def obtainSpectrum(dataset_type,datafile,paramfile,outfile,Lmax):
'''
Compute inverse covariance matrix for GP based on observed data and chosen
hyperparameters.
Inputs:
dataset_type - str, "high_accuracy_spot","all_spot" or "spot_shiptrack"
datafile - Path to residual topography dataset
pa... |
def endGame(self):
return sum([self.alone(i,j) for i in range(self.nc)
for j in range(self.nr)]) == self.nr * self.nc
def score_correction(self):
rem = sum(bool(self.colors[c][r]) for c in range(self.nc)
for r in range(self.nr))
if... | The main task of the code is to render a game board by drawing colored tiles based on the game state, display the current score, and handle end-game logic by compacting tiles and displaying an "End of Game" message when the game concludes. It uses Py5 (p5.js) for visual rendering, iterating over a grid to position tile... | def plotBoard(self):
for row in range(NROWS):
for col in range(NCOLS):
xc, yc = self.pos[col][row]
p5.fill(cell_colors[self.colors[col][row]])
p5.rect(xc,yc,B_WIDTH,B_WIDTH)
p5.fill(255)
p5.textSize(20)
p5.te... |
def read_filecontent():
file_read = open("movies_data.csv", "r")
file_content = [line.strip() for line in file_read.readlines()]
file_read.close()
linenumber = 0
headers = []
datacontent = []
dictionary_form = []
for data in file_content:
if linenumber == 0:
data = da... | The main task of the code is to update the "read_status" of a specified movie in a file. It searches for the movie by name, prompts the user to input a new read status ("yes" or "no"), updates the status if changed, appends the modified data to the file, deletes the original entry, and confirms the update. If the movie... | def change_readstatus(movie_name):
dictionary_form = read_filecontent()
search_field = movie_name
for data in dictionary_form:
if data["movie_name"] == search_field:
read_status_update = input("Can you please update the read status as 'yes' or 'no' :- ")
if data["read_status"... |
def get_numerator(x_points_list_removed_current_point):
number_of_points = len(x_points_list_removed_current_point)
# print("number_of_points => ",number_of_points)
coefficient_value_list = [1] * (number_of_points+1)
# print(x_points_list_removed_current_point)
for i in range(1,number_of_points... | The code calculates the **Lagrange interpolation polynomial** coefficients (in a finite field of prime 17) that pass through the given points. It constructs each basis polynomial for the points, computes their modular inverses, scales by the corresponding y-values, and sums the coefficients modulo 17. The result is a l... | def calculate_lagrange_polynomial(points):
"""
Calculate lagrange polynomial.
Consider the example below
Given points = [[1, 3], [4, 4], [16, 5], [13, 9]], the returned value calculated on base field of 17
should be list - [1, 13, 3, 3]
:param points: List of elements of form [x, y]. The retur... |
def operator_sz(spins: int) -> list:
'''
Returns the total square spin angular momentum operator along the z direction as a matrix.
'''
sz = operator_single_sz(spins, 0)
for i in range(1, spins):
sz += operator_single_sz(spins, i)
return sz
def operator_sxx(spins: int) -> ... | The code simulates the time evolution of a Dicke system with multiple two-level spins using a given Hamiltonian. It calculates and returns the probabilities of the system being in the fully-up state, along with internal and coupling energy observables at each time step. The simulation involves quantum state evolution v... | def classical_simulator(times: list, spins: int, coupling: float) -> (list, list, list):
'''
Given a time discretization, the number of two-level systems and the parameters of the Dicke
system, simulates the evolution of the system and calculate the average value of the observables
of interest at each ... |
def build_mass_and_metallicity_history(SAM_choice, directory, firstfile, lastfile, snap_limit):
'''
Build mass and metallicity history from the output directory of dusty-sage
Input: - SAM_choice (int): (0) SAGE (1) Dusty-SAGE
- directory (string) -- path to the directory containing dusty-sage o... | The code computes and saves multiple spectral energy distribution (SED) models for galaxies using different attenuation prescriptions (e.g., Lagos+19, Somerville+12, CF00). It processes input data to generate stellar, dust, and combined spectra, applying IR corrections, and stores results in an HDF5 file for a specifie... | def save_spectra(directory_input, fileNR, snap_limit, directory_output, Hubble_h):
Age = np.asarray([0.0124, 0.0246, 0.0491, 0.1037, 0.1871, 0.2120, 0.2399, 0.2709, 0.3054, 0.3438, 0.3864, 0.4335, 0.4856, 0.5430, 0.6062, 0.6756, 0.7517, 0.8349, 0.9259, 1.0249, 1.1327, 1.2496, 1.3763, 1.5131, 1.6606, 1.8192, 1.... |
def build_mass_and_metallicity_history(SAM_choice, directory, firstfile, lastfile, snap_limit):
'''
Build mass and metallicity history from the output directory of dusty-sage
Input: - SAM_choice (int): (0) SAGE (1) Dusty-SAGE
- directory (string) -- path to the directory containing dusty-sage o... | The code generates and saves galaxy spectral energy distributions (SEDs) using dust attenuation models, combining stellar and dusty components. It processes input data to compute mass, metallicity, and dust properties, applies attenuation parameters, generates SEDs with specified models (e.g., Lagos+19), and stores res... | def save_spectra_default(directory_input, fileNR, snap_limit, directory_output, Hubble_h):
Age = np.asarray([0.0124, 0.0246, 0.0491, 0.1037, 0.1871, 0.2120, 0.2399, 0.2709, 0.3054, 0.3438, 0.3864, 0.4335, 0.4856, 0.5430, 0.6062, 0.6756, 0.7517, 0.8349, 0.9259, 1.0249, 1.1327, 1.2496, 1.3763, 1.5131, 1.6606, 1.... |
def handle_edg(user_input):
if len(user_input) != 3:
print("[Client]: Correct usage: EDG [fileID] [dataAmount]")
return
_, file_id, data_amount = user_input
# ensure arguments are integers and that id is >= 0 and amount is > 0
if (not file_id.isdigit() or not data_amount.isdigit()) or (... | The main task of the code is to process user commands by routing them to corresponding handler functions. It continuously prompts the user for valid commands (EDG, UED, SCS, DTE, AED, UVF, OUT), validates the input, and executes the associated function with the appropriate parameters, such as client_socket or udp_socke... | def handle_commands(client_socket: socket, udp_socket: UdpSocketThread):
commands = ["EDG", "UED", "SCS", "DTE", "AED", "UVF", "OUT"]
while True:
user_input = input(
"Enter one of the following commands (EDG, UED, SCS, DTE, AED, UVF, OUT): "
).split()
# ensure a valid command... |
def verify_correct_usage(argv):
correct_usage = True
# check that the correct number of arguments have been provided
# also check that the port numbers given are in the correct range
if (
len(argv) != 4
or (not (1024 <= int(argv[2]) <= 65353))
or (not (1024 <= int(argv[3]) <= 65... | The code's main task is to initialize a client that connects to a server via TCP, authenticates, and sends its UDP port for communication. It verifies correct usage, checks port availability, starts a UDP socket thread, establishes TCP connection, handles authentication, transmits the UDP port to the server, and proces... | def main(argv):
# ensure the user is using the program correctly
if not verify_correct_usage(argv):
return
print("[Client]: Welcome!")
server_ip = argv[1]
server_port = int(argv[2])
client_udp_port = int(argv[3])
# ensure the udp_port is available
if not is_port_available((""... |
def remove_first(self):
"""
Remove the first element of the list. The list's current element becomes the next element of the removed one.
Returns:
element that has been removed.
Raises:
Exception: if list is empty.
"""
if self.is_empty():
... | This method removes an element at a specified index from a list. It checks if the index is valid, handles edge cases for first/last elements by calling remove_first/remove_last, otherwise navigates to the position, removes the element, and returns it. | def remove_at_position(self, index: int):
"""
Remove element at a given position from the list.
Once it has been removed, the list's current element becomes the previous
element of the removed element. However, if the element that was removed was
the list's first element, then t... |
def insert_at_start(self, value) -> None:
"""
Insert element at the start of the list.
Args:
value: element to be inserted.
Raises:
Exception: if list is full.
"""
if self.__num_of_elements == 0:
return self.__handle_insertion_with_em... | The main task of the code is to insert a specified value at a given index in a linked list. It validates the index range, handles edge cases for inserting at the start/end, and navigates to the target position using helper methods before inserting the value before the current node. | def insert_at_position(self, index: int, value) -> None:
"""
Insert element at a given index in the list.
Args:
index (int): position to insert the element in.
value: element to be inserted.
Raises:
Exception: if index is less than one or greater tha... |
def parse_args():
'''
Parse from command line
'''
parser = argparse.ArgumentParser(description="Read in edgelist and draw SCC decomposition")
parser.add_argument("--edgelist",
dest="edgelist", type=str, default=None,
help="edgelist to load.")
parser.add_argument("--output", dest="output",
type=str, defau... | The code decomposes a directed graph into strongly connected components (SCCs), analyzes the resulting hierarchy, and saves merge depths and the decomposed structure. It loads a graph from an edgelist, processes edge attributes, determines SCCs with specified constraints, identifies a root node, calculates merge depths... | def main():
args = parse_args()
edgelist_file = args.edgelist
print ("decomposing", edgelist_file)
g = load_graph(edgelist_file)
# g = nx.read_weighted_edgelist(edgelist_file,
# create_using=nx.DiGraph(),
# delimiter="\t")
if len(g) == 0:
print ("Graph is empty, nothing to decompose")
return
prin... |
def lambert_window(self, radius, lat0, long0):
''' Square Lambert Azimuthal equal area projection of
a window centered at (lat0, long0) with a given radius (km).
Args:
radius(float): Radius of the window (km).
lat0(float): Latitude at the center (degree).
lon... | This method generates a topographic map of a specified geographic region using LOLA instrument data from LRO. It creates a Lambert azimuthal equal-area projection, plots elevation data with a colormap, adds a reference point, scale bar, and colorbar, and optionally saves the image as a PNG file. | def lola_image(self, save=False, name='BaseLola.png'):
''' Draw the topography of the region of interest
Args:
save (Optional[bool]): Weither or not to save the image.
Defaults to False.
name (Optional[str]): Absolut path to save the resulting
ima... |
def lambert_window(self, radius, lat0, long0):
''' Square Lambert Azimuthal equal area projection of
a window centered at (lat0, long0) with a given radius (km).
Args:
radius(float): Radius of the window (km).
lat0(float): Latitude at the center (degree).
lon... | The main task of the code is to generate and display a wide-angle image of a specified geographic region using data from the LROC WAC instrument. It creates a map projection, plots the image data with a grayscale colormap, adds a central marker, a scale, and optionally saves the resulting image to a file. | def wac_image(self, save=False, name='BaseWac.png'):
''' Draw the wide angle image of the region of interest
Args:
save (Optional[bool]): Weither or not to save the image.
Defaults to False.
name (Optional[str]): Absolut path to save the resulting
... |
def lambert_window(self, radius, lat0, long0):
''' Square Lambert Azimuthal equal area projection of
a window centered at (lat0, long0) with a given radius (km).
Args:
radius(float): Radius of the window (km).
lat0(float): Latitude at the center (degree).
lon... | The main task of the code is to generate an image overlaying topography data (from LOLA) onto a wide-angle image (from LROC) of a lunar region using a Lambert azimuthal projection. It visualizes the combined data, adds a scale, colorbar, and a marker at a specified location, and optionally saves the result as a PNG fil... | def overlay(self, save=False, name='Baseoverlay.png'):
''' Draw the topography over a wide angle image of the region
Args:
save (Optional[bool]): Weither or not to save the image.
Defaults to False.
name (Optional[str]): Absolut path to save the resulting
... |
def _map_center(self, coord, val):
''' Identitify the center of the Image correspond to one coordinate. '''
if self.ppd in [4, 8, 16, 32, 64]:
res = {'lat': 0, 'long': 360}
return res[coord] / 2.0
elif self.ppd in [128]:
res = {'lat': 90, 'long': 90}
... | This function determines the processing case based on longitude and latitude overlaps between two coordinate sets. It checks if there's no overlap (case 1), longitude-only overlap (case 2), latitude-only overlap (case 3), or both (case 4), returning corresponding methods and printing processing time estimates. | def _define_case(self):
''' Identify case '''
lonBool = self._map_center(
'long', self.lonM) != self._map_center('long', self.lonm)
latBool = self._map_center(
'lat', self.latM) != self._map_center('lat', self.latm)
if not lonBool and not latBool:
pr... |
def entropy_discretization(s):
I = {}
i = 0
n = s.nunique()['Class']
s1 = pd.DataFrame()
s2 = pd.DataFrame()
distinct_values = s['A1'].value_counts().index
information_gain_indicies = []
print(f'The unique values for dataset s["A1"] are {distinct_values}')
for i in distinct_values:
... | The main task of the code is to process a dataset through entropy discretization, natural partitioning segmentation, correlation calculation, PCA dimensionality reduction, and output the transformed data to a compressed CSV file. It reads 'A1-dm.csv', applies statistical transformations, and writes the final results to... | def main():
s = pd.read_csv('A1-dm.csv')
print("******************************************************")
print("Entropy Discretization STARTED")
s = entropy_discretization(s)
print("Entropy Discretization COMPLETED")
print(s)
print("***********... |
def read_ligra_symmetric_graph(input_file):
G = nx.Graph()
with open(input_file, 'r') as reader:
reader.readline() # Discard AdjacencyGraph
n = int(reader.readline())
m = int(reader.readline())
offsets = [None] * (n+1)
offsets[n] = m
edges = [(0, 0)] * m
G.add_nodes_from(range(n))
fo... | The main task of the code is to execute a specified graph algorithm (from a predefined list) on a given input file, using either symmetric or directed graph reading based on command-line arguments. It processes three arguments: the input file path, symmetry flag, and the algorithm name, then parses and runs the selecte... | def main():
argv_len = len(sys.argv)
input_file = sys.argv[1] # First arg should be file name (ligra)
symmetric = (sys.argv[2] == "s") # Second arg should be s or w/e for symmetric or not
all_programs = ["ActualCoSimRank","CoSimRank","CoSimRankNumpy","BFS", "MaximalMatching", "KCore", "PageRank", "CliqueCountin... |
def get_knn(self, target: Union[int, np.ndarray], k: int = 4):
""" Returns ids to the nearest neighbours
from the target query. The target can be
an id from the dataset or a feature vector.
"""
target = self._get_feature_vector(target)
distances = np.dot(self._features, t... | This function identifies and visualizes the k-nearest neighbors of a given target (either a dataset ID or external feature vector) by retrieving them via `get_knn`, then displaying them in a grid with labels showing each neighbor's ID and similarity score to the target using `show_grid` | def show_knn(self, target: Union[int, np.ndarray], k: int = 4):
""" Shows images from the nearest neighbourhood
of the target. The target can be an id from the
dataset or an external feature vector."""
neighbors = self.get_knn(target, k)
self.show_grid(neighbors, lambda neigh,
... |
def get_nth_neighbours(self, target: Union[int, np.ndarray], nths: Iterable):
""" Returns ids to the nths nearest neighbours.
The target can be an id from the dataset or an
external feature vector.
"""
target = self._get_feature_vector(target)
distances = np.dot(self._fe... | The code displays the n-th nearest neighbors of a given target, either by dataset ID or external feature vector. It retrieves neighbors using `get_nth_neighbours`, then visualizes them in a grid with labels showing each neighbor's ID, similarity score to the target, and corresponding n-th value. | def show_nth_neighbours(self, target: Union[int, np.ndarray], nths: Iterable):
""" Shows the nths nearest neighbours.
The target can be an id from the dataset or an
external feature vector.
"""
neighbors = self.get_nth_neighbours(target, nths)
self.show_grid(neighbors, l... |
def get_track_subsamples(tracks, region, name):
subsamples = read_subsamples(SUBSAMPLE_DIR / f"TC_{region}_{name}.txt")
subsamples = filter_subsamples(name, region, subsamples)
track_names = np.array([tr.sid for tr in tracks.data])
if name == "IBTrACS_old":
# some IBTrACS storms changed their ... | The function `region_stats` computes and saves statistical metrics (e.g., track counts, landfall frequencies, intensity distributions) for wind events in specified regions (or globally) using threshold-based analyses. It processes subsampled tracks, calculates max/min wind data, derives normalized frequencies, and stor... | def region_stats(tracks_global, tr, reg, out_path):
if reg != "global":
tracks, subsamples_idx = get_track_subsamples(tracks_global, reg, tr)
else:
tracks = tracks_global
stats = {}
for thresh_km in [0, 50, 100, 150, 200, 250, 300]:
for mode in ["max", "all"]:
max_wi... |
def plot_stats(path, stats, with_separate):
fig = plt.figure(figsize=(16, 9))
if with_separate:
outer = matplotlib.gridspec.GridSpec(1, 2, width_ratios=[2, 1])
plot_stats_separate(outer[1], stats)
else:
outer = matplotlib.gridspec.GridSpec(2, 1, height_ratios=[20, 1])
ax_leg... | The main task of the code is to generate statistical plots from hazard or track data based on input parameters. If mode is "haz" or None, it plots hazard statistics. Otherwise, it iterates over thresholds (0–300) and modes ("max", "all") to generate track-based plots, saving them in the OUTPUT_DIR with filenames indica... | def main(mode=None, with_separate=False):
suffix = "_wsep" if with_separate else ""
if mode is None or mode.lower() in ["haz", "hazard", "hazards"]:
plot_stats(OUTPUT_DIR / f'from_hazard{suffix}.pdf', get_haz_stats(), with_separate)
return
for thresh in [0, 50, 100, 150, 200, 250, 300]:
... |
def get_haz_subsamples(hazard, region, name):
subsamples = read_subsamples(SUBSAMPLE_DIR / f"TC_{region}_{name}.txt")
subsamples = filter_subsamples(hazard, subsamples)
event_names = hazard[0]
event_names_sorted_idx = np.argsort(event_names)
event_names_sorted = event_names[event_names_sorted_idx]
... | The main task of the code is to generate and save statistical hazard data for specified regions (`reg`) and time periods (`tr`). It checks if a compressed NumPy file already exists at the computed path; if not, it retrieves hazard data, computes intensity statistics (mean, standard deviation, frequency norms), and stor... | def main(tr, reg):
out_path = STATS_DIR / f"haz_hist_{reg}_{tr}.npz"
if out_path.exists():
print(f"File exists: {out_path}, skipping...")
return
hazard, subsamples_idx = get_haz_subsamples(read_max_wind(tr, reg), reg, tr)
ints, fq, freq_normed, std = derive_stats(hazard[1], subsamples_i... |
def read_tracks_IBTrACS(name="IBTrACS"):
cache = DATA_DIR / "tracks" / f"{name}.pickle"
if cache.exists():
with open(cache, "rb") as fp:
tracks = pickle.load(fp)
else:
tracks = TCTracks.from_netcdf(TRACKS_DIR / name)
with open(cache, "wb") as fp:
pickle.dump(t... | The main task of the code is to read, process, and cache tropical cyclone track data from various sources (e.g., IBTrACS, MIT, CHAZ_ERA5), apply standardization (e.g., equal time steps, coastal distance), and generate region-specific statistical outputs. It checks for existing files, uses caching for efficiency, and ha... | def main(tr, pool):
read_fun = {
'IBTrACS': read_tracks_IBTrACS,
'IBTrACS_old': read_tracks_IBTrACS,
'IBTrACS_p': lambda: read_tracks_IBTrACS(name="IBTrACS_p"),
'MIT': read_tracks_MIT,
'STORM': lambda: read_tracks_STORM(pool=pool),
'CHAZ_ERA5': lambda: read_tracks_CHA... |
def __send_test_network(self, id_common, id_ek, id_sia, name_group):
self.__send(id_common, True)
if name_group == 'EK':
self.__send(id_ek, False)
elif name_group == 'SIA':
self.__send(id_sia, False)
def __send_main_network(self, id_common, id_ek, name_group):
sel... | This code sends network alerts or common messages based on the cluster type ('t' or 'm'), checking conditions like delinquency, skip thresholds, and balance status. It uses `__send_test_network` or `__send_main_network` with predefined constants and the user's first name, prioritizing alarm messages under specific crit... | def send(self):
if self.__cluster == 't':
if self.__delinquent:
self.__send_test_network(constant.T_CHAT_ALARM, constant.T_CHAT_ALARM_EK, constant.T_CHAT_ALARM_SIA, self.__first_name)
elif self.__skip > (self.__cluster_skip + self.__max_cluster_skip) and self.__epoch_perc... |
def time_forward(model, init_state, time_context_length, training_data):
input, target = training_data # No batches now, will do it latter!
lstm_states = []
loss = 0
for t in range(time_context_length):
prev_state = lstm_states[t-1][network_depth-1] if t>=1 else init_state
input_emb = np... | This function trains an LSTM model on time-series data by iterating through each training sample. It performs forward propagation to compute outputs and loss, then backpropagates gradients to update model weights using a learning rate. The process repeats for all data points, periodically storing intermediate outputs. ... | def train_lstm(model, training_data, time_window):
loss = 0
for i in range(len(training_data)):
lstm, loss = time_forward(model, init_state, time_window, training_data[i])
if i %100 ==0:
out_value = lstm[time_window-1][network_depth-1]['h_t']
#print(f"The output is: ({out... |
def read_bookie_blacklist():
filepath = "bookieblacklist.txt"
with open(filepath, "r") as file:
lines = file.read().splitlines()
return lines
def read_bookie_whitelist():
filepath = "bookiewhitelist.txt"
with open(filepath, "r") as file:
lines = file.read().splitlines()
return li... | This code identifies arbitrage opportunities by comparing sports betting odds across bookmakers. It filters future games, extracts odds data, calculates implied probabilities, and records opportunities where the total implied probability falls below a threshold. Valid opportunities are stored in an ArbitrageManager, wh... | def search(key, region, mkt, soccer=True, threshold=0.99):
# Formally the main method
bookie_blacklist = read_bookie_blacklist()
bookie_whitelist = read_bookie_whitelist()
responses = get(key, region, mkt, soccer)
arbitrage_manager = ArbitrageManager()
for resp in responses: # for all sports
... |
def read_bookie_whitelist():
filepath = "bookiewhitelist.txt"
with open(filepath, "r") as file:
lines = file.read().splitlines()
return lines
def read_keys():
filepath = "keys.txt"
with open(filepath, "r") as file:
lines = file.read().splitlines()
return lines
def search(key, reg... | The code continuously monitors sports betting opportunities by iterating through API keys, filtering valid combinations based on bookmaker whitelists, odds thresholds, and time differences. It tracks unique opportunities, updates their lifespans, and outputs/persists qualifying combinations meeting criteria (e.g., low ... | def main():
# parameters
allow_soccer = False
maxtip = .99
interval_secs = 10
#
whitelist = read_bookie_whitelist()
unique_combos = {} # persistent opportunities are keys here, in the form of Combination class
c = 0 # index of key
iteration = 0
while True:
print("Itera... |
def _get_policy_type(self):
"""
:return: a tuple of (1) is_ingress bool flag (2) str of policy type (Ingress/Egress)
:rtype (bool, str)
"""
is_ingress = not isinstance(self.target, IpSelector)
return is_ingress, 'Ingress' if is_ingress else 'Egress'
def _selectors_as_netp... | This function generates one or two Calico GlobalNetworkPolicy resources to enforce network rules across all namespaces. It constructs policies for ingress/egress traffic based on selectors, ports, and protocol, ensuring bidirectional connectivity when required. The output includes policies for both directions if the ru... | def to_global_netpol_calico(self):
"""
Create Calico GlobalNetworkPolicy resources representing the connections specified by the rule.
Relevant for baseline rules with no namespace, thus using GlobalNetworkPolicy which applies to all namespaces.
Note that two GlobalNetworkPolicy resource... |
def get_policy_for_mailbox(self, mailbox):
self.db.clear()
data = self.db.get_mailbox_by_mail(mailbox)
if data:
return data['PolicyID']
return 0
def get_policy_actions_by_id(policy_id):
actions = {
"url_remove": False,
"attachments_remove": False,
... | The main task of the code is to process an incoming email message by applying a predefined policy. It extracts sender and recipient details, retrieves the appropriate policy actions, executes them on the mail content, and logs the result. The function returns a log string detailing the email's origin, destination, and ... | def process_mail(self, message):
if type(message) is tuple:
sent_to = message[1].sent_to[0]['email']
policy_id = self.get_policy_for_mailbox(sent_to)
actions = get_policy_actions_by_id(policy_id)
mail_content = get_content(message)
log = "From: " + mai... |
def load_file(path):
df = pd.read_csv(path, index_col="rec_id")
return df
def generate_train_sets(df_train):
# TRAIN SET CONSTRUCTION
train_true_links = generate_true_links(df_train)
print("df_train:", df_train.head())
print("train_true_links:", train_true_links)
print(
"Train set s... | The main task of the code is to train and evaluate machine learning models for a classification task using either local data or newly generated data. It loads training and test datasets, processes them into feature-label pairs, trains models, and evaluates performance metrics (precision, sensitivity, F-score, and false... | def main(local=False):
# PATH_FILES = "../data/ePBRN/"
# PATH_IMAGES = "../images/"
# PATH_OUTPUT = "../output/"
PATH_FILES = "./data/ePBRN/"
PATH_IMAGES = "./images/"
PATH_OUTPUT = "./output/"
np.random.seed(42)
# if generating new files
if local:
trainset = PATH_FILES + ... |
def conv_col_to_float(col):
# print([ord(c) for c in c1[i]])
c_arr = col.to_numpy()
return np.array([0.00 if (str(c_arr[i])[0] == str(chr(45))) else float(c_arr[i]) for i in range(len(col))])
def merge(keepCols, mergeCols):
# sorry
colMap = {{} if (len(keepCols) == 0) else keepCols[i]:conv_col_to_fl... | The main task of the code is to merge and clean a dataset by selecting specific columns from the original DataFrame (`df`), grouping them into new aggregated fields (e.g., "Total Population," "WT reclaimed wastewater"), and combining related data using a `merge` function. It constructs a dictionary (`dest_map`) to orga... | def main():
# resulting merged & cleaned data frame
dest_map = {}
# Dimension data
dimensions = np.array(['state_name', 'county_nm', 'year'])
dest_map.update({dimensions[i]:df[dimensions[i]] for i in range(3)})
# Misc measure data
dest_map.update({'Total Population':conv_col_to_float(df['T... |
def init_tests():
payload = {'mkey': 'eightfoldwitch'}
r = requests.post(baseurl+"/api/tests/resetall", data=payload)
def test_RegisterUser_Valid(uname,pword,mfaid):
session = requests.Session()
(r,res,resp) = send_register(session, uname, pword, mfaid)
return ("success" in res)
def test_LoginGoodUs... | The code tests the login functionality with valid credentials by first initializing tests, registering a user with valid details, and then asserting that the login process succeeds using `self.assertTrue`. The main task is to verify that a valid user can successfully log in after registration. | def test_LoginGood(self):
init_tests()
test_RegisterUser_Valid(valid_user,valid_pass,valid_mfaid)
self.assertTrue(test_LoginGoodUser(valid_user,valid_pass,valid_mfaid)) |
def init_tests():
payload = {'mkey': 'eightfoldwitch'}
r = requests.post(baseurl+"/api/tests/resetall", data=payload)
def test_RegisterUser_Valid(uname,pword,mfaid):
session = requests.Session()
(r,res,resp) = send_register(session, uname, pword, mfaid)
return ("success" in res)
def test_CSRF_Login(... | This test method verifies CSRF protection by registering a valid user and asserting that the CSRF login test passes, ensuring the system correctly prevents cross-site request forgery attacks during authentication. | def test_CSRF(self):
init_tests()
test_RegisterUser_Valid(valid_user,valid_pass,valid_mfaid)
self.assertTrue(test_CSRF_Login()) |
def init_tests():
payload = {'mkey': 'eightfoldwitch'}
r = requests.post(baseurl+"/api/tests/resetall", data=payload)
def test_RegisterUser_Valid(uname,pword,mfaid):
session = requests.Session()
(r,res,resp) = send_register(session, uname, pword, mfaid)
return ("success" in res)
def test_LoginGoodUs... | The code tests Unicode string handling in user registration, login, and spellcheck processes. It verifies valid user registration and login with Unicode credentials, then checks if a spellcheck function correctly identifies misspellings in Unicode text using a session. The test ensures proper handling of Unicode charac... | def test_UnicodeStrs(self):
init_tests()
self.assertTrue(test_RegisterUser_Valid(uc_str,valid_pass,valid_mfaid))
self.assertTrue(test_LoginGoodUser(uc_str,valid_pass,valid_mfaid))
text = uc_str
msp = []
session = requests.Session()
(r,res,resp) = send_login(sessio... |
def init_tests():
payload = {'mkey': 'eightfoldwitch'}
r = requests.post(baseurl+"/api/tests/resetall", data=payload)
def test_RegisterUser_Valid(uname,pword,mfaid):
session = requests.Session()
(r,res,resp) = send_register(session, uname, pword, mfaid)
return ("success" in res)
def test_LoginGoodUs... | This test method verifies if a system can handle and successfully register a user with extremely long (30,000 characters) malicious-looking username and password inputs, followed by a login test using the same credentials. It checks if the registration and authentication processes accept such inputs without rejecting t... | def test_MalignRegister(self):
init_tests()
malign_user = ''.join(random.choice(string.printable) for i in range(30000))
malign_pass = malign_user
self.assertTrue(test_RegisterUser_Valid(malign_user,malign_pass,valid_mfaid))
self.assertTrue(test_LoginGoodUser(malign_user,malign_p... |
def init_tests():
payload = {'mkey': 'eightfoldwitch'}
r = requests.post(baseurl+"/api/tests/resetall", data=payload)
def test_RegisterUser_Valid(uname,pword,mfaid):
session = requests.Session()
(r,res,resp) = send_register(session, uname, pword, mfaid)
return ("success" in res)
def test_MalignSpell... | The main task of the code is to test the `test_MalignSpellCheck` function by verifying its return value with inputs 1 through 4, ensuring it returns `True` for each. It initializes test setup, registers a valid user, and checks the spell-check functionality's correctness against multiple test cases. However, the code m... | def test_MalignSpellCheck(self):
init_tests()
test_RegisterUser_Valid(valid_user,valid_pass,valid_mfaid)
self.assertTrue(test_MalignSpellCheck(1))
self.assertTrue(test_MalignSpellCheck(2))
self.assertTrue(test_MalignSpellCheck(3))
self.assertTrue(test_MalignSpellCheck(4)) |
def init_tests():
payload = {'mkey': 'eightfoldwitch'}
r = requests.post(baseurl+"/api/tests/resetall", data=payload)
def test_LoginBadUser():
session = requests.Session()
(r,res,resp) = send_login(session, fake_user, fake_pass, fake_mfaid)
return ("Incorrect" in res)
def test_RegisterUser_Valid(una... | The code runs a series of test cases for a system, executing functions like initializing tests, validating user registration, checking login attempts with bad credentials, and testing spell-check functionality. It prints results for each test to verify system behavior, ensuring security measures (e.g., MFA) and input v... | def run_basetests():
print("init: "+str(init_tests()))
print("login bad user: "+str(test_LoginBadUser()))
print("register user: "+str(test_RegisterUser_Valid()))
print("login bad mfaid: "+str(test_LoginBadMFAid()))
print("login good user: "+str(test_LoginGoodUser(va... |
def init_tests():
payload = {'mkey': 'eightfoldwitch'}
r = requests.post(baseurl+"/api/tests/resetall", data=payload)
def test_RegisterUser_Valid(uname,pword,mfaid):
session = requests.Session()
(r,res,resp) = send_register(session, uname, pword, mfaid)
return ("success" in res)
def test_SpellCheck(... | The code's main task is to test a spell-check function by initializing test setup, registering a valid user with credentials, and verifying if the spell-check method correctly identifies misspelled text. It uses `test_SpellCheck` to assert that the specified text and misspelled words are detected accurately, ensuring t... | def test_SpellCheck(self):
init_tests()
test_RegisterUser_Valid(valid_user,valid_pass,valid_mfaid)
self.assertTrue(test_SpellCheck(check_text,check_misspelled)) |
def init_tests():
payload = {'mkey': 'eightfoldwitch'}
r = requests.post(baseurl+"/api/tests/resetall", data=payload)
def test_RegisterUser_Valid(uname,pword,mfaid):
session = requests.Session()
(r,res,resp) = send_register(session, uname, pword, mfaid)
return ("success" in res)
def test_SessionMana... | This test method verifies session management functionality by initializing tests, registering a valid user, and asserting that session access is restricted when not logged in. It then logs in successfully and confirms session management works post-authentication, ensuring proper access control and validation of user se... | def test_SessionManagement(self):
init_tests()
test_RegisterUser_Valid(valid_user,valid_pass,valid_mfaid)
self.assertTrue(test_SessionManagement()) #not logged in, shouldn't allow
self.assertTrue(test_LoginGoodUser(valid_user,valid_pass,valid_mfaid))
self.assertTrue(test_SessionM... |
def build_network(filename: str) -> (dict, List[str], List[str]):
network = {}
starting_nodes = []
with open(filename) as f:
instructions = f.readline().strip()
f.readline()
for line in f:
line = line.strip()
node = line[0:3]
if node.endswith('A')... | The code processes a network of nodes from a file, calculates steps to navigate from "AAA" to "ZZZ" using given instructions (part one), and determines the number of steps required for all starting nodes to reach a 'Z' node simultaneously (part two). | def main(filename: str):
directions = { 'L': 0, 'R': 1}
network, instructions, starting_nodes = build_network(filename)
part_one(network, directions, instructions, "AAA", "ZZZ")
part_two(network, directions, instructions, starting_nodes, 'Z') |
def FindBuiltDistributedEnum(filePath):
enumCode = {};
builtEnum = {};
# Parse the file
file = fileinput.FileInput(filePath);
for line in file:
matches = re.findall(DistributedEnumDefinitionFullSyntaxRegEx, line);
if len(matches) > 0: # A distributed enum has been found
matches = matches[0];
enumCod... | The code updates distributed enum values in a specified file by comparing existing enum definitions with predefined values in EnumDictionary. If discrepancies are found, it modifies the file's enum syntax, removes trailing semicolons, inserts corrected values, and handles read-only file errors. The function tracks line... | def InjectDistributedEnum(filePath):
global LineChangedCount;
global CurrentPath, CurrentLine;
# Look for existing enum with values
currentFileDistributedEnumList = FindBuiltDistributedEnum(filePath);
for enum in currentFileDistributedEnumList:
lineToChangeCount = DistributedEnumValuesDifferenceCount(current... |
def PrintWarning(enumName, message, path = None, lineNo = None):
if path == None:
path = CurrentPath;
if lineNo == None:
lineNo = CurrentLine;
ErrorHandling.PrintWarning(path, lineNo, "Distributed Enum '" + enumName + "' " + message);
def DoesEnumHasArgument(enumName, argumentName):
return argumentName in Enu... | The function validates assignments in distributed enums by checking for numerical validity, uniqueness, and compatibility with enum arguments like NULLABLE, COUNT, and UNIQUE. It warns about undefined assignments, duplicates, and conflicting arguments, removing invalid assignments. If an enum has no values, it adds a d... | def ValidateDistributedEnum():
global CurrentPath, CurrentLine;
# Validate assignments
for enumName in EnumDictionary:
enum = EnumDictionary[enumName];
assignmentDict = {};
numericAssignment = False;
# for assignmentValues in enum['values']:
for assignmentValueIndex in range(len(enum['values'])):
a... |
def DoesEnumHasArgument(enumName, argumentName):
return argumentName in EnumDictionary[enumName]['arguments'];
def AddValueToDistributedEnum(enumName, value, source, srcPath = None, srcLine = None):
valueTuple = BuildValueAssignmentTupleFromString(enumName, value);
valueDict = {'value': valueTuple[0], 'source': sour... | The function builds distributed enum values by initializing enums with arguments (NULLABLE, VALUE, COUNT), parsing code files to populate enum values, validating them, and setting the COUNT value's assignment to the last index of the enum list. | def BuildDistributedEnumValues():
# Use arguments to start building distributed enum
for enumName in EnumDictionary:
EnumDictionary[enumName]['values'] = [];
# fill Enum with default arguments values (NULLABLE and COUNT will be sorted later on to be first and last respectively)
if DoesEnumHasArgument(enumName, ... |
def readRouterConfig(id, auth, d = {}) -> Dict[str,Any]:
conn = db.connect(
db_host,
database,
user,
password,
db_port
)
if "ERROR" not in str(conn):
records = db.fetch(conn,"*", "gateway_data... | The function `update_info` processes a request to update router information by validating authentication, retrieving configuration data, encoding credentials, signatures, and firmware, then logging and returning the structured response with encoded components for a CUPS (Common Unix Printing System) update process. | def update_info():
req = request.get_json()
if request.headers.get('authorization'):
auth = request.headers['authorization']
else:
fk_abort(401,description="Authentication Header Not Found")
#print("HELLLLO",auth)
routerid = req['router']
cfg = readRouterConfig(routerid, auth... |
def token_validation(id, auth):
conn = db.connect(
db_host,
db_name,
db_user,
db_password,
db_port,
db_ssl_ca
)
if "ERROR" not in str(conn):
records = db.fetch(conn,"*", "gateway_data", ... | The main task of the code is to handle an HTTP request for firmware update processing. It validates the Authorization header, parses JSON request body, checks device credentials, reads router configuration, encodes firmware data (URIs, credentials, signature), and returns a structured HTTP response with encoded payload... | def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
auth = req.headers.get("Authorization", None)
if not auth:
return func.HttpResponse(
"Authentication error: Authorization header is missing",
status_co... |
def read_data(self):
session_path=self.session.replace('_','/')
final_path=session_path[:-1]+'_'+session_path[-1:]
print(final_path)
f = h5py.File('/content/gdrive/MyDrive/npc_v4_data.h5','r')
natural_data = f['images/naturalistic'][:]
x = np.array([np.array(self... | The code initializes a neural network mapper (RegMapper) by loading layer prediction data from a JSON file, identifying the layer with the highest neural prediction score, setting up a predefined layer list, and attaching PCA and regression components for analysis. It prepares input data, session parameters, and prepro... | def __init__(self, arch=None, best_layer=None,input_images=None,neuron_target=None,session=None,preprocess=None):
super(RegMapper, self).__init__()
self.arch=arch
with open(f'/content/gdrive/MyDrive/V4/{session}/st_resnet_natural_mean.json') as json_file:
load_data = json.load(json_fil... |
def delay_translate (src_vec, new_dim):
'''
Creates from [1xN] vec [Mx(N-M*__tau)] vec
'''
print("delay translate, tau = {}".format(__tau))
result = list()
for i in range (new_dim):
tmp_vec = src_vec[i*__tau: len (src_vec) - (new_dim-i-1)*__tau]
result.append (tmp_vec)
return... | This function calculates the correlation dimension of a source vector (`src_vec`) across varying dimension values (`dim`) between `min_dim` and `max_dim`, using a given epsilon (`eps`). It stores results in `dataX` (dimensions) and `dataY` (correlation dimensions), writes each result to a file, and generates a 2D plot ... | def build_variation_of_dim(src_vec, eps, min_dim, max_dim):
dataX = list()
dataY = list()
for dim in range (min_dim, max_dim + 1):
formated_vec = delay_translate (src_vec, dim)
cr_temp = correlation_dimension (formated_vec, eps)
dataX.append (dim)
dataY.append (cr_temp)
... |
def get_target(p):
mac = p.src
# If it exists, return it
try:
return pcdict[mac]
except KeyError:
try:
fqdn = get_fqdn(p)
except IndexError:
fqdn = ''
pcdict[mac] = Target(mac,fqdn)
return pcdict[mac]
def should_spoof_dhcpv6(fqdn):
# If... | This code processes network packets to handle DHCPv6 requests, ARP responses, and DNS queries. It spoofs DHCPv6 advertisements and replies for IPv6 address assignment, updates ARP tables, and sends DNS replies when packets match specific conditions, such as target host checks or self-MAC addresses. | def parsepacket(p):
if DHCP6_Solicit in p:
target = get_target(p)
if should_spoof_dhcpv6(target.host):
send_dhcp_advertise(p[DHCP6_Solicit], p, target)
if DHCP6_Request in p:
target = get_target(p)
if p[DHCP6OptServerId].duid == config.selfduid and should_spoof_dhcpv6... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.