dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def gen_rand_prefix_code(depth_limit: int, rec_depth: int = 0) -> str:
"""
Generates one small formula,
from OPERATORS and ints from -100 to 200
"""
rec_depth += 1
if rec_depth < depth_limit:
if random.random() < 0.9:
return (
random.choice(OPERATORS)
... | The function `initialize_pop` generates a population of individuals for evolutionary processes. It creates a list of `Individual` objects by producing random prefix codes with a depth limit of 4, inserting an 'x' into each code, and initializing each modified code as an individual with a fitness value of 0. The populat... | def initialize_pop(pop_size: int) -> Population:
"""
Purpose: Create population to evolve
Parameters: Goal string, population size as int
User Input: no
Prints: no
Returns: a population, as a list of Individuals
Modifies: Nothing
Calls: random... |
def initialize_pop(pop_size: int) -> Population:
"""
Purpose: Create population to evolve
Parameters: Goal string, population size as int
User Input: no
Prints: no
Returns: a population, as a list of Individuals
Modifies: Nothing
Calls: random... | The code performs an evolutionary computation (EC) run to evolve a population of solutions. It initializes a population, iteratively selects parents, recombines and mutates them, evaluates offspring, and applies survival selection. The process tracks the best fitness, prints updates when it improves, and terminates ear... | def evolve(io_data: IOdata, pop_size: int = 200) -> Population:
"""
Purpose: A whole EC run, main driver
Parameters: The evolved population of solutions
User Input: No
Prints: Updates every time fitness switches.
Returns: Population
Modifies: Various data ... |
def _make_default_CNN(self):
L = self.stack
L = self.add_conv2d_block(L, (32, 64))
L = self.add_conv2d_block(L, (64, 128))
L = self.add_conv2d_block(L, (128, 128))
L = self.add_conv2d_block(L, (128, 128, 256))
L = self.flatten(L)
return L
def add_dense_block(self... | The code constructs a default neural network model by first creating a CNN with `_make_default_CNN()`, then adding a dense layer with 128 units via `add_dense_block()`, setting the output layer with `add_output()`, and finally compiling the model with `compile_model()`. The primary task is to define and prepare a neura... | def make_default_model(self):
flat = self._make_default_CNN()
L = self.add_dense_block(flat, (128,))
self.add_output(L)
self.compile_model() |
def _format_validation_data(self, validation_data):
return validation_data
def _create_train_data_gen(self):
return BatchImgGen(data=self.train_data, batch_size=self.batch_size,
pixel=self.pixel, aug_times=self.aug_times,
aug_params=self.aug_params)
... | This method trains a model using a generator for batches of data, setting up training and validation data, and invoking the underlying training process for a specified number of epochs. | def fit_generator(self, data_df, batch_size=64, steps_per_epoch=None,
validation_data=None, epochs=1, **kwargs):
# to do: make find_thresholds optional
self.batch_size = batch_size
self.train_data = data_df
self.validation_data = self._format_validation_data(validat... |
def predict(self, *args, **kwargs):
return self.model.predict(*args, **kwargs)
def _bin_Y_pred(self):
if self.validation_data is not None:
self.thresholds = self._find_thresholds()
return bin_by_thresholds(self.Y_pred, self.thresholds)
return bin_by_thresholds(self.Y_pre... | The main task of the code is to process a test dataset in batches, predict labels for each batch using a model, compile predictions into a matrix, convert them to final labels, and save results. It initializes a test data iterator, iterates through batches, updates prediction scores, binarizes outputs, and returns the ... | def predict_testset(self, data_test_df, test_batch_size=256):
self.test_data_iter = TestImgIter(data=data_test_df,
batch_size=test_batch_size,
pixel=self.pixel)
Y_pred = np.zeros((len(data_test_df), N_LABELS))
... |
def load_subgraph(path):
graphs = {}
with open(path, encoding='utf-8') as f:
for line in f:
data = json.loads(line)
graph = {}
for i, (head, relation, tail) in enumerate(data['subgraph']['tuples']):
if (head, tail) in graph:
graph[(... | The main task of the code is to evaluate a question-answering model on a knowledge base dataset. It processes test data, computes predictions using a pre-trained model with subgraph reasoning, compares results against ground truth answers, and logs evaluation metrics (Hits@1) along with detailed predictions, reasoning ... | def main():
args = parse_args()
print(args)
dataset_dir = os.path.join('datasets', args.dataset)
cache_dir = os.path.join('cache', args.dataset+'_test_results')
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
correct_f = open(os.path.join(cache_dir, 'correct.log'), 'w')
wro... |
def neighborhood_aware_softmax(self, scores_per_edge, trg_index, num_of_nodes):
"""
As the fn name suggest it does softmax over the neighborhoods. Example: say we have 5 nodes in a graph.
Two of them 1, 2 are connected to node 3. If we want to calculate the representation for node 3 we should ta... | The code implements a Graph Attention Network (GAT) with multi-head attention, incorporating instruction-based feature bridging. It projects node and edge features, computes attention scores using instruction-specific bridges, applies neighborhood-aware softmax for edge weighting, and aggregates weighted features. Dire... | def forward(self, in_nodes_features, edge_index, edges, instructions, batch_ids, max_local_entity):
"""
in_nodes_features: [ batch size, feature dim ]
edge_index: [ 2, edge size ]
"""
src_index, trg_index = edge_index[0], edge_index[1]
#
# Step 1: Linear Projecti... |
def ils(path):
return subprocess.check_output(['ils', path]).decode('UTF-8').split('\n')
def import_data(db, accn, args, listing):
stagingdir = args['stagingdir']
targetdir = args['targetdir']
skipIput = 'skipirods' in args
skipDB = 'skipdb' in args
skipMissing = 'skipmissing' in args
exist... | The main task of the code is to import experimental data into a PostgreSQL database. It connects to the database using provided credentials, lists target directory contents, and either imports a single experiment (via 'accn') or processes multiple runs from a JSON file/database. It iterates through each run, calling 'i... | def main(args=None):
conn = None
if not 'skipdb' in args:
conn = psycopg2.connect(host='', dbname=args['dbname'], user=args['username'], password=args['password'] if 'password' in args else None)
listing = ils(args['targetdir'])
if 'accn' in args: # for debug
import_data(conn, args['ac... |
def delete_all(db):
print("Deleting all tables ...")
cursor = db.cursor()
cursor.execute(
"TRUNCATE project_to_sample CASCADE;"
"TRUNCATE sample_to_sampling_event CASCADE;"
"TRUNCATE project_to_file CASCADE;"
"TRUNCATE run_to_file CASCADE;"
"TRUNCATE file CASCADE;"
... | The code processes data packages by connecting to a PostgreSQL database, loading campaigns, sampling events, and samples, then inserting projects. It optionally deletes existing data, logs details based on flags, and stores CTD/Niskin files in iRODS if a path is provided. | def main(args=None):
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)
logger = logging.getLogger()
if 'nowarn' in args:
logger.setLevel(logging.ERROR)
elif 'debug' in args:
logger.setLevel(logging.DEBUG)
conn = psycopg2.connect(host='', dbname=args['dbnam... |
def init_routers(fic_intent):
routers = []
name_rts = []
i = 1
while i<len(fic_intent):
name_rts_link = [fic_intent[i]["link_1"][0], fic_intent[i]["link_2"][0]]
AS_rt = fic_intent[i]["protocol"]
for rt in name_rts_link:
if rt not in name_rts:
name_rts... | The main task of the code is to configure router settings based on input data. It initializes routers, sets their paths, identifies border routers, and assigns networks to each router using functions like `init_routers`, `set_chemins`, `set_border_router`, and `set_networks`, ultimately returning the configured router ... | def get_routers(fic_intent):
routers, name_rts = init_routers(fic_intent)
set_chemins(fic_intent, routers)
set_border_router(fic_intent, routers)
for name_rt in name_rts:
set_networks(fic_intent, routers, name_rt)
return routers |
def get_nbr_rt(fic_intent):
name_rts = []
i = 1
nbr_rt = 0
while i<len(fic_intent):
rt_ids = [fic_intent[i]["link_1"][0], fic_intent[i]["link_2"][0]]
for rt_id in rt_ids:
if rt_id not in name_rts:
name_rts.append(rt_id)
nbr_rt += 1
i+=1... | The code translates network intent data from a JSON file into a structured router configuration JSON, focusing on Autonomous System (AS) details. It processes link information, separates routers by protocol (e.g., OSPF), assigns AS parameters, and generates a standardized output format with IGP, BGP, and IP-range speci... | def translate(dir_link, dir_router):
#init networks
net = []
intent = []
with open(dir_link, 'r') as rt_file:
intent = json.load(rt_file)
nbr_rt = get_nbr_rt(intent)
#set networks
i = 1
while i<len(intent):
r1 = intent[i]["link_1"][0]
r... |
def evaluation(self):
train_loss = []
validation_acc = []
best_model = None
best_acc = None
best_epoch = None
max_epoch = 10000
no_improvement = 5
epochList = []
for n_epoch in range(max_epoch):
train_dataloader = DataLoader(self.train... | The main task of the code is to evaluate a PyTorch model, save it, and enable interactive image classification. It prompts users to input image filepaths, processes them using the model, and outputs predictions until "exit" is entered. Error handling ensures valid inputs, while evaluation and model-saving functions are... | def main(self):
print("Pytorch Output. . .\n. . .")
self.evaluation()
self.save_model()
print("Done!")
model = self.get_model()
input_object = None
while input_object != "exit":
input_object = input("Please enter a filepath:\n")
if input_ob... |
def postorder_traversal(self, node):
to_return = ""
if not node.children:
return node.value
if node.value == "ISZERO":
to_return = self.postorder_traversal(node.children[0])
if isinstance(to_return, int):
if to_return == 0:
... | This function generates Boogie-style assignment paths for storage variables by processing AST nodes. It constructs variable names from nested map structures, handling both dotted and resolved map IDs, then appends formatted assignments to a path list with type-specific suffixes. The code traverses nodes to extract keys... | def boogie_gen_sstore(self, node0, node1):
sym_this = str(self.postorder_traversal(self._sym_this_addresses[-1]))
if node0.value=="MapElement":
if node0.children[0].value=="MapElement":
map_ID = (node0.children[0].children[0])
self.postorder_traversal(node0.c... |
def find_key(self, node):
if not node.children:
if isinstance(node.value, str) or (self.is_hex(str(node.value))):
return node.value
for c in node.children:
if not isinstance(c, tuple):
return_val = self.find_key(c)
if return_val:
... | The code processes Ethereum smart contract opcodes, simulating execution by managing the stack, memory, and call stack. It handles contract calls (CALL/STATICCALL) by setting up new contract contexts, copying calldata, and tracking symbolic variables. It processes returns (RETURN/STOP), updating return data and popping... | def run_instruction(self, instr, branch_taken):
PC = instr[0]
opcode = instr[1]
operand = instr[2]
if opcode=="JUMPDEST" or opcode=="CALL" or opcode=="STATICCALL":
if (opcode=="CALL"):
self._non_static_calls.append("non-static")
elif (opcode... |
def read_config():
global config, config_file
config_file = config.read("config.ini")[0]
Creds = namedtuple("Creds", ["email", "password", "otp", "token", "refresh_token"])
db_cfg = Config().query.one()
creds = Creds(email=config['Credentials']["email"],
password=config['Credential... | The function `ws_get_positions` retrieves user stock positions by handling authentication via OTP, refreshing access tokens when necessary, and making a GET request to a positions API endpoint. It logs errors, saves debug data, and returns a dictionary mapping stock symbols to their details from the API response. | def ws_get_positions():
creds = read_config()
if not creds.token:
logging.debug("access token NOT present")
if creds.otp == '':
logging.error("otp is required but blank")
update_config("Credentials", "token", '')
update_config("Credentials", "refresh_token", '... |
def end_session():
pygame.display.quit()
pygame.quit()
quit()
def check_sequence(players_sequence):
if players_sequence != cpu_sequence[:len(players_sequence)]:
game_over()
def generate_hud(show_reset=False, show_time=False, time_left=""):
global clock, reset_rect
clock.tick(60)
pyg... | The code handles a player's turn in a sequence-matching game, allowing the player to select colored buttons within 3 seconds. It captures mouse clicks, appends selected colors to the player's sequence, checks correctness, resets the timer on each input, and triggers a game over if the player fails to respond in time. T... | def player_turn():
global streak, clock
turn_time = time.time()
players_sequence = []
handled = None
count = 0
while time.time() <= turn_time + 3 and len(players_sequence) < len(cpu_sequence):
handled = False
show_time = True
# Calculate remaining time in turn
... |
def init_embeddings(self, hparams, scope):
"""Init embeddings."""
self.embedding_decoder = (model_helper.create_emb_for_encoder_and_decoder(tgt_vocab_size=self.tgt_vocab_size,
tgt_embed_size=hparams.num_units,
... | This code initializes a neural machine translation model with CNN (AlexNet) and attention mechanisms, handling training, evaluation, and inference modes. It sets up embeddings, output projection, gradient optimization, learning rate decay, and vocabulary mappings. The model processes input sequences, computes losses, g... | def __init__(self, hparams, mode, iterator, target_vocab_table, reverse_target_vocab_table=None, scope=None, single_cell_fn=None):
"""Create the model.
Args:
hparams: Hyperparameter configurations.
mode: TRAIN | EVAL | INFER
iterator: Dataset Iterator that feeds data.
... |
def sliding_window(img, x_start_stop=[None, None], y_start_stop=[None, None], xy_window=(64, 64),
xy_overlap=(0.5, 0.5)):
"""Implementation of a sliding window search"""
list_overall = [] # storage
if x_start_stop[0] == None:
x_start_stop[0] = 0
print("Got None..\n")
... | The function detects windows in an image using sliding windows across predefined regions (bottom, middle, top). It initializes window coordinates if not already set, processes the frame's color space, and returns detected windows. Debug mode visualizes detected regions with colored boxes. | def get_detected_windows(frame, debug=False):
"""Get coordinates for detected windows."""
global coord_windows_bottom
global coord_windows_middle
global coord_windows_top
if coord_windows_bottom is None:
coord_windows_bottom = sliding_window(frame, x_start_stop=search_ranges["bottom1"][0],
... |
def extract_features(imgs, cspace='RGB', spatial_size=(16, 16),
hist_bins=32, hist_range=(0, 256), debug = False):
features = list()
scale = 1.5
color_space = cspace
spatial_size = spatial_size
hist_bins = hist_bins
h_range = hist_range
orient = 8
pix_per_cell = 8
... | The code tests a pre-trained Support Vector Machine (SVC) model for car detection by loading stored model parameters, extracting features from test images, predicting car presence, and visualizing results with detected bounding boxes. It evaluates model accuracy, displays feature shapes, and shows input images with lab... | def test_model():
global X_test
global Y_test
global svc
global scaling_param
global model_stored
svc = model_stored['svc']
scaling_param = model_stored['scalar']
pix_per_cell = model_stored['pixel_per_cell']
cell_per_block = model_stored['cell_per_block']
orient = model_stored['... |
def get_detected_windows(frame, debug=False):
"""Get coordinates for detected windows."""
global coord_windows_bottom
global coord_windows_middle
global coord_windows_top
if coord_windows_bottom is None:
coord_windows_bottom = sliding_window(frame, x_start_stop=search_ranges["bottom1"][0],
... | The main task of the code is to perform sliding window detection on video frames to identify vehicles, accumulate heat maps over multiple frames to reduce false positives, apply thresholding to detect regions of interest, and render bounding boxes on the frame. It uses a deque to maintain heat maps across frames, combi... | def process_frame(frame):
"""Sliding window detection on the video frame."""
global heatmap_prev
global boxes_prev
global frame_count
global heatmap_deque
frame_count += 1
draw_boxes_on_frame = False
print("Image shape: ", frame.shape)
heatmap_current = np.zeros_like(frame[:, :, 0])... |
def load_model(path = None):
"""Load a trained model."""
model = None
if path is None:
path = '../model/model.p'
if os.path.isfile(path):
with open(path, 'rb') as f:
model = pickle.load(f)
return model
def train_model():
global car_features
global noncar_features
... | The main task of the code is to either load a pre-trained model or train a new one, initialize a centroid tracker with 10 centroids, and process a video file using a pipeline to generate an output video. The `test_model()` function is commented out, indicating it is not executed in this context. | def main():
global model_stored
if load_model() is None:
train_model()
else:
model_stored = load_model()
# test_model()
init_centroid_tracker(10)
video_pipeline("../videos/project_video.mp4", "../videos/output.mp4") |
def preorder(self, root):
if root != None:
print("-> " + str(root.data), end=" ")
self.preorder(root.left)
self.preorder(root.right)
def inorder(self, root):
if root != None:
self.preorder(root.left)
print("-> " + str(root.data), end=" ")
... | The main task of the code is to perform and display three types of tree traversals—preorder, inorder, and postorder—starting from the root node. It prints each traversal's result sequentially with labels, providing a structured view of the tree's node order in different traversal methods. | def traverse(self):
print("Preorder : ", end="")
self.preorder(self.root)
print("\nInorder : ", end="")
self.inorder(self.root)
print("\nPostorder : ", end="")
self.postorder(self.root)
print() |
def get_level_names():
with os.scandir(config.SUBMISSIONS_DIR) as d:
return [x.name for x in d]
def get_student_names():
names_list = []
for _, _, files in os.walk(config.SUBMISSIONS_DIR):
for f in files:
if f not in names_list and not f.startswith("good_"):
names... | The code generates a report scoring students' test outputs against expected results. It reads test data, processes student and level names, calculates scores by comparing outputs with "good" benchmarks, populates a DataFrame with scores and possible points, sorts columns, fills missing values, and exports the structure... | def generate_report():
with open(config.TESTSFILE, 'r') as testsfile:
tests = json.load(testsfile)
level_names = get_level_names()
student_names = get_student_names()
student_names.sort()
student_names.append("possible_points")
df = pd.DataFrame(index=student_names, columns=level_names)
... |
def print_single_overview(out, good_outs, level):
i = 0
print(f"binary name: {out['name']}")
for test in out["test_outputs"]:
goodness = find_goodness(test, good_outs, out["name"], level, i)
print(f"\tTest #{i}: ", end="")
print_goodness(goodness)
i += 1
def prompt_list_index... | This function allows users to interactively inspect a submission's test outputs by viewing specific test results, comparing outputs to known good versions, or returning to inspect other submissions. It provides options to view detailed test outputs, compare against references, or exit the grading program, enhancing man... | def _prompt_inspect(selection, good_outs, tests, level):
print(f"What would you like to do with submission '{selection['name']}'? ")
print_single_overview(selection, good_outs, level)
while True:
inp = input("[v]iew output from a specific test, [c]ompare outputs against a known good version, [o]verv... |
def genTiffName(param='dem', iCode='bi'):
iCode = iCode.lower()
if param == 'dem_250':
param = 'dem'
pCODE = genParamCode(param)
TiffName = PARAM_TIFF_DIR + param + \
'/' + iCode + '_' + pCODE + '_250m.tif'
return TiffName
def get_Coordinates(GeoTiff_name):
# Read raster
... | The function generates a grid of island data by retrieving coordinates and parameter values from TIFF files, compiling them into a pandas DataFrame, and returning the DataFrame along with a mask and shape for further analysis or visualization. | def get_island_grid(iCode, params):
TiffName = genTiffName(iCode=iCode)
LON, LAT = get_Coordinates(TiffName)
LON = LON.reshape(-1)
LAT = LAT.reshape(-1)
myDict = {'LON': LON, 'LAT': LAT}
for param in params:
myDict[param] = getDataArray(iCode=iCode, param=param).reshape(-1)
isla... |
def genTiffName(param='dem', iCode='bi'):
iCode = iCode.lower()
if param == 'dem_250':
param = 'dem'
pCODE = genParamCode(param)
TiffName = PARAM_TIFF_DIR + param + \
'/' + iCode + '_' + pCODE + '_250m.tif'
return TiffName
def get_Coordinates(GeoTiff_name):
# Read raster
... | This function generates a DataFrame containing geographic coordinates (LON, LAT) and specified parameters for an island grid, derived from TIFF files. It reshapes data arrays into 1D formats, constructs a pandas DataFrame, and retrieves a mask and shape for further analysis. | def get_island_grid(iCode, params):
TiffName = genTiffName(iCode=iCode)
LON, LAT = get_Coordinates(TiffName)
LON = LON.reshape(-1)
LAT = LAT.reshape(-1)
myDict = {'LON': LON, 'LAT': LAT}
for param in params:
myDict[param] = getDataArray(iCode=iCode, param=param).reshape(-1)
isla... |
def makeModel(predictand,params,model,threshold=2.5):
"""
Description: Updated version of makeModel.
Development notes:
--Predictand replaces df for clarity. Only available and relevant stations of general predictand should be passed from this variable
--Params replaces parameter list. Param... | The function performs cross-validation for a predictive model using leave-one-out (LOO) methodology. It trains a model on all stations except one target station, predicts its value, and compares it to the actual value. Metrics like MAE, RMSE, R2, and information criteria are calculated. Results are compiled into a Data... | def cross_validation(predictor, response, iCode, varname, MODEL, metadata, threshold=2.5,inversion=2150):
if iCode == 'MN':
isl_list = ['MA','KO','MO','LA']
else:
isl_list = [iCode]
#Only select test values from target island
meta_stn = metadata.set_index('SKN')
targ_skns = []
pr... |
def monthly_mean(temp_data,varname,threshold=15):
#Get monthly mean of temperature for specified island
valid_counts = temp_data.count(axis=1)
stns_threshold = valid_counts[valid_counts>=threshold].index.values
valid_mean = temp_data.loc[stns_threshold].mean(axis=1).rename(varname)
temp_meta_master... | The function generates monthly mean temperature grids and standard error maps using a predictive model. It processes input data (temperature, predictors), trains a model, applies it to a grid, and outputs TIFF files for temperature and uncertainty maps, with parameters like varname, iCode, and date_str defining the out... | def minmax_main(varname,iCode,date_str,params=['dem_250'],inversion=2150):
"""
Full monthly mean temperature grid for 1 month of data
"""
threshold = 2.5
station_dir = RAW_DATA_DIR
pred_dir = PRED_DIR
output_dir = MAP_OUTPUT_DIR + varname + '/' + iCode.upper() + '/'
output_se_dir = MAP_O... |
def get_island_grid(iCode, params):
TiffName = genTiffName(iCode=iCode)
LON, LAT = get_Coordinates(TiffName)
LON = LON.reshape(-1)
LAT = LAT.reshape(-1)
myDict = {'LON': LON, 'LAT': LAT}
for param in params:
myDict[param] = getDataArray(iCode=iCode, param=param).reshape(-1)
isla... | The function generates geospatial maps (GeoTIFF and PNG) of temperature and standard error for a specified island or region, using a statistical model fitted with environmental predictors. It processes input data, performs quality control, creates gridded outputs, and returns fitted model parameters and metadata. | def generate_county_map(iCode, varname, params, date_str, output_dir=None):
if output_dir == None:
map_dir = MAP_OUTPUT_DIR + varname + '/' + iCode.upper() + '/'
se_dir = SE_OUTPUT_DIR + varname + '_se/' + iCode.upper() + '/'
png_dir = PNG_OUTPUT_DIR + iCode.upper() + '/'
else:
... |
def createOrder(numCities):
order = []
indices = list(range(numCities))
for i in range(numCities):
index = random.choice(indices)
order.append(index)
indices.remove(index)
return order
def calculateFitness(cities, population, domain, yRange):
currentBest = domain ** 2 + yRang... | This code implements a genetic algorithm to solve the Traveling Salesman Problem (TSP). It evolves a population of city order permutations over multiple generations, selecting and mutating the fittest routes (shortest distances) to iteratively find the optimal path through all cities. The function returns the best reco... | def bestOrder(cities, numGenerations):
numCities = len(cities)
population = [createOrder(numCities) for i in range(popSize)]
fitnessList, recordOrder, recordDistance = calculateFitness(cities, population, 10000, 10000)
count = 0
while count < numGenerations:
normalizeFitness(fitnessList)
... |
def equity_ratio(self):
return self.equity() / self.voa()
def voa(self):
return self.share_price * self.shares
def equity(self):
return self.init_voa + self.cash - self.voa() | This function determines if a margin call is triggered by comparing the equity ratio to a maintenance threshold. If the equity ratio exceeds the threshold, it returns 0; otherwise, it calculates the margin call amount as (maintenance threshold × voa) minus current equity, indicating the required funds to meet the margi... | def is_margin_call(self):
if self.equity_ratio() > self.maintain:
return 0
else:
return (self.maintain * self.voa()) - self.equity() |
def equity_ratio(self):
return self.equity()/self.voa()
def voa(self):
return self.shares * self.share_price
def equity(self):
return self.voa() - self.debt | This function determines if a margin call is triggered. If the equity ratio exceeds the maintain threshold, it returns 0. Otherwise, it calculates the required margin adjustment by subtracting current equity from the product of maintain ratio and voa (value of assets), indicating the amount needed to meet margin requir... | def is_margin_call(self):
if self.equity_ratio() > self.maintain:
return 0
else:
return (self.maintain * self.voa()) - self.equity() |
def svn_host(self, url):
"""parse url to a host/domain
"""
self.debug("svn_host")
if not self.prevurl:
self.prevurl = url
self.svnhost = urlparse.urlparse(self.prevurl).netloc
return self.svnhost, self.prevurl
def savefile(self, filepath, data):
... | The main task of the code is to retrieve SVN working copy database (wc.db) entries from a remote URL, save the extracted data locally, parse SVN entries and author information from the database, and return the authors, SVN URLs, and directories. It handles HTTP requests, error checking, file storage, and internal state... | def wcdb(self, url, output):
"""get svn entries from remote wc.db
"""
self.debug("wcdb")
wcdburl = "%s/.svn/wc.db" % url
self.output(wcdburl)
resp = self.request(wcdburl)
self.svn_host(url)
if resp.status_code != 200:
self.output("(%s) - %s" ... |
def country_city(self, offset, ip=0):
"""get country / city from a record"""
byte = ord(self.data[offset])
if byte == 1: # record string
return self.country_city(self.record(offset+1))
elif byte == 2: # record redirect
return (self.country_redirect(self.reco... | The function determines the geographical location of an IP address by retrieving country and city information from a database using calculated offsets. It locates the IP's record via self.index(ip), adjusts the offset by 4 bytes, extracts the record, and passes it to self.country_city() to return (country, city) as a t... | def ip_location(self, ip):
# a record = IP_start (4 bytes) + IP_record_offset (3 bytes)
# get ip record from ip from offset
(country, city) = self.country_city(
self.record(self.index(ip) + 4) + 4)
return (country, city) |
def _db_to_amp(x):
return np.power(10.0, x * 0.05)
def _denormalize(S):
return (np.clip(S, 0, 1) * -hparams.min_level_db) + hparams.min_level_db
def _griffin_lim(S):
'''librosa implementation of Griffin-Lim
Based on https://github.com/librosa/librosa/issues/434
'''
angles = np.exp(2j * np.pi * np.random.ran... | The code converts a spectrogram back to a waveform using librosa by first converting the spectrogram from dB scale to linear amplitude, then applying the Griffin-Lim algorithm to reconstruct the phase and generate the time-domain signal. | def inv_spectrogram(spectrogram):
'''Converts spectrogram to waveform using librosa'''
S = _db_to_amp(_denormalize(spectrogram) +
hparams.ref_level_db) # Convert back to linear
# Reconstruct phase
return _griffin_lim(S ** hparams.power) |
def _db_to_amp_tensorflow(x):
return tf.pow(tf.ones(tf.shape(x)) * 10.0, x * 0.05)
def _denormalize_tensorflow(S):
return (tf.clip_by_value(S, 0, 1) * -hparams.min_level_db) + hparams.min_level_db
def _griffin_lim_tensorflow(S):
'''TensorFlow implementation of Griffin-Lim
Based on https://github.com/Kyubyong/te... | The function converts a spectrogram into a waveform using TensorFlow by first denormalizing the input, converting it from decibels to amplitude, and then applying the Griffin-Lim algorithm to reconstruct the audio signal. This process is essential for audio synthesis or reconstruction tasks. | def inv_spectrogram_tensorflow(spectrogram):
'''Builds computational graph to convert spectrogram to waveform using TensorFlow.'''
S = _db_to_amp_tensorflow(_denormalize_tensorflow(
spectrogram) + hparams.ref_level_db)
return _griffin_lim_tensorflow(tf.pow(S, hparams.power)) |
def initial_theta(num_particles, mean = 0):
mean_vec = np.repeat(mean, 2)
cov = np.identity(2)
return multivariate_normal(mean_vec, cov, size=num_particles)
def initial_state(num_particles, a=0.91, SD=1.1):
#scale = sqrt(SD ** 2 / (1 - a ** 2))
scale = SD # Fix paramter constraint at a = 1
retur... | The code implements a particle filter for Bayesian inference, initializing particles with parameters `theta_sample` and states `chains`. It computes initial weights `w` for the first observation `y[0]` using a likelihood function and parameter `delta`. The main task is to calculate particle weights based on observed da... | def Filter(tmax, y, initial_theta, initial_state, num_particles = 100,
delta = 0.98):
theta_sample = initial_theta(num_particles)
chains = np.empty((tmax + 1, num_particles))
for i in range(num_particles):
chains[0,i] = initial_state(1, theta_sample[i,0])
w = weights(y[0], chains[0,:... |
def cursor(self):
return (
pl.scan_parquet(
Path(self.session).parent / f"{self.trial}.parquet",
)
.select("x", "y")
.collect()
)
def fixation_period(self):
time_fp_off = self.timefpoff()
if time_fp_off > 0:
end ... | The code generates a visualization combining a plotted cursor with selected x/y data, fixation periods, and two vertical lines indicating specific time points (timetargetoff and timeoutcome) in black and blue, respectively, using HoloViews. | def view(self):
return (
self.cursor().select("x", "y").plot().opts(tools=["vline"])
* self.fixation_period()
* hv.VLine(self.timetargetoff()).opts(color="black")
* hv.VLine(self.timeoutcome()).opts(color="blue")
) |
def generatePinkNoise(t, fs):
N = int(t*fs)
state_pink = np.random.RandomState()
uneven = N % 2
X = state_pink.randn(N // 2 + 1 + uneven) + 1j * state_pink.randn(N // 2 + 1 + uneven)
S = np.sqrt(np.arange(len(X)) + 1.) # +1 to avoid divide by zero
y_pink = (irfft(X / S)).real
y_pink_norm = ... | This function generates an excitation signal with a specified rise time, excitation duration, decay time, and noise type (pink/white). It creates a noise array, applies rise and decay ramps, scales the signal, and returns the processed excitation waveform along with its corresponding time array for further analysis or ... | def createExcitation(rise_time, excitation_time, decay_time, fs, noise_color="pink"):
t_in = rise_time+excitation_time
if noise_color == "pink":
initial_array = generatePinkNoise(t=t_in, fs=fs)
elif noise_color == "white":
initial_array = generateWhiteNoise(t=t_in, fs=fs)
ramped_excitati... |
def appendBytesToDeque(queue,byteslist): # TODO : write this in cython
for byte in byteslist:
queue.append(bytes([byte]))
def elapsed(self):
if self.last_byte_capture_time == 0:
self.last_byte_capture_time = time.perf_counter()
return time.perf_counter() - self.last_byte_capture... | The main task of the code is to monitor and process incoming bytes from a serial port buffer, handling two modes (reading directly from the port or from a deque buffer), checking for timeouts, and terminating operations if a timeout occurs while capturing bytes. It also records the last byte capture time and adds conte... | def checkByte(self, max_time = 0.0015, mode = 0):
if mode == 1 :
if self.port.in_waiting :
appendBytesToDeque( self.buffer, self.port.read(self.port.in_waiting) )
if self.running :
timeover = self.elapsed() > max_time
item = None
if mode ... |
def isMoveValid(self, row: int, column: int) -> bool:
'''
Checks if the player's move is on the board
'''
if row-1 in range(self.rows):
if column-1 in range(self.columns):
if self.board[row-1][column-1] == NONE:
return True
def possibleDirectionsToFlip(self, row: int, column: int) -> list:
'''
... | The method adds a player's move to the game state by validating the move, checking for possible piece flips, updating the board with the current player's symbol, flipping affected pieces, and returning True if the move is successfully executed. | def addMoveToState(self, row: int, column: int) -> bool:
'''
Adds player's move into the game state
'''
if self.isMoveValid(row, column):
if self.possibleDirectionsToFlip(row, column) != []:
self.board[row-1][column-1] = self.turn
self.flipPieces(row, column)
return True |
def isBoardFull(self) -> bool:
'''
Check if the board is full
'''
for row in range(self.rows):
for column in range(self.columns):
if self.board[row][column] == NONE:
return False
def anyPossibleMoves(self) -> list:
'''
Check for all possible coordinates that a player can input
'''
allMoves =... | Your returnThe main task of the code is to determine if a game is over by checking either if the board is full or if no valid moves remain after switching turns. It returns `True` when the board is full or when no possible moves exist after changing the player's turn, indicating the game has ended. | def isGameOver(self) -> bool:
'''
Checks if the game is over
'''
if self.isBoardFull() != False:
return True
elif self.anyPossibleMoves() == []:
self.changeTurn()
if self.anyPossibleMoves() == []:
return True |
def sendData(self, header, data):
send_data = {"header": header, "data": data}
self.server.send_message_to_all(json.dumps(send_data))
def get_baglist(self):
files = sorted(glob.glob("{0}/.ros/*.bag".format(os.environ['HOME'])), reverse=True)
response = []
for file in files:
... | This method processes incoming messages by parsing JSON data and executing actions based on the message header. It handles file list requests, topic list requests, recording control (start/stop), file deletion, and bag file information retrieval. Each header triggers a specific function call, such as sending responses,... | def on_message(self, client, server, message):
msg = json.loads(message)
if msg["header"] == "requestFileList":
self.sendData("requestFileListResponse", self.get_baglist())
if msg["header"] == "requestTopicList":
self.sendData("requestTopicListResponse", self.get_topic_l... |
def request_relay_api(self, endpoint):
return requests.get(self.relay_api_url + "/" + endpoint).json()
def build_network_info_dictionary(network, network_graph, transfer_events):
current_time = time.time()
one_month = 30 * 24 * 3600
transfer_events_last_month = filter_events_for_time_window(
... | This code analyzes currency networks by retrieving network data, building graph structures, and exporting network information. It fetches network details, creates CurrencyNetworkGraph instances, processes trustlines and transfer events, constructs data dictionaries, and exports results. The main task involves network d... | def analyze_networks(self):
networks_list = self.request_relay_api("networks")
for network in networks_list:
network_address = network["address"]
network_graph = CurrencyNetworkGraph(
capacity_imbalance_fee_divisor=100, # TODO: The endpoint of the relay does no... |
def getPastEventsTfidfVector(userPastEvents, eventsCsv):
#past_events_ids = get_past_events_of_user(uid)
userPastEventsList = userPastEvents.split(",")
#print("past list: ", userPastEventsList)
pastEventsTfidfVectorList = [getEventTfidfVector(eventName, eventsCsv) for eventName in userPastEventsList]
... | The code computes the relevance of an upcoming event to a user's past events by calculating cosine similarity between TF-IDF vectors of the user's historical events and the upcoming event, using data from an events CSV file. | def compute_relevence_feature(userPastEvents, upcomingEventName, eventsCsv):
pastEventsTfidfVector = getPastEventsTfidfVector(userPastEvents, eventsCsv)
upcomingEventTfidfVector = getEventTfidfVector(upcomingEventName, eventsCsv)
eventsCosineSimilarity = computeCosineSimilarity(pastEventsTfidfVector, upcom... |
def create_models(models_dir: str, sceretions_dir):
secretions = generate_final_secretions(secretions_dir)
secreting_gsmms = sorted([i for i in list(secretions.keys())])
models = []
for model_name in secreting_gsmms:
print(model_name)
try:
model = cobra.io.read_sbml_model(mod... | The code generates a dictionary mapping each model's ID to its specific medium requirements by creating models from given directories, retrieving a final medium configuration, and applying model-specific modifications to determine uptake parameters for each model. | def get_models_uptakes(secretions_dir, models_dir, medium_dir, final_medium_file):
models = create_models(models_dir, secretions_dir)
uptake_dict = {}
medium = get_final_medium(medium_dir, final_medium_file)
for model in models:
medium_specific = get_model_specific_medium_mod(model, medium)
... |
def calculate_malahanobis(point, centroid, std_dev):
return np.sqrt(np.sum(np.square((point-centroid)/std_dev)))
def centroid(stats):
# centroid = SUM / N
return stats[1] / stats[0]
def variance(stats):
# variance = (SUMSQ / N) - np.square(SUM / N)
return stats[2] / stats[0] - np.square((stats[1] / ... | This function processes data chunks in a clustering algorithm by discarding points based on Mahalanobis distance thresholds relative to existing centroids, appending retained points to a global set, and triggering cluster analysis on discarded points. It uses Spark for parallel processing, updates global retained/disca... | def continue_bfr(chunk):
global DISCARD_SET
global RETAINED_SET
global COMPRESSION_SET
batch = sc.parallelize(chunk)
DISCARD_SET = batch.map(lambda point: point if
min([calculate_malahanobis(point[1:], centroid(x[1]), np.sqrt(
variance(x[1... |
def create_lung_mask(self):
# binary threshold
binary = helper_functions.create_binary_mask(self.lung_vol)
return binary
def read_in_morphometry_info(self):
data = pd.read_csv(self.morphometry_path, sep=" ", header=None)
data.columns = ["generation", "num_tubes", "length_cm", "di... | The main task of the code is to initialize and process 3D medical imaging data of the lungs and bronchial trees. It creates lung masks, performs morphometry analysis, applies cavity enhancement filters, and conducts Hessian-based analysis for bronchial structures. The code handles both standard processing and demo mode... | def __init__(self, volume, lung_segmentations, x_mm, y_mm, number, demo=False, bronchial_segmentation='') -> None:
self.number = number
self.volume = volume
self.lung_vol = np.dstack(lung_segmentations)
self.lung_mask = self.create_lung_mask()
self.x_mm = x_mm
self.y_mm ... |
def is_empty(self) -> bool:
"""
model.feed_manager.FeedManager.is_empty
Determines whether the model contains any feeds.
Returns True if the FeedManager is empty
"""
fm_logger.debug('FeedManager.is_empty')
if self.size() == 0:
return True
... | (The code adds a new article to a specified feed only if the feed exists and the article is not already present. It returns False if the feed is not found, the article exists, or the feed manager is empty. The function retrieves the feed, adds the article, and returns True on success, handling exceptions to return Fals... | def add(self, new_article: Article, feed_name: str) -> bool:
"""
model.feed_manager.FeedManager.add
Add a new article to a feed ONLY if the feed already exists and the feed does not already have the article.
Returns False if the no feed could be found corresponding to the article given.... |
def projectLOD(lod, camera, scaling, tree_pos):
p0 = project(np.dot(camera["WorldToView"], vec4(scaling * np.array(lod["P0"]) + np.array(tree_pos), 1.0)), camera)
p1 = project(np.dot(camera["WorldToView"], vec4(scaling * np.array(lod["P1"]) + np.array(tree_pos), 1.0)), camera)
p2 = project(np.dot(camera["Wo... | The function selects the appropriate level of detail (LOD) for a 3D object based on camera visibility and coverage. It checks if the coarsest LOD is fully outside the camera's frustum, calculates the projected area, and iterates through sorted LOD sizes to find the smallest valid LOD that meets coverage requirements, r... | def selectLOD(camera, tree_pos, scaling, lods, generate_gt, min_lod, covered_pixels):
if generate_gt:
return "0"
# use coarsest volume if outside frustum
max_lod_size = "0"
for lod_size in lods:
if float(lod_size) > float(max_lod_size):
max_lod_size = lod_size
max_lod =... |
def sampleModelPosition(relevant_models, index, volume_max_bounds):
model = relevant_models[index]
model_name = model["Name"]
model_space_height = model["Dimensions"][1]
expected = model["ExpectedHeight"]
randomHeight = np.random.normal(expected, expected * 0.01)
scaling = randomHeight / model_s... | The code generates a random forest scene with non-overlapping trees of varying sizes (large, medium, small) by sampling positions from predefined models, checking collisions with existing trees, and saving the final scene description to a JSON file. It uses probability distributions to control tree size ratios, ensures... | def generateRandomForest(generate_gt, min_lod, covered_pixels):
tree_cdf = [0.9, 0.98, 1.0] # large, medium, small
np.random.seed(0)
with open('relevant_models.json', 'r') as f:
relevant_models_dict = json.load(f)
with open('../../../build/raytracer/filtering/volume_description.json', 'r') as ... |
def log_begin_manager_thread():
loggerINFO(f"starting manager thread")
loggerINFO({"environ": os.environ})
def start_all_daemon_processes():
for name in daemon_processes:
start_daemon_process(name)
def start_all_managed_processes():
for name in managed_processes:
start_managed_process(n... | The code defines a manager thread that subscribes to "thermal" topic messages, processes temperature and system load data, and dynamically manages running processes. It continuously monitors thermal status, logs updates, and adjusts managed processes based on critical conditions (currently disabled). The loop blocks on... | def manager_thread():
ras_subscriber = Subscriber("5556")
ras_subscriber.subscribe("thermal")
log_begin_manager_thread()
start_all_daemon_processes()
start_all_managed_processes()
#thermal = ThermalStatus() # instance of class ThermalStatus
while 1:
# get thermal status
topic... |
def acceleration_command(self,theta,phi,T):
"""
Derive ax,ay,az from theta,phi,T
"""
ax = ( - c(phi)*s(theta)*c(self.yaw) - s(phi)*s(self.yaw) )*T/self.m
ay = ( - c(phi)*s(theta)*s(self.yaw) + s(phi)*c(self.yaw) )*T/self.m
az = ( self.g - ( c(phi)*c(theta))*T/s... | The main task of the code is to propagate a system's state through combinations of control parameters (Theta, Phi, T) over a time interval. It calculates new states using acceleration commands, validates them, and stores valid states and corresponding control-edge mappings. The function iterates through all parameter c... | def PropagateState( self, Theta_in , Phi_in , T_in , time , CurrState ):
numCntrls = len( Phi_in )
ProState = []
for th in Theta_in:
for ph in Phi_in:
for T in T_in :
cnt =0
for dt in time:
... |
def cuboid_data(self,box):
l = box[3] - box[0]
w = box[4] - box[1]
h = box[5] - box[2]
x = [[0, l, l, 0, 0],
[0, l, l, 0, 0],
[0, l, l, 0, 0],
[0, l, l, 0, 0]]
y = [[0, 0, w, w, 0],
[0, 0, w, w, 0],
[0, 0, 0, 0, 0],... | The main task of the code is to generate and visualize the evolution of a 3D Rapidly-exploring Random Tree (RRT) for path planning in a cluttered environment. It iteratively propagates states, checks for goal reachability, and saves snapshots of the tree's growth (e.g., snap1.png, snap2.png). Upon reaching the goal, it... | def showtree(self , Theta_in , Phi_in , T_in , Time ):
"""
Create a new directory (say nonholonomic_tree) and save snapshots of the evolution of the RRT tree
at every step with the step index.
e.g: snap1.png, snap2.png ...
"""
parent = [self.x_start , self.y_star... |
def get_up_stations(current_solution, depot_failure_rate):
return {
key: value for key, value in current_solution.items()
if random.random() > depot_failure_rate
}
def super_simple_solution_maker(tornado_event, scanning_d, max_t_bar,
CURRENT_solution, depot_failur... | This function optimizes station placement for tornado response using a heuristic algorithm. It iteratively generates and evaluates station configurations, prioritizing feasibility and efficiency. Key tasks include: precomputing station-event distances, logging parameters, applying tabu search to avoid cycles, and pertu... | def station_locator_heuristic(ALL_stations,
tornado_cases,
pars,
heuristic_pars=None,
INITIAL_solution=None):
if INITIAL_solution is None:
INITIAL_solution = copy.deepcopy(ALL_stations)
... |
def delete(self, indexes):
logger.info("Deleting Item")
for index in reversed(indexes):
if index.column() == 1:
continue
self.model.removeRow(index.row(), index.parent())
def copy_shot(self, indexes):
logger.info("Shot Copied")
index = indexes[0]
... | This code creates a context menu with actions like delete, copy/paste shots, refresh, and render options based on the selected item's type in a Qt application. It dynamically adds menu items depending on whether the selected item is a "shot" or "render_node", connecting actions to corresponding methods for operations l... | def open_menu(self, position):
index = self.view.selectedIndexes()[0]
item = self.model.itemFromIndex(index)
menu = QtWidgets.QMenu()
self.delete_action = QtWidgets.QAction("delete [ctrl+d]", self)
self.delete_action.triggered.connect(lambda: (self.delete(self.view.selectedIndexe... |
def delete(self, indexes):
logger.info("Deleting Item")
for index in reversed(indexes):
if index.column() == 1:
continue
self.model.removeRow(index.row(), index.parent())
def iterate(self, indexes, changeType):
logger.info("Iterate with changeType {0}".for... | This code initializes a GUI window with a tree view to manage shots and frame ranges, setting up shortcuts for actions like deletion, grouping, and rendering, and connecting events for data changes and context menus. It configures the model-view structure, enables drag-and-drop, and loads or populates data based on use... | def __init__(self):
super(Window, self).__init__()
self.model = StandardItemModel()
self.model.setColumnCount(2)
self.model.setHorizontalHeaderLabels(['shot', 'frame range'])
self.setGeometry(50, 50, 700, 900)
self.view = QtWidgets.QTreeView()
self.view.setModel(s... |
def play_a_different_song(self):
next_song = random.choice(SONGS)
while next_song == self.currently_playing_song:
next_song = random.choice(SONGS)
self.currently_playing_song = next_song
pygame.mixer.music.load(next_song)
pygame.mixer.music.set_volume(MUSIC_VOLUME)
... | The code implements a Snake game loop, handling user input, snake movement, collision detection, apple consumption, score tracking, and game over states. It updates the game display, manages game states (running/over), and plays background music, continuing until the player quits or restarts after a game over. | def game_loop(self):
game_exit = False
game_over = False
direction = "right"
snake_block_size = 20
snake_body = []
snake_length = INITIAL_SNAKE_LENGTH
start_position = [BOARD_WIDTH / 2, BOARD_HEIGHT / 2] # x, y
snake_head = start_position
pos_chan... |
def startClean():
str_cmd = "sudo rm -rf energy.out power.out efficiency.out *.ipc ipc.out"
command = str_cmd.split(" ")
p = subprocess.Popen(command)
p.wait()
def applyDVFS(core):
f = threading.Thread(target=startFunc, args=("./dvfs.sh " + str(core), 0))
f.start()
def makeThreads(mapping):
... | The function `run_experiment` executes a series of iterations to evaluate system efficiency under DVFS (Dynamic Voltage and Frequency Scaling) control. It applies DVFS to cores with "tcc" in the mapping, runs workloads, measures performance (IPS), calculates efficiency, and restores system states. The experiment repeat... | def run_experiment(withDVFS, mapping, iters):
startClean()
print("Current mapping: " + str(mapping))
attack_core = -1
for i in range (iters):
if (withDVFS):
for c in range(len(mapping)):
if "tcc" in mapping[c]:
attack_core = c
p... |
def restoreFreqs():
startFunc("utils/setallmax.sh", 0)
def generateApps():
apps = []
attack_core = randrange(6)
for i in range(6):
apps.append(available_apps[randrange(len(available_apps))])
apps[randrange(6)] = tcc
return apps
def run_experiment(withDVFS, mapping, iters):
startClean... | The code repeatedly attempts to find a scenario where enabling DVFS (Dynamic Voltage and Frequency Scaling) results in a significant efficiency loss (>20%) compared to a baseline configuration. It generates application mappings, runs experiments with and without DVFS, calculates the efficiency loss, and stops when a va... | def findMotiv():
found = False
tries = 0
while not found:
restoreFreqs()
time.sleep (2)
mapping = generateApps()
print("trying..")
print(mapping)
baseline = run_experiment(False, mapping, 1)
print("baseline efficiency = " + str(baseline))
time.... |
def stopBelt(self):
self.plc.writeMem('QX0.0', False)
self.plc.writeMem('QX0.1', False)
def setRobotMode(self, robot, runState):
setVal = runState
reg = '7'
output = self.plc.getMem('MW{0}'.format(reg), True)
block = output[1]
mask = 0b11110000
if robot ==... | The code provides a menu-driven interface for controlling a robot's actions, allowing users to select commands like "Go Home," "Pick Red/Black," "Sort," or "Return." Each option triggers specific operations: stopping the belt, setting robot modes to designated positions (home, game positions A-D), pausing after actions... | def robotMenu(self):
menuChoice = ""
menuText = ("----- Robot Commands -----"
"\n\t1. Go Home"
"\n\t2. Pick Red"
"\n\t3. Pick Black"
"\n\t4. Sort"
"\n\t5. Return")
while menuChoice != '5':
... |
def setRobotMode(self, robot, runState):
setVal = runState
reg = '7'
output = self.plc.getMem('MW{0}'.format(reg), True)
block = output[1]
mask = 0b11110000
if robot == 1:
block = block & mask
setVal = setVal & ~mask
elif robot == 2:
... | This code manages a game between two players (robot and human) using PLC communication. It initializes robots, handles game rounds, alternates moves between players, checks for wins, updates game states, and ensures proper PLC disconnection. The robot uses AI for moves, while the human inputs moves. The game runs for s... | def start(self, numRounds=1):
try:
self.setRobotMode(1, runState.home)
self.setRobotMode(2, runState.home)
sleep(5)
self.setRobotMode(1, runState.hold)
self.setRobotMode(2, runState.hold)
while self.plc.getMem('IX8.0') == True or self.plc.g... |
def deal_card(self, hand):
# Deal a card from the deck and add it to the specified hand.
card = self.deck.pop()
hand.append(card)
return card
def player_turn(self):
# Allow the player to take their turn, prompting for hit or stand and handling the logic.
while True:
... | The main task of the code is to simulate a Blackjack game by dealing initial cards, handling the player's and dealer's turns, checking for busts or Blackjacks, and determining the winner based on hand values. The function returns outcomes like win, loss, or tie according to game rules. | def play_game(self):
# Play the entire game, including initial dealing, player and dealer turns, and result comparison.
# Initial deal
self.deal_card(self.player_hand)
self.deal_card(self.dealer_hand)
self.deal_card(self.player_hand)
self.deal_card(self.dealer_hand)
... |
def is_king_checked(self, tile_selected, chess_piece_state):
if self.turn_color == '0':
self.turn_color = '1'
check = '0'
elif self.turn_color == '1':
self.turn_color = '0'
check = '1'
not_valid = []
i = 0
location_of_turn_king = ()
while i<len(tile_layout):
j = 0
while j < len(tile_layou... | This code calculates valid moves for a selected chess piece based on its type and the current game state. It checks if the selected piece belongs to the current player, determines its movement rules, and filters moves to prevent leaving the king in check. Valid moves are adjusted if the king is under threat, ensuring o... | def calculate_valid_moves(self, chess_piece_state, tile_selected):
selected_chess_piece = chess_piece_state[tile_selected[0]][tile_selected[1]]
if selected_chess_piece.split('_')[0] == self.turn_color:
self.can_select = True
else:
self.can_select = False
if not self.can_select:
return None
print('... |
def create_list_of_states(self):
self.list_of_states = create_list_of_tree_elements(self.tree_depth,
self.max_number_of_subpages,
self.number_of_main_pages, state = 'S')
def generate_system(self... | This code initializes a system with configurable parameters (tree depth, pages, bugs), generates states/actions, creates a system model, injects random bugs into states/actions via BugCreator, and exports the bug-injected system to a file. | def __init__(self, tree_depth=params['tree_depth'],
max_number_of_subpages=params['max_number_of_subpages'],
number_of_main_pages=params['number_of_main_pages'],
number_of_bugs_in_states=params['number_of_bugs_in_states'],
number_of_bugs_in_actions=par... |
def find_flush(hand):
suitOccur = {'s': 0, 'c': 0, 'h': 0, 'd':0}
for card in hand.cards:
if card.is_valid():
suitOccur[card.suit] += 1
if suitOccur['s'] >= 5:
return 's'
elif suitOccur['c'] >=5:
return 'c'
elif suitOccur['h'] >=5:
return 'h'
elif ... | The code evaluates a poker hand to determine its rank (e.g., straight flush, four of a kind, etc.) and returns the sorted hand and its name. It checks for high-value hands first (e.g., straight flush, four of a kind) using helper functions, then progressively lower ranks (full house, flush, straight, etc.), finally def... | def evaluate_hand(hand):
# straight flush
fs = find_flush(hand)
straight = find_straight(hand, fs)
if fs and straight:
return straight, 'straight flush'
# four of a kind
val_counts = count_values(hand)
v, n = get_max_count(hand, val_counts)
assert n <= 4
ind = get_kind_index(... |
def evaluate_hand(hand):
# straight flush
fs = find_flush(hand)
straight = find_straight(hand, fs)
if fs and straight:
return straight, 'straight flush'
# four of a kind
val_counts = count_values(hand)
v, n = get_max_count(hand, val_counts)
assert n <= 4
ind = get_kind_index(... | The function `compare_hands` evaluates and compares two 5-card poker hands. It sorts both hands, determines their ranks and values using `evaluate_hand` and `num_from_rank`, and returns 1, -1, or a comparison result based on rank hierarchy. If ranks are equal, it compares specific card values to decide the winner. The ... | def compare_hands(hand1, hand2):
# return (5 card hand, rank)
hand1.sort()
hand2.sort()
ans1 = evaluate_hand(hand1)
ans2 = evaluate_hand(hand2)
final_hand1 = ans1[0]
final_hand2 = ans2[0]
r1 = num_from_rank(ans1[1])
r2 = num_from_rank(ans2[1])
if r1 > r2:
return 1
... |
def create_popularity_view(pcollection):
return (
pcollection
| 'PackageUsage' >> beam.FlatMap(lambda rowdict: resolve_package_usage(rowdict['content'], 'import'))
| 'TotalPackageUsage' >> beam.CombinePerKey(sum)
| 'TopNPackageUsage' >> beam.transforms.combiners.Top.Of(TOP_N, co... | This function creates an Apache Beam pipeline to process Java code data from BigQuery, generate popularity and help views, calculate composite scores by combining these views, and output results as CSV files to Google Cloud Storage. It handles data limiting for DirectRunner, uses custom view functions, and writes outpu... | def create_pipeline(argv, runner, project, bucket, folder):
limit_records=''
if runner == 'DirectRunner':
limit_records='LIMIT 3000'
source_query = 'SELECT content FROM [fh-bigquery:github_extracts.contents_java_2016] {0}'.format(limit_records)
pipeline = beam.Pipeline(argv=argv)
source = pipe... |
def generator_X(AddressSizeHere, dataSizeHere):
X = np.zeros((max_size,(3+dataSizeHere+AddressSizeHere)))
#opcodes
X[0:2,0:3] = np.zeros((2,3))
X[4:6,0:2] = np.zeros((2,2))
X[4:6,2] = np.ones((2,1)).squeeze(1)
X[2,0:3] = random.choice(ALU_ops)
X[3,0:3] = random.choice(ALU_ops)
#Add... | The main task of the code is to generate a list of (X, Y) integer pairs by converting binary tensors into integers, using custom generator functions. It iterates `trainDataLength` times, creates binary tensors with `generator_X` and `generator_Y`, converts them to integers via `binary_tensor_to_int`, and stores the res... | def PairGenerator(trainDataLength):
pairs = []
for i in range(trainDataLength):
X = generator_X(AddressSizeHere,dataSizeHere)
Y = generator_Y(X, AddressSizeHere, dataSizeHere)
X = torch.from_numpy(X)
Y = torch.from_numpy(Y)
pair = (binary_tensor_to_int(X), binary_tensor_t... |
def find_cycle(adj, nodes):
node_list = list(nodes.keys())
color = dict()
parent = dict()
for node in node_list:
color[node] = 0
parent[node] = -1
global cycle_start, cycle_end
cycle_start = -1
for v in node_list:
if color[v] == 0 and dfs(v, color, parent, adj):
... | This function assembles contig sequences by analyzing cycles in a graph structure. It iteratively identifies cycles, merges contigs along these cycles considering edge orientations (+, -, *), and extends assemblies using non-cyclic paths. The best assembly is selected based on distance metrics and written to a FASTA fi... | def get_final_assembly_for_cycles(contig_map, path_to_output, ref_size, edges, nodes):
cycle = find_cycle(get_adjacency_list_with_all_nodes(edges, nodes), nodes)
true_edges = edges.copy()
while True:
cyclic_assemblies, all_rotations, cyclic_contigs_list = get_assembly_for_all_rotations_of_a_cycle(co... |
def get_assembly_map(assembly):
assembly_map = dict()
for record in assembly:
seq = record.seq
assembly_map[str(record.id)] = (seq, Seq(seq).reverse_complement())
return assembly_map
def paf_reader(infile, slack):
data = []
with open(infile, newline='') as csvfile:
reader = c... | The code merges overlapping contigs into a final assembly by constructing an overlap graph from PAF data. It checks if the graph is empty, a DAG, or contains cycles, then applies specific assembly strategies for each case. Results are logged in a CSV file, and the final assembly is generated based on graph structure an... | def merge_assembly():
slack = 100
tolerance_limit = 1000
ref_size = int(sys.argv[2])
rows = [["label", "nodes", "edges", "cycle"]]
path_to_output = sys.argv[1] + "/final"
paf_file = path_to_output + "/merge_overlaps.paf"
contigs_file = SeqIO.parse(path_to_output + "/combined.fasta", 'fasta'... |
def bestAttribute(data):
#finds the mutual info for each attribute
mutinfolist = np.empty((1,len(data[0])-1))
for i in range(len(data[0])-1):
mutinfolist[0][i] = mutualInfo(i, data)
#find biggest one and return if > 0
index = np.argmax(mutinfolist)
if mutinfolist[0][index]... | Your returnThe function `buildTree` recursively constructs a decision tree up to a specified maximum depth. It selects the best attribute to split the current stump, creates new child stumps, and recursively builds left and right subtrees if depth allows. The process halts when reaching the max depth or when no further... | def buildTree(stump, maxDepth, currentDepth):
#find best attribute
splitindex = bestAttribute(stump.data)
if (maxDepth <= currentDepth) or (splitindex == None):
#base case, just return the stump we're at without adding left or right
return stump
else:
#create a stump using the creat... |
def request_mt5_symbol_info(symbol):
try:
element = mt5.symbol_info(symbol)._asdict()
contract_size = element['trade_contract_size']
trade_point = element['point'] # num ticks
trade_tick = element['trade_tick_value'] # value per tick in USD per 1 standard lot
... | This code initializes a backtesting framework for trading strategies, setting up parameters like symbol, timeframe, lot size, and commission. It processes training and test dataframes, validates inputs, configures trading sessions, and creates evaluation metrics (e.g., Sharpe ratio, max drawdown). It builds multiple da... | def __init__(self,
symbol:str,
timeframe:str,
train_raw: pd.DataFrame,
test_raw: pd.DataFrame,
lot: float,
starting_balance: int,
commission: float = 3.5,
max_loss_pct: float =... |
def check_park(
park_id, start_date, end_date, campsite_type, campsite_ids=(), nights=None
):
# park_info = { siteID: [dates] } (e.g. { 85116: ['2022-09-08T00:00:00Z', ...], ... })
# want it to be { siteID: { name: [dates] } }
# or { name: { siteID: [dates] } }
# or [ { name: 'abc', siteID: '123', d... | The main task of the code is to check campsite availability for specified parks within given date ranges and parameters, then output the results in either JSON or human-readable format. It iterates through each park ID, retrieves availability data using `check_park`, aggregates results, and generates output based on th... | def main(parks, json_output=False):
info_by_park_id = {}
for park_id in parks:
info_by_park_id[park_id] = check_park(
park_id,
args.start_date,
args.end_date,
args.campsite_type,
args.campsite_ids,
nights=args.nights,
)
... |
def _save_checkpoint(self, epoch):
r"""Store the model parameters information and training information.
Args:
epoch (int): the current epoch id
"""
state = {
'config': self.config,
'epoch': epoch,
'cur_step': self.cur_step,
'b... | The code trains a machine learning model using provided training data, optionally validating with validation data. It performs early stopping based on validation performance, saves the best model checkpoints, logs training/evaluation metrics, and returns the best validation score and results. The function handles epoch... | def fit(self, train_data, valid_data=None, verbose=True, saved=True, show_progress=False, callback_fn=None):
r"""Train the model based on the train data and the valid data.
Args:
train_data (DataLoader): the train data
valid_data (DataLoader, optional): the valid data, default: ... |
def _download(self):
import tarfile
if self._check_integrity():
print("Files already downloaded and verified")
return
download_url(self.url, self.root, self.filename, self.tgz_md5)
with tarfile.open(os.path.join(self.root, self.filename), "r:gz") as tar:
... | This code initializes a dataset class by setting up parameters like root directory, train/test mode, transforms, and downloads the dataset if specified. It checks data integrity, adjusts class labels to start from zero, and prepares mappings/class names for the dataset, likely for a 200-class classification task like C... | def __init__(
self,
root: str,
train: bool = True,
transform=None,
loader=default_loader,
download: bool = True,
num_classes: int = 200,
):
self.root = os.path.expanduser(root)
self.transform = transform
self.loader = default_loader
... |
def build_from_cache(project_list, page_template_file, config):
projects = collections.defaultdict(list)
for p in project_list:
projects[p['author']].append(p)
for author, project_list in projects.items():
if config!=None:
config.seek(0)
projetu = Projetu(page_template_f... | The main task of this code is to process and generate project data from GitLab or a cache, filter projects based on input criteria, assign students, and output structured CSV and LaTeX files. It handles project metadata, updates assignments from a CSV, sorts projects, and exports results with optional debugging. | def cli(page_template_file, template_file, config, gitlab_host, token, profs, project_type, academic_year, output, project_filter, debug, from_cache,tag, updated_assignation):
if debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
if tag is not... |
def U(self, x):
return 1 + sum(self.MBH[i]/norm(x-self.PosBH[i]) for i in range(self.NBH))
def dUdxi(self, x, j):
return (sum(self.MBH[i]*(self.PosBH[i, j] - x[j])/norm(x-self.PosBH[i])**3 for i in range(self.NBH)))
def dUdxi2(self, x, j, i):
return self.MBH[i]*(self.PosBH[i, j] - x[j])/norm(x-s... | The main task of the code is to compute a time-step `dt` and update the system's state (position, momentum) for an extremal black hole simulation. It calculates distances and vectors between the particle and moving black holes, derives `dt` using a time-dilation function `U` and its derivatives, then returns an array o... | def dF2(self, lam, xp): # Extremal black hole
t = xp[0]
x = xp[1:3]
p = xp[3:5]
r = np.zeros(self.NBH)
q = np.zeros((self.NBH, 2))
for i in range(self.NBH):
r[i] = np.sqrt((x[0] - self.PosBH[i, 0])**2 + (x[1] - (self.PosBH[i, 1] + (-1)**i*self.v*(t-1e4)))**2)... |
def ProxCheck(self, xp0):
Prox = [(norm(xp0[1:3]-self.PosBH[0]) < self.switch), (norm(xp0[1:3]-self.PosBH[1]) < self.switch)]
if Prox[0]:
return 1
elif Prox[1]:
return 2
else:
return 0
def norm(vec):
return np.linalg.norm(vec)
def convert(self, arr... | This code performs numerical integration of a particle's trajectory under combined Newtonian and Schwarzschild gravitational regimes. It iteratively solves ODEs using scipy's solve_ivp, switching between coordinate systems and integration methods based on proximity to black holes. The result accumulates particle states... | def CalcCombined(self, lam, xp0, dLam): # Does the numerical integration for method 3.
TotalResFlag = False
self.state = self.ProxCheck(xp0)
for n in range(10):
# print('n', n, xp0, self.state)
if self.state == 0: # Newtonian
res = scipy.integrate.solve... |
def CalcCombined(self, lam, xp0, dLam): # Does the numerical integration for method 3.
TotalResFlag = False
self.state = self.ProxCheck(xp0)
for n in range(10):
# print('n', n, xp0, self.state)
if self.state == 0: # Newtonian
res = scipy.integrate.solve... | The code performs numerical integration to compute equations of motion (EoMs) for different scattering scenarios using `scipy.integrate.solve_ivp`. It selects integration methods based on `self.method` (1-4), handles coordinate transformations, and returns integrated results. Method 4 is incomplete, involving spherical... | def GRCalc(self, lam, xp0, dLam): # Perform numerical integration to find the EoMs under various types of scattering.
if self.method == 1:
res = scipy.integrate.solve_ivp(self.dF1, (0, lam), xp0, method='LSODA', events = self.GRhit, dense_output=True, vectorized=False, max_step=dLam)
if sel... |
def Calc(self, lam):
res = scipy.integrate.solve_ivp(self.pdF, (0, lam), self.xp0, method='RK45', events = hit, dense_output=True,
vectorized=False, max_step=self.res)
return res.y
def finalOrbit(ret):
Fangle = angle(ret[1:3, -1])
for i in range(len(ret[0... | The code computes orbital parameters by processing input data `T` through `Calc(T)`, then analyzing the resulting orbit (`lRet`) to determine key metrics like position, center of mass, and orbital characteristics (e.g., minimum/maximum radii, eccentricity-like ratio). It prints final positions, CoM, radial extremes, an... | def setupOrbit(self, T):
Ret = self.Calc(T)
lRet = finalOrbit(Ret)
r0 = [min(lRet[1])/2+ max(lRet[1])/2, min(lRet[2])/2 + max(lRet[2])/2]
rmin = min(distance(lRet[1:3], [0, 0]))
rmax = max(distance(lRet[1:3], [0, 0]))
print('final pos', Ret[:, -1])
print('E, L, ... |
def norm(vec):
return np.linalg.norm(vec)
def finalOrbit(ret):
Fangle = angle(ret[1:3, -1])
for i in range(len(ret[0, :])-2, 1, -1):
ang0 = abs(angle(ret[1:3, i-1]) - Fangle) % (2*np.pi)
ang1 = abs(angle(ret[1:3, i]) - Fangle) % (2*np.pi)
ang2 = abs(angle(ret[1:3, i+1]) - Fangle) % (... | This code generates plots to visualize Kepler orbits under various perturbative forces (Radial, Drag, MassPlanet, MassSun), showing orbital paths and time-dependent variations in energy, angular momentum, and Runge-Lenz vectors. It computes these quantities using orbital mechanics calculations, applies method-specific ... | def CoMplot(T, xp0, M, m, res, dpArr, method='Radial', rDep=-2, pDep=1):
font = {'family' : 'normal',
'weight' : 'bold',
'size' : 12}
plt.rc('font', **font)
fig, ax = plt.subplots(2, figsize=(10, 9), tight_layout=True)
orbit = Kepler_Orbit(xp0, M, m, G, dpArr[0], res, method, rDep=r... |
def initCond(self, B, R, ang): # Convert initial conditions in terms of scattering theory into cartesian coordinates, with relativistic correction terms.
x0 = (-R*np.cos(ang)-B*np.sin(ang), -R*np.sin(ang) + B*np.cos(ang))
if self.method == 1 or self.method == 3:
v0 = self.vel*np.array((np.co... | The function calculates the momentum transfer of a particle to two black holes, considering whether the particle is captured by one. It returns the combined momentum components based on the capture status and method, with different formats for captured vs. un-captured cases. | def SimMomentum(self, B, T, dlam, ang=0): # Compute the momentum transfer of a particle to both black holes.
R = 1e4
xp0 = self.initCond(B, R, ang)
Ret = self.GRCalc(T, xp0, dlam)
dP = self.GRmomentum(xp0, Ret[:, -1])
cap = self.GRIdentify(Ret[:, -1]) # Was it captured by... |
def train_theta(self, data, epochs, epoch_attack, gamma, end_flag = False):
optimizer = optim.Adam(self.model.parameters(), lr=0.01)
for i in range(epochs):
if i % 10 == 0 or not end_flag:
images_adv, labels = self.attack(gamma, data, step=epoch_attack)
else:
... | This code trains a model by iteratively adjusting its parameters and weights using gradient-based optimization. It computes gradients of a risk metric (rtheta), updates model parameters (theta), and adjusts weights (w) with a learning rate derived from gradient magnitudes. The process includes enforcing non-negative we... | def trainAll(self, epoch, epoch_theta, epoch_attack, epoch_w=1):
min_weight = torch.min(self.weights)
attack_gamma = (1.0 / min_weight).data
deltaall = 20
alpha = 0.5
zero_list = []
dim_x = self.environments[0][0].size(1)
end_flag = False
for t in range... |
def find_empty_location(arr,l):
minimum=19
for row in range(9):
for col in range(9):
if(arr[row][col]==0):
count=0
for x in range(1,10):
if check_location_is_safe(arr,row,col,x):
count=count+1
if co... | This function solves a Sudoku puzzle using backtracking. It recursively fills empty cells with valid numbers (1-9), checking safety via the `check_location_is_safe` method. If a valid number is found, it places it and continues solving; if no solution exists, it backtracks by resetting the cell. The process repeats unt... | def solve_sudoku(arr):
l=[0,0]
if(not find_empty_location(arr,l)):
return True
row=l[0]
col=l[1]
for num in range(1,10):
if(check_location_is_safe(arr,row,col,num)):
arr[row][col]=num
if(solve_sudoku(arr)):
return True
... |
def _selection(self):
"""
class internal function triggering the selection process of the fittest parents from the population.
The function chooses only two parents for each run form the population. So there is no multi-parent crossover
supported yet, even if it would be easy to implemen... | The code trains a neural network using a genetic algorithm by iteratively evaluating population members' fitness, selecting top performers, generating offspring via crossover, and replacing lower-fitness members. The process continues until generation limits or fitness targets are met, returning the fittest model. Moni... | def train(self, x: np.array, y: np.array, generation_replacement: float = 0.2, monitor: bool = False):
"""
main function of the model. it will run the entire training with given feature and label data in order to create
a NumpyNet model with is able to run predictions. It executes the main genet... |
def receive_data_via_tcp(destination_path):
total_messages_received = 0
total_bytes_received = 0
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('New connection from', addr)
... | The main task of the code is to receive data using either TCP or UDP protocols from a specified source path, track the total number of messages and bytes sent, and display performance statistics including duration, messages, and bytes transferred. The function initializes counters, selects the appropriate protocol hand... | def receive_data(protocol, source_path):
start = time.time()
total_messages_send = 0
total_bytes_sent = 0
if protocol == Protocol.TCP:
total_bytes_sent, total_messages_send = receive_data_via_tcp(source_path)
elif protocol == Protocol.UDP:
total_bytes_sent, total_messages_send = rec... |
def send_data_via_tcp(source_path):
total_bytes_sent = 0
total_messages_send = 0
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
for filename in os.listdir(source_path):
file_path = os.path.join(source_path, filename)
with open(... | The function `send_data` transmits data using either TCP or UDP based on the specified protocol, calculates total bytes and messages sent, and displays transmission statistics including duration. It initializes counters, selects the appropriate sending method, records timing, and outputs results via `show_stats` for pe... | def send_data(protocol, path_sent):
total_bytes_sent = 0
total_messages_send = 0
start = time.time()
if protocol == Protocol.TCP:
total_bytes_sent, total_messages_send = send_data_via_tcp(path_sent)
elif protocol == Protocol.UDP:
total_bytes_sent, total_messages_send = send_data_via... |
def get_image_index(self, img_path: str):
if img_path not in self.images:
return -1
return self.images.index(img_path)
def get_image_at(self, index: int) -> str:
try:
return self.images[index]
except IndexError:
return self.images[0]
def change_image(... | This method navigates to the previous image in a sequence by retrieving the current image's index, decrementing it to find the prior image's path, converting the path to a Path object, and then updating the display to show the previous image. | def prev_image(self, *args):
current_index: int = self.get_image_index(self.current_image.location)
prev_img_path = self.get_image_at(current_index - 1)
prev_img_path = pathlib.Path(prev_img_path)
self.change_image(prev_img_path) |
def get_image_index(self, img_path: str):
if img_path not in self.images:
return -1
return self.images.index(img_path)
def get_image_at(self, index: int) -> str:
try:
return self.images[index]
except IndexError:
return self.images[0]
def change_image(... | The main task of the code is to navigate to the next image in a sequence by incrementing the current image's index, retrieving the corresponding image path, converting it to a pathlib object, and updating the displayed image using `change_image`. This function assumes a pre-defined list of images and their locations fo... | def next_image(self, *args):
current_index: int = self.get_image_index(self.current_image.location)
next_img_path = self.get_image_at(current_index + 1)
next_img_path = pathlib.Path(next_img_path)
self.change_image(next_img_path) |
def assign_centroids(X, centroids):
idx = np.zeros(X.shape[0], dtype=int)
for i in range(X.shape[0]):
distances = np.zeros(centroids.shape[0])
for k in range(centroids.shape[0]):
distances[k] = norm(X[i] - centroids[k])
idx[i] = np.argmin(distances)
return idx
def move_ce... | The code implements the K-means clustering algorithm, iteratively assigning data points to cluster centroids and updating centroids based on assigned points. It runs for a specified number of iterations, printing progress and distortion metrics if enabled, and returns final centroids and cluster indices. | def k_mean(X, initial_centroids, max_iter, verbos=True):
centroids = initial_centroids
K = initial_centroids.shape[0]
idx = np.zeros(X.shape[0], dtype='int')
for i in range(1, max_iter + 1):
if verbos: print(f'Iteration {i}/{max_iter}')
idx = assign_centroids(X, centroids)
centro... |
def random_initial_centroids(X, K):
a = np.random.permutation(X.shape[0])
return X[a[:K]]
def k_mean(X, initial_centroids, max_iter, verbos=True):
centroids = initial_centroids
K = initial_centroids.shape[0]
idx = np.zeros(X.shape[0], dtype='int')
for i in range(1, max_iter + 1):
if verb... | The code performs K-means clustering optimization by running the algorithm multiple times (`out_of` iterations) with random initial centroids. It tracks the minimum distortion cost across all runs and returns the centroids and cluster assignments from the iteration achieving the lowest cost. The function iteratively in... | def k_mean_optimization(X, K, max_iter, out_of=100, verbos=True):
min_cost = -1
outcome = ()
for i in range(1, out_of + 1):
if verbos: print(f'Iteration {i}/{out_of}')
initial_centroids = random_initial_centroids(X, K)
centroids, idx = k_mean(X, initial_centroids, max_iter, False)
... |
def generate_keys(bits=512, min_e_value=3, return_p_q=False):
p = generate_random_primary(bits)
q = generate_random_primary(bits)
n = p * q
phi = (p - 1) * (q - 1)
e = generate_public_key_e(phi, min_value=min_e_value)
d = compute_private_key_d(e, phi)
if return_p_q:
return n, e, d, p... | The main task of the code is to demonstrate RSA encryption/decryption processes, including key generation, number/text encryption/decryption, performance comparison between standard and CRT decryption methods, and testing various text-to-number encryption variants. It validates correctness and measures computational ef... | def test():
print("Generating keys...")
n, e, d, p, q = generate_keys(bits=512, min_e_value=3, return_p_q=True)
print("n=", n)
print("e=", e)
print("d=", d)
print('-' * 20)
print("Encrypting a number:")
number = random.getrandbits(8)
print("Number to send:", number)
cipher_numb... |
def display(self):
# clear the background canvas to empty_cell_color
stddraw.clear(self.empty_cell_color)
# draw the game grid
self.draw_grid()
# draw the current (active) tetromino
if self.current_tetromino is not None:
self.current_tetromino.draw()
#... | The `merge` function identifies adjacent tiles in a grid with identical values, merges them by doubling the value, updates their visual appearance (color and text), adds the merged value to the score, removes the merged tile, and triggers a recursive merge if any changes occur. It also handles tile dropping to fill gap... | def merge(self):
# recursion check variable
merged = False
# determine the merge height border
if self.current_tetromino.bottom_left_corner.y + self.current_tetromino.n > len(self.tile_matrix):
up_merge_border = len(self.tile_matrix)
else:
up_merge_border ... |
def drop_tile(self, i, k):
# check if there is a tile with a space under it
while self.tile_matrix[i - 1][k] is None:
# move the tile down
self.tile_matrix[i][k].move(0, -1)
# move the tile down in matrix
self.tile_matrix[i - 1][k] = self.tile_matrix[i][k]... | This function removes gaps in a tile matrix by recursively dropping controlled tiles into empty spaces below, checking edge and middle columns for adjacent tiles, and triggering merges and rechecks after each removal to ensure the board is updated properly. | def remove_gaps(self):
# recursive check variable
removed = False
# check every row except start and finish columns
for i in reversed(range(1, len(self.tile_matrix) - 1)):
# check every column
for k in range(len(self.tile_matrix[0])):
# check if co... |
def mainMenu(preset_mode=-1):
pygame.mixer.music.play(-1)
blink_count = 0
mode = -1
preset_mode = preset_mode if preset_mode in [-1, 0, 1, 2] else 0
run = True
runMain = True
if preset_mode == -1:
while run:
for event in pygame.event.get():
if event.type =... | This code implements a Pong-style game with multiple players/AI, handling input, collision detection, scoring, and game state transitions. It initializes game elements via mainMenu(), processes keyboard events for movement, updates paddle positions, manages ball physics, checks for goals, displays scores, and cycles th... | def main():
window, players, ball, walls, goals, runMain = mainMenu()
global paddle_vel, largest_score
blink_count = 0
run = runMain
game_run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.ty... |
def create_backdoor(self) -> None:
""" Creates the backdoor file
"""
if not self.obfuscate_backdoor():
self.print_verbose_message("Failed to encode backdoor", prefix="-")
exit()
hash = get_sha1_file_hash(self.config.out_file)
self.print_verbose_message(f"S... | The code's main task is to determine the execution path based on configuration flags. If neither 'just_listen_and_host' nor 'just_listen' is set, it creates a backdoor. If 'just_listen_and_host' is enabled, it starts a threaded HTTP server. Finally, it initiates a session regardless of the prior actions, handling netwo... | def start(self) -> None:
if not self.config.just_listen_and_host and not self.config.just_listen:
self.create_backdoor()
elif self.config.just_listen_and_host:
self.start_threaded_http_server()
self.start_session() |
def push_first_node(self):# For first node
x_move_counter = 0
while x_move_counter < 70 - 5:
self.make_label.place_forget()
self.label_position_x += 2
self.make_label.place(x=self.label_position_x, y=self.label_position_y)
self.make_canvas.move(self.make_n... | This method inserts a new node into a binary search tree (BST) visualization by determining its correct position based on value comparisons. It creates a node on the canvas, adjusts horizontal/vertical positioning through directional movement logic, enforces depth restrictions (≤4 levels), handles duplicate value error... | def make_default_node_with_set_position(self):# For node make and set at right position in canvas
try:
self.status_note.config(text="Insertion Process")
self.status_note.place(x=500, y=130)
self.make_node = self.make_canvas.create_oval(505, 85+50, 555, 135+50, width=2, fill=... |
def make_default_node_with_set_position(self):# For node make and set at right position in canvas
try:
self.status_note.config(text="Insertion Process")
self.status_note.place(x=500, y=130)
self.make_node = self.make_canvas.create_oval(505, 85+50, 555, 135+50, width=2, fill=... | This code validates an input value as an integer, then performs BST operations (node creation or deletion) based on the 'indicator' flag, while managing UI elements by hiding input widgets and showing appropriate error messages or executing actions like node creation/deletion. | def filtration_of_input_value(self, e, indicator): # Filtration with button deactivation and activation
self.take_input.place_forget()
self.take_entry.place_forget()
self.add_btn.place_forget()
try:
if int(self.take_entry.get()):
if indicator == 1:
... |
def _buildInit(self, mDict):
init = [] # you may choose to change initial conditions
for sp in mDict['idSp']:
init.append(mDict['spDict'][sp]['initConcentration'])
return init
def _gen_interactions(self):
inacts = set()
for key, mod in self.modules.items():
... | The code initializes an ODE-based model by copying structural and parametric data from `mDict`, including species, reaction matrices, rate laws, and initial conditions. It constructs interaction maps, local response matrices, and prepares the model for integration using `scipy.integrate.odeint`, enabling simulation of ... | def __init__(self, mDict):
"""
mDict: Dictionary object containing model description.
(including decomposition in modules)
HOW TO INTEGRATE ODES:
m = OdeModel(S, idSp, idRs, rateDict, param, init)#simTime
m.performSubstitutions()
m.buildRateVector()
fr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.