dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def clear_layout_view(self):
if self.scroll_area:
self.scroll_area.setWidget(QWidget())
def display_pcap_list(self):
pcap_rows_widget = QWidget()
pcap_rows = QVBoxLayout()
pcap_len = len(self.pcap_dicts)
for i in range(pcap_len):
packet_btn = QPushButton("... | The main task of the code is to load a PCAP file via a dialog, parse its packet data (headers, connections, IP4 datagrams), and display the parsed results in a GUI. It disables the load button during processing, updates status messages, clears existing layouts, generates packet display widgets, visualizes TCP streams a... | def pcap_loader(self):
self.pcap_ldr_btn.setDisabled(True)
self.pcap_loading_status.setText("Loading pcap...")
QApplication.processEvents()
dialog = QFileDialog()
dialog.setNameFilter("All PCAP files (*.pcap)") ## only open PCAP files
dialog.setFileMode(QFileDialog.FileMo... |
def pcap_loader(self):
self.pcap_ldr_btn.setDisabled(True)
self.pcap_loading_status.setText("Loading pcap...")
QApplication.processEvents()
dialog = QFileDialog()
dialog.setNameFilter("All PCAP files (*.pcap)") ## only open PCAP files
dialog.setFileMode(QFileDialog.FileMo... | This code initializes a GUI for a TCPDump analysis tool, setting up a window with layouts for importing PCAP files, displaying loading status, visualizing packets via a scrollable area, and providing hidden buttons for analyzing streams and TCP handshakes. It organizes widgets using Qt layouts and connects buttons to m... | def __init__(self):
super().__init__()
self.setWindowTitle("TCPDump Analysis and Visualisation Tool")
pagelayout = QVBoxLayout()
pcap_loader_layout = QHBoxLayout()
# packet_layer_button_layout = QHBoxLayout()
pcap_loading_status_layout = QHBoxLayout()
pagelayou... |
def convert_book_status(status):
readstatus = None
readpages = -1
if status.is_read:
readstatus = "read"
readpages = -1
elif status.is_wishlisted:
readstatus = "wishlisted"
readpages = -1
elif status.read_pages != -1:
readstatus = "reading"
readpages... | The function `feed_read_update` generates a structured reading status update by converting input `status` into `readStatus` and `readpages`, then compiling user, book, and timestamp data into a dictionary with an "updateType" of "readingUpdate" for tracking or notification purposes. | def feed_read_update(status, userId):
readstatus, readpages = convert_book_status(status)
return {
"updateType": "readingUpdate",
"readStatus": readstatus,
"readpages": readpages,
"user": user_mini_alter(status.user),
"timeStamp": status.timestamp,
"book": book_m... |
def remember(self, state, action, reward, next_state, done):
self.memory.append((state, action, reward, next_state, done))
def replay(self, batch_size):
x_batch = np.ndarray(shape=(0,(self.numStatesX + self.numStatesY)*self.stateHistSize))
y_batch = []
minibatch = random.sample(self.memory, min(len(self.m... | The code updates a reinforcement learning model by storing experiences in memory, performing experience replay when sufficient data is available, and periodically synchronizing the target model with the main model to improve training stability and convergence. | def update(self, old_state, new_state, action, reward, done):
# Train our model with new data
self.remember(old_state, action, reward, new_state, done)
if done:
# self.remember(old_state, action, reward, new_state, done)
if len(self.memory) > 127:
self.replay(128)
self.updateCount += 1
if self.upd... |
def is_selecting_cell(self) -> bool:
return self.is_selecting_start or self.is_selecting_exit
def stop_selecting_cell(self):
self.is_selecting_start = False
self.is_selecting_exit = False
self.custom_start = None
self.set_mouse_visible(True)
def generate_maze(self, _event=None):
... | This method handles keyboard inputs to control maze generation and navigation. It stops cell selection on ESC/E, closes the window on ESC, generates a maze on SPACE, finds a default path on ENTER, selects a custom path on E, and breaks walls on B. | def on_key_press(self, symbol: int, modifiers: int):
if self.is_selecting_cell():
if symbol in (arcade.key.ESCAPE, arcade.key.E):
self.stop_selecting_cell()
return
if symbol == arcade.key.ESCAPE:
arcade.close_window()
elif symbol == arcade.ke... |
def clear():
os.system('cls||clear')
def one_path(start_code, end_code):
#Holds all stations being passed through
ret = []
#Gets all the stations between the start and end code
r = http.client.HTTPSConnection('api.wmata.com')
params2 = urllib.parse.urlencode({
'FromStationCode'... | The main task of the code is to retrieve and process Washington Metro station data from an API, validate user input for start/end stations, determine station codes and line colors, compute a route between stations (same or different lines), and display the calculated path with station list and count. | def main():
#Gets all stations from this API call
req = http.client.HTTPSConnection('api.wmata.com')
req.request("GET", "/Rail.svc/json/jStations?%s", "{body}", headers)
response = req.getresponse()
#Converts the binary data to UTF-8 and into a json format
lines = response.read().decode('UT... |
def filter_by_rnacentral(library_list: list, Rnacentral_dir: str,
path_write: str) -> None:
'''
This function filters the libraries by eliminating those sequences that
map against the RNAcentral database.
Parameters
----------
library_list : list
List with the ab... | The code processes small RNA (sRNA) libraries by filtering out non-coding RNAs (rRNA, tRNA, etc.) using the RNAcentral database. It generates absolute counts and reads per million (RPM) tables for each library, then merges these into a unified project table. Key steps include argument validation, RNAcentral indexing, s... | def main():
'''
Main program
'''
parser = argparse.ArgumentParser(prog='FILTAB V2',
description='''This program filters sRNA \
sequences using RNAcentral to discard \
rRNA, tRNA, snRNA a... |
def get_ds(config):
"""
Loading datasert which takes the configuration of the model
"""
ds_raw = load_dataset('opus_books', f'{config["lang_src"]}-{config["lang_tgt"]}',
split='train')
# building tokenizer
tokenizer_src = get_or_build_tokenizer(config, ds_raw, config['lang_... | The code trains a sequence-to-sequence transformer model for tasks like translation. It initializes the model, loads data, configures optimizer and loss function (with label smoothing), and performs training over multiple epochs. Each batch computes loss, backpropagates gradients, and validates the model. Training prog... | def train_model(config):
# define the device on which you want to put your tensors on
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f'Using device {device}')
Path(config['model_folder']).mkdir(parents=True,exist_ok=True)
# loading dataset
train_dataloader,val_data... |
def read_boats(race, path):
print("Reading boats")
if not "boat1.json" in os.listdir(path) and not "boat2.json" in os.listdir(path):
raise FileNotFoundError
with open(f"{path}/boat1.json", "rb") as f:
boat1 = json.load(f)
with open(f"{path}/boat2.json", "rb") as f:
boat2 = json.l... | The code reads and processes a race's data from a JSON file, incorporating boat details, course information, and YouTube video timestamps. It calculates time differences between consecutive races, adjusts video offsets, and optionally compresses data by interpolating boat positions and saving results. | def read_race(i, event):
path = f"{event}/{i}"
with open(f"raw/{path}/stats.json", "rb") as f:
race = json.load(f)
boats = read_boats(race, f"raw/{path}")
race["course_info"] = get_course_info(path)
date = datetime.fromtimestamp(race["course_info"]["startTime"])
race["course_info"]["star... |
def do_setup():
global configs
global headers
global current_datetime
required_config_keys = ["ORG_NAME", "AUTH_KEY", "CRITICAL", "WARNING", "SLEEP_TIME", "ALERT_RULE_SUFFIX"]
try:
# Init logger
current_datetime = datetime.now().strftime('%m-%d-%Y_%I:%M:%S %Z')
logging.basicC... | The code's main task is to set up and create alerts for specified or all projects in an organization. It initializes configurations, checks user confirmation for mass operations, retrieves alerts and project data, generates alerts, and outputs a script report with a log file reference. Global variables track configurat... | def main(argv):
global alert_list
global configs
global headers
global script_report
global current_datetime
projects_to_operate_on = argv
do_setup()
if not projects_to_operate_on:
selection = input(f"Caution: you are about to create alerts for all projects in {configs.get('... |
def score(line, criteria, total_lengths, filetype):
avg = 0
count = 0
total_scores = np.zeros(len(line))
for i, c in enumerate(criteria):
scores = np.array(c.get_score(line, filetype))
if i == 0: scores *= 2
total_scores += scores
for val in scores:
if not val... | This code processes input lines from a file, filters them based on specified criteria and dynamic thresholds, and writes accepted lines to output files in either JSON or TXT format. It adjusts the acceptance cutoff dynamically using average acceptance rates and handles multiple output files. The function evaluates each... | def singlefile(path_in, path_outs, criteria, context_length, outlength = [-1], whole_line = False, keepWrapper = False):
filetype = ""
total_lengths = np.zeros(200)
target_length = outlength[0]
current_file = 0
cutoff = 1.5
if isinstance(path_outs, str):
path_out = path_outs
else:
... |
def get_validation_subjects(
data_path: Path, max_size: int, seed: int, val_split_file: str = None
) -> List[Path]:
"""This function returns a list of subjects that should be used for evaluation. If there is a split file, it tries to include them in the set.
Arguments:
data_path: root directory cont... | The main task of the code is to select subjects from an input directory for validation (using parameters like max_val_size, seed, and val_split_file), anonymize them if specified, and copy the selected subjects to designated output directories for data and labels. It also generates a mapping between anonymized aliases ... | def run_preparation(
input_dir: str,
output_data_dir: str,
output_label_dir: str,
max_val_size: int = 200,
seed: int = 108493,
val_split_file: str = None,
anonymize_subjects: bool = True,
) -> None:
"""This function selects subjects from input_dir (and possibly the val_split_file) for va... |
def line_segmentation(img):
lines_start_and_end = projection_histogram(img, type='vertical', dil=False)
return lines_start_and_end
def crop_line(img, line_start_and_end):
line_img = img[line_start_and_end[0]:line_start_and_end[1]]
return line_img
def word_segmentation(line_img):
no_words, line_img =... | The main task of the code is to perform character segmentation on an input image by sequentially splitting it into lines, words, and individual characters using projection histograms. It reads a grayscale image, segments lines, extracts words from each line, and finally isolates characters via horizontal projection, re... | def character_segmentation(img_name):
characters = []
img = cv2.imread(img_name, 0)
lines_start_and_end = line_segmentation(img)
print('lines')
print(lines_start_and_end)
for line in lines_start_and_end:
line_img = crop_line(img, line)
print('line')
word_start_and_end = w... |
def crop_line(img, line_start_and_end):
line_img = img[line_start_and_end[0]:line_start_and_end[1]]
return line_img
def word_segmentation(line_img):
no_words, line_img = calculate_no_words_in_line(line_img)
word_start_and_end = []
for i in range(1, 16, 2):
for j in range(1, 16, 2):
... | This function recognizes text in a line from an image by cropping the line, segmenting it into words, processing each word's image (upscaling, thresholding, contour detection), sorting contours, and combining recognized characters into a string. | def recognize_line(line_coord, img):
line = []
line_img = crop_line(img, line_coord)
word_start_and_end = word_segmentation(line_img)
for word_coord in word_start_and_end:
word_img = crop_word(line_img, word_coord)
upimg = cv2.pyrUp(word_img)
thresh_word = process_image(upimg)
... |
def line_segmentation(img):
lines_start_and_end = projection_histogram(img, type='vertical', dil=False)
return lines_start_and_end
def crop_line(img, line_start_and_end):
line_img = img[line_start_and_end[0]:line_start_and_end[1]]
return line_img
def word_segmentation(line_img):
no_words, line_img =... | The code processes an image by segmenting it into lines and words, counts the number of lines, words, and calculates the average words per line. It then recognizes a paragraph from the image and updates GUI labels with these statistics, finally inserting the recognized paragraph into a textbox. | def run(self):
img = cv2.imread(self.img_name, 0)
lines_coord = line_segmentation(img)
total_no_of_lines = len(lines_coord)
total_no_of_words = 0
total_spaces = []
for line in lines_coord:
line_img = crop_line(img, line)
word_start_and_end = word_s... |
def spaceX():
return findElement(9, matrix)[0]
def shift(x):
global matrix
y=9
findx=findElement(x, matrix)
findy=findElement(y, matrix)
matrix[findx[0]][findx[1]],matrix[findy[0]][findy[1]] = matrix[findy[0]][findy[1]], matrix[findx[0]][findx[1]]
def spaceY():
return findElement(9, matrix)[... | The main task of the code is to select the next optimal move in a sliding puzzle (e.g., 8-puzzle) by evaluating all possible moves around the blank tile, avoiding previously visited states, and choosing the move with the lowest cost. If all moves are revisited, it randomly selects a valid move. The function updates the... | def chooseConfig():
#Global allows us to to make changes in global variables, matrix and not form local variables
global matrix
copyMat=copy.deepcopy(matrix)
cost_list=[]
pref=0
#possible_list contains the which of the 4 moves(up,down,left,right) are possible for the given blank tile
possi... |
def size_below(dir: dict, size: int) -> bool:
return get_size(dir) < size
def get_size(dir: dict):
if not dir:
return 0
else:
return sum([item[1] if type(item[1]) == int else get_size(item[1]) for item in dir.items()]) | The function calculates the total size of all elements in a nested dictionary structure, adding the size of each sub-dictionary only if its size is below 100,000. It recursively processes each item, checking conditions to accumulate sizes conditionally. | def find_all_below(fs: dict) -> int:
if size_below(fs, 100000):
return get_size(fs) + sum([find_all_below(item[1]) if type(item[1]) == dict else 0 for item in fs.items()])
else:
s = 0
for item in fs.items():
if type(item[1]) == dict:
s += find_all_below(item[1... |
def parse_input(puzzle_input):
fs = dict()
current_wd = ''
current_dir_dict = fs
for c in puzzle_input:
match c.split(' '):
case ['dir', name]:
current_dir_dict[name] = dict()
case ['$', 'cd', name]:
if name == '..':
cur... | The code calculates the minimum directory size that, when deleted, would free enough space to meet the required 30 million bytes. It parses the input into a file system, computes total size, determines needed free space, and returns the smallest directory size exceeding this requirement. Your return | def solve_part_2(puzzle_input: str):
fs = parse_input(puzzle_input)
total_size = get_size(fs)
current_free = 70000000 - total_size
min_free_required = 30000000 - current_free
all_sizes = get_all_sizes(fs)
return min([x for x in all_sizes if x > min_free_required]) |
def set_target(self):
return self.app.c_pos
def time_to_move(self):
if int(self.pix_pos.x+TOP_BOTTOM_BUFFER//2) % self.app.cell_width == 0:
if self.direction == vec(1, 0) or self.direction == vec(-1, 0) or self.direction == vec(0, 0):
return True
if int(self.pix_pos.y... | The code updates an object's position by moving it toward a target position using directional speed, then converts pixel-based coordinates to grid-based coordinates for game grid alignment. | def update(self):
self.target = self.set_target()
if self.target != self.grid_pos:
self.pix_pos += self.direction * self.speed
if self.time_to_move():
self.move()
# Setting grid position in reference to pix position
self.grid_pos[0] = (self.pix_po... |
def time_frame_ohlc_data(self, pair, time_frame):
time_frame_data = self.kraken.get_time_frame_data(pair, time_frame)
time_frame_data = time_frame_data['ohlc'][::-1]
now = datetime.now()
time_frame_data.loc[pd.to_datetime(now.strftime("%Y-%m-%d %H:%M:%S"))] = [int(time.time()),0,0,0,floa... | This function processes trading signals for specified time frames. It checks enabled time frames matching a command-line argument, fetches OHLC data, generates buy/sell signals via a strategy, displays signals, updates trade status, evaluates signals, checks open orders/positions, and triggers trades if enabled. The co... | def time_frame_signals(self, pair, time_frames):
for time_frame in time_frames:
if time_frame['enabled'] and (int(time_frame['tf']) == int(sys.argv[2])):
u.show('timeframe', time_frame['label'], 'above')
if self.trading_enabled:
self.trade_data = s... |
def cancel_expired_order(self):
open_orders = self.trade.get_orders()
if self.account_data['open_orders'].empty:
for open_order in open_orders:
self.trade.close_order(open_order['txid'])
for index, row in self.account_data['open_orders'].iterrows():
if (in... | The code's main task is to update trading status, cancel expired orders, manage account data, and process trading signals for a specific cryptocurrency pair. It checks if trading is enabled, retrieves pair data, generates signals across time frames, and updates realized trading status, while handling order management a... | def go(self):
print(datetime.now())
u.show('trading_enabled', self.trading_enabled)
u.show_object('account_balance', self.account_data['account_balance'])
self.cancel_expired_order()
if self.trading_enabled:
self.cancel_expired_order()
self.save_trades(sel... |
def CurrentChar(self) -> chr:
return self.line[self.mark]
def Seek(self) -> chr:
self.mark += 1
return self.line[self.mark - 1]
def ScanNum(self):
token = Token()
while not self.EOL() and self.CurrentChar().isdigit():
token.lexeme += self.Seek()
token... | This method identifies and returns the next token from the input by checking the current character's type: skipping whitespace, scanning numbers, dots, identifiers/keywords, or operators accordingly. | def GetToken(self):
if self.CurrentChar().isspace():
return self.Seek()
elif self.CurrentChar().isdigit():
return self.ScanNum()
elif self.CurrentChar() == DOT:
return self.ScanDot()
elif self.CurrentChar().isalpha():
return self.ScanIdOrK... |
def forward(self, duty, n):
"""
move forward: action = 0
:param duty: the duty to put on the servo
:param n: number of seconds
:return: outcome
"""
# set motor control
GPIO.output(self.GPIO_RIGHT_FORWARD, True)
GPIO.output(self.GPIO_RIGHT_BACKWARD... | This code defines a '_test' method that processes user input commands to control a robot's movement. It continuously reads commands, splits them into direction (f/b/cw/ccw) and steps (n), then calls corresponding methods with fixed duty (100) and steps. The loop exits on KeyboardInterrupt, setting 'testing' to False an... | def _test(self):
try:
while True:
cmd = input()
cmd = cmd.split(" ")
dir = cmd[0]
n = int(cmd[1])
duty = 100
if dir == "f":
self.forward(duty, n)
elif dir == "b":
... |
def get_ultrasound(self):
return self._ultrasound
def stop(self, duty, n):
GPIO.output(self.GPIO_RIGHT_FORWARD, False)
GPIO.output(self.GPIO_RIGHT_BACKWARD, False)
GPIO.output(self.GPIO_LEFT_FORWARD, False)
GPIO.output(self.GPIO_LEFT_BACKWARD, False)
# time.sleep(n)
... | The code implements an autonomous obstacle avoidance system. It continuously checks ultrasound sensor data; if an obstacle is within 20 units, the robot stops, reverses, and turns left to avoid it. Otherwise, it moves forward. This loop enables real-time navigation and collision avoidance for a robotic system. | def _autonomous_simple(self):
while True:
print(self.get_ultrasound())
if self.get_ultrasound() <= 20:
self.stop(1)
self.backward(100, 1)
self.turn_ccw(100, 0.5)
else:
self.forward(100, 0.1) |
def causal_layer(self, X, ema=None):
fw = self.filter_length
r = self.n_channels
with tf.name_scope('causal_layer'):
W = get_weight_variable('W', shape=(1, fw, 1, r), ema=ema) # filter_height, filter_width, in_channels, out_channels
Y = conv(X, W)
if self.... | The code processes input audio `X` through a series of causal and dilated FFT layers (with varying dilation rates) to model temporal dependencies, then applies post-processing to generate a clean audio prediction. The `ema` parameter suggests the use of exponential moving average for training stability, while `is_train... | def inference(self, X, is_training, ema):
with tf.variable_scope('FFTNet', reuse=True):
#X ->Causal_layer -> FFT_layer0-> ... FFT_layerN
X = self.causal_layer(X, ema)
# FFT Layers
for i, dilation in enumerate(self.dilations):
X= self... |
def detect_obstacles(self):
""" function to detect obstacles from RGB and depth image """
config_space = self.depth_img.data
discrete_graph = self.voronoi_diagram(config_space)
path = self.A_star(discrete_graph)
return path
def path_to_traj(self, path):
""" function to... | The main task of the code is to plan a trajectory for obstacle avoidance by first detecting obstacles, converting the detected path into a trajectory, updating the trajectory's timestamp, and then translating the trajectory into joint commands for execution. This ensures the robot navigates around obstacles smoothly an... | def avoid_obstacles(self):
""" function to plan trajectory for avoiding obstacles """
path = self.detect_obstacles()
traj = self.path_to_traj(path)
traj.header.stamp = rospy.Time.now()
self.traj_to_joints(traj) |
def tryMatch(self,s):
self.skipWhitespace()
if self.input[self.pos:self.pos+len(s)] == s:
self.skipWhitespace()
return True
self.skipWhitespace()
return False
def value_braces(self):
braces = ["{"]
self.match("{")
start = self.pos
w... | This function parses and returns a single value from the input based on its format: either enclosed in braces, quoted, a predefined key in `self.strings`, or a numeric key. It raises an exception if no valid value is found. | def single_value(self):
start = self.pos
if self.tryMatch('{'):
return self.value_braces()
elif self.tryMatch('"'):
return self.value_quotes()
else:
k = self.key()
if k in self.strings:
return self.strings[k]
eli... |
def single_value(self):
start = self.pos
if self.tryMatch('{'):
return self.value_braces()
elif self.tryMatch('"'):
return self.value_quotes()
else:
k = self.key()
if k in self.strings:
return self.strings[k]
eli... | This method collects values by initially retrieving a single value, then repeatedly checking for and appending additional values each time a '#' character is matched, finally returning the concatenated result. | def value(self):
values = self.single_value()
while self.tryMatch('#'):
self.match('#')
values+=self.single_value()
return values |
def key(self):
self.skipWhitespace()
start = self.pos
while True:
if self.pos == len(self.input):
raise Exception("Runaway key")
if re.match("[a-zA-z0-9_:\\./-]", self.input[self.pos]) is not None:
self.pos += 1
else:
... | This function parses a key-value pair from input. It retrieves a key using `self.key()`, checks for an equals sign (`=`), and if found, retrieves the corresponding value with `self.value()`, returning them as a list. If the equals sign is missing, it raises an exception indicating the syntax error. | def key_value(self):
k = self.key()
if self.tryMatch('='):
self.match('=')
v = self.value()
return [k,v]
else:
raise Exception("... = value expected, equals sign missing:"+self.input[self.pos]) |
def die(msg):
print("Error:", msg, """Use:
python mapreduce.py [map OR reduce] [path_to_script] [source_file] [destination_file]""",
sep="\n", file=sys.stderr)
sys.exit(1)
def fmap(script, src, dst):
inp = ""
try:
with open(src, encoding="utf8", newline="\n") as f:
ind = 1
... | The main task of the code is to validate command-line arguments for a map-reduce framework. It checks for exactly 5 arguments, identifies whether the operation is "map" or "reduce", and delegates execution to `fmap` or `freduce` functions with the remaining parameters. If arguments are invalid or the operation is unrec... | def main():
if len(sys.argv) != 5:
die("Incorrect number of arguments")
if sys.argv[1] == "map":
fmap(*sys.argv[2:])
elif sys.argv[1] == "reduce":
freduce(*sys.argv[2:])
else:
die("Option not recognized") |
def build_fallback(fallback_filename):
with open(fallback_filename) as f:
fallback = [l.strip() for l in f.readlines()]
return fallback
def build_family_cmap(fontlist):
family_cmap = defaultdict(set)
for font in fontlist:
family_cmap[font.family].update(font.cmap)
return dict(family_... | The code generates multiple CSS files for the Noto font family by iterating through configurations of variable fonts, minimal subsets, and WOFF file inclusion. It constructs filenames, prunes font lists, builds CSS content, writes files, and minifies them using 'csso', creating variants like 'noto-sans.css' and 'noto-s... | def build_css_file(fontlist, style="sans", script=""):
family_name = "Noto " + style.capitalize()
suffix = f"-{style}"
if script:
suffix += f"-{script}"
fallback = build_fallback(f"fallback{suffix}.txt")
family_cmap = build_family_cmap(fontlist)
for variable in [True, False]:
fo... |
def mean(vals):
average = sum(vals) / len(vals)
return average
def variance(vals):
avg = mean(vals)
total = 0
for i in vals:
x = (i - avg)**2
total += x
calc = total / len(vals)
return calc
def standard_deviation(vals):
avg = mean(vals)
total = 0
for i in vals:
... | The code calculates and returns summary statistics (mean, variance, standard deviation, standard error) of a dataset with two decimal places. | def summary(vals):
pass
avg = mean(vals)
var = variance(vals)
sd = standard_deviation(vals)
se = standard_error(vals)
return f'Summary Statistics:\nThe mean of your data is {avg:.2f}\nThe variance of your data is {var:.2f}\nThe standard deviation of your data is {sd:.2f}\nThe standard error of y... |
def set_error(self, error_num, random_pos=True):
self.error_num = error_num
l = [i for i in range(self.cir.size())]
if random_pos == False:
self.error_pos = NOISE_POS
else:
self.error_pos = random.sample(l, error_num)
self.error_pos.sort()
def print_info(s... | The main task of the code is to perform repeated tensor network calculations with configurable error parameters, accumulating results from multiple enumerated configurations. It constructs and contracts tensor networks using input/output operators, computes their product, and writes the results along with runtime to a ... | def enumurate_io(
self, output, error_num=0, random_pos=True, ps1=[], ps2=[], enum=1
):
self.set_error(error_num, random_pos)
self.print_info(output)
if len(ps1) > 0 or len(ps2) > 0:
self.set_io(ps1, ps2)
try:
t_start = time.time()
res = 0
... |
def set_error(self, error_num, random_pos=True):
self.error_num = error_num
l = [i for i in range(self.cir.size())]
if random_pos == False:
self.error_pos = NOISE_POS
else:
self.error_pos = random.sample(l, error_num)
self.error_pos.sort()
def print_info(s... | The main task of the code is to perform error enumeration in a tensor network calculation by iterating over specified error configurations, constructing and contracting tensor networks, computing tensor products, and accumulating results. It logs the computation time and final result to an output file, handling excepti... | def enumurate_dm(self, output, error_num=0, random_pos=True, ps1=[], enum=1):
self.set_error(error_num, random_pos)
self.print_info(output)
if len(ps1) > 0:
self.set_io(ps1, [])
try:
t_start = time.time()
res = 0
for e in range(enum + 1):
... |
def set_error(self, error_num, random_pos=True):
self.error_num = error_num
l = [i for i in range(self.cir.size())]
if random_pos == False:
self.error_pos = NOISE_POS
else:
self.error_pos = random.sample(l, error_num)
self.error_pos.sort()
def print_info(s... | This function performs a fidelity test by enumerating tensor network contractions, handling errors, and computing a fidelity measure. It iterates through configurations, constructs tensor networks, contracts them, and aggregates results. The output includes runtime and computed fidelity values, saved to a file. Excepti... | def enumurate_fidility_test(
self, output, error_num=0, random_pos=True, ps1=[], enum=1
):
self.set_error(error_num, random_pos)
self.print_info(output)
if len(ps1) > 0:
self.set_io(ps1, [])
try:
t_start = time.time()
res = 0
fo... |
def set_error(self, error_num, random_pos=True):
self.error_num = error_num
l = [i for i in range(self.cir.size())]
if random_pos == False:
self.error_pos = NOISE_POS
else:
self.error_pos = random.sample(l, error_num)
self.error_pos.sort()
def print_info(s... | This function performs tensor network contraction tests, measures execution time, and logs results/errors to a file. It initializes errors, sets I/O parameters, constructs a tensor network, executes contraction, records runtime and output, and handles exceptions by writing error messages. | def io_test(self, output, error_num=0, random_pos=True, ps1=[], ps2=[]):
self.set_error(error_num, random_pos)
self.print_info(output)
if len(ps1) > 0 or len(ps2) > 0:
self.set_io(ps1, ps2)
try:
self.construct_tn(self.ps1, self.ps2)
t_start = time.time... |
def set_error(self, error_num, random_pos=True):
self.error_num = error_num
l = [i for i in range(self.cir.size())]
if random_pos == False:
self.error_pos = NOISE_POS
else:
self.error_pos = random.sample(l, error_num)
self.error_pos.sort()
def print_info(s... | The main task of the code is to simulate a quantum system's density matrix by constructing and contracting a tensor network, handling errors, and logging the computation time and results to a file. It sets errors, constructs the tensor network, performs contraction, records runtime, and writes outcomes, while capturing... | def simu_dm(self, output, error_num=0, random_pos=True, ps1=[], ps2=[]):
self.set_error(error_num, random_pos)
self.print_info(output)
if len(ps1) > 0:
self.set_io(ps1, [])
try:
qubits = self.construct_tn_dm(self.ps1)
t_start = time.time()
... |
def set_error(self, error_num, random_pos=True):
self.error_num = error_num
l = [i for i in range(self.cir.size())]
if random_pos == False:
self.error_pos = NOISE_POS
else:
self.error_pos = random.sample(l, error_num)
self.error_pos.sort()
def print_info(s... | The main task of the code is to perform a fidelity test by constructing and contracting a tensor network (TN) with specified error parameters, measuring the computation time, and saving the results (runtime and fidelity value) to an output file. It handles errors, initializes TN structures, executes contraction using g... | def fidelity_test(self, output, error_num=0, random_pos=True, ps1=[]):
self.set_error(error_num, random_pos)
self.print_info(output)
if len(ps1) > 0:
self.set_io(ps1, [])
try:
if error_num == 0:
self.construct_tn_single_inv(self.ps1)
el... |
def __create_module(self, msg, send_wasm=False):
"""Handle create message."""
if send_wasm:
# If here, send the WASM file over to the runtime.
module = self._get_object(
msg.get('data', 'details', 'uuid'), model=Module)
if module.filetype != FileType.W... | This code handles control messages by routing them to appropriate methods based on their type and action. It processes 'arts_resp' and 'runtime_resp' messages with specific logic, such as sending files or acknowledging module creation. For 'arts_req' messages, it triggers actions like creating, deleting, or handling mo... | def control(self, msg):
"""Handle per-module control message."""
# arts_resp -> is a message we sent, should be ignored
msg_type = msg.get('type')
if msg_type == 'arts_resp':
return None
print("\n[Control] {}".format(msg.payload))
if msg_type == 'runtime_res... |
def pdebug(self, *args):
if self.debug:
print('CACHE', *args, file=stderr, flush=True)
def _set(self, key, data, info={}, chunk_size=100*1024):
if key == '':
raise Exception('Empty key value')
fname = self.filename(key)
# possible race condition, but that's fine... | The main task of the code is to store data under a specified key, handling potential errors by attempting to delete the key if an exception occurs during storage. It logs the operation, iterates through the result of an internal `_set` method, retrieves the stored data via `lookup`, and re-raises exceptions after clean... | def set(self, key, data, info={}):
self.pdebug('set: %s' % key)
try:
for chunk in self._set(key, data, info):
pass
return self.lookup(key)
except Exception as e:
try:
self.delete(key)
except:
pass
... |
def get_setting(key, default=None):
return config.get('settings', {}).get(key, default)
def get_info(url, uri=None, download=True):
print(f'get info: {url}', flush=True)
i=None
# if this is a file URL simply load the image
if url.startswith('file:'):
i = Image.open(url[7:])
try:
... | The main task of the code is to save an image's metadata and potentially its full-size version to a cache, using specified settings. It generates a cache key, retrieves image info (or downloads the image if needed), handles JPEG2000 tiling avoidance, and stores image dimensions/format in the cache. The function returns... | def save(url, uri=None, info=None):
uri = uri or url
key = create_key(uri, 'full', 'max', '0', 'default', get_setting('cache_format', 'jpg'))
info = info or get_info(url, uri, download=False)
if not info:
i = get_image(uri, url)
info = { 'width': i.width, 'height': i.height, 'format':... |
def coord2radial(self, edge_index, coord):
row, col = edge_index
coord_diff = coord[row] - coord[col]
# print('coorddiff',coord_diff)
radial = paddle.sum(coord_diff**2, 1).unsqueeze(1)
# print('radial',radial)
if self.normalize:
norm = paddle.sqrt(radial).det... | This code performs a forward pass in a graph neural network, updating node features and coordinates by computing edge features from radial distances and attributes, then refining node representations and spatial coordinates through edge and node models. | def forward(self, h, edge_index, coord, edge_attr=None, node_attr=None):
row, col = edge_index
# print('e',edge_index)
# print('r',row)
# print('c',col)
# print('jjjj',coord)
radial, coord_diff = self.coord2radial(edge_index, coord)
# print('r',radial)
edg... |
def coord2radial(self, edge_index, coord):
row, col = edge_index
coord_diff = coord[row] - coord[col]
# print('coorddiff',coord_diff)
radial = paddle.sum(coord_diff**2, 1).unsqueeze(1)
# print('radial',radial)
# if self.normalize:
# norm = paddle.sqrt(radial)... | This code performs a forward pass in a graph neural network, updating node features (h), vector representations (vec), and 3D coordinates (coord) through message passing. It computes edge-wise interactions (M_ij), applies attention mechanisms with query/key/value projections, aggregates neighbor information, and derive... | def forward(self, x, vec, edge_index, c_ij, f_ij, d_ij,coord,ha,alledge):
# print("x",x.shape)
# print("vec",vec.shape)
# print("r_ij",r_ij.shape)
# R = self.construct_3d_basis(xxx[0], xxx[1], xxx[2]) # (N, L, 3, 3)
# qq = paddle.matmul(R, xxx.T)
# # print(qq)
# ... |
def parseArgs():
"""Parse command line arguments and return args dict"""
parser = argparse.ArgumentParser(description='Summarize annovar annotated vcfs')
parser.add_argument('-I', '--input', type=str, nargs=1, dest='input_file')
parser.add_argument('-d', '--directory', type=str, nargs=1, dest='directory... | The main task of the code is to process VCF files by generating gene-based and coordinate-based summaries. It reads input VCFs, creates gene-level and position-level summary tables, and exports them as CSV files named with "GENE" and "COORDINATE" suffixes, respectively. The output files contain structured data for down... | def main():
args = parseArgs()
vcfs = read_input_file(args['input_file'], args['directory'])
print('Building gene based summary file')
gene_summary = summarize_by_gene(vcfs)
gene_summary_filename = '{}_{}.csv'.format(args['output_file'],
'GENE')
... |
def parseArgs():
args = createParser()
if args.directory is None:
directory = os.getcwd()
else:
directory = ''.join(args.directory)
if os.path.isdir(directory) is False:
raise ValueError("{} does not exist!".format(directory))
if args.inputFile is None:
inputFile =... | The main task of the code is to parse command-line arguments, read input files or directories, generate samples, and launch processing jobs. It handles input files or directory paths, extracts samples using `getSamples`, and initiates parallel jobs via `launchJobs`, enabling batch processing or task execution based on ... | def main():
args = parseArgs()
if args['inputFile'] is not None:
files = read_input_file(args['inputFile'])
else:
files = None
samples = getSamples(args['directory'], files)
launchJobs(samples, args['directory']) |
def parseArgs():
args = createParser()
if args.directory is None:
directory = os.getcwd()
else:
directory = ''.join(args.directory)
if os.path.isdir(directory) is False:
raise ValueError("{} directory does not exist!")
if args.inputFile is None:
inputFile = None
... | The main task of the code is to process genomic data by parsing command-line arguments, reading input files or directory structures, extracting read group information from a predefined file, retrieving sample data, and launching parallel processing jobs using the parsed data and read group metadata for downstream analy... | def main():
args = parseArgs()
if args['inputFile'] is not None:
files = read_input_file(args['inputFile'])
else:
files = None
removedRGDirectory = '/scratch/groups/carilee/forTomas/CollagenFQData/alldata/rg_removed_fqs'
infoFile = os.path.join(removedRGDirectory, 'RG_info.txt')
... |
def parseArgs():
args = createParser()
if args.directory is None:
directory = os.getcwd()
else:
directory = ''.join(args.directory)
if os.path.isdir(directory) is False:
raise ValueError("{} directory does not exist!")
if args.inputFile is None:
inputFile = None
... | The main task of the code is to parse command-line arguments, read input files or directories, generate samples from the data, and launch processing jobs based on the samples. It handles both file-based and directory-based input, prepares sample data, and initiates job execution in a structured workflow. | def main():
args = parseArgs()
if args['inputFile'] is not None:
files = read_input_file(args['inputFile'])
else:
files = None
samples = getSamples(args['directory'], files)
#print(samples)
#print(len(samples))
launchJobs(samples, args['directory']) |
def setup_env():
"""Sets up environment for training or testing."""
if dist.is_master_proc():
# Ensure that the output dir exists
os.makedirs(cfg.OUT_DIR, exist_ok=True)
# Save the config
config.dump_cfg()
# Setup logging
logging.setup_logging()
# Log the config as bo... | The main task of the code is to train a machine learning model by setting up the environment, initializing the model and optimizer, loading pre-trained weights or checkpoints, iterating over training epochs with data loaders, performing training and evaluation phases, computing batch normalization statistics, and perio... | def train_model():
"""Trains the model."""
# Setup training/testing environment
setup_env()
# Construct the model, loss_fun, and optimizer
model = setup_model()
loss_fun = builders.build_loss_fun().cuda()
optimizer = optim.construct_optimizer(model)
# Load checkpoint or initial weights
... |
def show_elapsed_time():
global prev_time
cur_time = time.process_time()
diff = cur_time - prev_time
prev_time = cur_time
print(f"[{cur_time}] took: {diff} sec.")
def controlled_input_read():
read_input_thread = Thread(target=read_input, daemon=True, )
read_input_thread.start()
read_inpu... | The main task of the code is to measure and display time intervals during execution, read input data, compute two solutions (A and B) using specific functions, and print the results. The code structure includes timing checks before and after processing steps, though some debug prints are commented out. The core operati... | def do_main():
show_elapsed_time()
# print("read input")
controlled_input_read()
show_elapsed_time()
# print("len input_data:", len(input_data))
# print("input_data:\n", pprint.pformat(input_data))
result_a = find_solution_a()
print(f"result_a: {result_a}")
show_elapsed_time()
... |
def is_valid(board, ans, row, col):
"""
This function checks the validity of a digit in certain square according to
rules of Sudoku
:param: board: 2D array of objects Square
ans: digit that is being places in that position
row: row where the digit is located
... | This recursive function implements a backtracking algorithm to solve a Sudoku board by testing digits 1-9 in empty cells. It checks validity via is_valid(), updates the UI with Pygame when placing values, and proceeds to the next cell. If a solution path fails, it backtracks by resetting the cell. Returns True if the b... | def solve(board,row,col, game_window):
"""
This recursive function tries to fit digits 1 to 9 into the square
and see if it is valid or not. This functions helps implement
backtracking algorithm that allows computer to solve the board for
the user
:param: board: 2D array of object... |
def getChat(filename):
'''
Takes a filename and a type, where type is either 'json' or 'csv'
'''
# fetches data and converts to pd dataframe
if isJsonFile(filename):
return spawnDF(filename)
elif isCsvFile(filename):
chat = pd.read_csv(filename)
chat['time'] = pd.to_date... | The main task of the code is to generate multiple visualizations from input data files (JSON or CSV), creating bar and line graphs to analyze metrics like messages per person, conversations started, words sent, response time, and sentiment over time. The function processes the data, extracts key statistics, and generat... | def createPlots(filename):
'''
Fetches visualizations of data.
'''
# converts data into pd dataframe
chat = getChat(filename)
file = None
if isJsonFile:
file = filename[0:len(filename) - 5]
elif isCsvFile:
file = filename[0:len(filename) - 4]
# plots messages per pe... |
def get_playlist(self, spotify_id, playlist_id):
req_url = common.SPOTIFY_USER_PLAYLIST_ADDRESS(spotify_id, playlist_id)
req_headers = self.create_auth_header()
res = requests.get(req_url, headers=req_headers)
if res.status_code == 200:
return res.json()
else:
... | The function copies tracks from the user's Discover Weekly playlist to an archive playlist, creating the archive playlist if it doesn't exist. It retrieves the archive playlist ID from user data, creates a new one if necessary, fetches Discover Weekly track URIs, and copies them to the archive playlist using API reques... | def copy_discoverweekly_to_archive(self):
logging.info("finding/creating archive playlist")
archive_playlist_id = self.user_data[common.ARCHIVE_PLAYLIST_ID_DB_KEY]
archive_playlist = None
if archive_playlist_id != None:
archive_playlist = self.get_playlist(
se... |
def detect_edge_cnn(img, model, device):
image = cv2.resize(img, (MODEL_INPUT_SIZE, int(MODEL_INPUT_SIZE * img.shape[0] / img.shape[1])),
interpolation=cv2.INTER_LINEAR)
tf = transforms.Compose(
[
transforms.ToTensor(),
transforms.Normalize([0.196, 0.179, 0... | The main task of the code is to perform image rectification by detecting edges using a trained CNN model or a fallback method, applying a four-point perspective transformation to correct the image's perspective, enhancing contrast, and saving the processed result to the specified output path. | def inference(input_path, output_path, trained_model, device):
image_format = [".jpg", ".jpeg", ".bmp", ".png"]
if os.path.isfile(input_path):
if os.path.splitext(input_path)[1] not in image_format:
print("Parameters Error: invalid input or output.")
sys.exit()
else:
... |
def detect_edge_cnn(img, model, device):
image = cv2.resize(img, (MODEL_INPUT_SIZE, int(MODEL_INPUT_SIZE * img.shape[0] / img.shape[1])),
interpolation=cv2.INTER_LINEAR)
tf = transforms.Compose(
[
transforms.ToTensor(),
transforms.Normalize([0.196, 0.179, 0... | This function processes images in a directory to rectify document-like content by detecting edges using a trained CNN model or a fallback method, applying perspective correction, and saving outputs. It handles multiple image formats, skips invalid files, and tracks successful rectifications. | def inference_all(input_dir, output_dir, trained_model, device):
count = 0
image_format = [".jpg", ".jpeg", ".bmp", ".png"]
file_list = os.listdir(input_dir)
file_list.sort()
for i in range(0, len(file_list)):
# print("[{}/{}] ".format(i+1, len(file_list)), end='')
in_path = os.path.... |
def fetch_from_origin(self, article: str) -> bytes:
with urlopen(f"{self.origin_url}/{article}") as response:
return response.read()
def add(self, article: str, article_raw_bytes: bytes, views: int) -> LookupInfo:
"""
Attempts to add a new article to the cache.
:param articl... | The function `get_helper` manages article retrieval and caching. It processes a URL, checks encoding, and verifies existence in a cache. If the article is not cached, it fetches it from the origin, compresses it, and caches it optimistically. If cached on disk or in memory, it retrieves the compressed article. It retur... | def get_helper(self, article: str) -> (bool, bytes):
# Strip away leading slash from URLs
if article[0] == "/":
article = article[1:]
if not utils.is_url_encoded(article):
article = quote(article)
if article not in self.articles:
return False, None
... |
def stat_sample(lam,mu,num,tol):
values = range(tol)
prob = [0]*tol
prob[0] = 1 - lam/mu
prob[1] = lam*(mu - lam)/((mu**2)*(1 - lam))
s = prob[0] + prob[1]
for i in range(2,tol):
prob[i] = prob[1]*(lam*(1-mu)/(mu*(1 - lam)))**(i-1)
s = s + prob[i]
for i in range(tol) :
prob[i] = prob[i]/s
#print values
#... | The code implements an epsilon-greedy algorithm with UCB (Upper Confidence Bound) for multi-armed bandit problems, where exploration schedules and optimal matching are used to balance exploration and exploitation. It initializes parameters, computes initial values, and iteratively updates reward estimates (UCB) and act... | def ep_greedy_wopt(mu,u,K,l,t):
np.random.seed()
random.seed()
q = [0]*u
q_o = [0]*u
N = np.zeros([u,K])
ucb_avg = np.zeros([u,K])
N_o = np.zeros([u,K])
ucb_avg_o = np.zeros([u,K])
for i in range(u):
mui = np.amax(mu[i,:])
lam = l[i]
q[i] = stat_sample(lam,mui,1,200)
q_o[i] = q[i]
queue = np.empty((0,... |
def __actions(self):
actions = dict();
actions[self.STAY] = (0, 0);
actions[self.MOVE_LEFT] = (0,-1);
actions[self.MOVE_RIGHT] = (0, 1);
actions[self.MOVE_UP] = (-1,0);
actions[self.MOVE_DOWN] = (1,0);
return actions;
def __states(self):
states ... | The code initializes a Maze environment for reinforcement learning, setting up actions, states, transition probabilities, and rewards. It processes input parameters like the maze structure, reward weights, random reward flags, and minotaur movement limits. The constructor defines the environment's state-space, action-s... | def __init__(self, maze, weights=None, random_rewards=False, minotaur_moves=4):
""" Constructor of the environment Maze.
"""
self.maze = maze;
self.min_moves = minotaur_moves;
self.actions = self.__actions();
self.state... |
def strIsInt(givenStr):
try:
int(givenStr)
return True
except ValueError:
return False
def GetFilledGrid():
result = -1
while result == -1:
grid = InitGrid()
result = FillGrid(grid)
return grid
def RemoveNums(grid, remaining=5):
newGrid = copy.deepcopy(gr... | The main task of the code is to generate puzzle and solution pages for a Sudoku-like grid. It uses command-line arguments to determine the number of pages and remaining numbers per puzzle. For each page, it creates two unsolved puzzles from solved grids, generates both puzzle and solution pages using MakePic, and print... | def main():
print("Starting page generation\n")
numPages = 1
if len(sys.argv) > 1 and strIsInt(sys.argv[1]):
numPages = int(sys.argv[1])
remaining = 40
if len(sys.argv) > 2 and strIsInt(sys.argv[2]) and int(sys.argv[2]) <= 81:
remaining = int(sys.argv[2])
for _ in range(numPag... |
def _open_resource(self, resource: str):
self.browser = webdriver.Chrome(options=self._set_chrome_options())
wait = WebDriverWait(self.browser, 10)
self.browser.get(self.base_url)
search_bar = self.browser.find_element(
"xpath",
"/html/body/div[3]/div/div/sectio... | The code scrapes data from a specified resource by opening it, extracting information based on predefined data formats, and returning the results in a structured dictionary. It initializes an empty data container, iterates through defined data types to collect values, and ensures the browser is closed afterward. | def scrape(self, resource: str) -> dict:
self._open_resource(resource)
data = {}
for data_type in self.data_format:
data[data_type["name"]] = self._get_data(data_type)
self._close_browser()
return data |
def get_best_split(self, dataset, num_samples, num_features):
best_split={"feature_index":None,"threshold":None,"dataset_left":None,"info_gain":0}
max_info_gain=-float("inf")
for featureindex in range(num_features):
feature_values=dataset[:,featureindex] #verticle row of particular... | This function recursively builds a decision tree by splitting the dataset based on information gain. It checks if the current node can split further using minimum samples and maximum depth constraints. If valid, it finds the optimal feature-threshold split, recursively constructs left and right subtrees, and returns a ... | def build_tree(self,dataset,curr_depth=0):
x,y=dataset[:,:-1],dataset[:,-1]
num_samples,num_features=np.shape(data)
num_features-=1#150 samples and 4 features
if num_samples >= self.min_sample_split and curr_depth <= self.max_depth:
best_split=self.get_best_split(dataset,num_... |
def evaluate_algorithm(dataset, algorithm, n_folds, *args):
folds = cross_validation_split(dataset, n_folds)
# print(folds)
scores = list()
for fold in folds:
train_set = list(folds)
# print(train_set)
# train_set.remove(fold)
train_set = sum(train_set, [])
test_s... | The code evaluates a Naive Bayes classifier's accuracy on the Iris dataset using 5-fold cross-validation, then predicts the class of a new sample defined by input features `x1-x4`. It returns the average accuracy (as a percentage) and the predicted Iris species (setosa, versicolor, or virginica). The task combines mode... | def solve_bynb(x1,x2,x3,x4):
n_folds = 5
scores = evaluate_algorithm(dataset, naive_bayes, n_folds)
# print('Scores: %s' % scores)
acc=(sum(scores)/float(len(scores)))*(10**-2)
summaries = summarize_by_class(dataset)
row = [x1,x2,x3,x4]
pred = predict(summaries,row)
if(pred==0):
... |
def data_getDay(day):
import csv
#print("loading day ",day)
path = "data/2019/"
filename = "dag_"+str(day)+".csv"
data = []
with open(path+filename) as csvDataFile:
csvReader = csv.reader(csvDataFile)
for row in csvReader:
data.append(row[1])
... | The code simulates a year of energy consumption and production, using a battery to store excess energy. It calculates the total electricity purchased and sold, considering battery capacity constraints. The function returns these totals in kWh and generates visualizations of daily/annual energy flows, battery levels, an... | def bereken(verbruik_m, batterijCap, plots):
plt.close('all')
dt = 1/4 # 15 minutes
tijd = np.arange(0, 24, dt)
batterijCap = batterijCap*1000 # maximale cappaciteit van de batterij [Wh], tesla heeft 6.4 en 13.5 kWh
batterijCap = batterijCap/dt # cappaciteit in Wkwartier
batterij = 0 # star... |
def str2Float(string):
try:
return float(string)
except:
print("Error, ",string," is not a float")
return 0
def strArray2FloatArray(stringArray):
floatArray = []
for element in stringArray:
floatArray.append(str2Float(element))
return floatArray
def bereken(verbruik_... | The main task of the code is to calculate energy consumption, production, and financial outcomes (kWh and euros) for a solar panel system based on user inputs from a UI. It processes orientation efficiency, monthly/daily energy data, battery capacity, and plot options, then computes total energy bought/sold, net result... | def bereken_uit_UI(ui):
print("ik bereken met:")
print(ui.lineEdit_verbruikJan.text())
paneelRichting = ui.comboBox_orientatie.currentText()
if paneelRichting == "Zuid":
orientatieRendement = 1
elif paneelRichting == "Noord":
orientatieRendement = 0.5
elif paneelRichting == ... |
def getListOfFiles(dirName, subset, train):
# create a list of file and sub directories
# names in the given directory
listOfFile = os.listdir(dirName)
allFiles = list()
# Iterate over all the entries
for entry in listOfFile:
if entry == 'canneal':
print(entry)
if di... | The main task of the code is to process and organize data files into training and test sets by creating directories, generating CSV files with specific configurations, and writing best configurations. It samples subsets, retrieves file lists, constructs file paths, and executes data processing functions to prepare stru... | def main():
dirName = '../data'
print("Starting the program")
# Get the list of all files in directory tree at given path
subset = sample([i for i in range(5)], 4)
listOfTrainFiles = getListOfFiles(dirName, [0], True)
listOfTestFiles = getListOfFiles(dirName, [0], False)
run_number = str(r... |
def _theAreOnWay(self, requestedFloor, direction): #[OK]
"""Function to check if one or more elevators are on the same way.
It creates a list of elevator on the same way, then returns the list.
Args:
requestedFloor (int): floor requested for the user
direction (str): "up" or "down"
Returns:
... | The main task of the code is to select the best elevator for a given floor request and direction by checking if an elevator is already on its way, idle, or not on its way, and returning the appropriate elevator object. | def _choiceElevator(self, requestedFloor, direction): #[OK]
"""Function to choice the best elevator
It calling others functions and returns the best elevator
Args:
requestedFloor (int): floor requested for the user
direction (str): "up" or "down"
Returns:
Elevator: The best elevator
"""
... |
def generate_random(self, pass_length):
"""
Generates a random list of chars from types available in usable_chars.
Args:
pass_length (int): length of random passwords string to be generated.
"""
return [secrets.choice(self.usable_chars[self.usable_chars.index(secrets.choice(self.usable_chars))]) for ... | The function generates secure passwords based on user-defined settings, creating multiple passwords with options to remove duplicates, exclude English/excluded words, and enforce character proportions. It checks for password breaches recursively and appends valid passwords to `self.passwords` if they pass security chec... | def generate_password(self, pass_number=PSWRD_NO, remove_repeating=False, remove_english=False, check_proportions=False,
fixed_len=FIXED_LEN):
"""
The function will generate a password string from the set of usable characters described by the user in settings.py.
Generated passwords are appended to self.p... |
def get_words(self, library_name=None):
"""
Extracts words from nltk resources or custom text files.
Args:
library (str): Name of the nltk resources or custom text file to be used.
"""
library_name = library_name or self.library_name
local_file_name = library_name + '.txt'
local_model_name = f"{MODEL... | The code generates random sentences using NLTK's trigram model, adhering to specified length constraints. It removes special characters, adjusts whitespace, and recursively regenerates if the output is too short or truncates if too long. It also checks if the generated "password" is breached via an external API, regene... | def form_sentece(self):
"""
Method for generating random sentences, taking into account params of this class instance.
"""
print(f'Generating random text with length {self.min_sentence_length}.')
today = datetime.now()
self.sent_generator = nltk.Text(self.get_words())
# Existing model is loaded instead... |
def generate_random(self, pass_length):
"""
Generates a random list of chars from types available in usable_chars.
Args:
pass_length (int): length of random passwords string to be generated.
"""
return [secrets.choice(self.usable_chars[self.usable_chars.index(secrets.choice(self.usable_chars))]) for ... | The main task of the code is to generate secure, human-like passwords adhering to common security rules (e.g., inclusion of multiple character types, no repeated sequences, exclusion of sensitive words) while ensuring they are not present in known data breach databases. It creates passwords resistant to cracking method... | def generate_human_password(self, pass_number=PSWRD_NO, fixed_len=FIXED_LEN):
"""
The function will generate a password conforming to most common rules recommended for passwords generation.
The idea is to generate passwords which are resistant to breaking attempts where the malicious actor presumes
that the p... |
def is_crawl_allowed(self, url, base_url):
# scheme, netloc_host, path, params, query, fragment = urlparse(url)
print("In is_crawl_allowed")
time_start = time.time()
robot_url = base_url + 'robots.txt'
try:
# if robot_url not in self.robot_dict.keys():
rob... | The main task of the code is to crawl web pages by extracting links from URLs, respecting robots.txt rules, avoiding blocked domains and file types, parsing content, and storing documents in batches. It manages frontiers for URL prioritization, enforces crawling delays, and periodically writes crawled data to files whi... | def crawl_seeds(self):
current_domain = ''
file_num_count = self.file_no + 1
doc_text = ''
while self.doc_count < COUNT_DOC: # or not self.frontier.empty():
delay = False
if self.frontier.empty():
self.frontier = self.aux_ftier
se... |
def load_file(path):
with open(path, "rb") as file:
return dill.load(file)
def get_file_names(file_no):
PATH_TO_DOC_COUNT = ROOT / 'doc_count_{}'.format(file_no)
PATH_TO_INLINKS = ROOT / 'INLINKS_{}'.format(file_no)
PATH_TO_OUTLINKS = ROOT / 'OUTLINKS_{}'.format(file_no)
... | The main task of the code is to resume a web crawling process by loading previously saved state data from files, including frontier, visited pages, links, and document counts, to continue crawling from where it left off. It restores all necessary data structures and triggers the crawl_seeds method to restart the crawli... | def resume_crawl(self):
self.file_no = self.load_file(PATH_TO_FILE_NUM)
files = self.get_file_names(self.file_no)
self.aux_ftier = self.load_file(files['PATH_TO_AUX_FRONTIER'])
self.frontier = self.load_file(files['PATH_TO_FRONTIER'])
self.robot_dict = self.load_file(files['PATH... |
def entropy(dataset): #Todo: parameter type
counts = class_counts(dataset)
entropy = 0
for label in counts:
prob_lbl = counts[label] / float(len(dataset))
entropy += -prob_lbl * math.log(prob_lbl, 2)
return entropy
def get_attr_list(dataset):
attr_list=[]
for attr in dataset[0]:
if attr != 'Clas... | This function identifies the optimal attribute for splitting a dataset by calculating information gain. It computes the prior entropy, evaluates each attribute's information gain after partitioning the dataset, and selects the attribute with the highest gain to maximize data segmentation efficiency in decision tree alg... | def find_best_split(dataset): #return attribute, gain with best split in the current example portion
best_gain = 0
best_attribute = None
H_prior = entropy(dataset)
attr_list=get_attr_list(dataset)
for attr in attr_list:
attr_IG=IG(partition(dataset, attr), H_prior)
if attr_IG >= best_gain:
bes... |
def find_best_split(dataset): #return attribute, gain with best split in the current example portion
best_gain = 0
best_attribute = None
H_prior = entropy(dataset)
attr_list=get_attr_list(dataset)
for attr in attr_list:
attr_IG=IG(partition(dataset, attr), H_prior)
if attr_IG >= best_gain:
bes... | The code implements the ID3 algorithm to build a decision tree. It recursively splits examples based on the attribute with the highest information gain, creating nodes for each partition. Missing attribute values are replaced with a placeholder node. If no gain is achieved, it returns a leaf node. The tree is construct... | def ID3(examples, default):
print("ID3")
'''
Takes in an array of examples, and returns a tree (an instance of Node)
trained on the examples. Each example is a dictionary of attribute:value pairs,
and the target class variable is a special attribute with the name "Class".
Any missing attributes are denote... |
def hasGC(node):
for child in node.getChildren():
if len(child.getChildren()) > 0:
return True
return False
def mode_class(examples): #returns the mode Class among examples.
class_count = count_classes(examples)
return max(class_count, key=class_count.get)
def getSubset(examples,attr,val):
subset = ... | The code's main task is to prune a trained decision tree using a validation set to enhance its accuracy. It recursively evaluates nodes, checking if removing branches (pruning) improves validation performance. If pruning reduces accuracy, the original structure is restored; otherwise, the pruned node remains. The funct... | def prune(node, examples):
print("prune function")
'''
Takes in a trained tree and a validation set of examples. Prunes nodes in order
to improve accuracy on the validation data; the precise pruning strategy is up to you.
'''
if hasGC(node): #if node has children of children
for child in node.getChildr... |
def mse(image1, image2, dtype=np.float32):
"""Mean Squared Error (MSE).
Note: independently on the dynamic range of the input, the metric
is scaled as if values were in the [0, 1] range.
"""
dr = max(_guess_dynamic_range(image1), _guess_dynamic_range(image2))
diff = np.subtract(image1, image2,... | The code generates two images, one reversed vertically, and calculates their Mean Squared Error (MSE), Peak Signal-to-Noise Ratio (PSNR), and Structural Similarity Index (SSIM) to evaluate perceptual and statistical differences. It tests image quality metrics by comparing the original and flipped images. | def _test():
image1 = (np.arange(1800) % 256).reshape(30, 20, 3).astype(np.uint8)
image2 = image1[::-1, :, :]
print(mse(image1, image2))
print(psnr(image1, image2))
print(ssim(image1, image2)) |
def get_current_user() -> User:
return find_user_by_id(current_user.id)
def get_current_set():
set_id = get_current_team().set_id
my_set = find_set_by_id(set_id)
return my_set
def get_current_team():
return find_team_by_id(get_current_user().team_id) | The code handles user and team settings in a web application. It checks if a user is part of a team, filters sets by problem count, and processes form submissions for updating team/user details, validating inputs like email, name, goals, and passwords. It also allows leaving a team or toggling dark mode, with appropria... | def settings():
if not get_current_user().team_id:
return redirect(url_for('views.home'))
set_problems_count = get_current_set().count
sets = sorted(list(Set.objects), key=lambda x: x.count, reverse=True)
sets = [i for i in sets if i.count >= 40]
print([i.name for i in sets])
if request... |
def is_new_day(team):
return str(team.last_updated) != str(get_date_cairo())
def is_someone_solved_today(team):
return team.solved_today
def set_dues(team):
members = get_team_members(team.id)
for i in members:
for j in get_today_unsolved_problems(i):
i.due_ids.append(j.id)
i... | The function `new_day(team)` checks if it's a new day. If so, it updates the team's progress by setting dues, incrementing their index based on daily goals, resetting counters when goals are met, and advancing to the next set. It also updates the team's status, marks tasks as unsolved, and records the last update time ... | def new_day(team):
if is_new_day(team):
if is_someone_solved_today(team) and team.duty_days[get_today_name_initials_cairo()]:
set_dues(team)
team.index += team.daily_goal
if team.index > get_set(team.set_id).count:
team.index = 1
team.set_i... |
def generate_training(img, block):
"""
This function will generate the training codevector from the image via non-overlapped patch.
"""
train_vec = []
x = block[0]
y = block[1]
for i in range(0, img.shape[0], x):
for j in range(0, img.shape[1], y):
train_vec.append(img[i:... | This function simulates an image compression protocol by generating a codebook from training data, encoding the input image using the codebook, decoding it, and saving the reconstructed image and codebook parameters. It processes the image in blocks, outputs a grayscale PNG of the decoded image, and stores codebook dat... | def sim_protocol(img, cb_size, epsilon, block, root, outpng):
"""
This function needod for doing simulation for different scenario.
"""
train_X = generate_training(img, block)
cb, cb_abs_w, cb_rel_w = lbg.generate_codebook(train_X, cb_size, epsilon)
cb_n = np.array(cb)
cb_abs_w_n = np.array(... |
def encode_image(img, cb, block):
"""
This function will encode (compress) the image by sending the image block, vectorize it then get the index of the
closest vector to form the compressed data.
"""
x = block[0]
y = block[1]
compressed = np.zeros((img.shape[0] // y, img.shape[1] // x))
... | This function simulates image encoding/decoding using a weight matrix for different scenarios. It processes input images, calculates PSNR values, and visualizes four reconstructed images in a grid with their PSNR metrics. The workflow includes loading weights, encoding images, decoding results, saving outputs, and disp... | def sim_testing_protocol(inpath_list, weight, block, outpng):
"""
This function needod for doing simulation for different scenario.
"""
fig, ax = plt.subplots(nrows=1, ncols=4)
idx = 1
for inpath in inpath_list:
img = cv2.imread(inpath, cv2.IMREAD_GRAYSCALE)
cb = pd.read_csv(weig... |
def get_path_file(ext: str):
"""_summary_
Args:
ext (str): File format extension
Raises:
Exception: _description_
Returns:
mypath (str): absolute path to directory of the file
file (str): name of selected file
"""
mypath = getcwd()
xlsx_list = scan_fi... | The main task of the code is to process an Excel file containing protein data, calculate parameters if enabled, create new protein records when IDs are missing, generate stock information, and update the workbook with changes. It handles exceptions, tracks created entries and added stocks, and outputs summary statistic... | def add_to_lg():
"""
"""
try:
mypath, file = get_path_file('xlsx')
except Exception:
return
prot_list = []
prot_count = 0
params_flag = if_calc_params() # TODO add to method
wb = load_workbook(join(mypath, file), data_only=True)
# ws_selection = select_shee... |
def get_path_file(ext: str):
"""_summary_
Args:
ext (str): File format extension
Raises:
Exception: _description_
Returns:
mypath (str): absolute path to directory of the file
file (str): name of selected file
"""
mypath = getcwd()
xlsx_list = scan_fi... | The function updates protein records and stock information from an Excel workbook. It loads the workbook, iterates through proteins, updates their Excel entries if they have an ID, updates stock data, and saves changes back to the file. | def update_from_lg():
try:
mypath, file = get_path_file('xlsx')
except Exception:
return
prot_list = []
wb = load_workbook(join(mypath, file), data_only=True)
for protein in protein_from_sheet_gen(wb):
if protein.id is not None:
protein.update_excel_rec... |
def prng(n=128):
if sys.version_info[1] >= 9 :
rand = int.from_bytes(random.randbytes(n),"big")
while not is_prime(rand):
rand = int.from_bytes(random.randbytes(n),"big")
return rand
else:
return old_prng(n*8)
def public_exp(phi, standard=True):
# Default e acordi... | The main task of the code is to generate an RSA key pair (public and private keys) by selecting two distinct prime numbers p and q, computing the modulus n = p*q, calculating Euler's totient function φ(n), choosing a public exponent e, and determining the private exponent d via the extended Euclidean algorithm. The fun... | def rsa_keypair(s=2048):
size_q = s // 2
size_p = s - size_q
p = 0
q = 0
n = 0
while(p == q):
# prng() takes size in bytes
p = prng(size_p//8)
q = prng(size_q//8)
n = p*q
phi = (p-1)*(q-1)
e = public_exp(phi)
one,d = eea(phi,e)
assert... |
def getProcessEntity(session,tenant,token,entityID,reqcount,duration):
if not "PROCESS_GROUP_INSTANCE" in entityID:
return {}
# check if entity is in cache
citem = entitycache.get(entityID)
if citem is not None:
tags = json.loads(citem)
if tags:
return tags
... | The function `getEntity` routes requests to specific entity-handling functions based on the `entityID` type (e.g., PROCESS_GROUP_INSTANCE, HOST, SERVICE), delegating tasks to functions like `getProcessEntity` or `getHostEntity`. It handles exceptions by logging errors and returning an empty dictionary if no valid entit... | def getEntity(session,tenant,token,entityID,reqcount,duration):
try:
if "PROCESS_GROUP_INSTANCE" in entityID:
return getProcessEntity(session,tenant,token,entityID,reqcount,duration)
if "HOST" in entityID:
return getHostEntity(session,tenant,token,entityID,reqcount,dur... |
def getStartTimestamp(tenant,timeseries):
ts = getLastCheckTimestamp(tenant, timeseries)
return ts - backlog_shift
def getEndTimestamp(tenant,timeseries):
return time.time() - backlog_shift
def setLastCheckTimestamp(tenant,timeseries):
entitycache.set('LCTS-'+tenant+'-'+timeseries,time.time())
def isBla... | The function fetches metrics from the Dynatrace API for a specified tenant, processes time-series data, maps values to standardized formats, and writes them to InfluxDB in line protocol. It manages API rate-limiting via randomized delays, handles entity tags, splits data into chunks for posting, and logs request/post d... | def getmetrics(mymetric,tenant,token):
# randomize some process startup dealy to avoid hitting the Dynatrace API heavily upon startup
time.sleep(random.randint(1,10))
requestcount = [0]
postcount = metriccount = 0
now = time.time()
valuemap = { 'AVAILABLE':1,'NOT_AVAILABLE':0,'UNMONITORED':... |
def _reanalyze(self, replay_buffer: ReplayBuffer, env_ids, positions,
mcts_state_field):
batch_size = env_ids.shape[0]
mini_batch_size = batch_size
if self._reanalyze_batch_size is not None:
mini_batch_size = self._reanalyze_batch_size
self._reanalyze_mcts... | The main task of the code is to preprocess experience data from a replay buffer for the MuZero algorithm, extracting values, candidate actions, policies, rewards, and game-over states. It structures the data into [B, T, ...] format, applies reanalysis if enabled, calculates bootstrap/Monte Carlo returns, and prepares `... | def preprocess_experience(self, root_inputs: TimeStep,
rollout_info: MCTSInfo, batch_info):
"""Fill rollout_info with MuzeroInfo
Note that the shape of experience is [B, T, ...]
"""
assert batch_info != ()
replay_buffer: ReplayBuffer = batch_info.re... |
def write_script_to_file(scripts, idx, out_dir):
out_fp = os.path.join(out_dir, f'script_{idx}.txt')
out_file = open(out_fp, 'w')
for line in scripts[idx]['raw_script']:
out_file.write(line + '\n')
out_file.close()
print()
print(f'Wrote script {idx} ("{scripts[idx]["title"]}" ... | The code reads JSON script files, processes command-line arguments to either write scripts to a directory or parse them. It loads scripts from a file, checks for write/parsing flags, and executes corresponding actions like writing specific scripts or parsing individual/all scripts. | def run():
parser = argparse.ArgumentParser()
parser.add_argument('script_fp', type=str)
parser.add_argument('-wi', '--write_idx', type=int)
parser.add_argument('-wd', '--write_dir', type=str)
parser.add_argument('-p', '--parse', action='store_true')
parser.add_argument('-pi', '--parse_idx', typ... |
def _load_params(self):
return load_dir(join(self.template_dir, 'data'))
def _load_config(self):
code_gen_config_file = join(self.template_dir, 'data/_config.yml')
if not exists(code_gen_config_file):
return {}
return yaml.load(open(code_gen_config_file))
def _transform_para... | The main task of the code is to generate output files from templates by first loading parameters and configurations, transforming parameters, and then generating content from a "master" template and individual item templates. It iterates through item-specific configurations, creates parameter objects, and applies them ... | def generate(self):
params = self._load_params()
config = self._load_config()
# pprint(config)
# Transform params
self._transform_params(config, params)
# Generate master
generate(join(self.template_dir, 'master'),
params,
outpu... |
def get_oid(name: str) -> str:
if name == "@":
name = "HEAD"
# Name is ref
refs_to_try = [
f"{name}",
f"refs/{name}",
f"refs/tags/{name}",
f"refs/heads/{name}",
]
for ref in refs_to_try:
if data.get_ref(ref, deref=False).value:
# if refere... | The main task of the code is to switch the working directory to the commit or branch specified by 'name' by updating the HEAD reference. It retrieves the commit object, reads its tree, and sets HEAD to either a symbolic reference (for branches) or a direct object ID (for commits), ensuring the repository's working stat... | def checkout(name: str):
oid = get_oid(name)
commit = get_commit(oid)
read_tree(commit.tree)
if is_branch(name):
HEAD = data.RefValue(symbolic=True, value=f"refs/heads/{name}")
else:
HEAD = data.RefValue(symbolic=False, value=oid)
data.update_ref("HEAD", HEAD, deref=False) |
def get_merge_base(oid1: str, oid2: str) -> str:
"""
Return the common ancester OID of two commits, None if no common ancestor.
"""
parents1 = set(iter_commits_and_parents({oid1}))
for oid in iter_commits_and_parents({oid2}):
if oid in parents1:
return oid
def get_commit(oid: str... | This code merges the 'other' branch into the current HEAD branch. It checks for a fast-forward merge (if possible, updates the working tree and HEAD reference directly). If not, it sets up a merge by recording the other branch as MERGE_HEAD, combines the trees of the current branch, other branch, and their common ances... | def merge(other: str):
"""
Merge other branch to HEAD (current branch)
"""
HEAD = data.get_ref("HEAD").value
assert HEAD
merge_base = get_merge_base(other, HEAD)
c_other = get_commit(other)
# Handle fast-forward merge
if merge_base == HEAD:
read_tree(c_other.tree)
... |
def assign_clusters(data, centroids):
"""
"""
# Compute distances between each data point and the set of centroids:
# Fill in the blank (RHS only)
distances_from_centroids = pairwise_distances(data, centroids, metric='euclidean')
# Compute cluster assignments for each data point:
... | The function performs k-means clustering on input data using initial centroids, iterating up to maxiter times. It assigns data points to nearest centroids, updates centroids by averaging cluster data, checks for convergence (no assignment changes), and optionally records heterogeneity scores or prints iteration updates... | def kmeans(data, k, initial_centroids, maxiter, record_heterogeneity=None, verbose=False):
""" This function runs k-means on given data and initial set of centroids.
maxiter: maximum number of iterations to run.
record_heterogeneity: (optional) a list, to store the history of heterogeneity as function... |
def solve(**kwargs):
name = kwargs.get("name")
integral_list = kwargs.get("integral_list")
sense = kwargs.get("sense", mip.MINIMIZE)
A = kwargs.get("A")
b = kwargs.get("b")
c = kwargs.get("c")
verbose = kwargs.get("verbose")
# Solve the problem
start_time = time.time()
m, x, con... | The code generates features and labels for a FacilityLocation problem instance by solving it with different cut strategies. It creates problem instances, solves them without cuts to establish a baseline time, then iteratively applies cuts to measure solving efficiency. Features (normalized average cut features) and lab... | def main():
problem_names = ["SetCover", "TravelingSalesman", "GeneralMIP", "Knapsack", "FacilityLocation"]
n_features = 14
dens = 0.3
max_coef = 10
total_features = np.array([])
total_labels = []
cut_choice_method = "CollectLabels"
cut_percentage = 0.3
n_steps = 10
for prob... |
def displayIntro():
# displays intro screen
readLine_Print(0, 23)
def play():
user_input_set = set()
cur_word = getWord().strip()
temp_word = cur_word
displayed_word = "-" * len(cur_word)
lives = 5 # give 5 lives
while True:
displayHangman(lives) # display hangman
pri... | The main task of the code is to run a Hangman game loop, repeatedly displaying the introduction, playing the game, showing results, and prompting the player to continue or quit. The loop breaks only when the player inputs "no", ensuring multiple game sessions until the user decides to stop. | def hangman():
while True:
displayIntro()
result = play()
displayEnd(result)
player_decision = input("Do you want to play again? (yes/no) ")
while player_decision != "yes" and player_decision != "no":
player_decision = input("Do you want to play again? (yes/no) ")... |
def receive_json_data():
"""
Receive JSON data from the client.
Binds the server socket to the IP and port, listens for incoming connections, accepts the client connection,
receives the JSON data, decodes it, and prints the computer information.
"""
server_socket = socket.socket(socket.AF_INET, ... | The main task of the code is to determine whether the program operates as a server or client based on the existence of a JSON file. If the file exists, it receives JSON data; if not, it sends JSON data, creates a dictionary, and saves it to the file. The process concludes with a completion message. | def main():
"""
Main function to handle server and client operations.
Checks if the JSON file exists. If it does, assumes it is the server and receives JSON data.
If the file does not exist, assumes it is the client and sends JSON data.
Finally, if it is the client, writes the JSON data to a file.
... |
def all_keys(examples):
keys = []
for example in examples:
keys += example['data'].keys()
return set(keys)
def create_predicates(key, examples):
values = set()
for example in examples:
if key in example['data']:
values.add(example['data'][key])
else:
v... | This function identifies the optimal predicate for splitting data by evaluating all possible predicates derived from example features. It iterates through each feature, generates candidate predicates, calculates their information gain, and selects the predicate with the highest gain. If multiple predicates have approxi... | def best_predicate(examples):
choice, highest_gain = None, 0.0
for key in all_keys(examples):
for predicate in create_predicates(key, examples):
gain = measure_predicate(predicate, examples)
if approximately_equal(gain, highest_gain) and is_is_none(predicate):
cho... |
def test_with_no_data_result_is_divided():
examples = [{'data': {'weather': 'sunny'}, 'conclusion': 'happy'},
{'data': {'weather': 'rainy'}, 'conclusion': 'sad'}]
tree = build(examples)
assert(tree.decide({}) == {'happy': 0.5, 'sad': 0.5})
def test_with_no_data_falls_back_training_weights():... | The code tests how a decision-making algorithm handles missing data scenarios, including fallback mechanisms when no data is present, probability distribution along decision paths, treating missing data as an option, and ensuring decisions are determined emphatically when test data is missing. It verifies correctness i... | def test_deciding_with_missing_data():
test_with_no_data_result_is_divided()
test_with_no_data_falls_back_training_weights()
test_probablity_is_apportioned_down_the_tree()
test_missing_data_in_examples_is_treated_as_an_option()
test_missing_example_determines_decision_emphatically_when_test_data_is_... |
def best_predicate(examples):
choice, highest_gain = None, 0.0
for key in all_keys(examples):
for predicate in create_predicates(key, examples):
gain = measure_predicate(predicate, examples)
if approximately_equal(gain, highest_gain) and is_is_none(predicate):
cho... | The main task of the code is to recursively build a decision tree by selecting the best predicate to split examples, partitioning them into subsets, and creating leaf nodes for base cases or tree nodes with weighted subtrees when partitions are non-trivial. | def build(examples):
predicate = best_predicate(examples)
if predicate == None:
return Leaf(probability_distribution(examples))
yesses, nos = partition(predicate, examples)
if len(yesses) == len(examples):
return Leaf(probability_distribution(yesses))
if len(nos) == len(examples):
... |
def play() -> None:
global songs, play_button_state, current_song
try:
if bool(songs):
if play_button_state and mixer.music.get_busy():
play_button_state = False
mixer.music.pause()
buttons_player_play_button.configure(image=play_img)
... | This function handles playing the next song in a playlist. It selects a random song (if in 's_p' mode) or increments the index, ensures no repetition, loads the song into the mixer, updates UI elements (play button, playlist view), and handles exceptions by refreshing the directory. | def forward() -> None:
global songs, play_button_state, current_song, config, random_list, played_songs
try:
if bool(songs):
if config["mode"] == "s_p" and (len(songs)) > 2:
current_song = choice(sample(random_list, k=int(len(songs) / 2)))
while current_song i... |
def play() -> None:
global songs, play_button_state, current_song
try:
if bool(songs):
if play_button_state and mixer.music.get_busy():
play_button_state = False
mixer.music.pause()
buttons_player_play_button.configure(image=play_img)
... | The function 'previous()' navigates to and plays the prior song in a playlist, adjusting the current song index based on playback mode. It stops the current track, loads the previous song, updates UI elements, and manages the played songs list. If in shuffle mode, it selects the last played song before the current one;... | def previous() -> None:
global songs, play_button_state, current_song, played_songs
try:
if bool(songs):
if config["mode"] == "s_p" and (len(songs)) > 2 and bool(played_songs):
if len(played_songs) > 1:
current_song = played_songs[-2]
elif ... |
def clear_search() -> None:
global search_list
if bool(search_list):
search_list = []
top_player_search_box.delete(0, 'end')
refresh_window()
def play() -> None:
global songs, play_button_state, current_song
try:
if bool(songs):
if play_button_state and mixer.... | This function handles playing a selected song from a listbox by updating the current song index, managing play/pause button state, loading and playing the audio file, and updating song attributes, with error handling that triggers a directory refresh if exceptions occur. | def list_box_play(event=None) -> None:
global songs, play_button_state, current_song, search_list
try:
if bool(songs) and bool(search_list):
current_song = songs.index(search_list[left_player_music_list.curselection()[0]])
clear_search()
elif bool(songs) and bool(left_pla... |
def dijk_routing(self,start,end):
self.disarray.clear()
self.disarray=self.dijk_array(start)
print('start:',start,'distance',self.disarray)
visited=[0,0,0,0,0,0,0,0,0,0]
self.initPath(start)
visited[start]=1
while(True):
if visited[end] !=0:
... | This function configures OpenFlow flow entries on switches along a routing path to handle both ARP and IPv4 traffic between source and destination. It creates bidirectional rules for ARP requests and IPv4 packets, using Dijkstra's algorithm to determine the path. Flow entries are added to each switch in the path with s... | def setFlowEntry(self,src,dst,parser):
arptodstmatch = parser.OFPMatch(eth_type=0x0806, arp_spa='10.0.0.1' + src, arp_tpa='10.0.0.1'+dst)
arptosrcmatch = parser.OFPMatch(eth_type=0x0806, arp_spa='10.0.0.1' + dst, arp_tpa='10.0.0.1'+src)
pkttodstmatch = parser.OFPMatch(eth_type=0x0800, i... |
def dijk_routing(self,start,end):
self.disarray.clear()
self.disarray=self.dijk_array(start)
#print('start:',start,'distance',self.disarray)
visited=[0,0,0,0,0,0,0,0,0,0]
self.initPath(start)
visited[start]=1
while(True):
if visited[end] !=0:
... | This code configures OpenFlow entries to route packets between source and destination IP addresses via a precomputed path using Dijkstra's algorithm. It creates bidirectional flow rules for UDP/TCP/ARP traffic, matching packets by IP/UDP/TCP fields or ARP parameters, and installs actions to forward packets through swit... | def setFlowEntry(self,src,dst,parser,type,src_port=NONE,dst_port=NONE):
print('Routing ','10.0.0.1'+src,' to ','10.0.0.1'+dst)
if type =='udp':
pkttodstmatch = parser.OFPMatch(eth_type=0x0800, ipv4_src='10.0.0.1'+src, ipv4_dst='10.0.0.1'+dst, ip_proto=17,udp_src=src_port, udp_dst=dst_port)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.