dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def is_train_test_file_exists(self) -> bool:
"""
It checks if the training and testing files are present in the specified path
:return: The return value is a boolean value.
"""
try:
logging.info(
'Checking if Training And Testing File is Available!!!!?... | The main task of the code is to validate data by checking the existence of train/test files, verifying dataset schema compliance, and detecting data drift, then returning a DataValidationArtifact with validation status and file paths if successful, or raising an exception if errors occur during the process. | def initiate_data_validation(self) -> DataValidationArtifact:
"""
It checks if the train and test files exist, validates the schema of the dataset, and checks if
there is any data drift
:return: DataValidationArtifact
"""
try:
self.is_train_test_file_exists()
... |
def initialise():
global density_v,density_l,mass_v,mass_l,A_injector,D_loss,P_tank,V_tank, temp, Error
try:
temp = float(input("Enter initial Nitrous temperature in Kelvins:"))
density_v = NP.densityV(temp)
density_l = NP.densityL(temp)
V_tank = float(input("Enter the Ni... | The main task of the code is to simulate a rocket's operation by initializing parameters, collecting data (pressure, thrust, temperature, mass) during a burn phase, handling errors, executing vapor-phase calculations, and plotting results. It runs loops to update values, appends data to lists, and terminates when condi... | def main():
p_tank = []
thrustPlot = []
temperature = []
rocket_mass = []
initialise()
if Error:
return None
while not burnout:
loop()
if not Error:
temperature.append(temp)
p_tank.append(P_tank)
thrustPlot.appen... |
def get_first_generation_node_children(driver):
'''
We are concerned about filtering out the parent node
from the list of children.
'''
time.sleep(2)
thoughts = [tag.text for tag in driver.find_elements_by_class_name('thought')]
cleaned_nodes = deduplicate_and_clean_root_nodes(thou... | The function allows users to select a node from a list of topics by index, then performs actions based on their choice: scraping data, saving, or continuing navigation. It handles input errors with exits and uses conditional logic to determine the next steps, ensuring user-friendly interaction through enumeration and c... | def utilitarianly_traverse(driver):
'''
for making a user friendly system we are allowing a user to choose
the index value of a node hence the enumeration while looping over
the nodes to show to a client
hence all this cleaned_nodes[node] business
yet to handle having three c... |
def _read_reg(self, reg):
"""Read 1 byte from a given register"""
return self._bus.read_byte_data(self._address, reg)
def _reset(self):
"""Reset the device to return all settings to the startup state
Finally wakes up the device."""
# Read the current value
cur_reg_reading = self._read_reg(_MPU6050_PWR_MGMT_... | The code initializes an MPU6050 IMU sensor via I2C, verifies device address, sets default gyroscope/accelerometer ranges, resets the sensor, configures sample rate and filter settings, selects clock source, and introduces a delay for stabilization. | def __init__(self, address=_MPU6050_I2CADDR_DEFAULT):
self._bus = smbus.SMBus(1) # Channel = 1
self._address = address
if(self._read_reg(_MPU6050_WHO_AM_I) != _MPU6050_I2CADDR_DEFAULT):
raise RuntimeError("Error loading MPU-6050 IMU")
self._cur_gyro_setting = _MPU6050_GYRO_250
self._cur_accel_setting = _M... |
def makeset(v):
v.pi = v
v.height = 0
return
def find(v):
if v != v.pi:
v.pi = find(v.pi)
return v.pi
def union(u, v):
# First, find the root of the tree for u # and the tree for v
ru = find(u)
rv = find(v)
# If the sets are already the same, return
if ru == rv:
... | The main task of the code is to construct a Minimum Spanning Tree (MST) using Kruskal's algorithm. It processes edges in increasing order, adding each edge to the MST if it connects disjoint components (detected via Union-Find's `find` and `union` operations), thereby avoiding cycles and ensuring the MST's optimality. | def kruskal(adjList, edgeList):
# Initialize all singleton sets for each vertex
for v in adjList:
makeset(v)
# Initialize the empty MST
X = []
# Loop through the sorted edges in increasing order.
for e in edgeList:
# If the min edge crosses a cut, add it to our MST
u, v... |
def convert_char_list_to_ints(chars, chars_to_int):
for i, char in enumerate(chars):
chars[i] = chars_to_int[char]
return chars
def one_hotify(vec):
mat = np.zeros((len(vec), K))
for i, val in enumerate(vec):
mat[i] = one_hot(val)
return mat.T
def forward_pass(RNN, X_chars, Y_chars, ... | The code trains a Recurrent Neural Network (RNN) to predict the next character in a sequence using book data. It employs Adagrad optimization, processes sequences in batches, updates model parameters via backpropagation, and tracks loss over iterations. Periodic text generation evaluates the model's ability to synthesi... | def fit(RNN, book_data, char_to_int, int_to_char, epochs=3):
# record keeping
e = 0
epoch = 0
updates = 0
smoothed_loss = None
loss_development = []
h_prev = np.zeros((m, 1))
# adagrad params
m_RNN = {}
m_RNN['b'] = np.zeros((m, 1))
m_RNN['c'] = np.zeros((K, 1))
m_RNN['U'... |
def ComputeCost(X, Y, W, b, lambda_reg):
assert X.shape[1] == Y.shape[1]
weight_sum = 0
for w in W:
weight_sum += np.sum(w ** 2)
reg_term = lambda_reg * weight_sum
predictions = forward_pass(X, W, b)[-1]
ce_term = - np.log((Y * predictions).sum(axis=0)).mean()
total_cost = ce_term + ... | The function implements mini-batch gradient descent with cyclical learning rates to train a model, updating weights (W) and biases (b) using batched data. It tracks training/validation costs and accuracies over cycles, adjusting the learning rate (eta) using a triangular schedule. The process continues until the specif... | def MiniBatchGD(train_set, val_set, GDparams, W, b, lambda_reg):
# unpack arguments
n_batch, etas, n_cycles = GDparams
eta_min, eta_max, step_size = etas
train_X, train_Y, train_y = train_set
val_X, val_Y, val_y = val_set
n_batches_per_epoch = int(train_X.shape[1] / n_batch)
batches = [(x *... |
def ComputeCostBatchNorm(X, Y, W, b, gamma, beta, lambda_reg, mu=None, var=None):
assert X.shape[1] == Y.shape[1]
weight_sum = 0
for w in W:
weight_sum += np.sum(w ** 2)
reg_term = lambda_reg * weight_sum
predictions = forward_pass_batch_norm(X, W, b, gamma, beta, mu, var)[0][-1]
ce_term... | The function implements mini-batch gradient descent with batch normalization, using cyclical learning rates. It trains a neural network by iterating through shuffled batches, computes gradients, updates weights/biases, and maintains moving averages of batch statistics. It logs training/validation costs/accuracies perio... | def MiniBatchGDBatchNorm(train_set, val_set, GDparams, W, b, gamma, beta, lambda_reg, alpha=0.9):
# unpack arguments
n_batch, etas, n_cycles = GDparams
eta_min, eta_max, step_size = etas
train_X, train_Y, train_y = train_set
val_X, val_Y, val_y = val_set
n_batches_per_epoch = int(train_X.shape[... |
def flip_half_images(X):
N = X.shape[1]
to_flip = round(N / 2)
to_flip = sample(list(range(N)), to_flip)
for idx in to_flip:
X[:, idx] = flip_image(X, idx)
def forward_pass(X, W, b):
s = W @ X + b
return softmax(s)
def ComputeGradients(X, Y, P, W, lambda_reg):
assert P.shape[1] == X.... | The main task of the code is to perform mini-batch gradient descent for training a model. It iteratively updates weights (W) and bias (b) over multiple epochs, using shuffled training data and data augmentation (image flipping). For each batch, it computes gradients, updates parameters, and tracks training/validation c... | def MiniBatchGD(train_X, train_Y, val_X, val_Y, GDparams, W, b, lambda_reg):
n_batch, eta, n_epochs = GDparams
n_batches = list(range(int(train_X.shape[1] / n_batch)))
batches = [(x * n_batch, (x + 1) * n_batch - 1) for x in n_batches]
train_cost_per_epoch = np.zeros(n_epochs)
val_cost_per_epoch = n... |
def ComputeCost(X, Y, W, b, lambda_reg):
assert X.shape[1] == Y.shape[1]
weight_sum = 0
for w in W:
weight_sum += np.sum(w ** 2)
reg_term = lambda_reg * weight_sum
predictions = forward_pass(X, W, b)[1]
ce_term = - np.log((Y * predictions).sum(axis=0)).mean()
total_cost = ce_term + r... | This function implements mini-batch gradient descent with cyclical learning rates to train a model. It shuffles training data, divides it into batches, and iteratively updates weights (W) and bias (b) using gradients from each batch. The learning rate (eta) cycles between min and max values over specified cycles. It lo... | def MiniBatchGD(train_set, val_set, GDparams, W, b, lambda_reg):
# unpack arguments
n_batch, etas, n_cycles = GDparams
eta_min, eta_max, step_size = etas
train_X, train_Y, train_y = train_set
val_X, val_Y, val_y = val_set
n_batches_per_epoch = int(train_X.shape[1] / n_batch)
batches = [(x *... |
def autentikasi_user(self, domain, password):
if domain not in self.domains:
return { 'status': 'ERROR', 'message': 'Domain Tidak Tersedia' }
tokenid = str(uuid.uuid4())
self.sessions[tokenid] = { 'domain': domain }
return { 'status': 'OK', 'tokenid': tokenid }
def s... | The code processes incoming data by splitting it into lines, identifies commands (e.g., 'auth', 'send', 'signin_group'), extracts parameters, and routes requests to corresponding methods for authentication, email sending, or group sign-in. It handles errors like invalid commands or missing data by returning structured ... | def proses(self,data):
j=data.split("\r\n")
try:
command=j[0].strip()
if (command=='auth'):
domain=j[1].strip()
password=j[2].strip()
logging.warning("AUTH SERVER, domain : {}, pass : {}" . format(domain, password))
... |
def val_to_bool(val):
if type(val) == str:
return bool(distutils.util.strtobool(val))
else:
return bool(val)
def val_to_date(val, format):
return datetime.datetime.strptime(val, format)
def save(self, path):
save_cfg(path, self.to_dict())
def validate(self, out):
#print("Vali... | This function parses command-line arguments, handling overrides, environment variables, and config files. It processes parameters, converts values (e.g., bool, datetime), applies config files, and validates inputs. It returns parsed values and configurations, with optional verbose output and source tracking. | def parse(self, args=sys.argv[1:], verbose=False, include_source=False):
# extract the override params - argparse will not see them
rest = []
for arg in args:
override = False
for key in self.config_overrides.keys():
if arg.startswith(key):
... |
def find_possible_banners(self):
possibles = []
banner_0 = self.banner_is_present_728x90_coinzilla()
if banner_0:
possibles.append(banner_0)
possibles.append(banner_0)
banner_1 = self.banner_is_present_sticky_footer()
if banner_1:
possibles.app... | The main task of the code is to randomly select and click a banner from a list of possible banners, handle interaction errors by retrying with other banners, check for IP changes to abort, and manage pop-up windows by switching contexts, scrolling, and closing them, ensuring the action is completed while maintaining st... | def click_rnd_banner_or_not(self):
possibles = self.find_possible_banners()
if isinstance(possibles, list):
banner = sec.choice(possibles)
with self.lock:
self.logger.warning(f"CLICKING ON BANNER!")
if self.ip_address_has_changed():
ret... |
def handle_CreateEntry(self, entityList):
if(len(entityList) <= 0):
print("No good format for the event!")
else:
subject = "none"
activity = "none"
date = "none"
day = "none"
hour = "none"
person = "none"
fo... | This code processes user intents related to calendar operations. It checks the top intent from the response and routes the request to corresponding handlers for creating, deleting, finding, or clearing calendar entries. For "FindCalendarEntry," it retrieves and prints events. It responds to greetings and handles unknow... | def handle(self, response):
entityList = response._entityList
topIntent = response._topIntent
if topIntent == "CreateCalendarEntry":
#print("Is create intent")
self.handle_CreateEntry(self, entityList)
elif topIntent == "DeleteCalendarEntry":
#print("... |
def add_user(self, mail, alias, pages):
if "@" in mail and " " not in mail and not self.user_exists(mail):
client = pymongo.MongoClient(
f"mongodb+srv://prasaadmin123:{self.password}@press-zn9bb.mongodb.net/test?retryWrites=true&w=majority")
project = client.PRESS
... | This code parses input text to extract and execute commands like JOIN, ADD, DELETE, or UNSUBSCRIBE. It filters words, identifies valid commands, and processes parameters to manage users and pages, such as adding/deleting pages or unsubscribing users. | def parse(self,text,sender):
text = ''.join(x for x in text if (x.isalpha() or x == "," or " "))
text = re.findall(r"[\w']+", text)
filtered = []
cons_bad = 0
for i in range(len(text)):
if cons_bad > 10:
break
if text[i] in self.commands or... |
def get_activity_type(self) -> str:
if self._activity_type == self.TYPE_UNKNOWN:
# Perform activity type detection only once.
self._activity_type = self._detect_activity_type()
return self._activity_type
def _get_pool_swim_data(self) -> list:
"""" Calculates the real swim... | The main task of the code is to retrieve swim data based on the activity type. It checks if the activity is pool swimming or open water swimming, calling the respective private method to fetch data. If the activity type is neither, it returns None. | def get_swim_data(self) -> Optional[list]:
if self.get_activity_type() == self.TYPE_POOL_SWIM:
return self._get_pool_swim_data()
elif self.get_activity_type() == self.TYPE_OPEN_WATER_SWIM:
return self._get_open_water_swim_data()
else:
return None |
def read_trajectory(self, filename, dim=4):
with open(filename) as f:
lines = f.readlines()
# Extract the point cloud pairs
keys = lines[0::(dim + 1)]
temp_keys = []
for i in range(len(keys)):
temp_keys.append(keys[i].split('\t')[0:3])... | The code benchmarks estimated trajectories against ground truth by evaluating recall metrics and error statistics across multiple scenes. It processes each scene's estimated and ground truth data, computes validity counts, and calculates recall (Predator-style and DSC-style) along with rotational and translational erro... | def benchmark(self, est_folder, gt_folder='configs/benchmarks/3DMatch'):
scenes = sorted(os.listdir(gt_folder))
n_valids, n_totals = [], []
predator_style_recall_per_scene, dsc_style_recall_per_scene = [], []
error_rs, error_ts = [], []
dsc_error_rs, dsc_error_ts = [], []
... |
def _create_cells(self):
for x in range(self._num_cols):
col_cells = []
for y in range(self._num_rows):
col_cells.append(Cell(self._win))
self._cells.append(col_cells)
for x in range(self._num_cols):
for y in range(self._num_rows):
... | This code initializes a maze generator with specified dimensions and cell sizes, creates maze cells, breaks walls recursively to form paths, sets entrance/exit, resets visited states, and solves the maze starting from the top-left cell. | def __init__(self, x1, y1, num_rows, num_cols,
cell_size_x, cell_size_y, win=None, seed=None):
self._x1 = x1
self._y1 = y1
self._num_rows = num_rows
self._num_cols = num_cols
self._cell_size_x = cell_size_x
self._cell_size_y = cell_size_y
self._wi... |
def get_width(self):
return self._width
def get_height(self):
return self._height
def draw_frame(self):
"""
Iterates through self._items and draw's them according to what type of item it is
"""
for item in self._items:
info = item.get_info()
if typ... | The code initializes a canvas with screen dimensions, establishes coordinate mappings for graphing, draws a grid with labeled axes, sets up geometric elements (circle, tangent point, sine/cosine lines), and prepares the canvas for dynamic rendering of a trigonometric visualization, including coordinate conversion and g... | def __init__(self, master):
tk.Canvas.__init__(self, master)
self._width, self._height = self.winfo_screenwidth(), self.winfo_screenheight() # height and width of canvas
self._step = int(self.get_width() / Graph.ZOOM) # distance of one step along either x or y axis
# build data ... |
def set_species(self, species):
self.__species = species.title()
def set_egg_group(self, group):
groups = {'amorphous', 'bug', 'ditto', 'dragon', 'fairy', 'field', 'flying', 'grass', 'human-like', 'mineral', 'monster', 'undiscovered', 'water 1', 'water 2', 'water 3'}
if group in groups:
... | This code initializes a Pokémon object with attributes like species, egg group, gender, IVs, and name, while setting up a GUI component using a Frame widget. It assigns the provided GUI reference and calls a setup method to configure the interface. | def __init__(self, species, egg_group, gender, ivs, gui, id, name='Unnamed'):
self.__id = id
self.set_species(species)
self.set_egg_group(egg_group)
self.set_gender(gender)
self.set_ivs(ivs)
self.set_egg_group(egg_group)
self.set_name(name)
self.__gui = gu... |
def down_sampling(x, size, filters, kernel_size):
new_size = [size[0], size[1]]
if size[0] % 2 != 0:
# x = reflection_padding(x, [np.int32(np.floor(kernel_size/2)), 0])
x = reflection_padding(x, [1, 0])
new_size[0] = size[0] + 1
if size[1] % 2 != 0:
# x = reflection_padding(x... | This code defines a neural network model with downsampling, upsampling, and skip connections. It constructs a U-Net-like architecture using convolutional layers, handling input dimensions dynamically. The model processes input data through alternating downsampling and upsampling stages, incorporating skip connections t... | def define_model(num_u, num_d, kernel_u, kernel_d, num_s, kernel_s, height, width, inter,
lr, input_channel=32, transconvo=False):
depth = len(num_u)
size = [height, width]
inputs = Input(shape=(height, width, input_channel))
x = inputs
down_sampled = []
sizes = [size]
fo... |
def isLetter(x):
if (x >= 'A' and x <= 'Z') or (x >= 'a' and x <= 'z'):
return True
return False
def my_edit_distance(s1, s2, threshold = 1):
"""
Calculate the Levenshtein edit-distance between two strings.
Improved from nltk library, with pruning.
"""
# set up a 2-D array
len1 = len(s1)
len2 = le... | This function generates Metaphone representations of words, computes Levenshtein distances between target and vocabulary items' Metaphones, and returns phonetically similar words below a threshold. If no matches are found, it adjusts thresholds or returns a random word for fallback. | def metaphone_sim_original(target, threshold = 1):
'''
First generate Metaphone representation for the word
Then, calculate the Levenshtein distance of the Mataphone representations
'''
ret = []
target_meta = metaphone.phonetics(target)
for i in range(len(vocab)):
word = vocab[i]
if isLetter(word... |
def isLetter(x):
if (x >= 'A' and x <= 'Z') or (x >= 'a' and x <= 'z'):
return True
return False
def metaphone_sim(target, threshold = 1):
'''
First generate Metaphone representation for the word
Then, calculate the Levenshtein distance of the Mataphone representations
'''
ret = []
target_meta = met... | This function replaces words in a text with phonetically similar alternatives using a probability threshold. It tokenizes input text, checks if words start with letters, and probabilistically substitutes them using metaphone and spelling similarity functions. Replacements are logged if verbose is enabled, and the modif... | def phonetical_replace_advanced(self, text, prob = 0.2, verbose = False):
self.prob = prob
words = nltk.word_tokenize(text.lower())
for i in range(len(words)):
if not isLetter(words[i][0]):
continue
if random.random() < self.prob:
word_list = metaphone_sim(words[i], 1)
ch... |
def isLetter(x):
if (x >= 'A' and x <= 'Z') or (x >= 'a' and x <= 'z'):
return True
return False
def metaphone_sim(self, target, threshold = 1):
'''
Returns a list of
First generate Metaphone representation for the word
Then, calculate the Levenshtein distance of the Mataphone representations
... | The main task of the code is to replace words in a given text with their phonetic equivalents using the Metaphone algorithm, with a specified probability. It tokenizes the input text, checks each word's first character, and randomly substitutes words with phonetically similar alternatives (via `metaphone_sim` or `spell... | def phonetic_replace(self, text, prob = 0.2, verbose = False, random_choice = True):
self.prob = prob
words = nltk.word_tokenize(text.lower())
for i in range(len(words)):
if not isLetter(words[i][0]):
continue
if random.random() < self.prob:
word_list = self.metaphone_sim(words[i... |
def maxcut_qfitness(n,gene_weight,best_fitness):
circuit = QuantumCircuit(3*n+2)
#initialize the first generation as uniform distribution
circuit.h(range(n))
#compute the fitness of a chromosone
for i in range(gene_weight.shape[0]):
for j in range(i+1,gene_weight.shape[0]):... | This function implements a quantum algorithm for solving the Max-Cut problem using amplitude amplification. It initializes a quantum circuit with a fitness-based state, applies Grover operators repeatedly to amplify solution probabilities, executes the circuit on a quantum simulator, and returns classical solutions fro... | def Maxcut_Genetic_Amplitude_Amplification(chromo_size,popu_size,gene_weight,best_fitness,steps):
circuit = QuantumCircuit(3*chromo_size+2,chromo_size)
#initialize the state with maxcut_qfitness
circuit.append(maxcut_qfitness(chromo_size,gene_weight,best_fitness),range(3*chromo_size+2))
#start the amp... |
def loop_monitor(t):
global globalInsertT
globalInsertT = Timer(t, insert_time_printer)
globalInsertT.start()
def insert_deep_dataset(collection, num, partition_num):
insert_dataset(collection, num, partition_num, gen_deep1b_fnames)
def insert_sift_dataset(collection, num, partition_num):
insert_dat... | The function `insert_collection` inserts data into a specified collection based on the provided dataset type. It routes to either `insert_deep_dataset` or `insert_sift_dataset` depending on whether the dataset is `DATASET_DEEP` or `DATASET_SIFT`, using predefined parameters like `NUM_FILES` and `PARTITION_NUM`. If an u... | def insert_collection(collection, dataset):
loop_monitor(1)
if dataset == DATASET_DEEP:
insert_deep_dataset(collection, NUM_FILES, PARTITION_NUM)
elif dataset == DATASET_SIFT:
insert_sift_dataset(collection, NUM_FILES, PARTITION_NUM)
else:
raise_exception("wrong dataset") |
def update_backtracking_metrics():
global is_backtracking, curr_backtrace_depth, dead_end_counter, longest_backtrace
if is_backtracking:
if curr_backtrace_depth > longest_backtrace:
longest_backtrace = curr_backtrace_depth
curr_backtrace_depth = 0
dead_end_counter += 1
... | This function solves a constraint satisfaction problem using the Minimum Remaining Values (MRV) heuristic with backtracking. It selects the cell with the fewest possible values, iterates through options, and recursively attempts to fill the board. Global counters track recursion depth, guesses, and backtracking steps. ... | def solve_with_mrv(borders, board):
# print_board(borders, board)
# print("")
global recursion_counter, changed_value_counter, guess_counter, is_backtracking, curr_backtrace_depth
update_backtracking_metrics()
recursion_counter += 1
possible_values_tracker = record_possible_values_for_empty_cell... |
def print_board(borders, board):
n_view = borders[0]
e_view = borders[1]
s_view = borders[2]
w_view = borders[3]
# Print north view first
for n_col in range(SIZE):
if not n_col:
print(" ", n_view[n_col], end="")
else:
print(" |", n_view[n_col], end="")
... | The code solves a Skyscrapers puzzle using backtracking with the MRV heuristic, filling known values, tracking recursion depth, value changes, guesses, dead ends, and longest backtrace during the solution process. It prints the input board, solved board, and performance metrics. | def main():
input_borders = skyscrapers_borders_5h3
input_board = skyscrapers_board_5h3
global SIZE
SIZE = len(input_board)
print("Input board:")
print_board(input_borders, input_board)
fill_known_values(input_borders, input_board)
solve_with_mrv(input_borders, input_board)
print("\n... |
def _initialize_session(self):
s = requests.session()
r = s.get(self.login_url)
hash_value = hash_extractor.search(r.content.decode('utf-8')).group(1)
#print(hash_value)
login_data = dict(login_email=POE_LOGIN_EMAIL, login_password=POE_LOGIN_PASSWORD, hash=hash_value)
s.p... | The code initializes a class to interact with Path of Exile's API, setting up URLs for login, account name retrieval, and stash data. It establishes a database connection, initializes tables for storing stash and item data, and prepares to fetch and process game-related information using session management and SQL oper... | def __init__(self, mdb):
self.login_url = 'https://www.pathofexile.com/login'
self.account_name_url = 'https://www.pathofexile.com/character-window/get-account-name'
self.session = self._initialize_session()
self.account_name = self._get_account_name()
self.stash_url = 'https://w... |
def create_traffic_lights(self):
"""
this functions creates the traffic lights.
"""
self.south_id = 100
self.north_id = 200
self.east_id = 300
self.west_id = 400
for item in self.map:
if len(item[2]) > 1:
if item[0] == "S":
... | This function initializes a traffic management system by creating traffic lights, constructing the map, connecting traffic lights to crossings, and establishing lane connections to enable coordinated traffic control and navigation. | def setup_map(self):
"""
this function setups everything like traffic lights map lane connections and traffic light crossing
"""
self.create_traffic_lights()
self.create_map()
self.connect_traffic_light_with_crossing()
self.create_lane_connections() |
def brake(self):
"""
this function decreases the speed of the Agent, based on the current speed,
and the mass of the Agent
"""
if self.speed > 0:
self.speed -= 1 * self.mass * 0.008
if self.speed <= 0:
self.speed = 0
sel... | This function determines an agent's next action based on traffic light signals and node positions. If at a 'start' node with no visible light, it identifies the next traffic light. At an 'end' node with a visible light, it brakes for red, drives for green, or checks braking for orange. If no applicable conditions are m... | def step_to_next_node(self):
"""
this function checks if the Agent can continue to the next Node
First it checks if the Agent has entered a 'start' node AND
doesnt currently see a traffic light, if these conditions are met,
then set the traffic_light_sight to the upcoming traf... |
def paths(result_dir, filename):
return [
result_dir / "rate_vs_angle.png",
result_dir / "ild_itd.png",
result_dir / "netvis.png",
result_dir / filename.replace(".pic", ".png"),
]
def draw_rate_vs_angle(data, filename, show_lso=True, show_mso=True, rate=True):
angle_to_rate =... | The function generates and saves visualizations (rate vs. angle plot, ITD/ILD plot, network visualization) from input data, merges them into a combined result file, and returns 1. | def generate_complete(res, result_dir, filename, cleanup=True):
RATE_VS_ANGLE, ILD_ITD, NETVIS, RESULT = paths(result_dir, filename)
fig = draw_rate_vs_angle(res, filename)
fig.savefig(RATE_VS_ANGLE)
itd_ild_fig = draw_ITD_ILD(res, filename)
itd_ild_fig.savefig(ILD_ITD)
generate_network_vis(re... |
def paths(result_dir, filename):
return [
result_dir / "rate_vs_angle.png",
result_dir / "ild_itd.png",
result_dir / "netvis.png",
result_dir / filename.replace(".pic", ".png"),
]
def draw_rate_vs_angle(data, filename, show_lso=True, show_mso=True, rate=True):
angle_to_rate =... | The main task of this code is to generate and merge multiple visualizations (rate vs. angle plots, ITD/ILD figures, and network diagrams) from input result files into a consolidated report image. It processes each file, extracts data, creates plots, saves them, and combines them using `merge_rows_files`. The final outp... | def generate_multi_inputs_single_net(results_paths, result_dir, cleanup=True):
filenames = [f.name for f in results_paths]
img_paths = []
for path, filename in zip(results_paths, filenames):
logger.debug(f"now working on result file {path}")
with open(path, "rb") as f:
res = dil... |
def carve_rooms(self, num_rooms):
rooms = []
for room in range(num_rooms):
room_height = randrange(3, self.height // 3 + 1, 2)
room_width = randrange(3, self.width // 3 + 1, 2)
room_start_x = randrange(1, (self.width - room_width) - 1, 2)
room_start_y = ra... | The code generates a maze by initializing a grid, carving rooms if specified, setting a starting position, and using a 'hunt-and-walk' algorithm to create paths. It iteratively explores the grid, connects passages, and finalizes the maze structure by assigning the grid to `self.maze` for output. | def generate(self):
self.grid = np.empty((self.height, self.width), dtype=np.int8)
self.grid.fill(1)
if self.num_rooms > 0:
self.carve_rooms(self.num_rooms)
curr_y, curr_x = self.set_start_pos()
self.grid[curr_y][curr_x] = 0
num_trials = 0
while (c... |
def gini(rows):
label_counts = label_counter(rows[:,0])
impurity = 1
for label in label_counts:
label_prob = label_counts[label] / float(len(rows))
impurity -= label_prob**2
return impurity
def partition(rows,col,val):
col_data=rows[:,col]
true_data, false_data = rows[col_data<... | The function `find_best_partition` identifies the optimal column and split value from a predefined set of columns to maximize information gain using Gini impurity. It calculates the initial uncertainty of the dataset, iterates through specified columns, partitions data at percentile thresholds (20th, 40th, etc.), evalu... | def find_best_partition(rows):
max_gain=0
best_question=None
random_cols=[0,7,32,53,30,23,145,146,108,179,61,11,107,118,140,23]
current_uncertainty=gini(rows[:,random_cols])
for col in random_cols[1:]:
feature_values=list(set(rows[:,col]))
partition_val=[np.percentile(feature_values,... |
def find_best_partition(rows):
max_gain=0
best_question=None
random_cols=[0,7,32,53,30,23,145,146,108,179,61,11,107,118,140,23]
current_uncertainty=gini(rows[:,random_cols])
for col in random_cols[1:]:
feature_values=list(set(rows[:,col]))
partition_val=[np.percentile(feature_values,... | The code recursively builds a decision tree by selecting the best feature to split the data, stopping when no gain is possible or maximum depth is reached, then creating a tree node with the split question and recursively built true/false branches. | def build_tree(rows,depth):
gain, question = find_best_partition(rows)
if gain == 0 or depth==9:
return label_counter(rows[:,0])
true_rows, false_rows = partition(rows, *question)
true_branch = build_tree(true_rows,depth+1)
false_branch = build_tree(false_rows,depth+1)
return TreeNo... |
def make_occur_dict(text):
"""Create dictionary with keys as unique letters and values as how many times they appear"""
letters = set(text)
data = {}
for letter in letters:
data[letter] = text.count(letter)
return data
def min_heap(self, occurrence_dict):
"""C... | The code compresses a given text file using a custom algorithm. It reads the input file, builds a frequency dictionary, constructs a min-heap for encoding, generates a code table, encodes the text into binary, converts it to a byte array, and saves the compressed result to a new file. The process includes validation to... | def compress_file(self, result_file_name):
print("==========================")
print("Starting compression")
with open(self.file) as f:
text = f.read()
occur_dict = self.make_occur_dict(text)
self.min_heap(occur_dict)
self.merge()
if ... |
def _covariance(y_j):
"""
Compute the empirical covariance for a source.
Args:
y_j (Tensor): complex stft of the source.
[shape=(nb_frames, nb_bins, nb_channels, 2)].
Returns:
Cj (Tensor): [shape=(nb_frames, nb_bins, nb_channels, nb_channels, 2)]
just y_j * conj(y... | (The function implements the Expectation-Maximization (EM) algorithm to refine source separation estimates by enforcing multichannel consistency. It iteratively re-estimates source parameters (power spectral densities and spatial covariance matrices) using the initial estimates `y` and mixture STFT `x`, then applies Wi... | def expectation_maximization(
y,
x,
iterations: int = 2,
eps: float = 1e-10,
batch_size: int = 200,
):
r"""Expectation maximization algorithm, for refining source separation
estimates.
This algorithm allows to make source separation results better by
enforcing multichannel consistenc... |
def inference(self, inp):
previous_out = inp
for layer in self.layers:
layer.net_value = np.dot(layer.weights, previous_out)
layer.outputs = layer.activation_function(layer.net_value)
previous_out = layer.outputs
def get_error(self, target):
return target - self.get_output()
def cal_new_weights(self, err... | This function trains a model by performing inference on input data, calculating the error compared to the target, updating model weights based on the error and input, substituting the old weights with the new ones, and returning the computed error for the training case. | def train_by_case(self, inp, target):
self.inference(inp)
error = self.get_error(target)
self.cal_new_weights(error, inp)
self.substitute_weights()
return error |
def train_by_case(self, inp, target):
self.inference(inp)
error = self.get_error(target)
self.cal_new_weights(error, inp)
self.substitute_weights()
return error
def get_square_error(self, target):
e = target - self.get_output()
e2 = np.square(e)
return np.sqrt(np.sum(e2))
def update_learning_rate(self,... | The code trains a model over multiple epochs by iterating through training data, updating weights via `train_by_case`, computing training error, adjusting the learning rate, evaluating on test data, and collecting epoch-wise errors and confusion matrices for analysis. | def train(self, train_data, test_data, epoch_num):
errors_per_epoch = []
for i in range(0, epoch_num):
train_error = 0
for d in train_data:
self.train_by_case(d[0], d[1])
train_error += self.get_square_error(d[1])
self.update_learning_rate(epoch=i+1)
test_error, test_conf_matrix = self.test(te... |
def delete_unacceptable_marks(avaliability_matrix, i, j, mark):
"""
Sets all the marks except chosen one to 0
:param avaliability_matrix: n**2 x n**2 x n**2 matrix with available labels: every num in sudoku matrix
is represented as row 1 x n with 0 and 1, 0 corresponds to una... | The function sets a 'mark' at position (i,j) in the availability matrix, but only if the specified location is unoccupied. If the mark already exists, it removes conflicting marks, neighboring marks, and invalid links. If the mark is absent, it prevents setting and prints an error message. | def set_mark(avaliability_matrix, i, j, mark):
"""
Func set 'mark' to the object with coordinates (i,j)
with all nessesary removement
"""
if avaliability_matrix[i, j, mark - 1] != 0:
delete_unacceptable_marks(avaliability_matrix, i, j, mark)
delete_mark_in_neighbors(avaliability_matr... |
def initiate_structure(n: int, init_states: List = None):
"""
Initiates sudoku matrix
:param n: num of rows or cols in one square
:param init_states: tuples (i, j, mark), optional
:return: initial availability matrix
"""
init_avaliability_matrix = np.ones(shape=(n ** 2, n ** 2, n ** 2), dtyp... | This code solves a Sudoku puzzle by iteratively filling empty cells with possible values. It initializes a structure to track valid numbers for each cell, populates initial values, and repeatedly selects the first valid number for empty cells until the grid is fully solved. The algorithm checks for completion and updat... | def sudoku_solver(init_sudoku, init_n=3, n=9):
"""
Solve sudoku
:param init_sudoku: n x n matrix with initial labels
:paran init_n: num of rows or cols in one square
:param n: num rows or num cols of sudoku matrix
:return: matrix with solved sudoku
"""
init_matrix = initiate_structure(in... |
def download_audio_files(self, video_urls=[], playlist_urls=[], start_date=None, end_date=None,
max_downloads=DEFAULT_MAX_DOWNLOADS_PER_PLAYLIST):
for video_url in video_urls:
VideoDownloader.download_playlist(video_url,
outp... | The main task of the code is to analyze audio/video content from specified URLs to extract and label sentiments related to specific coins. It downloads audio files, processes them into clips, converts audio to text, identifies coin mentions, extracts audio features, predicts sentiment, and returns a structured DataFram... | def get_sentiments(self, video_urls=[], playlist_urls=[], start_date=None, end_date=None,
clip_extraction_method="ffmpeg",
max_downloads_per_playlist=DEFAULT_MAX_DOWNLOADS_PER_PLAYLIST):
"""
Gets sentiments for specified coins from audio/video files.
... |
def energy_score_disc(batch, model_disc, sentiment=0, alpha=0):
"""Calculation of positive sentiment energy score
Args:
batch (torch.Tensor): batch of tokenized sentences with numerical values
model_disc (AutoModelForSequenceClassification): sentiment classifier
sentiment (int, optional... | This function generates text using a mix-and-match method by iteratively masking tokens, sampling replacements with BERT, and applying Metropolis-Hastings acceptance criteria based on normalized energy scores from sentiment classification and fluency metrics. It tracks metadata for each modification step and iteration,... | def parallel_sequential_generation(
batch: torch.Tensor, model_disc, args3, sentiment=0, batch_size=10, max_iter=300
):
"""Main execution of mix-and-match method.
Args:
batch (torch.Tensor): batch of tokenized sentences with numerical values
model_disc (AutoModelForSequenceClassificatio... |
def tokenize_batch(batch):
"""Uses the loaded tokenizer to assign numerical values to each token.
This is needed to perform calculations with these tokens.
Args:
batch (torch.Tensor): batch of string-tokenized sentences
Returns:
torch.Tensor: batch of tokenized sentences with numeri... | The code generates text samples using a model, either from a single input or a dataset. It tokenizes input text, creates batches, executes a "Mix and match" generation process, detokenizes outputs, selects optimal sentences, and writes results to output files. The task involves iterative processing of sentences, sentim... | def generate_samples(input=""):
"""Based on the --single argument here will be decided where it will get it's sentence from.
If --single = true then from the input mask
If --single = false or not declared then it will iteratively work through each sentencre from the dataset
Then follows the mai... |
def invalid(point, nStates):
return lowerInvalid(point, nStates) or higherInvalid(point, nStates)
def findLimitFactors(startVec, stopVec, nStates):
lf = []
if invalid(stopVec, nStates):
if invalidVector(startVec, stopVec, nStates):
return lf
lf = [0, 1]
for s in range(nStates):
... | The main task of the code is to generate valid endpoints by interpolating between consecutive points in a list, adjusting each subsequent point based on calculated limit factors. If the first point is invalid, it uses all limit factors to create multiple adjusted points; if valid, it uses only the minimum limit factor ... | def validEndpoints(points, nStates):
vep = []
if invalid(points[0], nStates):
for i in range(1, len(points)):
lf = findLimitFactors(points[0], points[i], nStates)
for f in lf:
vep.append(points[0] + f*(points[i] - points[0]))
else:
vep.append(points[0]... |
def linEqSolveZWL_UB_maxAllDim(cvProbs, nPeriods, nStates, statProbs):
estProbLoMatrix = np.zeros((nStates, nStates))
for s in range(nStates):
for n in range(nPeriods):
for cv, sCVProbs in cvProbs[n][s].items():
estProbLoMatrix[s, :] += sCVProbs.getInputProbsLo()
zwlEst =... | The code computes the maximum upper bounds (zwl_UB) for probabilistic states by solving linear equations with different constraints (all dimensions and per-state limits), validating resulting endpoints, and returning the highest valid probabilities across all states. | def findMaxProbs(cvProbs, nStates, statProbs, limits):
pointsList = []
zwl_UE = linEqSolveZWL_UB_maxAllDim(cvProbs, len(cvProbs), nStates, statProbs)
pointsList.append(zwl_UE)
for s in range(nStates):
zwl_UE_test = linEqSolveZWL_UB_1DLimit(cvProbs, len(cvProbs), nStates, statProbs, limits, s)
... |
def linEqSolveZWL_LE_minAllDim(cvProbs, nPeriods, nStates, statProbs, longerProbs):
estProbLoMatrix = np.zeros((nStates, nStates))
for s in range(nStates):
for n in range(nPeriods):
for cv, sCVProbs in cvProbs[n][s].items():
estProbLoMatrix[s, :] += sCVProbs.getInputProbsHi()... | The main task of the code is to compute the minimum probability distribution (zwL_LB) by solving linear equations under constraints defined by `cvProbs`, `nStates`, `statProbs`, and `limits`. It generates candidate solutions via `linEqSolveZWL_LE_minAllDim` and `linEqSolveZWL_LE_1DLimit`, filters valid endpoints using ... | def findMinProbs(cvProbs, nStates, statProbs, limits):
pointsList = []
zwl_LE = linEqSolveZWL_LE_minAllDim(cvProbs, len(cvProbs), nStates, statProbs, limits)
pointsList.append(zwl_LE)
for s in range(nStates):
zwl_LE_test = linEqSolveZWL_LE_1DLimit(cvProbs, len(cvProbs), nStates, statProbs, limit... |
def initCombinationVectorProbs(nStates, transitionMatrix, means, vars, nQs, statProbs):
cvProbsFirstPer = []
for s in range(nStates):
cvProbsFirstPer.append({})
for s in range(nStates):
combinationVector = [0]*nStates
combinationVector[s] = 1
cvTuple = tuple(combinationVector... | The code computes lower and upper bounds (zwl_lo/zwl_hi) for probabilistic values over multiple time periods using combination vectors, iteratively refining bounds until convergence (within epsilon) or max periods. It tracks beta values, DMP (deviation measure), and returns accumulated vectors, bounds, and intermediate... | def createAccVectorsZWLUBLinEqBound(nStates, means, vars, transitionMatrix, nQs, \
statProbs, beta_bound, deadline, epsilon, max_accum_periods = 20, period_bound = 1):
cvProbsPeriods = []
cvProbs = initCombinationVectorProbs(nStates, transitionMatrix, \
... |
def expected_failure(text):
return color(text, fg_light_cyan=True)
def print_failure_warning(failure_warning_list, status, tab_format, variant=None, expected=False, config=None, test=None, print_template=False):
for failure_warning in failure_warning_list:
msg = "{}Block name: '{}' - Condition: '{}'".fo... | The function summarizes test results by identifying and reporting discrepancies between expected and actual outcomes, including expected vs. unexpected failures, warnings, and skips. It checks lists of expected_failures, unexpected_failures, and related categories, printing alerts for each case. It also handles skipped... | def summary_unexpected_failures_test_module(result, test_name, module_id):
expected_failures = result['expected_failures']
unexpected_failures = result['unexpected_failures']
expected_failures_did_not_happen = result['expected_failures_did_not_happen']
expected_warnings = result['expected_warnings']
... |
def failure(text):
return color(text, bold=True, fg_red=True)
def warning(text):
return color(text, bold=True, fg_orange=True)
def print_failure_warning(failure_warning_list, status, tab_format, variant=None, expected=False, config=None, test=None, print_template=False):
for failure_warning in failure_warni... | This function generates a summary report for test results, highlighting unexpected outcomes (failures/warnings) based on specified keys. It iterates through test results, prints test names with links, and outputs failure/warning messages using a template, depending on the 'unexpected_type' and 'key' parameters. | def output_summary_test_plan_by_unexpected_type(variant, config_filename, overall_test_results, key, unexpected_type):
for test_result in overall_test_results:
result = test_result['test_result']
if result[key]:
test_name = test_result['test_name']
header = '\t\t{} {}'.format... |
def get_string_name_for_module_with_variant(moduledict):
name = moduledict['testModule']
variants = moduledict.get('variant')
if variants != None:
for v in sorted(variants.keys()):
name += "[{}={}]".format(v, variants[v])
return name
def failure(text):
return color(text, bold=Tru... | The function `show_plan_results` processes and displays detailed test results from a plan, summarizing each module's status, success/failure/warning counts, and execution time. It checks for incomplete tests, unexpected outcomes, and skipped tests, printing alerts for anomalies. It also generates an HTML report link an... | def show_plan_results(plan_result, analyzed_result):
plan_id = plan_result['plan_id']
plan_modules = plan_result['plan_modules']
test_info = plan_result['test_info']
test_time_taken = plan_result['test_time_taken']
overall_time = plan_result['overall_time']
detail_plan_result = analyzed_result['... |
def failure(text):
return color(text, bold=True, fg_red=True)
def split_name_and_variant(test_plan):
modules = None
op_test = None
op_config = None
if '{' in test_plan:
(test_plan, op_test) = test_plan.split("{", 1)
(op_test, op_config) = op_test.split("}", 1)
if ':' in test_plan... | The function summarizes and prints unexpected test outcomes from multiple test plans. It iterates through test results, checks for unexpected failures, warnings, skips, and their expected counterparts not occurring, then prints detailed summaries for each issue type, using specific formatting and helper functions to re... | def summary_unexpected_failures_all_test_plan(detail_plan_results):
for detail_plan_result in detail_plan_results:
if detail_plan_result:
config_filename = detail_plan_result['plan_config_file']
test_plan = detail_plan_result['plan_name']
print(failure('{} - {}: '.format(... |
def _define_args() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="op", required=True)
install = subparsers.add_parser("install")
sub_install = install.add_subparsers(dest="install_type", required=True)
install_startup = sub_install.add_parser(... | The main task of the code is to parse command-line arguments and execute installation/uninstallation operations. If the operation is "install", it handles either "startup" profile installation or "nbextension" setup based on flags. If "uninstall", it removes the startup configuration. The function delegates specific ta... | def main() -> None:
parser = _define_args()
t = parser.parse_args()
if t.op == "install":
if t.install_type == "startup":
_install_startup(t.profile)
if t.install_type == "nbextension":
_install_nbextension(t.show)
if t.op == "uninstall":
if t.install_type... |
def _pad_input(self, x):
target_shape = []
for s in x.shape[-2:]:
_s = s
while not self.is_valid_input_size(_s):
_s += 1
target_shape.append(_s)
return self.pad(x, tuple(target_shape))
def _crop_input(self, x):
target_shape = []
... | This code processes input through a UNet architecture by handling padding/cropping, validating input dimensions, applying batch normalization checks, and performing recursive feature extraction via encoder-decoder levels. It outputs processed features through a head module, adjusting spatial dimensions to match the ori... | def forward(self, x):
x_spatial_shape = x.shape[2:]
if self.pad_input:
x = self._pad_input(x)
if self.crop_input:
x = self._crop_input(x)
if self.padding == 0:
if not self.is_valid_input_size(x.shape[2:]):
raise ValueError(
... |
def clearCanvas():
global CANVAS
CANVAS.destroy()
CANVAS = Canvas(APP) #this is just a clear out button
CANVAS.pack()
def findSaveFiles(list_box):
csv_s = [pth for pth in Path.cwd().iterdir() if pth.suffix == '.csv'] #finds all '.csv' files in the current directory
for csv in csv_s:
list_box.insert(END, str(csv... | This function creates a GUI interface for selecting a saved file to schedule. It displays a label, listbox (with scrollbar) populated via findSaveFiles(), and a 'Schedule Routine' button. Clicking the button triggers schedulerScreen() with the selected file from the listbox, enabling user-driven scheduling of routines. | def scheduleINSTRUCTION():
global CANVAS
global APP
clearCanvas()
small_font = font.Font(size=5)
instruction_select_label = Label(CANVAS, text='Select the file you want to schedule', font=('bold', 12))
instruction_select_label.pack()
listbox = Listbox(CANVAS)
listbox.config(width=60, height=3,font=small_font)
... |
def clearCanvas():
global CANVAS
CANVAS.destroy()
CANVAS = Canvas(APP)
CANVAS.pack()
def findSaveFiles(list_box):
csv_s = [pth for pth in Path.cwd().iterdir() if pth.suffix == '.csv']
for csv in csv_s:
list_box.insert(END, str(csv).split('/')[-1])
def schedulerScreen(csv):
global CANVAS
clearCanvas()
loop_ti... | This function creates a GUI interface for scheduling files. It displays a label, listbox with scrollable saved files, and a 'Schedule Routine' button. When a file is selected and the button is clicked, it triggers the schedulerScreen function with the chosen file, allowing users to schedule selected routines. | def scheduleINSTRUCTION():
global CANVAS
global APP
clearCanvas()
small_font = font.Font(size=5)
instruction_select_label = Label(CANVAS, text='Select the file you want to schedule', font=('bold', 12))
instruction_select_label.pack()
listbox = Listbox(CANVAS)
listbox.config(width=60, height=3,font=small_font)
... |
def gamestate(self) -> GameState:
return GameState(
game_won=self.game_won,
is_initial_state=self.is_initial_state,
draw_pile=self.draw_pile,
hands=self.hands,
discard_pile=self.discard_pile,
current_agent_idx=self.current_agent_idx,
... | This method processes an agent's action in a turn-based card game, updating game state by handling card plays, draws, and special effects (e.g., reversing direction, drawing cards). It validates actions, modifies hand/discard piles, manages turn progression, enforces win conditions when a player empties their hand, and... | def step(self, agent_idx, action: Action):
self.gamestate().assert_valid(agent_idx, action)
hand = self.hands[agent_idx]
match action:
case PlayCard(card):
increment = 1
match card.sign:
case Sign.SKIP:
incr... |
def get_next_agent_idx(observation):
return (observation.current_agent_idx + observation.direction) % len(
observation.cards_left)
def get_prev_agent_idx(observation):
return (observation.current_agent_idx - observation.direction) % len(
observation.cards_left)
def calc_should_ch... | The function selects an action from the given action space based on game state observations. It prioritizes challenging Draw Four if applicable, ranks optimal card plays using histograms, and randomly selects from ranked actions or fallbacks to random choices if no optimal moves exist, ensuring game progression without... | def pick_action(self, current_observation: Observation,
last_observation: Observation,
action_space: set[Action]):
# If we only have one choice, we just have to choose it regardless. Skip all other logic.
is_only_choice = len(action_space) == 1
if is_only_... |
def prepare_for_new_round(self, current_observation):
# We must assume that the observation used here is a fresh hand for the current agent
self.reset_round()
self.update_hand_probabilities(current_observation, False)
def update_from_observations(self, observations):
if self.prev_observa... | The code determines the next action by analyzing observations, checking if the score has changed to reset the round, updating internal state, and selecting an action based on current and previous observations using the action space. | def get_action(self, observations, **kwargs) -> Action:
action_space = observations[-1].action_space()
# try:
current_observation = observations[-1]
current_score = sum(current_observation.scores)
# If the score has changed, we've reset and started a new round.
score_ha... |
def collect_student_info():
student_info = {}
print("Please input your information")
student_info['gpa'] = float(input("GPA (X.X): "))
student_info['act-score'] = int(input("ACT Score (Enter 0 if not taken): "))
student_info['sat-score'] = int(input("SAT score (Enter 0 if not taken): "))
studen... | The code filters and sorts scholarship data based on user input criteria (ethnicity, study field, state, school, GPA, SAT, ACT), calculates a scholarship score as "Award / Number Applied", ranks scholarships by this score, and outputs the top 3 results. | def main():
data = pd.read_csv(r"C:\Users\phurl\Downloads\scholarships (1).csv")
df = pd.DataFrame(data)
input = collect_student_info()
if input['first-gen']=='N':
df=df[df['First Gen'] != 'Y']
df = stringSort(df, input['ethnicity'], 'Ethnicity')
df = stringSort(df, input['study'], 'Stud... |
def get_redis_conn(username=None, password=None):
if not hasattr(frappe.local, "conf"):
raise Exception("You need to call frappe.init")
elif not frappe.local.conf.redis_queue:
raise Exception("redis_queue missing in common_site_config.json")
global redis_connection
cred = frappe._dict()
if frappe.conf.get("... | The function initializes and starts an RQ worker to monitor Redis queues, using configurable strategies (round_robin/random) and parameters like logging level, burst mode, and authentication. It connects to Redis, processes tasks from specified queues, and handles site initialization and logging setup. | def start_worker(
queue: str | None = None,
quiet: bool = False,
rq_username: str | None = None,
rq_password: str | None = None,
burst: bool = False,
strategy: Literal["round_robin", "random"] | None = None,
) -> NoReturn | None:
"""Wrapper to start rq worker. Connects to redis and monitors these queues."""
DEQ... |
def backspace(self):
if (len(self.Display["text"]) > 0 and self.Display["text"] != '0'):
self.Display.configure(text=self.Display["text"][:-1])
self.Display["text"] = self.Display["text"] if self.Display["text"] else '0'
def equalpressed(self):
result = 0.0
if(not self.oper... | This code handles keyboard input events to trigger specific actions in a calculator-like interface. It maps 'BackSpace' to a backspace function, 'equal', 'KP_Enter', or 'Return' to an equals operation, 'C' to a clear function, mathematical operators to operation handling, and digits/decimal points to number input proce... | def keypress(self,e):
symbol = e.keysym
#print(symbol)
if (symbol == 'BackSpace'):
self.backspace()
if (symbol == 'equal' or symbol == 'KP_Enter' or symbol == 'Return'):
self.equalpressed()
if (symbol.lower() == 'c'):
self.clear('C')
... |
def make_frequency_dict(self, imagearr):
frequency = {}
for pixel in imagearr:
if not pixel in frequency:
frequency[pixel] = 0
frequency[pixel] += 1
return frequency
def make_heap(self, frequency):
for key in frequency:
... | The code compresses an image using Huffman coding, converting it into a binary file (.bin) while updating a progress bar and UI labels. It reads the image, processes pixel data, generates frequency tables, builds a Huffman tree, encodes the image, pads the encoded data, and writes it to a file. | def compress(self,path,fun):
filename = os.path.splitext(path)[0]
output_path = filename + ".bin"
fun.refresh()
with open(output_path, 'wb') as output:
image = mpimg.imread(path)
self.imshape=image.shape
plt.imshow(image)
plt.s... |
def pipe(inp,xs):
'''inp is the data , pipe inp through each function in xs all is unary function'''
return inp if len(xs) == 0 else pipe(xs[0](inp),xs[1:])
def TR(candles,i):
'''raw gemini changes TR depending on the i, i is usually 0'''
curr = candles[i]
if i+1 == len(candles):
return 0
... | The code computes the Average True Range (ATR) indicator for financial data. It first calculates the True Range (TR) for each candlestick in the input list, then applies a moving average (MA) over a specified period `p` to smooth the TR values, resulting in the ATR, which measures market volatility. | def ATR(candles,p):
return pipe(candles,[
lambda inp: list(map( lambda index : TR(inp,index) ,range(len(inp)))),
lambda inp: MA(inp,p)
]) |
def admin_menu():
print("please choose one of the following menu items")
print("by choosing the corosponding menu item and hitting enter")
print("1. Create a user")
print("2. Connect to the chat")
print("3. Change user role")
print("4. List all registered users")
print("5. Exit.")
def option... | The main task of the code is to manage an admin account interface, allowing an admin user to navigate through a menu of options (1-5). It validates selections, executes specific functions (e.g., user switching, data operations), and recursively re-enters the admin menu after actions. If a user switch fails or a non-adm... | def admin_account(users, current_user):
usertypes = users[current_user]
if usertypes["Usertype"] == 'Admin':
admin_menu()
selection = (input(""))
options = {'1' , '2' , '3', '4', '5'}
while selection not in options:
admin_menu()
selection = (input(""))
... |
def menu():
print("please choose one of the following menu items")
print("by choosing the corosponding menu item and hitting enter")
print("1. Create a user")
print("2. Connect to the chat")
print("3. List all registered users")
print("4. Exit.")
def option1(username):
userinput = input("Ple... | This function handles a non-admin user's menu options, allowing them to view account details (option1), perform actions (option5), or exit (option4). It validates input, updates the current user's data, and transitions to admin functions if the user type changes to 'Admin' | def non_admin_account(users, current_user):
current_user = current_user
menu()
selection = (input(""))
options = {'1', '2', '3', '4'}
usertypes = users[current_user]
while selection not in options:
menu()
selection = (input(""))
while selection != '4':
if selection ==... |
def login(users):
print("please enter username")
usercheck = input()
while usercheck not in users:
print("please enter a created user")
print("if you would like to go back and register a user please press enter")
usercheck = input()
if len(usercheck) == 0:
return ... | This code reads user data from a CSV file, allows users to login or register, authenticates credentials, and directs authenticated users to role-specific functions (admin or non-admin) based on their type, concluding with a thank-you message. | def main():
current_user = None
cr = None
users = {}
password = None
usertypes = None
with open("users.csv", "r") as handler:
reader = csv.DictReader(handler, delimiter=',')
for row in reader:
print(row)
cr = row['Username']
users[cr] = row
... |
def prompt_user():
coffee_choice = raw_input("What would you like? (espresso/latte/cappuccino): ")
return coffee_choice
def turn_off():
global is_on
is_on = False
def print_report():
water = str(get_resource("water"))
milk = str(get_resource("milk"))
coffee = str(get_resource("coffee"))
... | The code handles user selections in a system, checking if the input is "off" to terminate, "report" to display status, or processes a transaction after verifying resource availability. It orchestrates actions based on user input and system state checks. | def select_option():
selection = prompt_user()
if selection == "off":
turn_off()
elif selection == "report":
print_report()
elif check_resources(selection):
process_transaction(selection) |
def getsettings():
settings=TankConfig.objects
if settings.count() == 0:
settings=TankConfig()
else:
settings=settings.first()
return settings
def initwaterlevelFig(settings):
sounderHeight=settings.sounderheight;
#get since last week
since=datetime.now(timezone.utc)-t... | The main task of the code is to generate a web dashboard with interactive visualizations using Dash. It initializes a layout containing graphs for water level, pressure/temperature, and rainfall data, along with a frequency selector. The dashboard integrates Django by rendering the configured layout into the "dashboard... | def dashboard(request):
# get settings
settings=getsettings()
dccstyle={"color":"white","font-family":'"Open Sans", verdana'}
app_wl.layout = html.Div([
dcc.Graph(figure=initwaterlevelFig(settings),id='water-level-data', responsive=True),
dcc.Graph(figure=initPressureTempFig(),id='pres-... |
def get_device_info(self, cached: bool = True):
if cached:
cached_res = self.get_from_cache('device')
if cached_res is not None:
return cached_res
(res, failed) = self.clip_request('GET', '/resource/device')
if failed:
print('unable to get dev... | The main task of the code is to refresh a `cache.json` file by updating its contents with the latest device, light, room, and scene data based on specified parameters. It checks the last update timestamp to determine if a refresh is needed, wipes or reads the existing cache, collects new data if required, and writes th... | def refresh_cache(self,
refresh_rooms: bool = False,
refresh_device: bool = False,
refresh_scenes: bool = False,
refresh_lights: bool = False,
wipe: bool = False, log=lambda x: x, scheduled_refresh: bool = True... |
def highest(w: int) -> int :
global field
for h in range(FIELD_HEIGHT) :
if field[h][w] > 0 :
return h
return FIELD_HEIGHT
def set_animation() -> None :
combine_animation()
fall_animation()
def restart_game() -> None :
global field
global score
global fall_speed
... | The main task of the code is to implement a falling block puzzle game similar to 2048, where blocks fall and merge when they land on the same number. It handles game initialization, user input for movement, block animation, collision detection, score tracking, and game over logic. The game updates the field state, mana... | def main() :
global field
global score
global fall_speed
global is_moving
global moving_num
global next_num
global horizontal_input
global horizontal_delay
global vertical_input
global game_over
global is_animating
global animation_place
global animation_direct... |
def make_disc_dict():
dis15 = consolidate_dis_15_16(2015)
dis16 = consolidate_dis_15_16(2016)
dis_17_18_csvs()
dis17 = pd.read_csv('discipline_2017.csv', encoding='cp1252', header=3)
dis18 = pd.read_csv('discipline_2018.csv', encoding='cp1252')
dis_dfs_dict = {2015:dis15, 2016:dis16, 2017:dis17,... | The function processes a dataset for a specific year by adjusting columns, renaming entries, filtering out non-state data, converting relevant columns to numeric values, and finalizing the cleaned dataset for further analysis or use. | def get_disc(year):
a = make_disc_dict()[year]
adjust_columns(a)
rename_ny(a)
a = remove_non_states(a)
a = numeric_columns(a)
a = finalize(a)
return(a) |
def passrates_df(year): # Retrieves or builds the pass rate dataframe
if os.path.isfile(os.getcwd()+f'\\pass_rates_{year}.csv') == True:
pass_rate_df = pd.read_csv(os.getcwd()+f'\\pass_rates_{year}.csv')
else:
pass_rate_df = build_df(create_list(make_table(pass_rate_dict[year])))
pass_ra... | The function merges multiple year-specific dataframes (pass rates, poverty rates, demographics, education rates, and race data) into a single dataframe. It then adds unemployment rates (converted to decimal form) and a 'Year' column, returning the consolidated dataset for analysis. | def merge_it(year): # Merges dataframes for a given year
# Initial merge of all dataframes except unemployment
merged = pd.merge(passrates_df(year), povrates_df(year))
merged = pd.merge(merged, get_disc(year))
merged = pd.merge(merged, edrates_df())
merged = pd.merge(merged, race_by_state(year))
# Add c... |
def update_job_order(self, wait_jobs):
max_idx, selected_fv, max_job_wait_time = self.score_calculate(wait_jobs)
#print(wait_jobs,score_list)
#max_idx = score_list.index(max(score_list))
if max_idx>0:
temp_wait_jobs = [wait_jobs[max_idx]] + wait_jobs[:max_idx] + wait_jobs[ma... | The `start_scan` method manages job scheduling and reinforcement learning training. It processes waiting jobs, checks node availability, starts eligible jobs, and updates the agent's policy using rewards and gradients. It performs backfilling for remaining jobs and conducts batch training by computing discounted reward... | def start_scan(self):
#self.debug.debug("# "+self.myInfo+" -- start_scan",5)
while True:
temp_wait = self.module['job'].wait_list()
wait_num = len(temp_wait)
if wait_num == 0:
break
#print('temp_wait_before',temp_wait)
temp_wai... |
def submit(self, job_index):
#self.debug.debug("# "+self.myInfo+" -- submit",5)
self.debug.debug("[Submit] "+str(job_index),3)
self.module['job'].job_submit(job_index)
return
def finish(self, job_index):
#self.debug.debug("# "+self.myInfo+" -- finish",5)
self.debug.deb... | This function processes an event by executing either a 'submit' or 'finish' action based on the current event's parameters, initiates a scan, and sets up a monitor for the next scheduled event if available. It manages event sequencing and triggers appropriate operations within a task scheduling or workflow system. | def event_job(self, para_in = None):
#self.debug.debug("# "+self.myInfo+" -- event_job",5)
'''
self.debug.line(2,"xxxxx")
i = 0
while (i<len(self.event_seq)):
self.debug.debug(self.event_seq[i],2)
i += 1
self.debug.line(2,"xxxxx")
... |
def import_submit_events(self):
# fread jobs to job list and buffer to event_list dynamically
if self.read_job_pointer < 0:
return -1
temp_return = self.module['job'].dyn_import_job_file()
i = self.read_job_pointer
#while (i < len(self.module['job'].job_info())):
... | The main task of the code is to process events in a sequence by iterating through `event_seq`, handling each event based on its type (job, monitor, extend), updating system state, logging debug information, and removing processed events from the queue. It ensures events are executed in order, triggers corresponding act... | def scan_event(self):
# self.debug.debug("# "+self.myInfo+" -- scan_event",5)
self.debug.line(2," ")
self.debug.line(2,"=")
self.debug.line(2,"=")
self.current_event = None
#while (self.event_pointer < len(self.event_seq) or self.read_job_pointer >= 0):
while (len... |
def get_config():
# Instantiate Flask
app = Flask(__name__)
# Load App Config settings
# Load common settings from 'app/settings.py' file
app.config.from_object('app.settings')
# Load local settings from environmental variable
if 'APPLICATION_SETTINGS' in os.environ:
app.config.from... | Your return
The code creates and configures a Flask application by initializing it with base and extra settings, setting up extensions (SQLAlchemy, Migrate, Mail, CSRF, Cache, Celery), registering blueprints for views, integrating Flask-User for user management, and configuring error handling. It returns the fully co... | def create_app(extra_config_settings={}):
"""Create a Flask applicaction.
"""
# Instantiate Flask
app = Flask(__name__)
# Load extra config settings from 'extra_config_settings' param
base_config = get_config()
app.config.update(base_config)
# Load extra config settings from 'extra_conf... |
def str_clean_up(self):
self.df['title'] = self.df['title'].str.lower()
self.df['title'] = self.df['title'].str.replace(r'[^\w\s]+', '', regex = True)
self.df['address'] = self.df['address'].str.lower()
self.df['address'] = self.df['address'].str.replace(r'[^\w\s]+', '', regex = True)
... | The main task of the code is to preprocess data for an ablation study by cleaning text, handling abnormalities, encoding categorical features (property type, furnishing, tenure, built year), and dropping irrelevant columns like IDs, addresses, and descriptive fields from both training and test datasets to isolate featu... | def setup_ablation(self):
self.str_clean_up()
self.handle_train_abnormal()
self.property_type_method()
self.furnishing_method()
self.tenure_method()
self.tenure_method(for_test=True)
self.built_year_method2()
self.built_year_meth... |
def set_eval(self):
"""Convert all models to testing/evaluation mode
"""
for m in self.models.values():
m.eval()
def process_batch(self, inputs):
"""Pass a minibatch through the network and generate images and losses
"""
for key, ipt in inputs.items():
... | The code validates the model on a single minibatch by setting evaluation mode, fetching data, processing the batch, computing losses (including depth-specific ones if applicable), logging results, and resetting the model to training mode. It handles data iteration and ensures proper resource cleanup. | def val(self):
"""Validate the model on a single minibatch
"""
self.set_eval()
try:
inputs = self.val_iter.next()
except StopIteration:
self.val_iter = iter(self.val_loader)
inputs = self.val_iter.next()
with torch.no_grad():
... |
def set_train(self):
"""Convert all models to training mode
"""
for m in self.models.values():
m.train()
def process_batch(self, inputs):
"""Pass a minibatch through the network and generate images and losses
"""
for key, ipt in inputs.items():
inp... | This function executes one training epoch, including model optimization via backpropagation, loss computation, and logging. It processes training batches, updates model parameters, and conditionally logs metrics. Validation is triggered during training, with depth loss calculations when depth data is present. The epoch... | def run_epoch(self):
"""Run a single epoch of training and validation
"""
self.model_lr_scheduler.step()
print("Training")
self.set_train()
for batch_idx, inputs in enumerate(self.train_loader):
before_op_time = time.time()
outputs, losses = se... |
def __inverse__(self):
x = [None] * self.num
u = [random.uniform(0, 1) for i in range(self.num)]
for i in range(self.num):
p = np.exp(-1 * self.p_lambda)
f = p
k = 0
while 1:
if u[i] < f:
x[i] = k
... | The code defines a `generate` method that selects and returns different private methods based on the input `algo` value: `__inverse__()` for 1, `__inverse_2__()` for 2, and `__exp_generate__()` for 3. Its main task is to act as a dispatcher, routing requests to specific inverse or generation algorithms depending on the... | def generate(self, algo):
if algo == 1:
return self.__inverse__()
if algo == 2:
return self.__inverse_2__()
if algo == 3:
return self.__exp_generate__() |
def get_google_query(message):
hasil = ''
for pattern in google_patterns:
# hapus excessive whitespace
message = re.sub("\s\s+", " ", message)
if re.search(pattern, message):
hasil=re.search(pattern, message).group(1)
break
return hasil
def google_search(query):
response = get_google_results(query)
... | This function processes user input to generate responses based on detected intents. It checks the intent tag, fetches relevant data (e.g., student info, Google search results, datetime), performs calculations, or executes actions like clearing the screen. It returns the response, verbosity flag, and additional paramete... | def get_response(intents_list, message, intents_json):
lagi = 0
message_lagi = ''
if len(intents_list)==0:
result = "Mohon maaf saya tidak dapat memahami pertanyaan anda, silahkan bertanya kembali"
verbose = 1
else:
tag = intents_list[0]
list_of_intents = intents_json["in... |
def get_right_word(tulisan):
tulisan = re.sub("\s\s+", " ", tulisan)
words_list = tulisan.split()
hasil = []
tulisanx = ''
for word in words_list:
wordpilih, rasio = fuzzy_search(word, words, 0.8, 1)
# print ('asli=', word, ', fuzzy_search=', wordpilih, ', rasio=', rasio)
has... | The main task of the code is to process user input by classifying intent, generating responses, handling follow-up questions, and storing interactions in a dictionary. It retrieves user messages, predicts intent, fetches answers, manages multi-turn conversations, and combines results with stored Q&A pairs for dynamic r... | def get_data_from_html():
global qa_dict
message = request.form['message']
message, hasil = get_right_word(message)
intents = pred_class(message, words, classes)
result, verbose, lagi, message_lagi = get_response(intents, message, data)
if (lagi==1):
intents =... |
def peroid_plots():
try:
df = NWO.copy()
selection = selected()
if len(selection) ==0:
window.Comments.setText('Please Make a Selection')
return None
else:
GS_data = search_data(selection)
if selection[0]== 'Production Date':
... | The code defines a `build()` function that selects and executes different plotting functions based on user interface inputs: it runs `peroid_plots()` if a period check is enabled, otherwise checks the selected plot type from a list and executes `operator_kde()` or `product_kde()` accordingly, defaulting to `Build_a_gra... | def build():
if window.peroidCheck.isChecked():
peroid_plots()
elif window.PlotTypeList.currentItem().text() == 'Operator KDE':
operator_kde()
elif window.PlotTypeList.currentItem().text() == 'Product KDE':
product_kde()
else:
Build_a_graph() |
def get_user_query(query:str) -> list:
user_input = query.lower()
query_list = user_input.rstrip().split()
return query_list
def produce_top_K_doc_list(score_pq:PriorityQueue,K:int)->["docID"]:
doc_list = []
for i in range(K):
if not score_pq.empty():
doc = score_pq.get_nowait()
... | The main task of the code is to process user input, compute cosine similarity scores using a word dictionary, retrieve top 20 documents from a priority queue, and generate a list of URLs with descriptions for the top results. It transforms user queries into scores, prioritizes documents, and returns the most relevant w... | def start_search(user_input:str, WORD_DICT:dict)->list:
query_list = get_user_query(user_input)
computation = Cosine_computation.Cosine_computation(query_list, WORD_DICT)
total_score_dict = computation.total_score_dict
score_pq = computation.score_priotiy_queue #priority queue that stores all the docID ... |
def load_dict(file_name:str)->dict:
file = open(file_name, 'r')
js = file.read()
d = json.loads(js)
file.close()
return d
def get_user_query(query:str) -> list:
user_input = query.lower()
query_list = user_input.rstrip().split()
return query_list
def produce_top_K_doc_list(score_pq:PriorityQueue,... | The main task of the code is to generate a report part by processing multiple search queries (e.g., "Informatics", "artificial intelligence") against a word dictionary. For each query, it computes cosine similarity scores, retrieves top 20 documents, and logs the query, number of retrieved URLs, and top documents. Resu... | def generate_report_part_2(file_name:str):
report_query_list = ["Informatics","Mondego","Irvine",
"artificial intelligence","computer science"]
result = []
WORD_DICT = load_dict("WordList.txt")
for query in report_query_list:
query_list = get_user_query(query)
co... |
def sobol_test01 ( ):
#*****************************************************************************80
#
## SOBOL_TEST01 tests BITWISE_XOR.
#
# Licensing:
#
# This code is distributed under the MIT license.
#
# Modified:
#
# 22 February 2011
#
# Author:
#
# Original MATLAB version by John Burkardt.
# Py... | The `sobol_test` function tests the SOBOL library by executing multiple test cases (`sobol_test01` to `sobol_test05`). It timestamps the start and end of execution, prints a header, and ensures the library's routines are validated. The primary task is to verify the correctness and performance of Sobol sequence generati... | def sobol_test ( argv = None ):
#*****************************************************************************80
#
## SOBOL_TEST tests the SOBOL library.
#
# Licensing:
#
# This code is distributed under the MIT license.
#
# Modified:
#
# 25 October 2016
#
# Author:
#
# Original MATLAB version by John Burk... |
def msgFormatTrans(m1):
s = "{} {} {}".format(m1["sender"], m1["receiver"], m1["amount"])
return s
def validateTrans(self, t1, t2):
balance = self.calcBalance()
return (balance[t1["sender"]] - t1["amount"] - t2["amount"] >= 0)
def mineBlock(self, t1, t2):
prevHash = None
depth = 0
if (len(self.blockchain... | The function checks if at least two transactions exist in `self.set`. It formats the first two transactions, validates them, and if valid, mines a block using them. If validation fails, it logs an error and rotates the transaction list by moving the first two elements to the end. The result of mining or `None` is retur... | def transactionCheck(self):
val = None;
if (len(self.set)>=2):
t1 = msgFormatTrans(self.set[0])
t2 = msgFormatTrans(self.set[1])
if (self.validateTrans(self.set[0], self.set[1]) == True):
val = self.mineBlock(t1, t2)
else:
print("Previous 2 transactions not valid.")
temp = self.set.pop(0)
... |
def get_prj_list_modified(fromdate: str, todate: str):
data = json.dumps(
{"requestType": "getOrganizationLastModifiedProjects",
"userKey": conf.ws_user_key,
"orgToken": conf.ws_org_token,
"fromDateTime": fromdate,
"toDateTime": todate,
"includeRequestToken": Fal... | The function synchronizes work items by retrieving modified projects between dates, collecting project tokens via API calls, filtering against exclusion lists, and creating/updating work items for eligible projects. It returns the count of processed projects or a "nothing to create/update" message. | def run_sync(st_date: str, end_date: str, custom_flds: list, wi_type: str):
global exist_wis
res = []
logger.info("Getting a modified project list")
modified_projects = get_prj_list_modified(st_date, end_date)
if conf.wsproducttoken:
prd_list = conf.wsproducttoken.split(",")
for prd_... |
def get_azure_prj_id(prj_name: str):
res = ""
try:
r, errorcode = call_azure_api(api_type="GET", api="projects", data={}, version="7.0", header="application/json")
if errorcode == 0:
for prj_ in r["value"]:
if prj_["name"] == prj_name:
res = prj_["... | The main task of the code is to calculate or retrieve the "last run" timestamp. If `reset` is "true", it computes a future time by adjusting the current time with `time_delta` and `reset_back_time`. Otherwise, it fetches the "Lastrun" property from an Azure API using a project ID, defaulting to the calculated future ti... | def get_lastrun(time_delta: int, reset: str):
if reset.lower() == "true":
last_run = (datetime.datetime.now() + datetime.timedelta(hours=time_delta) -
datetime.timedelta(hours=reset_back_time)).strftime("%Y-%m-%d %H:%M:%S")
else:
azure_prj_id = get_azure_prj_id(conf.azure_pro... |
def get_azure_prj_id(prj_name: str):
res = ""
try:
r, errorcode = call_azure_api(api_type="GET", api="projects", data={}, version="7.0", header="application/json")
if errorcode == 0:
for prj_ in r["value"]:
if prj_["name"] == prj_name:
res = prj_["... | The function updates the 'Lastrun' property of an Azure project by sending a PATCH request to the Azure API. It retrieves the project ID, constructs the payload, and handles errors by logging issues and incrementing a global error counter if the API call fails or the project is not found. The function returns the error... | def set_lastrun(lastrun: str):
global global_errors
azure_prj_id = get_azure_prj_id(conf.azure_project)
errorcode = 2
if azure_prj_id:
data = [{
"op": "add",
"path": "/Lastrun",
"value": f"{lastrun}"
}]
r, errorcode = call_azure_api(api_type="... |
def get_field_ref(fld_name):
for c_fld_ in cstm_flds:
if fld_name == c_fld_["name"]:
return f"/fields/{c_fld_['referenceName']}"
return f"/fields/Custom.{fld_name}"
def analyze_fields(fld: dict, prj: list):
val = ""
if fld["defaultValue"]:
step1 = ... | This function creates or updates Azure work items by constructing a JSON payload with fields like title, priority, tags, and description. It handles custom fields dynamically, adds/removes them based on configuration, and links work items via API calls. It logs success/failure statuses, tracks item counts, and manages ... | def create_wi_content(issue_id):
global data, count_item, global_errors
data = [
{
"op": azure_operation,
"path": "/fields/System.Title",
"value": vul_title
},
{
"op": azure_operation,
"pa... |
def startup():
global conf
conf = Config(
ws_user_key=varenvs.get_env("wsuserkey").strip(),
ws_org_token=varenvs.get_env("wsapikey").strip(),
ws_url=varenvs.get_env("wsurl").strip(),
wsproducttoken=varenvs.get_env("wsproduct").strip(),
wsprojecttoken=varenvs.get_env("wspr... | The code updates Azure DevOps work items tagged with "LICENSE" or "VULNERABILITY_SCORE" by synchronizing them with an external system (e.g., Mend). It queries recent work items, extracts metadata, and sends updates via an API, handling errors globally. The task ensures external issue tracking aligns with Azure project ... | def update_wi_in_thread():
global conf, global_errors
if conf is None:
conf = startup()
conf.update_properties()
try:
logger.info("Start to update Mend’s data")
first_id = 0
executed_wi = 0
tag_lic = Tags.get_el_by_name("LICENSE")
tag_vul = Tags.get_el... |
def add_targets_to_roadmap(self, start, end, K, verbose=False):
print('\nAdding targets to roadmap...')
# Pick k-nearest neighbors for start and end nodes
[start_dists], [start_args] = self.kdtree.query(start.reshape(1, -1), k=K)
[end_dists], [end_args] = self.kdtree.query(end.reshape(1... | The function `query_roadmap` generates a roadmap for path planning by adding start and end targets, converting the roadmap to an undirected graph, and executing a path planner. It enhances the roadmap with specified targets, ensures graph symmetry for traversal flexibility, and optionally visualizes the roadmap. The co... | def query_roadmap(self, K=3, verbose=False):
# Add start and end targets to the roadmap
start = self.joint_targets['start']
end = self.joint_targets['end']
self.add_targets_to_roadmap(start, end, K=K, verbose=verbose)
self.roadmap = utils.convert_directed_to_undirected_graph(self... |
def get_all_heroes_screenshot(human_movement):
click_in_area(OPTIONS_BTN_POS, human_movement)
click_in_area(CONTROLS_BTN_POS, human_movement)
click_in_area(CHANGE_HERO_POS, human_movement)
move_to_pos(SAFE_EDGE, human_movement)
# sleep so we take a screenshot of the correct page
time.sleep(1)
... | This function automates setting sensitivity values for game heroes by locating hero images in a screenshot, navigating to their sensitivity settings, and inputting specified sensitivity values via keyboard actions. It processes a list of hero data containing names, sensitivity values, and image paths, performing image ... | def set_sensitivity_data(data, human_movement=True):
"""
Sets the sensitivity data for the heroes specified in the data list.
Args:
data (list): A list of dictionaries containing hero data. Each dictionary should have
the following keys: 'name', 'sensitivity', and 'filepath'. '... |
def move(self, xPercent, yPercent):
moveTo(self.windowX(xPercent), self.windowY(yPercent))
time.sleep(0.4)
def windowX(self, percentage):
return self.gameWindow.left + self.gameWindow.width * percentage
def windowY(self, percentage):
return self.gameWindow.top + self.gameWindow.height * ... | This code automates repetitive mouse movements and key presses to perform a sequence of actions in a game or application. It moves the cursor, drags it between predefined window coordinates, presses keys 'Q' and 'E', and repeats cycles of dragging and sleeping, likely simulating tasks like farming, resource gathering, ... | def dumbPlay(self):
self.move(0.2,0.9)
time.sleep(0.4)
for i in range(84):
pyautogui.dragTo(self.windowX(0.95), self.windowY(0.9),0.55)
pyautogui.dragTo(self.windowX(0.05), self.windowY(0.9),0.55)
print(i)
self.pressKey(0x51)
print('q')
... |
def fetch_event_id():
connection = mysql.connector.connect(
host=db_config["database"]["host"],
database=db_config["database"]["database_name"],
user=db_config["database"]["user"],
password=db_config["database"]["password"],
auth_plugin=db_config["database"]["auth_plugin"]
)
... | The code monitors a YouTube live stream by checking for updates in the event ID and corresponding YouTube link. It tracks the live stream's duration, triggers an API call to end the session with the recorded duration when the stream concludes, and dynamically adjusts monitoring for new links. The loop pauses for 15 min... | def monitor_live_stream():
global EVENT_ID, start_time, end_time
last_youtube_link = None
while True:
# Check for changes in the YouTube link
current_event_id,current_youtube_link = fetch_event_id()
if current_event_id != EVENT_ID:
# Reset monitoring with the ne... |
def minorsMatrix(self, matrix):
size = int(np.sqrt(matrix.size))
minors = np.zeros((size, size))
for x in range(size):
for y in range(size):
submatrix = np.zeros((size - 1, size - 1))
m = 0
for x1 in range(size):
if ... | The code calculates the inverse of a matrix using the adjugate method: it computes minors, applies cofactors, transposes to form the adjugate, and multiplies by the reciprocal of the determinant. | def inverse(self):
inverse = self.minorsMatrix(self.matrix)
inverse = self.cofactors(inverse)
inverse = self.adjucate(inverse)
inverse = self.multiplyConst(inverse, (1 / self.determinant(self.matrix)))
return (inverse) |
def return_fit(self, xx, nbins, nout, k):
xbulk = xx[nout:]
bulkmin, bulkmax = xbulk[0], xbulk[-1]
print(bulkmin, bulkmax)
xbulk = xbulk - xbulk[0]
xbulk = xbulk / xbulk[-1]
b, a = fit_cdf_power(xbulk, nbins, k=k)
G, Gd = get_func(a, 0.5)
rescal = lambd... | This code estimates population eigenvalues from sample eigenvalues using a statistical model based on random matrix theory. It processes sorted eigenvalues, fits a density function (Fd), and iterates over outliers to compute adjusted population eigenvalues (-1/mtil), their standard deviations, and overlap metrics. The ... | def square_root_est(self, eigs, n, k, nout):
if not (np.diff(eigs) <= 0).all():
print('Eigenvalues not sorted!')
eigs = np.sort(eigs)[::-1]
biggest = eigs[0]
xx = eigs[0:n]
xx = xx[0]-xx
bulkev = eigs[nout:]
G, Gd, lh, rh = self.return_fit(xx, 50... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.